/* Source code for .EXE file stamping program. Opens an existing .EXE file, */
/* calculated and writes a hash stamp to the end of the file. If you have   */
/* modified the .EXE file validation system in exevalid.c, you will want to */
/* also recompile this program. To do so, create a "makefile" or "project   */
/* file", and add the exestamp.c and exevalid.c files. Then rebuild the     */
/* exestamp.exe program.                                                    */

/* Standard header files. */
#include <stdio.h>

/* Our header file. */
#include "exevalid.h"

/* Program execution begins here. */
int main(int argc, char *argv[])
{
   FILE *pEXEFile;
   tHash nFileHash;
   long lnFileLength;

   /* Check that correct number of parameters have been provided. */
   if(argc != 2)
   {
      printf("Format: EXEVALID <Program's .EXE filename>\n");
      return(1);
   }

   /* Attempt to open .EXE for read and write in binary mode. */
   pEXEFile = fopen(argv[1], "r+b");

   /* If open failed, return with failure. */
   if(pEXEFile == NULL)
   {
      printf("Unable to access file %s.\n", argv[1]);
      return(1);
   }
  
   /* Determine length of .EXE file. */
   fseek(pEXEFile, 0, SEEK_END);
   lnFileLength = ftell(pEXEFile);
   fseek(pEXEFile, 0, SEEK_SET);

   /* Determine hash code of file. */
   if(!GetFileHash(pEXEFile, lnFileLength, &nFileHash))
   {
      printf("Unable to calculate hash code of file.\n");
      fclose(pEXEFile);
      return(1);
   }

   /* Move to position to write hash code. */
   fseek(pEXEFile, lnFileLength, SEEK_SET);

   /* Write hash code to file. */
   if(fwrite(&nFileHash, sizeof(tHash), 1, pEXEFile) != 1)
   {
      printf("Unable to add hash stamp to file.\n");
      fclose(pEXEFile);
      return(1);
   }

   /* Close .EXE file. */
   fclose(pEXEFile);

   /* Finish with success. */
   printf("Hash stamp has been added to file.\n");
   
   return(0);
}


