#include <stdio.h>
#define MAXFILENAME 80
#define STYLE "solid"
/* STYLE options:  "solid", "dots", "triangles impulses", "dotdashed", etc */
/* type "help style" in xmath for more details...                          */

main(argc, argv)
     int argc ;
     char *argv[] ;
{
  FILE *fopen(), *fp_out, *fp_in, *fp_X ;
  char outfile[MAXFILENAME], infile[MAXFILENAME], Xfile[MAXFILENAME] ;
  char s_option[3] ;
  int i_option, count_columns ;
  int probe_molecules, dummy_zero, line_count ;
  double x_time, y_variable, dummy ;
  double xmax, xmin, ymax, ymin, xmargin, ymargin ;

  if (argc != 5)
    {
      printf("Usage:  format_xmath -option [datafile] [xmath formatted file] [nIs]\n") ;
      printf("\t where -option is \t -V for membrane potential\n") ;
      printf("\t\t\t\t -G for conductance\n") ;
      printf("\t\t\t\t -n for pore density function\n") ;
      printf("\t\t\t\t -l for large pore density\n") ;
      exit(0) ;
    }

  strcpy(s_option, argv[1]) ;
  strcpy(infile, argv[2]) ;
  strcpy(outfile, argv[3]) ;
  strcpy(Xfile, "graphX") ;
  sscanf(argv[4], "%n", &probe_molecules) ;
  

  if (strcmp(s_option, "-V") == 0) i_option = 0 ;
  else if (strcmp(s_option, "-G") == 0) i_option = 1 ;
  else if (strcmp(s_option, "-n") == 0) i_option = 2 ;
  else if (strcmp(s_option, "-l") == 0) i_option = 3 ;

  fp_in = fopen(infile, "r") ;
  fp_out = fopen(outfile, "w") ;

  xmin = 0.e0 ;
  line_count = 1 ;
  fprintf(fp_out, "#xmath for output file:  %s\n", infile) ;
  fprintf(fp_out, "#x-axis:  time \t y-axis: %s\n", s_option) ;
  while( fscanf(fp_in, "%e", &x_time) != EOF)
    {
      for( count_columns = 0 ; count_columns < i_option ; count_columns++)
	  fscanf(fp_in, "%e", &dummy) ;
      fscanf(fp_in, "%e", &y_variable) ;
      if (line_count == 1) ymin = ymax = y_variable ;
      else
	{
	  if (y_variable < ymin) ymin = y_variable ;
	  if (y_variable > ymax) ymax = y_variable ;
	}
      for( count_columns = 0 ; count_columns < 3-i_option+probe_molecules ; 
	  count_columns++)
	fscanf(fp_in, "%e", &dummy) ;
      fscanf(fp_in, "%d", &dummy_zero) ;
      fprintf(fp_out, "%e \t %e\n", x_time, y_variable) ;
      line_count++ ;
    }
  xmax = x_time ;
  xmargin = (xmax - xmin) / 100.0 ;
  ymargin = (ymax - ymin) / 100.0 ;
  xmin = xmin - xmargin ;
  xmax = xmax + xmargin ;
  ymin = ymin - ymargin ;
  ymax = ymax + ymargin ;

  fp_X = fopen(Xfile, "w") ;
  fprintf(fp_X, "#  Usage in xmath:  type \n") ;
  fprintf(fp_X, "#        load 'graphX'\n") ;
  fprintf(fp_X, "#  at the xmath> prompt\n") ;
  fprintf(fp_X, "#simulation data file:  %s\n", infile) ;
  fprintf(fp_X, "set x [%e:%e] \n", xmin, xmax) ;
  fprintf(fp_X, "set y [%e:%e] \n", ymin, ymax) ;
  fprintf(fp_X, "plot '%s' with %s \n", outfile, STYLE) ;
/*fprintf(fp_X, "print '%s.PS' \n", outfile) ;*/

  fclose(fp_in) ;
  fclose(fp_out) ;
  fclose(fp_X) ;
}
      
  

  

