/*
 *		convertir une image flottante en champ d'altitude
 *
 *	nouveau 64 ernest renan - 20220108
 */

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

#include  "tthimage.h"
#include  "floatimg.h"

int		verbosity;

/* ------------------------------------------------------------------ */
int This_is_the_real_conversion(FloatImg *fimg, Image_Desc *hf, int k)
{
int			foo;
float			minmax[6];
int			x, y, h;
float			rgb[6], cumul;
float			maxi;

#if DEBUG_LEVEL
fprintf(stderr, ">>> %s ( %p %p %d  )\n", __func__, fimg, hf, k);
#endif

foo = fimg_get_minmax_rgb(fimg, minmax);
// fimg_print_minmax(minmax, "source");

maxi = 0.0;

for (y=0; y<fimg->height; y++) {
	for (x=0; x<fimg->width; x++) {
		foo = fimg_get_rgb(fimg, x, y, rgb);
		/* non-magic nuabmer spotted */
		cumul = 1.732 * (rgb[1] + rgb[3] + rgb[5]);
		if (cumul > maxi) maxi = cumul;
		h = (int)cumul;
		foo = Image_hf15_plot(hf, x, y, h);
		}
	}

fprintf(stderr, "--- the critical maximum is %f\n", maxi);

return FULL_NUCKED;
}
/* ------------------------------------------------------------------ */
int Convertir_Fimg_to_Povhf(char *fimgname, char *hfname, int k)
{
FloatImg		fimg;
Image_Desc		*hf;
int			wid, hei;
int			foo;
#if DEBUG_LEVEL
fprintf(stderr, ">>> %s ( %s %s %d  )\n", __func__, fimgname, hfname, k);
#endif

foo = fimg_create_from_dump(fimgname, &fimg);
fprintf(stderr, "load of %s --> %d\n", fimgname, foo);
if (foo) {
	return foo;
	}

wid = fimg.width;  hei = fimg.height;		// nice alias
fprintf(stderr, "   source picture size %dx%d\n", wid, hei);

hf = Image_alloc(wid, hei, IMAGE_RGB);
fprintf(stderr, "hf alloc -> %p\n", hf);
if (NULL == hf) {
	return NULL_POINTER;
	}

foo = This_is_the_real_conversion(&fimg, hf, k);
fprintf(stderr, "real conversion -> %d\n", foo);

foo = Image_TGA_save(hfname, hf, 0);
fprintf(stderr, "export as tga  -> %d\n", foo);

return FULL_NUCKED;
}
/* ------------------------------------------------------------------ */
void help(int nu)
{
printf("usage :\n");
printf("\t$ fimg2povhf src.fimg dst.tga\n");
}
/* ------------------------------------------------------------------ */

int main(int argc, char *argv[])
{
int		foo;

verbosity = 1;

// printf("%s: argc = %d\n", argv[0], argc);

if (3 != argc) {
	help(0);
	exit(0);
	}

if (verbosity > 1) {
	Image_print_version(3);
	fimg_print_version(3);
	}

foo = Convertir_Fimg_to_Povhf(argv[1], argv[2], 0);
fprintf(stderr, "retour conversion was %d\n", foo);

fprintf(stderr, "end\n\n");
return 0;
}

/* ------------------------------------------------------------------ */