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

#include<stdio.h>
#include<stdlib.h>
#include<io.h>
#include<values.h>
#include<math.h>

#define colors 256

typedef struct {
	double r, g, b;
} RGB;

RGB palette[colors];

void loadpalette(char *name, RGB pal[]){
	FILE *in;
	int i;

	printf("Opening palette file %s to read palette.\n", name);

	in = fopen(name, "rb");
	if(in == NULL){
		perror("Couldn't open file");
		exit(1);
	}

	for(i = 0; i < colors; ++i){
		pal[i].r = (double) getc(in);
		pal[i].g = (double) getc(in);
		pal[i].b = (double) getc(in);
	}

	fclose(in);
}


#define sqr(a) ((a)*(a))

int rgb_to_index(RGB *desired){
	int n;
	double error, best_error;
	int best;

	best_error = MAXDOUBLE;
	for(n = 0; n < colors; ++n){
		error = pow(palette[n].r - desired -> r, 2) + pow(palette[n].g - desired -> g, 2) + pow(palette[n].b - desired -> b, 2);
		if(error < best_error){
			best_error = error;
			best = n;
		}
	}
	return best;
}
