/*
This product contains certain software code or other information
("AT&T Software") proprietary to AT&T Corp. ("AT&T").  The AT&T
Software is provided to you "AS IS".  YOU ASSUME TOTAL RESPONSIBILITY
AND RISK FOR USE OF THE AT&T SOFTWARE.  AT&T DOES NOT MAKE, AND
EXPRESSLY DISCLAIMS, ANY EXPRESS OR IMPLIED WARRANTIES OF ANY KIND
WHATSOEVER, INCLUDING, WITHOUT LIMITATION, THE IMPLIED WARRANTIES OF
MERCHANTABILITY OR FITNESS FOR A PARTICULAR PURPOSE, WARRANTIES OF
TITLE OR NON-INFRINGEMENT OF ANY INTELLECTUAL PROPERTY RIGHTS, ANY
WARRANTIES ARISING BY USAGE OF TRADE, COURSE OF DEALING OR COURSE OF
PERFORMANCE, OR ANY WARRANTY THAT THE AT&T SOFTWARE IS "ERROR FREE" OR
WILL MEET YOUR REQUIREMENTS.

Unless you accept a license to use the AT&T Software, you shall not
reverse compile, disassemble or otherwise reverse engineer this
product to ascertain the source code for any AT&T Software.

(c) AT&T Corp. All rights reserved.  AT&T is a registered trademark of AT&T Corp.

***********************************************************************

History:

      11/30/99  - initial release by Hartmut Liefke, liefke@seas.upenn.edu
                                     Dan Suciu,      suciu@research.att.com
*/

//**************************************************************************
//**************************************************************************

#include "stdafx.h"

/* contains three functions:
	AskOverwriteFile()
	HandleSingleFile()
	HandleFileArg()
*/

char Settings::AskOverwriteFile(char *file)
   // Asks the user whether to overwrite
   // Returns 1, if yes,
   // Returns 0, if no,
   // Returns -1, if quit
{
   int c;

   if((!FileExists(file))||(overwrite_files))
      // If the file doesn't exist or we automatically overwrite it,
      // then we can simply return true
      return 1;

   printf("Overwrite file %s ? (Y(es) | N(o) | A(ll) | Q(uit)) ",file);

   // We wait until the user presses 'y', 'n', 'q', or 'a'
   do
   {
#ifdef WIN32
      c=_getch();
      printf("\n");
#else
      c=getchar();
#endif
      switch(toupper(c))
      {
      case 'Y':   return 1;
      case 'N':   return 0;
      case 'Q':   skip_all_files=1;return 0;
      case 'A':   overwrite_files=1;return 1;
      }
   }
   while(1);
}

void Settings::HandleSingleFile(XMill *xmill, char *file, bool compress)
   // Considers a single file 'file' and (de)compresses it
   // Most importantly, the name of the destination file is
   // determines by modifying/adding/removing extensions '.xml', '.xmi', '.xm'
{
   int len=strlen(file);
   char  *outfilename=file+len+5;
      // We use the space after the input file 
      // and leave a little bit of space for possible extension '.xmi' or '.xm'

   strcpy(outfilename,file);

   //try{

		if (compress) {
   // For the compressor, we replace ending '.xml' with '.xmi'
   // Or, if there is no ending '.xml', we replace by '.xm'

   if((len>=4)&&(strcmp(file+len-4,".xml")==0))
      strcpy(outfilename+len-4,".xmi");
   else
      strcat(outfilename,".xm");

   xmill->Compress(file,usestdout ? NULL : outfilename);

#ifdef PROFILE
   if(verbose >= XMILL_VERBOSE_STATS)
      session->globalclabeldict->PrintProfile();
#endif

		} else {
	// For decompression, we omit ending '.xm' or replace
   // ending '.xmi' with '.xml'
   if((len>=3)&&(strcmp(file+len-3,".xm")==0))
      // Do we have ending '.xm' ?
   {
      outfilename[len-3]=0;   // We eliminate the ending in the out file name
      xmill->Uncompress(file,usestdout ? NULL : outfilename);
   }
   else
   {
      // We replace '.xmi' by '.xml'
      if((len>=4)&&(strcmp(file+len-4,".xmi")==0))
      {
         strcpy(outfilename+len-4,".xml");
         xmill->Uncompress(file,usestdout ? NULL : outfilename);
      }
      else
      {
         // Otherwise, we assume the user specified the *uncompressed*
         // file and we try to either replace '.xml' by '.xmi'
         // or append '.xm'.

         if((len>=4)&&(strcmp(file+len-4,".xml")==0))
         {
            strcpy(file+len-4,".xmi");
            if(FileExists(file))
            {
               xmill->Uncompress(file,usestdout ? NULL : outfilename);
               return;
            }
            strcpy(file+len-4,".xml");
         }

         // Let's try to append '.xm'
         strcpy(file+len,".xm");

         if(FileExists(file)==0)
         {
            strcpy(file+len,"");
            XMillException *e = new XMillException(XMILL_ERR_FILENOTFOUND, "Could not find file '");
            e->ErrorCont(file);
            e->ErrorCont("' with extension '.xm'!");
            e->PrintErrorMsg();
				trydel (e);
            return;
         }
         xmill->Uncompress(file,usestdout ? NULL : outfilename);
         return;
      }
   }
		}
   /*} catch (XMillException *)
      // An error occurred
   {
      XMillException *e = new XMillException(XMILL_ERR_IN_FILE, "Error in file '");
      e->ErrorCont(file);
      e->ErrorCont("'");
      e->PrintErrorMsg();
		trydel (e);
   }*/
}

void Settings::HandleFileArg(XMill *xmill, char *filepattern, bool compress)
   // Takes a file name argument from the command line
   // and forward the file names to 'HandleSingleFile'
   // In Windows, file patterns with '*' and '?' must be explicitly
   // resolved.
{
   char        fullpath[400];
#ifdef WIN32
   _finddata_t finddata;
   long        handle;
   char        *ptr;
   int         fullpathlen;

   // Let's check if we have any meta characters '*' or '?' ?
   // We don't have them, we go directly to 'HandleSingleFile'

   ptr=filepattern;
   while(*ptr!=0)
   {
      if((*ptr=='*')||(*ptr=='?'))
         break;
      ptr++;
   }

   if(*ptr==0) // We didn't find any metacharacter?
               // The file name gets directly forwarded to HandleSingleFile
   {
      strcpy(fullpath,filepattern);
      HandleSingleFile(xmill, fullpath, compress);
      return;
   }
   // Otherwise, we apply functions '_findfirst' and '_findnext'

   // We scan from the back of the file name and look
   // for a separator
   ptr=filepattern+strlen(filepattern)-1;

   while(ptr>=filepattern)
   {
      if((*ptr=='\\')||(*ptr=='/'))
         break;
      ptr--;
   }

   if(ptr<filepattern)   // We didn't find a separator ?
   {
      // The file path is empty
      *fullpath=0;
      fullpathlen=0;
   }
   else
   {
      // We the path part from the file pattern including
      // the separator that we found
      memcpy(fullpath,filepattern,ptr-filepattern+1);
      fullpath[ptr-filepattern+1]=0;
      fullpathlen=ptr-filepattern+1;
   }

   // Let's now look for the file
   handle=_findfirst(filepattern,&finddata);
   if(handle==-1)
   {
      printf("Could not find %s!\n",filepattern);
      return;
   }

   do
   {
      // We concatenate the file name to the path
      strcpy(fullpath+fullpathlen,finddata.name);

      HandleSingleFile(xmill,fullpath, compress);
      if(skip_all_files)
         break;

      if(_findnext(handle,&finddata)!=0)
         break;
   }
   while(1);

   _findclose(handle);
#else /* !WIN32 */

   // In UNIX, the file name expansion is done by the shell
   // ==> We only need to look at the specific file
   strcpy(fullpath,filepattern);
   HandleSingleFile(xmill, fullpath, compress);
#endif /* WIN32 */
}

