#include <stdio.h>
#include <string.h>
#include <ctype.h>
#include <dos.h>
#include "common.h"

static char oldcwd[256];
static int oldDrive = 0;
static struct ffblk fileBlock;

BOOL SetDir(char *dir)
{
  if (dir == 0)
    chdir(oldcwd);
  else
    chdir(dir);
  return(TRUE);
}
BOOL SetDrive(int drive)
{
  if (drive == -1)
    setdisk(oldDrive);
  else
    setdisk(drive);
  return(TRUE);
}
void ParseDir(char *spec, int *drive, char **dir, char **file)
{
   char *spec2;
   *drive = -1;
   *dir = 0;
   *file = 0;

   while (*spec == ' ') spec++;

   spec2 = spec;
   while (*spec2)
     *(spec2++) = toupper(*spec2);

   if (*spec) {
     if (*(spec+1) == ':') {
       *drive = *spec - 'A' ;
       *dir = spec + 2 ;
     }
     else
       *dir = spec;
   }

   if ((spec2 = strrchr(*dir,'\\')) != 0) {
     *spec2 = 0;
     *file = spec2+1;
   }
   else {
     *dir = 0;
     *file = spec;
   }
}
char *FirstFile(char *spec)
{
  if (findfirst(spec, &fileBlock, _A_NORMAL ))
    return(0);
  return(fileBlock.ff_name) ;
}
char *NextFile(void)
{
  if (findnext( &fileBlock))
    return(0);
  return(fileBlock.ff_name);
}
char *NewName( char *spec)
{
   static char namebuf[15];
   char *pos;
   strcpy(namebuf, spec);
   if (!(pos = strrchr(namebuf,'.')))
     strcat(namebuf,".~");
   else {
     *(pos+4) = 0;
     *(pos+3) = *(pos+2);
     *(pos+2) = *(pos+1);
     *(pos+1) = '~' ;
   }
   return(namebuf);
}
int FileRecurse( int count , char *FileNames[],
		char *Text, FILEFUNC routine, BOOL backup )
{
  int i;
  oldDrive= getdisk();
  getcwd(oldcwd,256);
  for (i=0; i< count; i++) {
    char buffer[256];
    char *dir;
    char *file;
    char *fileName;
    int drive;

    strcpy(buffer,FileNames[i]);
    ParseDir(buffer,&drive, &dir, &file);
    if (!SetDrive(drive) ) {
	fprintf(stderr,"Can't change to drive %c:", drive + 'A');
	continue;
    }
    getcwd(oldcwd,256);
    if (!SetDir(dir)) {
	fprintf(stderr,"Can't change to directory %s", dir);
	continue;
    }
    if ((fileName = FirstFile(file)) == 0) {
       fprintf(stderr,"No Such Files %s.\n",FileNames[i]);
       continue;
    }
    do {
      if (backup) {
	char *newName = NewName(fileName);
	FILE *inf,*outf;
	printf("%s %s to %s\n",Text, fileName, newName);
	outf = fopen(newName,"w");
	inf = fopen(fileName,"r");
	(*routine)(inf, outf, fileName);
	fclose (outf);
	fclose (inf);
	rename (newName,"ztbpjklx.xuz");
	rename (fileName, newName );
	rename ("ztbpjklx.xuz", fileName);
      }
      else {
	FILE *inf;
	printf("%s %s\n", Text, fileName);
	inf = fopen(fileName,"r");
	(*routine)(inf, 0, fileName);
	fclose( inf );
      }

    } while ((fileName = NextFile()) != 0);
    SetDir(0);
    SetDrive(-1);
  }
  return(0);
}