/*******************************************************/
/* 1.2.1.A. compare                                    */
/*                        COMPARE                      */
/*                  (c) Bruno Jennrich                 */
/*                                                     */
/*                                                     */
/* This program compares two files with each other.    */
/*******************************************************/
#include "stdio.h"

FILE *File1,                       /* File descriptors */
     *File2;

long filepos;                 /* current file position */

unsigned char Byte1,                      /* byte read */
              Byte2;

main (argc, argv)
int   argc;
char      **argv;
{
   if (argc != 3)
   {
      printf ("USAGE: compare FILE1 FILE2 \n");
      exit (10);
   }

   File1 = fopen (argv[1],"r");          /* open files */
   File2 = fopen (argv[2],"r");

   if (File1 == 0L)               /* file open() error */
   {
      printf ("%s cannot be opened !!!\n",argv[1]);
      CloseIt (10);
   }

   if (File2 == 0L)               /* file open() error */
   {
      printf ("%s cannot be opened !!!\n",argv[2]);
      CloseIt (10);
   }

   filepos = 0;           /* current file position = 0 */
   while (!feof(File1) && !feof(File2))
   {
      Byte1 = fgetc (File1);             /* read bytes */
      Byte2 = fgetc (File2);
      if (Byte1 != Byte2)         /* outout difference */
         printf ("$%08lx  $%02x <> $%02x\n", filepos,Byte1,Byte2);
      filepos++;            /* increment file position */
   }

   if (feof(File1) && !feof(File2))  /* file1 is empty */
                                  /* but File2 is not. */
   {
      printf ("Comparison terminated !!!\n");
      printf ("\"%s\" out of data at $%08lx\n",argv[1],filepos-1);
      while (!feof(File2))
      {
         fgetc (File2);
         filepos++;
      }
                                /* read to end of file */
      printf ("\"%s\" out of data at $%08lx\n",argv[2],filepos-1);
   }
   else
   if (!feof(File1) && feof(File2))  /* File2 is empty */
                                  /* but File1 is not. */
   {
      printf ("Comparison terminated !!!\n");
      printf ("\"%s\" out of data at $%08lx\n",argv[2],filepos-1);
      while (!feof(File1))
      {
         fgetc (File1);
         filepos++;
      }
                                /* read to end of file */
      printf ("\"%s\" out of data at $%08lx\n",argv[1],filepos-1);
   }
   else
   if (feof(File1) && feof(File2))
      printf ("\"%s\" and \"%s\" have the size: %08lx\n",
              argv[1],argv[2],filepos-1);

   CloseIt (0);
}

CloseIt (Error_Code)
int      Error_Code;
{
   if (File1 != 0) fclose (File1);
   if (File2 != 0) fclose (File2);
   exit (Error_Code);
}

