/*
 *fcmp 4.0
 *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.
 */

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

void usage(){
  printf("fcmp-4.0  -Finner ut om filer er like.\n"
         "Bruk: fcmp fil1 fil2 ...\n\n"
         "I tabellen som kommer symboliserer bokstaven x likhet mellom to filer.\n"
         "For eksempel betyr x i rad 1 kolonne 2 at fil1 og fil2 er like.\n\n"
         "Les tabellen vannrett. Tabellens nedre venstre halvdel betyr ikke noe.\n\n"
         "fcmp sammenlikner en byte om gangen fra hver fil med enhver annen fil,\n"
         "byte for byte, helt til likhetene tar slutt. Hvis tabellen sier at\n"
         "filer er like seg selv, betyr det at fcmp ikke leste resten av dem\n"
         "etter at alle likheter tok slutt. Tallet under tabellen er antall byte\n"
         "som filene maksimalt hadde til felles.\n");
}

int main(int filer, char *argv[]){
  filer--;
  if(filer < 2){
    usage();
    return 0;
  }
  int x=0, y=1;
  bool fortsett=1;
  FILE * filpek[filer];
  bool 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++;
  }

  int filstorleik=-1;
  char B[filer];

  while(fortsett == 1){

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

        if(tabell[y][y]==1 && tabell[x][x]==1){
          if(filstorleik == 0){
            if(B[y] == B[x]){
              tabell[x][y]=1;
              fortsett=1;
            }else{
              tabell[x][y]=0;
            }
          }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] == 0 && B[x] == 'a' && tabell[y][y] == 1){
            tabell[x][y]=0;
          }
          if(tabell[y][y] == 0 && B[y] == 'a' && tabell[x][x] == 1){
            tabell[x][y]=0;
          }
        }

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


  }

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

