// (C) M.A.Smith University of Brighton
//
// Permission is granted to use this code
//   provided this declaration and copyright notice remains intact.
//
// 26 August 1995

#include <iostream.h>
#include <fstream.h>
#include <iomanip.h>
#include <stdlib.h>
#include <time.h>
#include <string.h>


#include "parse.h"
#include "parse.cpp"

void process_script( char [] );
void process( char [] );
char* getenv_n( char [] );


// Main program
//

int main()
{
  char *query_str = getenv("QUERY_STRING");
  Parse list( query_str == 0 ? "file=mas2" : query_str );

  process_script( list.get_item( "file" ) );
  return 0;
}


void process_script( char file[] )
{
  enum State { NORMAL, IN_ESC };
  cout << "Content-type: text/html" << "\n"
       << "\n" << "\n";
  ifstream script( file );
  if ( script.fail() ) return;
  script >> resetiosflags( ios::skipws );
  const int MAX_MES = 200;
  char  c;
  char  mes[ MAX_MES ];
  char  start[] = "[=";  const int START_LEN = strlen( start );
  char  end[]   = "=]";  const int END_LEN = strlen( start );
  int   i, p=0, mes_len = 0;
  State state_is = NORMAL;

  while ( script >> c, !script.eof() )
  {
    switch ( state_is )
    {
      case NORMAL :
	if ( c == start[p] ) {         // Escape Sequence
	  p++;
	  if ( p >= START_LEN ) {      // Recognized Escape Seq.
	    state_is = IN_ESC;
	    mes_len = 0; p = 0;
	  }
	} else {                       // Not Escape Seq.
	  for ( i=0; i<p; i++ )        // Write any gather chars
	    cout << start[i];
	  cout << c;                   // Current char
	  p = 0;
	}
	break;
      case IN_ESC :                    // In Escape Sequence
	if ( c == end[p] ) {           // End of Escape Seq
	  p++;
	  if ( p >= END_LEN ) {        // End of Escape Seq
	    mes[ mes_len ] = '\0';     // Message to process
	    process( mes );
	    p = 0; state_is = NORMAL;
	  }
	} else {                       // Process goatherd chrs
	  if ( mes_len < MAX_MES - 10 ) {
	    for ( i = 0; i< p; i++ ) {
	      mes[mes_len++] = end[i];
	    }
	    mes[mes_len++] = c; p = 0; // Add to goatherd chrs
	  }
	}
	break;
    }
  }
}
    
void process( char mes[] )
{
  Parse list( mes );
  if ( list.get_item( "put_env" ) != 0 )
  {
    cout << getenv_n( list.get_item("put_env") );
  }
  if ( list.get_item( "exec" ) != 0 )
  {
    cout << list.get_item("exec");
  }
}
