/* Convert between LISE spectra files and Cricket Graph Data
*/

#include <stdio.h>
#include <spec.h>

float x,y,*spc,*err,*tim;

help()
{
  printf("graphio spectrum [-l2g] [-g2l]\n");
  printf("  converts spectra from LISE to CRICKETGRAPH and vice versa\n");
  printf("  options:\n");
  printf("     -l2g     convert from LISE to CRICKETGRAPH\n");
  printf("     -g2l     convert from CRICKETGRAPH to LISE\n");
}

main(argc,argv)
int argc;
char *argv[];
{
int n,m,i,max;
char z[80],comment[80];


   spc= (float *)calloc(_MAXSPCLEN+2,sizeof(float));
   err= (float *)calloc(_MAXSPCLEN+2,sizeof(float));
   tim= (float *)calloc(_MAXSPCLEN+2,sizeof(float));
   if(tim==NULL) {
      printf("sorry, not enough memory\n");
      exit(-1);
   }

   if(checkopt(argc,argv,"-l2g",z)) {
      max=readspec(argv[1],spc,err,tim,comment);
      strcpy(z,argv[1]); n = strlen(z);
      for(i = 0; i < n; i++) if(z[i] == '.') z[i] = 0;
      writeplot(z,spc,err,tim,max,comment);
   }

   if(checkopt(argc,argv,"-g2l",z)) {
      max = readplot(argv[1],spc,err,tim,comment);
      strcpy(z,argv[1]); n = strlen(z);
      for(i = 0; i < n; i++) if(z[i] == '.') z[i] = 0;
      writespec(z,spc,err,max,2,comment);
      strcat(z,".tim");
      writespec(z,tim,err,max,2,comment);
   }
   free(err); free(spc); free(tim);
   exit(0);
}

writeplot(name,spc,err,tim,max,comment)
char *name, *comment;
float *spc, *err, *tim;
int max;
{
FILE *fp;
int i,n,m;
char *s;

   s = (char *) malloc(256);

   sprintf(s,"%s.dat",name);
   fp = fopen(s,"w");
   if(fp == NULL) {
      fprintf(stderr,"graphio: could not open >%s< for write\n",s);
      free(s);
      return(0);
   }
/*
   fprintf(fp,"*TITLE* %s\n*XLABEL* Time\n*LEGEND* %s\n",comment,name);
*/
   for(n = 0; n < max; n++) {
      fprintf(fp,"%f\x09%f\x09%f\n",tim[n],spc[n],err[n]);
   }
   fclose(fp);

   free(s);
}

readplot(name,spc,err,tim,comment)
char *name, *comment;
float *spc, *err, *tim;
{
FILE *fp;
int i,n,max;
char *s, *z;

   s = (char *) malloc(256); z = (char *) malloc(256);

   strcpy(s,name);
   fp = fopen(s,"r");
   if(fp == NULL) {
      strcat(s,".dat");
      fp = fopen(s,"r");
      if(fp == NULL) {
         fprintf(stderr,"graphio: could not open >%s< for read\n",name);
         free(s); free(z);
         return(0);
      }
   }
/*
   while(!feof(fp)) {
      fgets(s,200,fp); sscanf(s,"%s",z);
      if(strcmp(z,"*TITLE*") == 0) {
         n = strlen(z); i = 0; while(s[n] != 0) comment[i++] = s[n++];
         comment[i] = 0;
      }
      if(strcmp(z,"*LEGEND*") == 0) break;
   }
*/
   max = 0;
   while(!feof(fp)) {
      fgets(s,200,fp);
      if(s[0] == '*') continue;
      if(strlen(s) < 1) break;
      sscanf(s,"%f %f %f\n",&tim[max],&spc[max],&err[max]);
      max = max + 1;
   }
   fclose(fp);

   free(s); free(z);
}

