#define version "v1.3.0 - 04.04.97"

/* Questions? Answers to my questions? Wanna improve my (*cough*
   *cough*) code? Write me.. cramey@alaska.net

   I'm not the greatest programmer on earth. So if you can't understand
   this or you think it sucks, I'm sorry.*/

#include <stdio.h>
#include <dir.h>
#include <string.h>
#include <stdlib.h>

int scanimage(long howmuch, char type[5]);
void helpme(void);

FILE *result;

void main(int argc, char *argv[]){
 long arg1;
 char arg2[5];
 argc=argc; /* I hate warnings. */

 printf("\nCompROM: %s\n", version);

 if (strcmpi(argv[1], NULL) == 0){
  printf("CompROM: Error: No syntax given.\n");
  helpme();exit(0);}

 if (strcmpi(argv[2], NULL) == 0){arg1=350;}
  else {arg1 = atol(argv[2]);}

 if (arg1 > 10000){
  printf("\nCompROM: Error: Invalid Argument.\n");
  helpme();exit(0);}

 printf("CompROM: %i byte read.\n", arg1);

 if((result = fopen("results.bat", "w")) == NULL){
  printf("\aCritical Error: Cannot open \"results.txt\" file for writing.");exit(0);}

 strcpy(arg2, argv[1]);
 scanimage(arg1, arg2);
 fclose(result);
 printf("CompROM: Complete.\n");}


int scanimage(long howmuch, char type[5]){
 FILE *image;
 struct ffblk ffbloc;
 struct ffblk ffback;
 unsigned char cone[10000], ctwo[10000];
 int dups=0;
 long counter;

 if (findfirst(type, &ffbloc, 0) != 0){
  printf("CompROM: Error: No images found. (%s)\n", type);exit(0);}

 do {
  ffback = ffbloc;

  if((image = fopen(ffbloc.ff_name, "rb")) == NULL){
   printf("\aCritical Error: Cannot open image %s for reading.", ffbloc.ff_name);
   exit(0);}

  fseek(image, SEEK_SET, 0);

  if(howmuch > ffbloc.ff_fsize){fread(cone, ffbloc.ff_fsize, 1, image);}
   else fread(cone, howmuch, 1, image);

  fclose(image);

  while (!(findnext(&ffbloc))){

   if (ffbloc.ff_fsize != ffback.ff_fsize){
    if ((image = fopen(ffbloc.ff_name, "rb")) == NULL){
     printf("\aCritical Error: Cannot open rom image %s for reading.", ffbloc.ff_name);
     exit(0);}

    printf("Compairing %s to %s              \r", ffback.ff_name, ffbloc.ff_name);

    fseek(image, SEEK_SET, 0);
    if(howmuch > ffbloc.ff_fsize){fread(ctwo, ffbloc.ff_fsize, 1, image);}
     else fread(ctwo, howmuch, 1, image);

    fclose(image);

    for(counter=0; counter != howmuch; ++counter){
     if (cone[counter] != ctwo[counter]){break;}}

    if(counter == howmuch){
     fprintf(result, "@ECHO %s == %s\n", ffback.ff_name, ffbloc.ff_name);
     fprintf(result, "@del %s\n",ffbloc.ff_name);++dups;}}}

	  ffbloc=ffback;
		} while (!(findnext(&ffbloc)));

   if (dups == 0){
    fprintf(result, "@ECHO No duplicate images found.");
    printf("CompROM: No duplicate images found.                \n");}
   return 1;}

void helpme(void){
 printf("CompROM: Usage: COMPROM [IMAGE FILTER] [BYTES TO READ(1-10000)]\n");}
