/*
 *	converting a floatimg to a PNG
 */

#include  <stdio.h>
#include  <stdlib.h>
#include  <stdint.h>
#include  <unistd.h>

#include  "../floatimg.h"

int		verbosity;

/* ----------------------------------------------------------------- */
int convertir_fimg_en_PNG(char *srcname, char *dstname, int grisaille)
{
int		foo, infos[3];
FloatImg	fimg;

#if DEBUG_LEVEL
fprintf(stderr, ">>> %25s ( '%s' '%s' %d )\n", __func__,
			srcname, dstname, grisaille);
#endif

foo = fimg_fileinfos(srcname, infos);
if (foo) {
	if (verbosity) fprintf(stderr, "'%s' get dims -> %d\n", srcname, foo);
	return foo;
	}

if (verbosity) {
	fprintf(stderr, "%s: image '%s' is %dx%d  %s\n", 
				__func__,
				srcname, infos[0], infos[1],
				fimg_str_type(infos[2]));
	}

foo = fimg_create_from_dump(srcname, &fimg);
if (foo) {
	fprintf(stderr, "create fimg from '%s' -> %d\n", srcname, foo);
	return -1;
	}

if (grisaille) {
	foo = fimg_desaturate(&fimg, &fimg, 0);
	}

foo = fimg_save_as_png(&fimg, dstname, 0);
if (foo) {
	fprintf(stderr, "%s: saving as png '%s' -> %d\n", __func__,
					dstname, foo);
	return -1;
	}

fimg_destroy(&fimg);

return 0;
}
/* ----------------------------------------------------------------- */
void help(int k)
{

puts("usage:\n\tfimg2png [options] from.fimg to.png");
puts("options:");
puts("\t-g\tconvert to gray");
puts("\t-v\tincrease verbosity");
if (verbosity) fimg_print_version(k);

exit(0);
}
/* ----------------------------------------------------------------- */

int main(int argc, char *argv[])
{
int		foo, opt;
int		to_gray = 0;

while ((opt = getopt(argc, argv, "ghv")) != -1) {
	switch(opt) {
		case 'g':	to_gray = 1;		break;
		case 'v':	verbosity++;		break;
		case 'h':	help(1);		exit(1);
		}
	}

if (2 != argc-optind) {
	fprintf(stderr, "error: %s need two filenames\n", argv[0]);
	exit(1);
	}

foo = convertir_fimg_en_PNG(argv[optind], argv[optind+1], to_gray);
if (foo) {
	fprintf(stderr, "%s : got a %d from convertor\n", argv[0], foo);
	}

return 0;
}
/* ----------------------------------------------------------------- */