/* printsmmain.c
 * Neil Moore <neil@cs.uky.edu>
 *  3 Mar 2000
 *
 * part of liblp.
 */
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
#include <errno.h>
#include <time.h>
#include <lp.h>
#include <lp_smrd.h>
#include <lp_print.h>
#include <lp_util.h>

#ifndef VERSION
#define VERSION "unknown"
#endif

static void usage(void);
static void version(void);

int main(int argc, char *argv[]) 
{
	const char *infilename = NULL;
	FILE *infile=0, *outfile=0;
	const char *outfilename = NULL;
	struct lp *prog;

	while (*++argv != NULL) {
		if(!strcmp(*argv, "-o") || !strcmp(*argv, "--output")) {
			++argv;
			if(*argv == NULL) {
				usage();
				return 1;
			}
			outfilename = *argv;
		} else if(!strncmp(*argv, "-o", 2)) {
			outfilename = *argv + 2;
		} else if(!strncmp(*argv, "--output=", 9)) {
			outfilename = *argv + 9;
		} else if(!strcmp(*argv, "-v") || !strcmp(*argv, "--version")) {
			version();
			return 0;
		} else if(!strcmp(*argv, "-h") || !strcmp(*argv, "--help")) {
			usage();
			return 0;
		} else if ((*argv)[0] == '-') {
			usage();
			return 1;
		} else {
			infilename = *argv;
		}		
	}
	
	if(infilename == NULL)
		infile = stdin;
	else
		if((infile = fopen(infilename, "r")) == NULL) {
			fprintf(stderr, "cannot open %s: %s\n", infilename, strerror(errno));
			goto failure;
		}


	if(outfilename == NULL)
		outfile = stdout;
	else
		if((outfile = fopen(outfilename, "w")) == NULL) {
			fprintf(stderr, "cannot open %s: %s\n", outfilename, strerror(errno));
			goto failure;
		}	

	prog = lp_malloc(sizeof(struct lp));
	if(lp_sm_read_file(infile, prog) < 0) {
		fprintf(stderr, "error in input: output not generated\n");
		goto failure;
	}

	lp_print_program(outfile,prog);
	
	if (infile != stdin)
		fclose(infile);
	if (outfile != stdout)
		fclose(outfile);
	
	lp_free_lp(prog);
	return 0;
	
 failure:
	if(infile && infile != stdin)
		fclose(infile);
	if(outfile && outfile != stdin)
		fclose(outfile);

	if(prog)
		lp_free_lp(prog);
	
	return 1;
}

void usage(void) 
{
	printf("usage: printsm [options] [filename]\n");
	printf("Compute the well-founded semantics of a logic program.\n\n");
	printf(" -o, --output=file  output goes to file (default stdout)\n");
	printf(" -v, --version      print version information to stdout\n");
	printf(" -h, --help         display this message\n\n");
	printf("Input is read from filename (defaults to stdin).\n");
}

void version(void) 
{
	printf("printsm " VERSION "\n");
}
