//////////////////////////////////////////////////////////////////////
//
//                             Pixie
//
// Copyright © 1999 - 2003, Okan Arikan
//
// Contact: okan@cs.berkeley.edu
//
// This library 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.
// 
// This library 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 this library; if not, write to the Free Software
// Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA  02111-1307  USA
//
///////////////////////////////////////////////////////////////////////
///////////////////////////////////////////////////////////////////////
//
//  File				:	colormap.cpp
//  Classes				:	CColorMap
//  Description			:
//
////////////////////////////////////////////////////////////////////////
#include <math.h>

#include "colorMap.h"
#include "error.h"

///////////////////////////////////////////////////////////////////////
// Class				:	CColorMap
// Method				:	CColorMap
// Description			:	Ctor
// Return Value			:	-
// Comments				:
// Date last edited		:	3/29/2003
CColorMap::CColorMap(const char *n) : CFileResource(n) {
	FILE	*in	=	fopen(name,"rb");
	int		i;

	if (in != NULL) {
		fread(&numColors,1,sizeof(int),in);
		temperatures	=	new float[numColors];
		colors			=	new float[numColors*3];
		fread(temperatures,numColors,sizeof(float),in);
		fread(colors,numColors*3,sizeof(float),in);
		fclose(in);
	} else {
		error(CODE_NOFILE,"Colormap %s not found\n",name);
		numColors		=	2;
		colors			=	new float[numColors*3];
		temperatures	=	new float[numColors];
		for (i=0;i<numColors*3;i++) {
			colors[i]	=	0;
		}
		temperatures[0]	=	0;
		temperatures[1]	=	1;
	}
}

///////////////////////////////////////////////////////////////////////
// Class				:	CColorMap
// Method				:	~CColorMap
// Description			:	Dtor
// Return Value			:	-
// Comments				:
// Date last edited		:	3/29/2003
CColorMap::~CColorMap() {
	delete [] temperatures;
	delete [] colors;
}

///////////////////////////////////////////////////////////////////////
// Class				:	CColorMap
// Method				:	lookup
// Description			:	Lookup a color
// Return Value			:	-
// Comments				:
// Date last edited		:	3/29/2003
void	CColorMap::lookup(float *dest,float index) {
	int	start,end;


	start	=	0;
	end		=	numColors-1;

	while(end > start) {
		const int	mid	=	(end + start) >> 1;

		if (temperatures[mid] < index) {
			start	=	mid+1;
		} else {
			end		=	mid-1;
		}
	}

	movvv(dest,colors+start*3);
}




