#include <stdio.h>
#include <math.h>

#ifndef TRUE
#define TRUE 1L
#endif
#ifndef FALSE
#define FALSE 0L
#endif

int flag_c;

main(argc,argv)
int argc;
char **argv;
{
char s[80];

   flag_c = 0;
   if(checkopt(argc,argv,"-c",s)) flag_c = 1;
   read_table(argv[1]);
   exit(0);
}


/* ----------------------------------------------------------------
      read parameter table
   ---------------------------------------------------------------- */
read_table(table)
char *table;
{
int i,j,n,flg;
double la,lb;
char *s, *z;
FILE *fp;

   s = (char *) malloc(128);
   z = (char *) malloc(128);
   fp = fopen(table,"r");
   if(fp == NULL) {
      fprintf(stderr,"could not open parameter table >%s<\n",s);
      exit(-1);
   }
   read_line(s,fp); /* read name of fit function */
   printf("SET fn %s\n",s);
   read_line(s,fp); sscanf(s,"%lf %d %lf",&la,&n,&lb);
   printf("SET eps %lf\n",la);
   printf("SET maxiter %d\n",n);
   printf("SET dchi2 %lf\n",lb);
   read_line(s,fp); n = atoi(s);
   printf("SET first %d\n",n);
   read_line(s,fp); n = atoi(s);
   printf("SET last %d\n",n);
   for(n = 1; n < 26; n++) {
      read_line2(s,fp);
      if(feof(fp)) break;
      i = 0; j = 0; flg = 0;
      while(s[i] != ' ') z[j++] = s[i++];
      z[j] = 0;
      if((z[0] > 42) && (z[0] < 58))printf("SET p%d %s\n",n,z);
      while(s[i] != 0) {
         if((s[i] == '+') && (s[i+1] == '-')) {
            j = 0; i = i + 2;
            while(s[i] == ' ') i++;
            while(s[i] != ' ') z[j++] = s[i++];
            z[j] = 0;
         printf("SET e%d %s\n",n,z);
         }
         if(s[i] == ';') {
            j = 0; i = i + 1;
            while(s[i] > 30) z[j++] = s[i++];
            z[j] = 0; i = i - 1;
            if(flag_c == 1) printf("SET c%d %s\n",n,z);
         }
         if(toupper(s[i]) == 'X') {
            if(s[i + 1] != '0') flg = 1;
         }
         i = i + 1;
      }
      printf("SET x%d %d\n",n,flg);
   }
   for(i = n; i < 26; i++) {
      printf("SET p%d 0\n",i);
      printf("SET e%d 0\n",i);
      printf("SET c%d ---\n",i);
      printf("SET x%d 0\n",i);
   }
   free(z); free(s);
   fclose(fp);
   return(0);
}

read_line(s,fp)
char *s;
FILE *fp;
{
int i,n;
char *z;

   z = (char *) malloc(128);
   read_line2(s,fp);
   i = 0; n = 0;
   while(s[i] == ' ') i++;
   while((s[i] != ';') && (s[i] != '\n') && (s[i] != 0))
                         z[n++] = s[i++]; /* break at comment */
   z[n] = 0; strcpy(s,z);
   free(z);
}

read_line2(s,fp)
char *s;
FILE *fp;
{

   fgets(s,128,fp);
   while(s[0] == ';') { /* skip comment lines */
      if(feof(fp)) {
         strcpy(s,"");
         return(0);
      }
      fgets(s,128,fp);
   }
   return(0);
}

checkopt(argc,argv,s,sv)
int argc;
char *argv[],s[],sv[];
{
int   n,erg;

   erg=FALSE;
   for(n=1;n<argc;n++) {
      if(strcmp(argv[n],s)==0) {
         erg=TRUE;
         strcpy(sv,argv[n+1]);
      }
   }
   return(erg);
}
