/*
Copyright (c) 2004-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	fig2vect.c	Main program module for fig2vect.

This program converts Fig file produced by XFig, jFig or WinFig
to vector graphics formats.

The program is intended for LaTeX users but may be useful to
other users too.
*/



/* include files */

#include "dktools-version.h"
#include "dkfig.h"


#line 56 "fig2vect.ctr"





#ifndef VERSNUMB
/** Version number. */
#define VERSNUMB "1.1.24"
#endif




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



#ifndef PACKAGNAME
/** Package name (definition). */
#define PACKAGENAME "dktools"
#endif

/** Package name (string constant).
*/
static char packagename[] = { PACKAGENAME };



/**	Check whether or not to run silently or as a filter.
	If the option --silent is used the application runs silently.
	If no output file name (second command line argument) is specified
	the application runs as filter and can not print log messages
	to standard output.
	@param	argc	Number of command line arguments.
	@param	argv	Command line arguments array.
	@param	rs	Pointer to run-silently flag variable.
	@param	rf	Pointer to run-as-filter flag variable.
*/
static void
silence_check DK_P4(int,argc,char **,argv,int *,rs,int *,rf)
{
  int isrs = 0; int isrf = 0;
  int i; int filenames;
  char *fn1, *ptr, **lfdptr;
  
  lfdptr = argv; lfdptr++; i = 1; filenames = 0; fn1 = NULL;
  while(i < argc) {
    ptr = *lfdptr;
    if(*ptr == '-') {
      ptr++;
      switch(*ptr) {
        case 's': isrs = 1; break;
	case 'l':
	case 'o': {
	  ptr++;
	  if(!(*ptr)) {
	    lfdptr++; i++;
	  }
	} break;
      }
    } else {
      filenames++;
      if(!fn1) fn1 = ptr;
    }
    lfdptr++; i++;
  }
  switch(filenames) {
    case 0: {
      isrf = 1;
    } break;
    case 1: {
      if(!dksf_is_directory(fn1)) {
        isrf = 1;
      }
    } break;
  }
  if(isrs) if(rs) *rs = isrs;
  if(isrf) if(rf) *rf = isrf;
  
}



/** Text to show for version number and license conditions.
*/
static char *version_text[] = {
"",
"fig2vect, version " VERSNUMB,
"Copyright (C) 2004-2010 Dipl.-Ing. D. Krause",
"http://dktools.sourceforge.net/fig2vect.html",
"",
"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 terms.
*/
static void
print_version DK_P0()
{
  char **xptr;
  
  xptr = version_text;
  while(*xptr) {
    fputs(*(xptr++), stdout); fputc('\n', stdout);
  }
  fputc('\n', stdout);
  xptr = dklic_get();
  fputs("Libraries used:\n\n", stdout);
#if DK_HAVE_PNG_H
  fputs("libpng       the official PNG reference library\n", stdout);
  fputs("\t     http://www.libpng.org/pub/png/libpng.html\n", stdout);
#endif
#if DK_HAVE_JPEGLIB_H
  fputs("jpegsrc      The Independent JPEG Group's free JPEG software\n", stdout);
  fputs("\t     http://www.ijg.org/\n", stdout);
#endif
#if DK_HAVE_PNM_H || DK_HAVE_NETPBM_PNM_H
  fputs("netpbm       The image conversion toolkit\n", stdout);
  fputs("\t     http://netpbm.sourceforge.net/\n", stdout);
#endif
  while(*xptr) {
    fputs(*(xptr++), stdout); fputc('\n', stdout);
  }
  fputc('\n', stdout);
  
}



/** Text to show as help text if the fig2vect.txt file is not found.
*/
static char *help_text[] = {
"fig2vect - XFig to vector graphics converter",
"",
"fig2vect [-l <language>] [-o <option>...] [-m] <directory>",
"fig2vect [-l <language>] [-o <option>...] [ <inputfile> [<outputfile>] ]",
"",
"-l language",
"      chooses the output language, must be defined in fig2vect.cfg",
"",
"-o option",
"      passes the option to the output driver",
"",
"-m",
"      enables make style when running on a directory",
"",
"-A",
"-A-",
"      suppress or allow messages about alpha channels transferred to PDF.",
"",
NULL
};



/** Name of help text file.
*/
static char help_file_name[] = { "fig2vect.txt" };



/**	Print help, either from help text file or the built-in help text.
	@param	a	Application structure.
*/
static void
print_help DK_P1(dk_app_t *,a)
{
  
  print_version();
  dkapp_help(a, help_file_name, help_text);
  
}



/**	Run the program either normally or for the application options.
	The function creates a new conversion job structure using
	dkfig_co_new(), applies the command line arguments
	using dkfig_co_apply_args() and calls either
	dkfig_co_run() or one of the functions to handle
	application options.
	@param	app	Application structure.
	@return	Positive value on success, 0 on error.
*/
int
run_the_program DK_P1(dk_app_t *,app)
{
  int back = 0;
  dk_fig_conversion *c = NULL;
  int action, xargc; char **xargv;
  
  c = dkfig_co_new(app);
  if(c) {
    xargc = dkapp_get_argc(app);
    xargv = dkapp_get_argv(app);
    action = dkfig_co_apply_args(c, xargc, xargv);
    if(!(action & DKFIG_WHAT_ERROR)) {
      if(action & DKFIG_WHAT_HELP) {		
        print_help(app);
	back = 1;
      } else {					
        if(action & DKFIG_WHAT_UNCONFIGURE) {	
	  dkapp_unconfigure(app);
	  back = 1;
	} else {				
	  if(action & DKFIG_WHAT_CONFIGURE) {	
	    back = dkfig_co_configure_app(c);
	  } else {				
	    if(action &  DKFIG_WHAT_SHOWCONF) {	
	      dkfig_co_showconf_app(c);
	      back = 1;
	    } else {				
	      if(action & DKFIG_WHAT_VERSION) {	
	        print_version();
		back = 1;
	      } else {				
	        if(action & DKFIG_WHAT_CONFIG_FILE) {
		  back = dkfig_co_show_config_file(c);
		} else {
		  if(action & DKFIG_WHAT_WRITE_CONFIG_FILE) {
		    back = dkfig_co_write_config_file(c);
		  } else {
		    back = dkfig_co_run(c);
		  }
		}
	      }
	    }
	  }
	}
      }
    }
    if(action & DKFIG_WHAT_ERROR) {
      back = 0;
    }
    dkfig_co_delete(c); c = NULL;
  } else {
    dkapp_err_memory(app, sizeof(dk_fig_conversion),1);
  }
  
  return back;
}



/**	The main() function.
The main() function checks, whether to run silently, craetes an
application structure and invokes run_the_program().

The run_the_program() function processes the command line arguments,
creates a conversion job structure and invokes dkfig_co_run()
or one of the functions to handle application options
(-h, -v, -c, -u, -C).

The dkfig_co_run() function searches for the base driver name, loads
the configuration file, processes the command line options
and invokes lets_go_now().

The lets_go_now() function inspects input and output file name.

The run_for_filenames(), run_with_ifn2(), run_for_stdio(), run_with_istream()
and run_with_ofn2() functions expand wildcards in file names if necessary and
open streams for input and output. Finally these functions call
run_for_streams().

The run_for_streams() function creates a new Fig drawing structure
and transfers setup options needed while reading a Fig file
from the conversion job structure into the
Fig drawing structure.
The dkfig_co_add_stream() function is used to read the Fig file,
the dkfig_co_out_to_stream() function produces the output file.
This function calls one the driver functions.

Most of the driver functions use 2 passes:
* One pass to gather information about all object styles, line widths etc.
* Another pass to produce the output.

One of the important parts of the first pass is to call
dkfig_flat_list() to produce a flattened sorted list of Fig objects
containing objects in order of drawing. Other tasks in the preparation
pass are finding object bounding boxes and the bounding box for the
entire drawing, information about used fonts, colors, fill patterns
etc.

@param	argc	Number of command line arguments.
@param	argv	Command line arguments array.
@return	0 on success, positive values on errors.
*/
#if DK_HAVE_PROTOTYPES
int
main(int argc, char *argv[])
#else
int
main(argc, argv)
  int argc;
  char *argv[];
#endif
{
  int exval = 0;	/* program exit status */
  int rs = 0;		/* run silently */
  int rf = 0;		/* run as filter */
  dk_app_t *app = NULL;
#ifdef RUNTIMELIMITSECS
#if DK_HAVE_ALARM
  alarm(RUNTIMELIMITSECS);
#endif
#endif
  
#line 388 "fig2vect.ctr"

  
  silence_check(argc, argv, &rs, &rf);
#if DK_HAVE_TZSET
  tzset();
#endif
  app = dkapp_open_ext1(argc, argv, packagename, sysconfdir, rs, rf);
  if (app) {
    exval = run_the_program(app);
    dkapp_set_source_lineno(app, 0UL);
    dkapp_close(app); app = NULL;
  } else {
    if (!rs) {
       fprintf(stderr, "ERROR: Not enough memory (RAM)!\n");
       fflush(stderr);
    }
  }
  exval = (exval ? 0 : 1);
  
  
#line 407 "fig2vect.ctr"

#ifdef RUNTIMELIMITSECS
#if DK_HAVE_ALARM
  alarm(0);
#endif
#endif
  exit(exval); return exval;
}






