/*
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 <stdlib.h>
#include <stdio.h>

#include <unistd.h>

void usage( int errcode = badCommandLine ) {
	fprintf( stderr, "Usage :\n\tvolboundary [ -i inputfile (default : stdin) ] [ -o outputfile (default : stdout) ] [ -v (verbose) ]\n\tvolboundary file\n\tvolboundary -h\n" );

	exit( errcode );

}

int main( int argc, char **argv ) {
	
	int option;
	char *file_in = "", *file_out = "";
	bool verbose = false;
	long count = 0, total = 0;
	bool inout_set = false;
	
	// Fast syntax : volbounday file
	if (argc == 2 && argv[1][0] != '-') {
		file_in = file_out = argv[1];
	} else {
		while ((option = getopt( argc, argv, "i:o:vh")) != -1) {
			switch (option) {
				case 'v':
					verbose = true;
					break;
				case 'i':
					file_in = optarg;
					inout_set = true;
					break;
				case 'o':
					file_out = optarg;
					inout_set = true;
					break;
	
				case 'h':
					usage( noError );
					break;
			}
		}
		
		if (optind != argc) {
			usage();
		}
	}


	Vol v( file_in );
	if (!v.isOK()) {
		fprintf( stderr, "Cannot open %s\n", file_in );
		return badInputFile;
	}

	
	int alpha = 0;
	v.getHeaderValueAsInt( "Alpha-Color", &alpha );

	Vol vout(v);
	
	int mins[] = { v.minX(), v.minY(), v.minZ() };
	int maxs[] = { v.maxX(), v.maxY(), v.maxZ() };
	
	for (int i = mins[0] + 1; i < maxs[0] - 1; ++i) {
		for (int j = mins[1] + 1; j < maxs[1] - 1; ++j) {
			for (int k = mins[2] + 1; k < maxs[2] - 1; ++k) {
				if (v(i, j, k) != alpha) {
					++total;
					if	( v(i - 1, j, k) != alpha && v(i + 1, j, k) != alpha && v(i, j - 1, k) != alpha
						&& v(i, j + 1, k) != alpha && v(i, j, k - 1) != alpha && v(i, j, k + 1) != alpha) {
						vout(i, j, k) = alpha;
						++count;
					} else {
						vout(i, j, k) = v(i, j, k);
					}
				}
			}
		}
	}

	if (verbose && total) {
		fprintf( stderr, "%d -> %d (%d%%)\n", total, total - count, (100*count)/total );
	}
	
	return vout.dumpVol( file_out ) != 0 ? badOutputFile : noError;

}
