/*
 * Copyright 2000 Greg Velichansky
 * released under the GNU General Public License    
 * see the files README and COPYING for details.
 */

#include<stdio.h>
#include<math.h>
#include<process.h>

/*#define ScrewArrays*/

#include"3dvector.h"
#include"3dpoly.h"

FILE *in, *out;

int gn;

int novertex = 0;
int allowzero = 0;

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


	puts("GNORM.EXE 1.3(suck) Vertex normal calculator, written by Hmaon for the 3d engine");
	puts("DJGPP Compilation");
	puts(" ");

	if((argc != 3) && !((argc == 4) && ((*argv[3] == 'n') || (*argv[3] == 'f') || (*argv[3] == '3')))){
		puts("Bad parameters");
		puts("Syntax: gnorm.exe in.mdl out.mdl [n/f/3]");
		puts("The optional lowercase 'n' tells gnorm not to create vertex normals.");
		puts("Lowercase f disables the zero length normal poly discarding.");
		puts("A 3 is like n and f put together, basically like 3dnorm.");
		exit(1);
	}

	if((argc == 4) && (*argv[3] == 'f')){
		allowzero = 1;
	}

	if((argc == 4) && (*argv[3] == 'n')){
		novertex = 1;
	}

	if((argc == 4) && (*argv[3] == '3')){
		novertex = 1;
		allowzero = 1;
	}



	in = fopen(argv[1], "rb");
	if(in == NULL){
		perror("Unable to open input file");
		exit(2);
	}

	readmodel_old(in);

	if(fclose(in) == EOF){
		perror("Error on closing input file");
	}

	printf("Read %d points and %d polygons.\n", pointnum, polynum);


	out = fopen(argv[2], "wb");
	if(out == NULL){
		perror("Unable to open output file");
		exit(3);
	}


	printf("Removing extra points.\n");
	audit_points();

	printf("Polygon normals ");
	for(gn = 0; gn < polynum; gn++){
		calculatenormal(gn);
		if(zero_length == 1 && allowzero == 0){
			--nextfreepoly;
			polys[gn] = polys[nextfreepoly];
			--gn;
			puts("Eliminated poly.");
		}
		printf(".");
	}
	if(!novertex){
		printf("\nVertex normals ");
		for(gn = 0; gn < pointnum; gn++){
			calculatevnormal(gn);
			printf(".");
		}
	}

	printf("\nOptimising normals.\n");
	optimise_normals(0);
	

	writemodel_old(out);
	if(fclose(out) == EOF){
		perror("Error on closing output file");
	}

	return 0;
}
