#include <stdio.h>
#include <dos.h>
#include <string.h>
#include <direct.h>
#include <stdlib.h> 

main(int argc, char *argv[])
{
int i, j, act_len, changed_flag;
char fallback[13], *found, oldpath[70];
struct FIND *f;
FILE *fp;

	found="(c) Ian Sharpe, December 1992, c/o PC Answers magazine";
	for(i=j=0; *found; i=i+ *(found++), j ^= i);
	if( (i-1)*3 != 13215 || j != 4684  )
		while(1);

	if ( argc==1 )	/* No parameters - do a popdir */
	{
		if( !(fp=fopen("\\oldpath.txt", "r")) )
		{
			puts("Can't open \\OLDPATH.TXT for reading: ABORTING");
			abort();
		}

		act_len=fread(oldpath, 1, 69, fp);
		fclose(fp);
		oldpath[act_len]='\0';
		if( act_len==0 || strncmp("ERROR", oldpath, 5)==0 )
		{
			puts("There was a problem with the saved path in \\OLDPATH.TXT: ABORTING");
			abort();
		}

		if( chdir(oldpath) != 0 )
			{
				printf("ERROR: Couldn't change to old directory %s\n", oldpath);
				abort();
			}
		exit(0);
	}

	/* SAVE CURRENT DIRECTORY */
	if ( !(fp=fopen("\\oldpath.txt", "w")) )
		puts("WARNING: Can't open \\OLDPATH.TXT to save current path");
	else
	{
		fputs(getcwd(NULL,0), fp);
		fclose(fp);
	}

	/* REPEATEDLY CHANGE DIRECTORY */
	for(i=1; i < argc; i++)
	{
		strupr(argv[i]);
		printf("%s\t\t->\t", argv[i] );

		/* Special cases: . \ \xxxxxxxx  */

		if( argv[i][0]=='.' && argv[i][1]=='\0' )
		{
			chdir("..");
			puts("..");
			continue;
		}

		if( argv[i][0]=='\\' && argv[i][1]=='\0' )
		{
			chdir("\\");
			puts("\\");
			continue;
		}

		if( argv[i][0]=='\\' && argv[i][1] != '\0' )
		{
			chdir("\\");
			strcpy(argv[i], argv[i]+1);
		}


		fallback[0]='\0';	/* ZERO FALLBACK DIR NAME STRING */
		for( changed_flag=0, f=findfirst("*.*", FA_DIREC); f ; f=findnext() )
		{
			/* FA_DIREC will also return ordinary files, so check */
			if( (f->attribute & FA_DIREC) == 0 ) /* Inner brackets shouldn't be necessary, but my compiler generates duff code without them */
				continue;

			strupr(f->name);
			if( (found=strstr(f->name, argv[i])) )
			{							/* MATCH AT LHS - CD AND NEXT i */
				if(found==f->name)
				{
					printf("Changing to %s\n", f->name);
					chdir(f->name);
					changed_flag=1;
					break;
				}

				/* ELSE IT'S INSIDE STRING - KEEP AS A FALLBACK OPTION */
				strcpy(fallback, f->name);
			}
		}
		if( changed_flag )
			continue;

		/* NO MATCH SO... */
		if( fallback[0] != '\0' )	/* USABLE FALLBACK NAME? */
		{
			printf("Changing to fallback option %s\n", fallback);
			chdir(fallback);
		}
		else		/* NO - ABORT */
		{
			puts("NO MATCH: ABORTING");
			abort();
		}
	}
}
