#include <cstdio>
#include <cstdlib>
#include "corlist.h"

#define min(x,y) ((x<y)?(x):(y))


Weight CorList::GetValue(char X[100], char Y[100], Weight (*H2)[100], int i, int j)
{
  Weight R = 9999*PREC;  // (+nieskonczonosc)
  int n;
  
  for (n=0; n<total; n++)
  {
    int la = List[n].la;
    int lb = List[n].lb;
    if (la<=i+1 && lb<=j+1)
      if (strncmp(List[n].a,X+i+1-la,la)==0 && strncmp(List[n].b,Y+j+1-lb,lb)==0) 
        R = min(R,H2[i-la][j-lb]+List[n].w);
    if (la<=j+1 && lb<=i+1)
      if (strncmp(List[n].b,X+i+1-lb,lb)==0 && strncmp(List[n].a,Y+j+1-la,la)==0) 
        R = min(R,H2[i-lb][j-la]+List[n].w);
  }
  return R;
}


int CorList::loadCWL(char *Name)
{
  FILE *f = fopen(Name,"r");
  int len=MAX_LEN*2+100;
  char a[100],b[100], buf[len+1];
  float wtmp;
  CorWeight w;
  
  cor_stdcor = 1 * PREC;
  cor_xchg   = 1 * PREC;
  
  List = (CorWeight*)malloc(sizeof(CorWeight));  // 100 BO NIE DZIALA REALLOC
  total=0;
  
  if (!f) { fprintf(stderr,"\nCan't open correction weight list file!\n"); return -1; }
  while (!feof(f) && fgets(buf,len,f))
  {
    if (buf[0]=='%')
     {
      sscanf(buf+1,"%s %f",&a,&wtmp);
      int ok=0;
      if (strcmp(a,"stdcor")==0) { ok=1; cor_stdcor=Weight(wtmp*PREC); /*printf("Standard letter correction set to: %1.2f\n",wtmp);*/ }
      if (strcmp(a,"xchg")==0) { ok=1; cor_xchg=Weight(wtmp*PREC); /*printf("Inverted letters correction set to: %1.2f\n",wtmp);*/ }
      if (!ok) { fprintf(stderr,"Error in file %s: Unknown keyword: '%s'.\n",Name,a); return -1; }
     }
    else
     { 
      sscanf(buf,"%s %s %f",&a,&b,&wtmp);
      w.w=(Weight)(wtmp*PREC);
      w.la=strlen(a); w.lb=strlen(b);
      if (w.la>MAX_LEN) { printf("ERROR in file %s: the string '%s' exceeds maximum length of %d characters.\n",Name,a,MAX_LEN); fclose(f); return -1; }
      if (w.lb>MAX_LEN) { printf("ERROR in file %s: the string '%s' exceeds maximum length of %d characters.\n",Name,b,MAX_LEN); fclose(f); return -1; }
      strcpy(w.a,a), strcpy(w.b,b);
      total++;
      List = (CorWeight*)realloc(List,total*sizeof(CorWeight));
      List[total-1]=w;
      //      printf("%s\t<->\t%s\t%1.2f\n",w.a,w.b,((float)w.w/PREC));
     }
  }
  fclose(f);
  //  printf("Total: %d\n\n",total);
  return(total);
}
