/*======================================================================
* extract some information out of the AMIGA logfile
*======================================================================*/
#include <stdio.h>
#include <stdlib.h>
#include <math.h>
#include <string.h>

#define MAXSTRING 2048

int main(argc,argv)
int argc;
char **argv;
{
   FILE *fpin, *fpout;
   char dummyline[MAXSTRING];
   char cdummy[MAXSTRING];
   float zred, accuracy;
   float C, K, U;
   
   if(argc<3)
     {
      fprintf(stderr,"usage: %s logfile outfile\n",*argv);
      exit(1);
     }
   
   printf("=================================================\n");
   printf("  Read AMIGA logfile and extract relevant info\n");
   printf("=================================================\n");
   if((fpin=fopen(argv[1],"rb"))==NULL)
     {
      printf("I cannot open %s", argv[1]);
      exit(1);
     }
   if((fpout=fopen(argv[2],"wb"))==NULL)
     {
      printf("I cannot open %s", argv[2]);
      exit(1);
     }
   
   /* find "++++++++++++++" indicating start of time-step loop */
   fgets(dummyline,MAXSTRING,fpin);
   fprintf(stderr,"%s",dummyline);
   while(strncmp(dummyline,"+",1) != 0)
     {
      fprintf(stderr,"%s",dummyline);
      fgets(dummyline,MAXSTRING,fpin);
     }
   
   
   zred = 10000.;
   /* read logfile until redshift z=0 has been reached */
   while(zred > 0.00001)
     {
      /* find "redshift" entry */
      fgets(dummyline,MAXSTRING,fpin);
      while(strncmp(dummyline,"r",1) != 0)
         fgets(dummyline,MAXSTRING,fpin);
      sscanf(dummyline,"%s %s %s %f %s %f", cdummy,cdummy,cdummy,&zred,cdummy,&zred);
      
      
      /* find "energy" entry */
      fgets(dummyline,MAXSTRING,fpin);
      while(strncmp(dummyline,"e",1) != 0)
         fgets(dummyline,MAXSTRING,fpin);
      sscanf(dummyline,"%s %s %s %s %f %s %s %s %f %s %s %s %f",
             cdummy,cdummy,cdummy,cdummy,&C,
             cdummy,cdummy,cdummy,&K,
             cdummy,cdummy,cdummy,&U);
      
      
      /* find "accuracy" entry */
      fgets(dummyline,MAXSTRING,fpin);
      while(strncmp(dummyline,"a",1) != 0)
         fgets(dummyline,MAXSTRING,fpin);
      sscanf(dummyline,"%s %s %f",cdummy,cdummy,&accuracy);
      
      
      /* dump the relevant information into the new file */
      //fprintf(stderr,"%f %f\n", zred, accuracy);
      fprintf(fpout,"%12.5f %16.8f %16.8f  %g %g %g\n", zred, accuracy, 1./(1.+zred),C,K,U);
      fflush(fpout);
      
      /* find "----------" indicating next step*/
      while(strncmp(dummyline,"f",1) != 0)
         fgets(dummyline,MAXSTRING,fpin);
      
     }
   
   
   fclose(fpin);
   fclose(fpout);
}
