#include <stdio.h>
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
#include <strings.h>

#define MAX_N_CHARS 1000

int main( int argc, char *argv[] )
{
  int i;
  char buffer[ MAX_N_CHARS + 1 ];
  char filename_in[ MAX_N_CHARS + 1 ];
  char filename_out[ MAX_N_CHARS + 1 ];
  float frequency;
  float voltage;
  float raw_voltage;
  float n_points;

  if ( argc != 2 )
    {
      fprintf( stderr, "Need a data directory argument: %s run33\n", argv[0] );
      exit( -1 );
    }

  sprintf( filename_in, "%s/files.txt", argv[1] );
  FILE *stream_in = fopen( filename_in, "r" );
  if ( stream_in == NULL )
    {
      fprintf( stderr, "Can't open %s for read.\n", filename_in );
      exit( -1 );
    }

  sprintf( filename_out, "%s.m", argv[1] );
  FILE *stream_out = fopen( filename_out, "w" );
  if ( stream_out == NULL )
    {
      fprintf( stderr, "Can't open %s for write.\n", filename_out );
      exit( -1 );
    }
  
  fprintf( stream_out, "fff( 1, 6 ) = 0;\n" );
  for( i = 1; ; i++ )
    {
      if ( fscanf( stream_in, "%s%g%g%g%g", buffer, &frequency, &voltage,
		   &raw_voltage, &n_points ) < 4 )
	break;
      fprintf( stream_out, "load %s\n", buffer );
      char *p = strchr( buffer, '/' );
      if ( p != NULL )
	{
	  p = strchr( p+1, '/' );
	  if ( p == NULL )
	    {
	      fprintf( stderr, "Can't find second / in %s\n", buffer );
	      fprintf( stderr, "Filenames should be something like ../run/f00x1\n" );
	      exit( -1 );
	    }
	}
      else
	{
	  p = strchr( buffer, '\\' );
	  if ( p == NULL )
	    {
	      fprintf( stderr, "Can't find slashes / or \\ in %s\n", buffer );
	      fprintf( stderr, "Filenames should be something like ../run/f00x1\n" );
	      exit( -1 );
	    }
	  p = strchr( p+1, '\\' );
	  if ( p == NULL )
	    {
	      fprintf( stderr, "Can't find second \\ in %s\n", buffer );
	      fprintf( stderr, "Filenames should be something like ../run/f00x1\n" );
	      exit( -1 );
	    }
	}
      fprintf( stream_out, "[ml pl mr pr] = process( %s, %g );\n",
	       p+1, frequency );
      fprintf( stream_out, "fff(%d,1) = %g;\n", i, frequency );
      fprintf( stream_out, "fff(%d,2) = ml;\n", i );
      fprintf( stream_out, "fff(%d,3) = pl;\n", i );
      fprintf( stream_out, "fff(%d,4) = mr;\n", i );
      fprintf( stream_out, "fff(%d,5) = pr;\n", i );
      fprintf( stream_out, "fff(%d,6) = %g;\n", i, voltage );
    }
  if ( i == 1 )
    {
      fprintf( stderr,
	       "Hmmm, there was something wrong with the input file %s\n",
	       filename_in );
      exit( -1 );
    }

  fclose( stream_in );
  fclose( stream_out );
}
