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

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

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

FILE *in, *out;

char buffer[1024];
int f; /* # of fields read. */
int n, m; /* scratch variables used in various parts of main() */
double x, y, z;
double scale = 500;
int cnt = -1;

int current_color = 0;
RGB desired_color;

main(int argc, char *argv[]){
	printf("3DConv 1.1\n\n");
	if (argc != 5){
		puts("Wrong number of parameters.");
		puts("Correct usage - 3dconv.exe in.obj out.mdl <scaling factor> palette.pal");
		exit(1);
	}

	if(sscanf(argv[3], "%lf", &scale) <= 0){
		puts("Jo mama is so fat you didn't specify the scaling factor properly.");
		exit(255);
	}

	printf("Scaling factor - %lf\n", scale);

	in = fopen(argv[1], "rt");
	if(in == NULL){
		perror("Error opening input file");
		exit(2);
	}
	out = fopen(argv[2], "wb");
	if(out == NULL){
		perror("Error opening output file");
		exit(3);
	}

	loadpalette(argv[4], palette);

	do{
		f = fscanf(in, "%s", buffer);
		if(f != -1){
			if(!strcmp(buffer, "v")){
				n = freepoint();
				fscanf(in, "%lf %lf %lf", &x, &y, &z);
				points[n].x = (int) (x * scale);
				points[n].y = (int) (y * scale);
				points[n].z = (int) (z * scale);
			} else
			if(!strcmp(buffer, "f")){
				n = freepoly();
				fscanf(in, "%d %d %d", &polys[n].vert[0], &polys[n].vert[1], &polys[n].vert[2]);
				if(fscanf(in, "%d", &polys[n].vert[3]) <= 0) polys[n].vert[3] = polys[n].vert[0];
				polys[n].vert[0]--;
				polys[n].vert[1]--;
				polys[n].vert[2]--;
				polys[n].vert[3]--;
				if(fscanf(in, "%d", &n) > 0) puts("Warning, polygons with more than 4 sides are not supported yet.");
				polys[n].color = (char) current_color;
			} else
			if(!strcmp(buffer, "c")){
				fscanf(in, "%lf %lf %lf", &desired_color.r, &desired_color.g, &desired_color.b);
				desired_color.r /= 4;
				desired_color.g /= 4;
				desired_color.b /= 4;
				printf("Color %lf %lf %lf ", desired_color.r, desired_color.g, desired_color.b);
				current_color = rgb_to_index(&desired_color);
				printf("quantized to %u - color %lf %lf %lf\n", current_color, palette[current_color].r, palette[current_color].g, palette[current_color].b);
			}
		}
		cnt++;
	} while(f != -1);

	writemodel(out);

	fclose(in);
	fclose(out);

	printf("%d points, %d polys, %d total strings.\n", pointnum, polynum, cnt);
}
