/*
Copyright 2002, 2003 Alexis Guillaume <aguillau@liris.univ-lyon2.fr> for "Laboratoire LIRIS, université Lyon II, France."
Copyright 2002, 2003 David Coeurjolly <dcoeurjo@liris.univ-lyon2.fr> for "Laboratoire LIRIS, université Lyon II, France."

This file is part of voltools.

    voltools is free software; you can redistribute it and/or modify
    it under the terms of the GNU General Public License as published by
    the Free Software Foundation; either version 2 of the License, or
    (at your option) any later version.

    voltools is distributed in the hope that it will be useful,
    but WITHOUT ANY WARRANTY; without even the implied warranty of
    MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
    GNU General Public License for more details.

    You should have received a copy of the GNU General Public License
    along with voltools; if not, write to the Free Software
    Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA  02111-1307  USA

*/
#include "vol.h"
#include "tools.h"

#include <unistd.h>

#include <stdio.h>

typedef enum { op_noop, op_or, op_and, op_minus } operator_t;



void usage( int errcode = badCommandLine ) {

	static const char *usage_str = "usage :\n\tvolarith [file1] [-x] [ -o | -a | -m ] file2\n";

	fprintf( stderr, "%s", usage_str );
	exit( errcode );
}

int main( int argc, char **argv ) {

	int option;
	char *file1 = "";
	char *file2 = "";
	operator_t op = op_noop;
	bool argone_used = false;
	bool axis = false;

	// hack
	if (argc >= 2 && argv[1][0] != '-') {
		file1 = argv[1];
		argone_used = true;
	}

	while ((option = getopt( argc - argone_used, argv + argone_used, "oamxh" )) != -1 ) {
		switch (option) {
			case 'a':
				if (op != op_noop)
					usage();
				op = op_and;
				break;
			case 'o':
				if (op != op_noop)
					usage();
				op = op_or;
				break;
			case 'm':
				if (op != op_noop)
					usage();
				op = op_minus;
				break;
			case 'x':
				axis = true;
				break;

			case 'h':
				usage( noError );
				break;
		}
	}

	if (op == op_noop)
		usage();

	if (optind == argc - argone_used - 1) {
		file2 = argv[optind + argone_used];
	} else {
		usage();
	}

	Vol v1( file1 );

	if (!v1.isOK()) {
		fprintf( stderr, "Cannot open %s\n", file1 );
		return badInputFile;
	}
	
	Vol v2( file2 );
	if (!v2.isOK()) {
		fprintf( stderr, "Cannot open %s\n", file2 );
		return badInputFile;
	}
	
	Vol v;
	switch (op) {
		case op_and:
			v = v1 & v2;
			break;
		case op_or:
			v = v1 | v2;
			break;
		case op_minus:
			v = v1 - v2;
			break;
	}

	if (axis)
		v.drawAxis();
	return v.dumpVol( "" ) != 0 ? badOutputFile : noError;
		
}
