/*
 *fcmp 4.1
 *Copyright Andreas Nordal
 *
 *You are hereby granted the permission to do whatever you want with this source code
 *and derivatives, as long as you inform about your changes to this source code below
 *this notice, and do not change or remove any notice above the beginning of the code.
 *This is free software, I am not responsible for anything you do with it.
 */

#include<stdio.h>
#include<string.h>
#include<errno.h>

void usage(){
  printf("fcmp-4.1  -Finner ut om filer er like.\n"
         "Bruk: fcmp fil1 fil2 ...\n\n"
         "fcmp viser hver fil-likhet på en ny linje, slik at hvis fil1 og fil2\n"
         "er like, svarer fcmp \"fil1 = fil2\". fcmp sammenlikner alle filer\n"
         "samtidig forfra byte for byte, helt til alle likheter tar slutt.\n"
         "Antall byte som maksimalt ble lest fra samme fil vises til slutt.\n");
}

int main(int filer, char *argv[]){
  filer--;
  if(filer < 2){
    usage();
    return 0;
  }
  int x=0, y=1;
  char fortsett=1;
  FILE * filpek[filer];
  char tabell[filer][filer];
  while(x < filer){
    filpek[x] = fopen(argv[y], "r");
    if (filpek[x] == NULL){
      fprintf(stderr, "%s: %s\n", argv[y], strerror(errno));
      tabell[x][x] = 0;
    }else{
      tabell[x][x] = 1;
    }
    x = y++;
  }

  unsigned int filstorleik=0;
  char B[filer];

  while(fortsett == 1){

    x=0;
    fortsett=0;
    //Les
    while(x < filer){
      if(tabell[x][x] == 1){
        if(fscanf(filpek[x], "%c", &B[x]) == EOF){
          tabell[x][x]=2;
        }
      }
      x++;
    }
    filstorleik++;
    x=1, y=0;
    while(x < filer){
      while(y < x){

        if(tabell[y][y]==1 && tabell[x][x]==1){
          if(filstorleik == 1){
            tabell[x][y]=0;
            if(B[y] == B[x]){
              tabell[x][y]=1;
              fortsett=1;
            }
          }else if(tabell[x][y] == 1){
            if(B[y] == B[x]){
              fortsett=1;
            }else{
              tabell[x][y]=0;
            }
          }
        }else if(tabell[x][y] == 1){
          if((tabell[x][x] == 2 && tabell[y][y] == 1) || (tabell[x][x] == 1 && tabell[y][y] == 2)){
            tabell[x][y]=0;
          }
        }

        y++;
      }
      x++;
      y=0;
    }

  }

  x=1, y=0;
  while(y < filer){
    while(x < filer){
      if(tabell[x][y] == 1) printf("%s = %s\n", argv[y+1], argv[x+1]);
      x++;
    }
    y++;
    x=y+1;
  }
  printf("%u B\n", filstorleik);
  return 0;
}

