#include "DEM.h"


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 = 41600;
	//unsigned int width = 43200;
	unsigned int height = 1800; //40
	unsigned int width  = 3600; //27
	ia->image = malloc(sizeof(unsigned char)*height*width*3);
    ia->width = width;
    ia->height = height;

	//double temp[27][40];
	//unsigned int temp_x = 0;
	//unsigned int temp_y = 0;

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

	for(count1=0; count1<height; count1++){
		//if(temp_y == 39)
		//	temp_y = 0;
		//for(temp_y=0; temp_y<40; temp_y++;
		/*
		temp_y++;
		if(temp_y!=40){
			for(count2=0; count2<src_width; count2++){
				fread(&two_b, 1, 2, fp);
			}
		}
		if(temp_y==40){
			temp_y = 0;
		*/
			for(count2=0; count2<width; count2++){

				fread(&two_b, 1, 2, fp);
				x.a[0] = two_b[0];
				x.a[1] = two_b[1];
				//temp_x++;
				//if(temp_x==27){
				//	temp_x=0;

					//data_sum += x.b;
					//data_pnt++;
					//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(data_pnt == src_width){
					//	x.b = ceil(data_sum/src_width);
					//	data_pnt = 0;
//						if(x.b < -9999)
//							printf("low !\n");
//						if(x.b > 5825)
//							printf("high !\n");

/*						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<1){
							rgb[0] = 0;
							rgb[1] = 0; //ceil(255-(x.b/-50)*255);
							rgb[2] = 255;
						}else{
							rgb[0] = 0;
							rgb[1] = 255;
							rgb[2] = 0;
						}
/*						
						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;
}