#include "DEM.h"

/*
E020N40.DEM
E020N90.DEM
E020S10.DEM
E060N40.DEM
E060N90.DEM
E060S10.DEM
E060S60.DEM
E100N40.DEM
E100N90.DEM
E100S10.DEM
E120S60.DEM
E140N40.DEM
E140N90.DEM
E140S10.DEM
W000S60.DEM
W020N40.DEM
W020N90.DEM
W020S10.DEM
W060N40.DEM
W060N90.DEM
W060S10.DEM
W060S60.DEM
W100N40.DEM
W100N90.DEM
W100S10.DEM
W120S60.DEM
W140N40.DEM
W140N90.DEM
W140S10.DEM
W180N40.DEM
W180N90.DEM
W180S10.DEM
W180S60.DEM
*/

//unsigned char 


int Load_Terrain(struct image_attr *ia, char *filename){
	FILE *fp = fopen(filename, "rb");
	if(!fp){
		printf("Error opening file: %s\n", filename);
		return 1;
	}
	//NROWS         6000
	//NCOLS         4800
	unsigned int height = 6000;
	unsigned int width = 4800;
	ia->image = malloc(sizeof(unsigned char)*height*width*3);
    ia->width = width;
    ia->height = height;

	char two_b[2];
	//u_int16_t
	union{ char a[2]; int16_t b;}x;
	int count1, count2;
	int result = 0;
	unsigned char rgb[3];

	for(count1=0; count1<height; count1++){
		for(count2=0; count2<width; count2++){
			fread(&two_b, 1, 2, fp);
			x.a[0] = two_b[1];
			x.a[1] = two_b[0];

			//if(x.b > 0){
			//	result = 
			//if(count1 < 20 && count2 < 20)
			//	printf("%d\n", x.b);
			//if(x.b != 12)
			//	printf("hmm\b");
			//1 -9999 5825 -2347.6 4873.5
			//the band number, minimum value, maximum value, mean value, and standard deviation of the values in the raster
			if(x.b < -9999)
				printf("low !\n");
			if(x.b > 5825)
				printf("high !\n");

			//rgb[0] = 0;
			//rgb[1] = (x.b>0)? ceil((x.b/5850)*255): 0;
			//rgb[2] = (x.b<0)? ceil(255-(x.b/-13000)*255): 0;
			/*
			if(x.b<0){
				rgb[0] = 0;
				//if(x.b<-6000){
				result = ceil(512-(x.b/-13000)*512);
				rgb[1] = (result<256)? 0: result-256;
				rgb[2] = (result<256)? result: 255;
			}else{
				rgb[2] = 0;
				result = ceil((x.b/9000)*512);
				rgb[0] = (result<256)? 0: result-256;
				rgb[1] = (result<256)? result: 255;

			}
			*/

			if(x.b<-5000){
				rgb[0] = 0;
				rgb[1] = 0;
				rgb[2] = 0; //ceil(255-(x.b/-13000)*255);
			}else if(x.b<-2500){
				rgb[0] = 0;
				rgb[1] = 0; //ceil(255-(x.b/-2500)*255);
				rgb[2] = 255;
				
			}else if(x.b<-1000){
				rgb[0] = 0;
				rgb[1] = 0;
				rgb[2] = 128; //ceil(255-(x.b/-1000)*255);
			}else if(x.b<-500){
				rgb[0] = 0; //ceil((x.b/-500)*255);
				rgb[1] = 128;
				rgb[2] = 128;
			}else if(x.b<-50){
				rgb[0] = 0;
				rgb[1] = 255; //ceil(255-(x.b/-50)*255);
				rgb[2] = 0;
			}else{
				rgb[0] = 255;
				rgb[1] = 255;
				rgb[2] = 255;
			}
			/*
			black -13000
			blue -4000
			turquise 0
			green 3000
			yellow 6000
			red 9000

			-13000
			-6000
			0
			4000
			9000
			*/
			ia->image[count1*width*3+(count2*3)] = rgb[0];
			ia->image[count1*width*3+(count2*3+1)] = rgb[1];
			ia->image[count1*width*3+(count2*3+2)] = rgb[2];
		}
	}

	

	fclose(fp);
	return 0;
}