#include <stdio.h>
#include <string.h>
#ifdef HAVE_UNISTD_H
#include <unistd.h>
#endif
#include "fudgit.h"
#include "head.h"

#ifndef USE_GETCWD
extern char *getwd(char *);
#endif

static int Cwdlevel = 0;
static char Path[MAXLEVEL+2][PATH_MAXIM];

extern char Ft_Cwd[PATH_MAXIM];

extern int chdir (const char *);
extern int Ft_filelevel (void);

int Ft_push_cwd(void)
{
#if defined(USE_GETCWD)
	if (getcwd(Path[Cwdlevel], PATH_MAXIM-1) == (char *)NULL) {
		perror("getcwd");
		return(ERRR);
	}
#else
	if (getwd(Path[Cwdlevel]) == (char *)NULL) {
		fprintf(stderr, "%s\n", Path[Cwdlevel]);
		return(ERRR);
	}
#endif
	strcpy(Ft_Cwd, Path[Cwdlevel]);
	if (++Cwdlevel > MAXLEVEL) {
		fputs("Error: Cwd stack overflow.\n", stderr);
		Ft_catcher(ERRR);
	}
	return(0);
}

int Ft_pop_cwd(void)
{
	if (Cwdlevel < 1) {
		fputs("Error: Cwd stack underflow.\n", stderr);
		Ft_catcher(ERRR);
	}
	if (chdir(Path[--Cwdlevel]) == ERRR) {
		perror("");
		return(ERRR);
	}
	strcpy(Ft_Cwd, Path[Cwdlevel]);
	return(0);
}

int Ft_clearpop_cwd(void)
{
	Cwdlevel = 1;
	if (chdir(Path[0]) == ERRR) {
		perror("");
		return(ERRR);
	}
	strcpy(Ft_Cwd, Path[0]);
	return(0);
}

int Ft_clearpush_cwd(void)
{
	if (!Ft_filelevel()) {
		Cwdlevel = 0;
		return(Ft_push_cwd());
	}
	return(0);
}
