#include <sys\types.h>
#include <sys\stat.h>
#include <fcntl.h>

char *strip_path();
char *skip_delim();
char *next_arg();
char *getenv();

/* 

	GO <dirname>

*/

main(argc,argv)
int argc;
char *argv[];
{
int f,n;
char *cp;
char dest[80];		/* GO target */
char fromfile[80];	/* =FILENAME from go file */
char ln[80],buff[80];
int found;

	--argc; ++argv;
	cpyarg(dest,*argv);				/* convenience pointer */
	if (! argc) {
		printf("GO -- Directory change/lookup tool -- 25 June 90\r\n");
		printf("Tom Jennings, World Power Systems/Fido Software\r\n");
		printf("Box 77731, San Francisco CA 94107 USA.\r\n");
		printf("\r\n");
		printf("    GO ?      Lists names and the drives/subdirs they belong to\r\n");
		printf("    GO =      Re-enter the last subdirectory\r\n");
		printf("\r\n");
		exit(0);
	}
	stolower(dest);					/* dest. dir. name */
	found= 0;					/* did not find it (yet) */
	*fromfile= '\0';				/* no 'from' filename yet */

	cp= getenv("GO"); 				/* find GO=filename, */
	if ((int) cp == 0) {				/* no GO=??? */
		printf("OOPS -- Can't locate the \"GO=\" environment variable (umm, did you set one)\r\n");
		exit(1);
	}
	f= open(cp,O_RDONLY);
	if (f == -1) {
		printf("OOPS -- Can't find the file you specified as \"GO=%s\"\r\n",cp);
		exit(1);
	}
	while (rline(f,ln,sizeof(ln))) {		/* locate the destination */
		if (*ln == ';') continue;
		cp= skip_delim(ln);

		if (*cp == '=') {			/* if a last-dir filename */
			cpyarg(fromfile,++cp);		/* remember the name */
			if (*dest == '=') {		/* ...and if dest is "=" */
				n= open(fromfile,O_RDONLY); /* use contents as 'dest' */
				if (n != -1) {
					rline(n,dest,sizeof(dest));
					close(n);
					continue;	/* now search for that */

				} else printf("OOPS -- Can't find the last-directory file \"%s\"\r\n",fromfile);
				break;

			} else continue;		/* (last-dir file but not "=") */
		}
		cpyarg(buff,cp);
		stolower(buff);				/* buff == 1st word in line */
		cp= next_arg(cp);
		stoupper(cp);				/* cp == destination drive/dir */

		if (*dest == '?') {			/* if just listing directories */
			found= 1;			/* prevent error messages */
			printf("%-16s %s\r\n",buff,cp);

		} else if (strcmp(buff,dest) == 0) {	/* else if a match, */
			if (cp[1] == ':') {		/* if a drive letter, */
				chdir("\\");		/* default root of current drive */
				bdos(14,*cp - 'A');	/* set new default drive */
				cp += 2;		/* skip the text */
			}
			cpyarg(buff,cp);		/* remove extraneous garbage */
			if (chdir(buff) == -1) printf("OOPS -- Cannot CHDIR to \"%s\"\r\n",buff);
			found= 1;
			break;
		}
	}
	close(f);

	if (found && *fromfile) {			/* remember where we went */
		f= creat(fromfile,S_IREAD | S_IWRITE);	/* so we can return */
		if (f != -1) {
			write(f,dest,strlen(dest));
			close(f);			/* to 'last dir' */

		} else printf("OOPS -- Can't create \"%s\"\r\n",fromfile);

	} else if (! found) printf("OOPS -- \"%s\" isn't in the list\r\n",dest);

	exit(found ? 0 : 1);
}

