/*
Copyright (c) 2000-2010, Dirk Krause
All rights reserved.

Redistribution and use in source and binary forms,
with or without modification, are permitted provided
that the following conditions are met:

* Redistributions of source code must retain the above
  copyright notice, this list of conditions and the
  following disclaimer.
* Redistributions in binary form must reproduce the above 
  opyright notice, this list of conditions and the following
  disclaimer in the documentation and/or other materials
  provided with the distribution.
* Neither the name of the Dirk Krause nor the names of
  contributors may be used to endorse or promote
  products derived from this software without specific
  prior written permission.

THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND
CONTRIBUTORS "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES,
INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES OF
MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE
DISCLAIMED.
IN NO EVENT SHALL THE COPYRIGHT OWNER OR CONTRIBUTORS BE
LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL,
EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT
LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES;
LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION)
HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN
CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE
OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS
SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH
DAMAGE.
*/



/**	@file	genau.c	The genau module in the genau program.
*/



#include <dk.h>
#include <dksf.h>
#include <dkmem.h>
#include <dkstr.h>
#include <dkapp.h>
#include <dklic.h>
#include <dkstream.h>
#include <dksto.h>
#include <dklogc.h>



/**	Inside the genau module.
*/
#define GENAU_C 1

#include <genau.h>
#include <readau.h>
#include <writeau.h>

#include <stdio.h>

#if DK_HAVE_STDLIB_H
#include <stdlib.h>
#endif
#if DK_HAVE_UNISTD_H
#include <unistd.h>
#endif
#if DK_HAVE_STRIN_H
#include <string.h>
#endif
#if DK_HAVE_STRINGS_H
#include <strings.h>
#endif
#include "dktools-version.h"




#line 83 "genau.ctr"





/**	System configuration directory.
*/
static char sysconfdir[] = { DK_SYSCONFDIR };

/**	Program group name.
*/
static char packagename[] = { "dktools" };

/**	Default file name, used when processing standard input.
*/
static char str_stdin[] = { "<STDIN>" };

/**	Text: double quote.
*/
static char str_quote[] = { "\"" };

/**	Text: space.
*/
static char str_space[] = { " " };

/**	Text: colon.
*/
static char str_colon[] = { ":" };



/**	Localized progress message texts.
*/
char *progress_strings[20];



/**	Flag: Show progress messages.
*/
static int show_progress = 0;



/**	Get localized progress messages.
	@return	Pointer to array of texts.
*/
char **genau_progress DK_P0()
{
  char **back;
  back = NULL;
  
  if(show_progress) { back = progress_strings; }
  
  return back;
}



/**	Default progress messages.
*/
dk_string_finder_t progress_msg[] = {
  {
    "/p/00",
    &(progress_strings[0]),
    "Processing options."
  },
  {
    "/p/01",
    &(progress_strings[1]),
    "Showing version/help text."
  },
  {
    "/p/02",
    &(progress_strings[2]),
    "Processing standard input."
  },
  {
    "/p/03",
    &(progress_strings[3]),
    "Processing input file."
  },
  {
    "/p/04",
    &(progress_strings[4]),
    "Reading state machine data."
  },
  {
    "/p/05",
    &(progress_strings[5]),
    "Processing options section."
  },
  {
    "/p/06",
    &(progress_strings[6]),
    "Writing header file."
  },
  {
    "/p/07",
    &(progress_strings[7]),
    "Writing state machine function."
  },
  {
    "/p/08",
    &(progress_strings[8]),
    "Writing reduced state machine description."
  },
  {
    "/p/09",
    &(progress_strings[9]),
    "Writing test file."
  },
  {
    "/p/10",
    &(progress_strings[10]),
    "Starting state reduction."
  },
  {
    "/p/11",
    &(progress_strings[11]),
    "Building output lookup table."
  },
  {
    "/p/12",
    &(progress_strings[12]),
    "Processing output lookup table."
  },
  {
    "/p/13",
    &(progress_strings[13]),
    "Checking state compatibility. States: "
  },
  {
    "/p/14",
    &(progress_strings[14]),
    "Building next-state lookup table."
  },
  {
    "/p/15",
    &(progress_strings[15]),
    "Processing next-state lookup table."
  },
  {
    "/p/16a",
    &(progress_strings[16]),
    "Checking state compatibility. Pass: "
  },
  {
    "/p/16b",
    &(progress_strings[17]),
    "   States: "
  },
  {
    "/p/17",
    &(progress_strings[18]),
    "State reduction finished."
  },
  {
    "/p/18",
    &(progress_strings[19]),
    "Grouping compatible states."
  },
  { NULL, NULL, NULL }
};



/**	Text array for localized messages.
*/
char *all_my_strings[30];



/**	Get localized messages.
	@return	Pointer to array of texts.
*/
char **genau_strings DK_P0()
{
  return (char **)all_my_strings;
}



/**	Default messages.
*/
dk_string_finder_t genau_msg[] = {
  {
    "/e/failed-to-read",
    &(all_my_strings[0]),
    "Failed to read automata specification."
  },

  {
    "/e/failed-to-open-gzfile",
    &(all_my_strings[1]),
    "Failed to read gzip'ed file."
  },
  {
    "/e/no-zlib-support",
    &(all_my_strings[2]),
    "We do not have zlib support here."
  },
  {
    "/e/failed-to-open-bz2file",
    &(all_my_strings[3]),
    "Failed to read bz2-compressed file."
  },
  {
    "/e/no-bz2-support",
    &(all_my_strings[4]),
    "We do not have bz2-compression support here."
  },
  {
    "/e/failed-to-read-file",
    &(all_my_strings[5]),
    "Failed to read input file."
  },
  {
    "/e/no-matching-file",
    &(all_my_strings[6]),
    "No matching file for pattern."
  },
  {
    "/e/fne",
    &(all_my_strings[7]),
    "Failed to allocate memory for filename expander."
  },
  {
    "/e/streamopen",
    &(all_my_strings[8]),
    "Failed to open stream for reading from stdin."
  },
  {
    "/e/state-exists",
    &(all_my_strings[9]),
    "State already exists."
  },
  {
    "/e/state-number-required",
    &(all_my_strings[10]),
    "No state number recognized."
  },
  {
    "/e/state-already-exists",
    &(all_my_strings[11]),
    "The state already exists."
  },
  {
    "/e/input-already-exists",
    &(all_my_strings[12]),
    "The input already exists."
  },
  {
    "/e/input-number-required",
    &(all_my_strings[13]),
    "No input number recognized."
  },
  {
    "/e/output-already-exists",
    &(all_my_strings[14]),
    "The output already exists."
  },
  {
    "/e/too-few-entries",
    &(all_my_strings[15]),
    "Too few entries in transition rule."
  },
  {
    "/w/current-state-undefined",
    &(all_my_strings[16]),
    "The current state is not yet defined."
  },
  {
    "/w/new-state-undefined",
    &(all_my_strings[17]),
    "The new state is not yet defined."
  },
  {
    "/e/failed-to-open-outputfile",
    &(all_my_strings[18]),
    "Failed to open output file."
  },
  {
    "/e/stream-stdout",
    &(all_my_strings[19]),
    "Failed to open a stream for writing to standard output."
  },
  {
    "/e/mem",
    &(all_my_strings[20]),
    "Not enough memory (RAM/swap)."
  },
  {
    "/e/sec-unk",
    &(all_my_strings[21]),
    "Unknown section name."
  },
  {
    "/e/sec-missing",
    &(all_my_strings[22]),
    "Section name missing."
  },
  {
    "/e/sec-unf",
    &(all_my_strings[23]),
    "Section name not finished."
  },
  {
    "/e/undef/in",
    &(all_my_strings[24]),
    "Undefined input, possibly typo."
  },
  {
    "/e/undef/out",
    &(all_my_strings[25]),
    "Undefined output, possibly typo."
  },
  {
    "/e/def/rule",
    &(all_my_strings[26]),
    "Rule already exists!"
  },
  {
    "/e/def/general",
    &(all_my_strings[27]),
    "General rule already defined!"
  },
  {
    "/e/too-many-states",
    &(all_my_strings[28]),
    "Too many states!"
  },
  { NULL, NULL, NULL}
};




/**	Command: Print help text.
*/
#define WANT_HELP	1

/**	Command: Print version.
*/
#define WANT_VERSION	2



/**	Application.
*/
dk_app_t *app = NULL;



/**	Long option: help. */
static char txt_help[] = { "help" };

/**	Long option: version. */
static char txt_version[] = { "version" };



/**	Process input stream.
	@param	is	Input stream.
	@param	name	File name.
	@return	1 on success, 0 on error.
*/
static
int
run_for_input_stream DK_P2(dk_stream_t *, is, char *, name)
{
  int back = 0;
  int flg;
  automata_t *au;
  char *errmsgs[6];
  
  flg = 0;
  /* progress 04 : reading */
  if(show_progress) {
    errmsgs[0] = progress_strings[4];
    dkapp_log_msg(app, DK_LOG_LEVEL_PROGRESS, errmsgs, 1);
  }
  au = readau_new(is,app,&flg,name);
  if(au) {
    if((au->initial_state) && (au->def_output)) {
      back = process_automata(au,app);
      readau_delete(au);
    } else {
      errmsgs[0] = str_quote;
      errmsgs[1] = name;
      errmsgs[2] = str_quote;
      errmsgs[3] = str_colon;
      errmsgs[4] = str_space;
      errmsgs[5] = all_my_strings[0];
      dkapp_log_msg(app, DK_LOG_LEVEL_ERROR, errmsgs, 6);
    }
  } else {
    /* 01 ERROR: Failed to read automata specification */
    errmsgs[0] = str_quote;
    errmsgs[1] = name;
    errmsgs[2] = str_quote;
    errmsgs[3] = str_colon;
    errmsgs[4] = str_space;
    errmsgs[5] = all_my_strings[0];
    dkapp_log_msg(app, DK_LOG_LEVEL_ERROR, errmsgs, 6);
  }
  
  return back;
}



/**	Process input file, either plain text or compressed.
	@param	filename	Input file name.
	@return	1 on success, 0 on error.
*/
static
int
run_for_real_file_name DK_P1(char *, filename)
{
  int back = 0;
  int compression_type;
  char *suffix;
  dk_stream_t *is;
  char *errmsgs[6];
  
  /* progress 03 : running for filename */
  if(show_progress) {
    errmsgs[0] = str_quote;
    errmsgs[1] = filename;
    errmsgs[2] = str_quote;
    errmsgs[3] = str_colon;
    errmsgs[4] = str_space;
    errmsgs[5] = progress_strings[3];
    dkapp_log_msg(app, DK_LOG_LEVEL_PROGRESS, errmsgs, 6);
  }
  compression_type = 0;
  suffix = dksf_get_file_type_dot(filename);
  if(suffix) {
    if(dkstr_casecmp(suffix, ".gz") == 0) { compression_type = 1; }
    if(dkstr_casecmp(suffix, ".bz2") == 0) { compression_type = 2; }
  }
  dkapp_set_source_filename(app, filename);
  dkapp_set_source_lineno(app, 1UL);
  switch(compression_type) {
    case 1: {
#if DK_HAVE_ZLIB_H
      is = dkapp_stream_opengz(app, filename, "rb");
      if(is) {
	back = run_for_input_stream(is, filename);
	dkstream_close(is);
      } else {
	/* 02 ERROR: Failed to open gzip file */
	errmsgs[0] = str_quote;
	errmsgs[1] = filename;
	errmsgs[2] = str_quote;
	errmsgs[3] = str_colon;
	errmsgs[4] = str_space;
	errmsgs[5] = all_my_strings[1];
	dkapp_log_msg(app, DK_LOG_LEVEL_ERROR, errmsgs, 6);
      }
#else
      /* 03 ERROR: No zlib support */
	errmsgs[0] = str_quote;
	errmsgs[1] = filename;
	errmsgs[2] = str_quote;
	errmsgs[3] = str_colon;
	errmsgs[4] = str_space;
	errmsgs[5] = all_my_strings[2];
	dkapp_log_msg(app, DK_LOG_LEVEL_ERROR, errmsgs, 6);
#endif
    } break;
    case 2: {
#if DK_HAVE_BZLIB_H
      is = dkapp_stream_openbz2(app, filename, "rb");
      if(is) {
	back = run_for_input_stream(is, filename);
	dkstream_close(is);
      } else {
	/* 04 ERROR: Failed to open bz2 */
	errmsgs[0] = str_quote;
	errmsgs[1] = filename;
	errmsgs[2] = str_quote;
	errmsgs[3] = str_colon;
	errmsgs[4] = str_space;
	errmsgs[5] = all_my_strings[3];
	dkapp_log_msg(app, DK_LOG_LEVEL_ERROR, errmsgs, 6);
      }
#else
      /* 05 ERROR: No bz2 support */
	errmsgs[0] = str_quote;
	errmsgs[1] = filename;
	errmsgs[2] = str_quote;
	errmsgs[3] = str_colon;
	errmsgs[4] = str_space;
	errmsgs[5] = all_my_strings[4];
	dkapp_log_msg(app, DK_LOG_LEVEL_ERROR, errmsgs, 6);
#endif
    } break;
    default : {
      is = dkapp_stream_openfile(app, filename, "r");
      if(is) {
	back = run_for_input_stream(is, filename);
	dkstream_close(is);
      } else {
	/* 06 ERROR: Failed to open file */
	errmsgs[0] = str_quote;
	errmsgs[1] = filename;
	errmsgs[2] = str_quote;
	errmsgs[3] = str_colon;
	errmsgs[4] = str_space;
	errmsgs[5] = all_my_strings[5];
	dkapp_log_msg(app, DK_LOG_LEVEL_ERROR, errmsgs, 6);
      }
    } break;
  } 
  return back;
}



/**	Check arguments for presence of input file
	name, expand patterns if necessary.
	@param	filename	Input file name or NULL.
	@return	1 on success, 0 on error.
*/
static
int
run_for_filename DK_P1(char *, filename)
{
  int back = 0;
  char *inputbuffer; int can_continue;
  dk_fne_t *fne;
  dk_stream_t *is;
  char *errmsgs[6];
  
  inputbuffer = dk_new(char,1024);
  if(inputbuffer) {
    if(filename) {
      dksf_correct_fnsep(filename);
      if(dksf_must_expand_filename(filename)) {
        fne = dkfne_open(filename, 1, 0);
        if(fne) {
	  if(dkfne_next(fne)) {
	    back = run_for_real_file_name(dkfne_get_fullname(fne));
	  } else {
	    /* 07 ERROR: No matching file */
	  errmsgs[0] = str_quote;
	  errmsgs[1] = filename;
	  errmsgs[2] = str_quote;
	  errmsgs[3] = str_colon;
	  errmsgs[4] = str_space;
	  errmsgs[5] = all_my_strings[6];
	  dkapp_log_msg(app, DK_LOG_LEVEL_ERROR, errmsgs, 6);
	  }
	  dkfne_close(fne); fne = NULL;
        } else {
	  /* 08 ERROR: Failed to open file name expander */
	  errmsgs[0] = str_quote;
	  errmsgs[1] = filename;
	  errmsgs[2] = str_quote;
	  errmsgs[3] = str_colon;
	  errmsgs[4] = str_space;
	  errmsgs[5] = all_my_strings[7];
	  dkapp_log_msg(app, DK_LOG_LEVEL_ERROR, errmsgs, 6);
        }
      } else {
        back = run_for_real_file_name(filename);
      }
    } else {
      /* progress 02 : run for stdin */
      if(show_progress) {
        errmsgs[0] = progress_strings[2];
        dkapp_log_msg(app, DK_LOG_LEVEL_PROGRESS, errmsgs, 1);
      }
      is = dkstream_for_file(stdin);
      if(is) {
        back = run_for_input_stream(is, str_stdin);
        dkstream_close(is);
        can_continue = 1;
        while(can_continue) {
	  if(feof(stdin)) {
	    can_continue = 0;
	  } else {
	    if(fread(inputbuffer,1024,1,stdin) == 0) {
	      can_continue = 0;
	    }
	  }
        }
      } else {
       /* 09 ERROR: Failed to open stream for stdin */
       errmsgs[0] = all_my_strings[8];
       dkapp_log_msg(app, DK_LOG_LEVEL_ERROR, errmsgs, 1);
      }
    }
    dk_delete(inputbuffer); inputbuffer = NULL;
  } 
  return back;
}



/**	Version number.
*/
static char the_version_number[] = { VERSNUMB } ;



/**	License conditions.
*/
static char *license_terms[] = {
"Redistribution and use in source and binary forms, with or without",
"modification, are permitted provided that the following conditions are met:",
"* Redistributions of source code must retain the above copyright notice, this",
"  list of conditions and the following disclaimer.",
"* Redistributions in binary form must reproduce the above copyright notice,",
"  this list of conditions and the following disclaimer in the documentation",
"  and/or other materials provided with the distribution.",
"* Neither the name of the Dirk Krause nor the names of other contributors may",
"  be used to endorse or promote products derived from this software without",
"  specific prior written permission.",
"THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS \"AS IS\"",
"AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE",
"IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE",
"ARE DISCLAIMED.",
"IN NO EVENT SHALL THE COPYRIGHT OWNER OR CONTRIBUTORS BE LIABLE FOR ANY",
"DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES",
"(INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES;",
"LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND",
"ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT",
"(INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS",
"SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.",
NULL
};



/**	Print version number and license conditions.
*/
static void print_version(void)
{
  char **ptr;
  printf("\n");
  printf("genau, version %s\n", the_version_number);
  printf("Copyright (C) 2002-2010 Dipl.-Ing. D. Krause\n");
  printf("http://dktools.sourceforge.net/genau.html\n\n");
  ptr = license_terms;
  while(*ptr) {
    printf("%s\n", *(ptr++));
  }
  printf("\nLibraries used:\n\n");
  ptr = dklic_get();
  while(*ptr) {
    printf("%s\n", *(ptr++));
  }
  printf("\n");
}



/**	Default help text if genau.txt is not found.
*/
static char *strings_help[] = {
  "genau <inputfilename>",
  "",
  "inputfilename: Name of input file to process.",
  NULL
};



/**	Print help text.
*/
static void print_help DK_P0()
{
  printf("\n");
  dkapp_help(app, "genau.txt", strings_help);
  printf("\n");
}



/**	Run the program.
	@param	argc	Number of command line arguments.
	@param	argv	Command line arguments array.
	@return	1 on success, 0 on error.
*/
static
int
run DK_P2(int, argc, char **, argv)
{
  int back = 0;
  int flags = 0;
  int i;
  char *cptr, **lfdptr;
  char *inputfilename;
  size_t lgt;
  char *errmsgs[6];

  
  /*
	Initialize
  */
  inputfilename = NULL;
  /*
	Traverse arguments
  */
  /* progress 00 : processing options */
  if(show_progress) {
    errmsgs[0] = progress_strings[0];
    dkapp_log_msg(app, DK_LOG_LEVEL_PROGRESS, errmsgs, 1);
  }
  lfdptr = argv; i = 1;
  lfdptr++;
  while(i < argc) {
    cptr = *lfdptr;
    switch(*cptr) {
      case '-' : { 			/* Option */
	cptr++;
	switch(*cptr) {
	  case '-' : {			/*   long option */
	    cptr++;
	    lgt = strlen(cptr);
	    if(lgt >= 4) {
	      if(strncmp(cptr, txt_help, 4) == 0) {
		flags |= WANT_HELP;
	      }
	    }
	    if(lgt >= 7) {
	      if(strncmp(cptr, txt_version, 7) == 0) {
		flags |= WANT_VERSION;
	      }
	    }
	  } break;
	  case 'v' : {			/*   version wanted */
	    flags |= WANT_VERSION;
	  } break;
	  case 'h' : {			/*   help wanted */
	    flags |= WANT_HELP;
	  } break;
	}
      } break;
      default : {			/* File name */
	if(!inputfilename) {
	  inputfilename = cptr;
	}
      } break;
    }
    lfdptr++; i++;
  }
  /*
	Ready to run
  */
  if(flags & (WANT_HELP | WANT_VERSION)) {
    
    /* progress 01 : showing help / version */
    if(show_progress) {
      errmsgs[0] = progress_strings[1];
      dkapp_log_msg(app, DK_LOG_LEVEL_PROGRESS, errmsgs, 1);
    }
    if(flags & WANT_VERSION) {
      print_version();
    }
    if(flags & WANT_HELP) {
      print_help();
    }
    back = 1;
  } else {
    
    back = run_for_filename(inputfilename);
  } 
  return back;
}



/**	The main() function of the genau program.
	@param	argc	Number of command line arguments.
	@param	argv	Command line arguments array.
	@return	0 on success, any other value indicates an error.
*/
#if DK_HAVE_PROTOTYPES
int main(int argc, char *argv[])
#else
int main(argc, argv) int argc; char *argv[];
#endif
{
  int exval = 0;
  int xargc;
  char **xargv;
  
#line 872 "genau.ctr"

  app = dkapp_open_ext1(argc,argv,packagename,sysconfdir,0,0);
  if(app) {
    dkapp_find_multi(app, genau_msg, "genau");
    if(dkapp_log_level_in_use(app, DK_LOG_LEVEL_PROGRESS)) {
      dkapp_find_multi(app, progress_msg, "genaup");
      show_progress = 1;
      
    }
    xargc = dkapp_get_argc(app); xargv = dkapp_get_argv(app);
    exval = run(xargc, xargv);
    dkapp_close(app); app = NULL;
  } else {
    /* ERROR: Failed to open app */
    if(!dkapp_silence_check(argc,argv)) {
      fprintf(stderr, "ERROR: NOT ENOUGH MEMORY!\n");
      fflush(stderr);
    }
  }
  exval = (exval ? 0 : 1);
  
  
#line 893 "genau.ctr"

  exit(exval); return exval;
}

