/**************************************************************

muniphot.c (C-Munipack project)
Photometry tool
Copyright (C) 2003 David Motl, dmotl@volny.cz

This program 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 program 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 program; if not, write to the Free Software
Foundation, Inc., 59 Temple Place - Suite 330, Boston, MA  02111-1307, USA.

**************************************************************/

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

#ifdef _WIN32
#include <io.h>
#endif

#include "cmunipack.h"
#include "cmdline.h"
#include "cfgfile.h"
#include "utils.h"

/* Program */
AppName prog = 
{ 
	"muniphot", 
	"photometry of calibrated CCD frames"
};

/* Options */
CmdOption opt[] =
{
	{ "configuration-file", 'p', "read parameters from configuration file", "filepath", CMD_PTYPE_FILEPATH },
	{ "set", 's', "set configuration parameter", "name=value", CMD_PTYPE_PARAMLIST },
	{ "read-dirfile", 'i', "read list of source CCD frames from specified file", "filepath", CMD_PTYPE_FILEPATH },
	{ "make-dirfile", 'g', "save list of output files to specified file", "filepath", CMD_PTYPE_FILEPATH },
	{ "output-mask", 'o', "change output file mask (default='frame???.pht')", "mask", CMD_PTYPE_FILEMASK },
	{ "counter", 'c', "set initial counter value (default=1)",  "value", CMD_PTYPE_INT },
	{ "help", 'h', "print list of command-line parameters" },
	{ "quiet", 'q', "quiet mode; suppress all messages" },
	{ "version", 0, "print software version" },
	{ "licence", 0, "print software licence" },
	{ "verbose", 0, "verbose mode; print debug messages" },
	{ NULL }
};

/* Input files */
CmdParam flist[] = 
{
	{ "files", "names of calibrated CCD frames to process", CMD_PTYPE_FILELIST },
	{ NULL }
};

/* Configuration parameters */
CfgParam cfg[] = 
{
	{ "readns", CFG_PTYPE_DOUBLE, "Readout noise" },
	{ "gain", CFG_PTYPE_DOUBLE, "ADC gain" },
	{ "minvalue", CFG_PTYPE_DOUBLE, "Min. pixel value" },
	{ "maxvalue", CFG_PTYPE_DOUBLE, "Max. pixel value" },
	{ "fwhm", CFG_PTYPE_DOUBLE, "Expected FWHM" },
	{ "thresh", CFG_PTYPE_DOUBLE, "Detection threshold" },
	{ "minsharp", CFG_PTYPE_DOUBLE, "Low sharpness cutoff" },
	{ "maxsharp", CFG_PTYPE_DOUBLE, "High sharpness cutoff" },
	{ "minround", CFG_PTYPE_DOUBLE, "Low roundness cutoff" },
	{ "maxround", CFG_PTYPE_DOUBLE, "High roundness cutoff" },
	{ "skyinner", CFG_PTYPE_DOUBLE, "Inner sky aperture" },
	{ "skyouter", CFG_PTYPE_DOUBLE, "Outer sky aperture" },
	{ "apertures", CFG_PTYPE_DOUBLE_V, "Star apertures" },
	{ "maxstar", CFG_PTYPE_INT, "Max. number of objects" },
	{ NULL }
};

/* Command-line definition */
AppInfo cmd = 
{ 
	&prog, opt, flist, cfg
};

static void report(int status, const char *file)
{
	PrintError(&cmd, file, 0, status);
}

static void error(int status, const char *file)
{
	PrintError(&cmd, file, 0, status);
	exit(status);
}

static int phot(CmpackPhot *lc, const char *srcpath, const char *dstpath)
{
	int res, nstars;
	CmpackCcdFile *src;
	CmpackPhtFile *dst;

	printf("%s => %s\n", srcpath, dstpath);

	res = cmpack_ccd_open(&src, srcpath, CMPACK_OPEN_READONLY, 0);
	if (res!=0) {
		report(res, srcpath);
		return res;
	}
	res = cmpack_pht_open(&dst, dstpath, CMPACK_OPEN_CREATE, 0);
	if (res!=0) {
		report(res, dstpath);
		return res;
	}
	res = cmpack_phot(lc, src, dst, &nstars);
	cmpack_ccd_destroy(src);
	if (res!=0) {
		cmpack_pht_destroy(dst);
		report(res, srcpath);
		return res;
	}
	res = cmpack_pht_close(dst);
	if (res!=0) {
		cmpack_pht_destroy(dst);
		report(res, dstpath);
		return res;
	}
	printf("%d stars found\n", nstars);
	return 0;
}

int main(int argc, char **argv)
{
	FILE	*din = NULL, *dout = NULL;
	int		i, icit, res, napertures, count, maxstar, in_files = 0, out_files = 0;
	double	readns, gain, minvalue, maxvalue, fwhm, thresh;
	double	minsharp, maxsharp, minround, maxround, skyinner, skyouter;
	double	*apertures;
	char 	line[MAXLINE], outf[MAXLINE], buf1[MAXLINE];
	char	*dirfile_in, *dirfile_out, *out_mask, *cfgfile, **files;
	CmpackPhot *lc;
	CmpackConsole *con;

	Init(&cmd);

	/* Parse command line */
	if (!cmdline_parse(argc, argv, &cmd))
		return CMPACK_ERR_CMDLINE_ERROR;

	/* Process standard options */
	if (cmdline_isdef(&cmd, "version")) {
		PrintVersion(&cmd);
		return 0;
	}
	if (cmdline_isdef(&cmd, "licence")) {
		PrintLicense(&cmd);
		return 0;
	}
	if (cmdline_isdef(&cmd, "help")) {
		PrintHelp(&cmd);
		return 0;
	}

	/* Print program info */
	PrintPrologue(&cmd);

	/* Create context */
	lc = cmpack_phot_init();
	if (!lc) error(CMPACK_ERR_MEMORY, NULL);
	
	/* Set callback function and output level */
	con = cmpack_con_init();
	if (cmdline_isdef(&cmd, "quiet")) 
		cmpack_con_set_level(con, CMPACK_LEVEL_QUIET);
	if (cmdline_isdef(&cmd, "verbose"))
		cmpack_con_set_level(con, CMPACK_LEVEL_DEBUG);
	cmpack_phot_set_console(lc, con);

	/* Read configuration file */
	if (cmdline_gets(&cmd, "configuration-file", &cfgfile)) {
		res = cfgfile_read(&cmd, cfgfile);
		if (res!=0) error(res, NULL);
	}

	/* Set configuration paremeters */
	if (cfgfile_getd(&cmd, "readns", &readns))
		cmpack_phot_set_rnoise(lc, readns);
	if (cfgfile_getd(&cmd, "gain", &gain))
		cmpack_phot_set_adcgain(lc, gain);
	if (cfgfile_getd(&cmd, "minvalue", &minvalue))
		cmpack_phot_set_minval(lc, minvalue);
	if (cfgfile_getd(&cmd, "maxvalue", &maxvalue))
		cmpack_phot_set_maxval(lc, maxvalue);
	if (cfgfile_getd(&cmd, "fwhm", &fwhm))
		cmpack_phot_set_fwhm(lc, fwhm);
	if (cfgfile_getd(&cmd, "thresh", &thresh))
		cmpack_phot_set_thresh(lc, thresh);
	if (cfgfile_getd(&cmd, "minsharp", &minsharp))
		cmpack_phot_set_minshrp(lc, minsharp);
	if (cfgfile_getd(&cmd, "maxsharp", &maxsharp))
		cmpack_phot_set_maxshrp(lc, maxsharp);
	if (cfgfile_getd(&cmd, "minround", &minround))
		cmpack_phot_set_minrnd(lc, minround);
	if (cfgfile_getd(&cmd, "maxround", &maxround))
		cmpack_phot_set_maxrnd(lc, maxround);
	if (cfgfile_getd(&cmd, "skyinner", &skyinner))
		cmpack_phot_set_skyin(lc, skyinner);
	if (cfgfile_getd(&cmd, "skyouter", &skyouter))
		cmpack_phot_set_skyout(lc, skyouter);
	if (cfgfile_getdv(&cmd, "apertures", &apertures, &napertures))
		cmpack_phot_set_aper(lc, apertures, napertures);
	if (cfgfile_geti(&cmd, "maxstar", &maxstar))
		cmpack_phot_set_limit(lc, maxstar);
	
	/* prepare format string for generating output file names */
	if (!cmdline_gets(&cmd, "output-mask", &out_mask))
		out_mask = "frame???.pht";
	if (!CheckFileMask(out_mask))
		error(CMPACK_ERR_INVALID_FILE_MASK, NULL);

	/* Initial counter value */
	if (!cmdline_geti(&cmd, "counter", &icit))
		icit = 1;

	/* Create output dirfile */
	if (cmdline_gets(&cmd, "make-dirfile", &dirfile_out)) {
		if (strcmp(dirfile_out, "@")==0) {
			dout = stdout;
		} else {
			dout = fopen(dirfile_out, "w+");
			if (dout==NULL) error(CMPACK_ERR_CANT_MAKE_DIRFILE, dirfile_out);
		}
	}

	if (cmdline_gets(&cmd, "read-dirfile", &dirfile_in)) {
		/* Image names are read from a file */
		if (strcmp(dirfile_in, "@")==0) {
			din = stdin;
		} else {
			din = fopen(dirfile_in, "r");
			if (din==NULL) error(CMPACK_ERR_CANT_OPEN_DIRFILE, dirfile_in);
		}
		if (din) {
			while (fgets(buf1, MAXLINE, din)) {
				if (sscanf(buf1, "%1023s", line) == 1 && CheckFilePath(line)) {
					in_files++;
					FormatOutputName(outf, MAXLINE, out_mask, line, icit++);
					res = phot(lc, line, outf);
					if (res == 0) {
						if (dout) fprintf(dout, "%s\n", outf);
						out_files++;
					}
				}
			}
		}
		if (din && din!=stdin)
			fclose(din);
	} else {
		/* images names are given through the command line */
		if (cmdline_getparsv(&cmd, "files", &files, &count)) {
			for (i=0; i<count; i++) {
				if (CheckFilePath(files[i])) {
#ifdef _WIN32
					struct _finddata_t fd;
					intptr_t fh = _findfirst(files[i], &fd);
					if (fh!=-1) {
						do {
							if ((fd.attrib & _A_SUBDIR)==0)  {
								in_files++;
								MakeInputName(line, MAXLINE, files[i], fd.name);
								FormatOutputName(outf, MAXLINE, out_mask, fd.name, icit++);
								res = phot(lc, line, outf);
								if (res==0) {
									if (dout) fprintf(dout, "%s\n", outf);
									out_files++;
								}
							}
						} while (_findnext(fh, &fd)==0);
						_findclose(fh);
					}
#else
					in_files++;
					FormatOutputName(outf, MAXLINE, out_mask, files[i], icit++);
					res = phot(lc, files[i], outf);
					if (res==0) {
						if (dout) fprintf(dout, "%s\n", outf);
						out_files++;
					}
#endif
				}
			}
		}
	}

	if (dout && dout!=stdout)
		fclose(dout);

	PrintEpilogueEx(&cmd, in_files, out_files);

	cmpack_phot_destroy(lc);
	cmpack_con_destroy(con);
	Clean(&cmd);

	return 0;
}
