/*
 ************************************************************************
 *
 *			  BIBLIOGRAPHY DATA BASE
 *	Root module of retreiving information from the data base
 *
 * Usage
 *	req_main	request_file_name target_dir
 *
 * where request_file_name specifies the request stream (preprocessed with
 * the 'req_pre' routine), and target_dir is the name of directory the
 * files with retreived information are to be written to.
 * Logical name 'DB_BIBLIOGRAPHY' has to be defined for the data base
 * file.
 *
 * Request stream preprocessed by the req_pre routine consists of one or
 * more records of the following form
 *	File_name		- Name of the file the rereived information
 *			  	  is to be written to
 *	Title        		- Arbitrary line specifying the request
 *	Select_clause		- SELECT SQL expression specifying relation
 *				  name, name of the fields retreived, and
 *				  the predicates controlling the set of
 *				  rows to be retreived (select criteria)
 *	END-REQUEST		- String denoting the end of the request
 * Blank lines in the request stream are ignored.
 *
 ************************************************************************
 */

#include "stdio.h"

			/* Local data				*/
static FILE * Req_stream;
static char * Target_directory;
#define End_of_request  "END-REQUEST"


extern void retreive(FILE * out_file, 
		     const char * select_stmt);	


/*
 *-----------------------------------------------------------------------
 *			Get Record system service
 */

static int Lines_counter;

static void report_error(title)
const char * title;
{
  message("\n\n%REQ_MAIN Error '%s'",title);
  message("\n- while processing the %d line of the request stream",
	  Lines_counter);
  if( ferror(Req_stream) )
    perror("\n- Request stream read error");
  _error("Processing is terminated due to errors listed above");
}


				/* Read a record from the Req_stream	*/
static char * get_record()
{
  static char buffer [120];
  register char * p;

  Lines_counter++;
  fgets(buffer,sizeof(buffer)-1,Req_stream);
  if( (p=strchr(buffer,'\n')) == (char *)0 )
    report_error("Too long line to read");
  *p = '\0';				/* Replace '\n' with end-of-str mark*/

  if( strspn(buffer," \t") == strlen(buffer) ) 	/* Ignore blank lines  	*/
    return get_record();
  return buffer;
}

				/* Return 1 if the request stream is	*/
				/* being ended				*/
static int is_eof()
{
  register int c = getc(Req_stream);
  if( c == EOF )
    return 1;
  ungetc(c,Req_stream);
  return 0;
}
/*
 *-----------------------------------------------------------------------
 * 			Parse the request
 */

				/* Open the specified file in the	*/
				/* Target_directory			*/
static FILE * open_output_file(file_name)
const char * file_name;
{
  static char full_file_name [120];

  strncpy(full_file_name,Target_directory,
	  sizeof(full_file_name)-strlen(file_name)-1);
  strcat(full_file_name,file_name);

  printf("\n\nNew user\nInfomation is being written to the file %s",
	 full_file_name);
  return fopenc(full_file_name,"w");
}

				/* Handle the title string		*/
static void handle_title(fp,title)
FILE * fp;
const char * title;
{
  printf("\nTitle: %s",title);
  fprintf(fp,"-----> %s <-----\n\n",title);
}


static void parse_request()
{
  static char select_clause [6000];
  FILE * out_file;
  register char * p;

  out_file = open_output_file(get_record());
  handle_title(out_file,get_record());
  
  for(p=select_clause;;)
  {
    register char * rec = get_record();
    register int len = strlen(rec);

    if( feof(Req_stream) || ferror(Req_stream) )
      report_error("End-of-file or other error while reading the request");
    if( strcmp(End_of_request,rec) == 0 )
      break;
    if( p+len >= select_clause + sizeof(select_clause) )
      report_error("Too long select-clause");
    strcpy(p,rec);
    p += len;
  }
  *p = '\0';			/* Terminate the Select-clause string	*/

  retreive(out_file,select_clause);

  if( ferror(out_file) )
    report_error("An error has occured while writing the user file");
  fclose(out_file);
}


/*
 *========================================================================
 *			Initialization routines
 */

static void help()
{
  message("\n\n\tRetreive information from the BEN data base on requests");
  message("\n\n\t\treq_main	request_file_name target_dir");
  message("\n\ntarget_dir specifies the directory files info are to be");
  message("\nwritten to");
  message("\n\nDon't forget to define the logical name DB_BIBLIOGRAPHY");
  message("\n\n");
  message("\nExample");
  message("\n\treq_main request.req user4:[library.nsl.userinfo]");
  exit();
}


/*
 *-----------------------------------------------------------------------
 *				Root module
 *  Parse the command string
 *  Two arguments are being expected (excluding the pgm name as the 0. arg)
 *  one     "request_stream_file_name"
 *  another "target_dir"
 */

main(argc,argv)
int argc;				/* No. of arguments being passed*/
char *argv[];				/* Vector of pointers to args 	*/
{
 int counter;

 if( argc != 3 )                        /* Too few or too many arguments*/
   help();

 Req_stream  = fopenc(argv[1],"r");
 Target_directory = argv[2];

 for(counter=0; !is_eof(); counter++)
    parse_request();

 message("\n\n========== %d requests have been processed\n\n",counter);

 fclose(Req_stream);
}

