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

munifind.c (C-Munipack project)
Making table of standard deviations vs. mean magnitudes for all stars
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 = 
{ 
	"munifind", 
	"utility for finding unknown variable stars"
};

/* Options */
CmdOption opt[] =
{
	{ "aperture", 'a', "aperture identifier", "index", CMD_PTYPE_INT },
	{ "comparison-star", 'c', "indentifier of the comparison star", "star", CMD_PTYPE_INT },
	{ "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 photometry files from specified file", "filepath", CMD_PTYPE_FILEPATH },
	{ "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 }
};

/* Configuration parameters */
CfgParam cfg[] = 
{
	{ "aperture", CFG_PTYPE_INT, "aperture identifier" },
	{ "comp", CFG_PTYPE_INT, "indentifier of the comparison star" },
	{ "threshold", CFG_PTYPE_INT, "fraction of good measurements required in percents" },
	{ NULL }
};

/* Input files */
CmdParam flist[] = 
{
	{ "output-file", "output file name", CMD_PTYPE_FILEPATH },
	{ "files", "list of input photometry files", CMD_PTYPE_FILELIST },
	{ NULL }
};

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

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

static int mfind(CmpackFrameSet *lc, const char *srcpath, int frame_id)
{
	int res, i, objcount;
	CmpackPhtFile *pht;
	CmpackPhtObject stinfo;
	CmpackCatObject cinfo;

	printf("%s\n", srcpath);

	res = cmpack_pht_open(&pht, srcpath, CMPACK_OPEN_READONLY, 0);
	if (res!=0) {
		error(res, srcpath);
		return res;
	}
	objcount = cmpack_pht_object_count(pht);
	for (i=0; i<objcount; i++) {
		cmpack_pht_get_object(pht, i, CMPACK_PO_REF_ID, &stinfo);
		if (stinfo.ref_id>=0 && cmpack_fset_find_object(lc, stinfo.ref_id)<0) {
			cinfo.id = stinfo.ref_id;
			cmpack_fset_add_object(lc, CMPACK_OM_ID, &cinfo);
		}
	}
	res = cmpack_fset_append_frame(lc, pht, frame_id, srcpath);
	if (res!=0) 
		error(res, srcpath);
	cmpack_pht_destroy(pht);
	return 0;
}

int main(int argc, char **argv)
{

	FILE	*din = NULL;
	int	    i, res, aperture, threshold, in_files = 0, count;
	int		ap_valid = 0;
	char 	line[MAXLINE], buf1[MAXLINE];
	char	*dirfile_in, *output, *cfgfile, **files;
	CmpackMuniFind *lc;
	CmpackFrameSet *fc;
	CmpackTable *tc;
	CmpackConsole *con;
	CmpackPhtAperture aper;

	Init(&cmd);

	tc = NULL;
	memset(&aper, 0, sizeof(aper));

	/* 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);

	lc = cmpack_mfind_init();
	if (!lc) error(CMPACK_ERR_MEMORY, NULL);
	fc = cmpack_fset_init();
	if (!fc) error(CMPACK_ERR_MEMORY, NULL);

	if (!cmdline_getpars(&cmd, "output-file", &output))
		error(CMPACK_ERR_NO_OUTPUT_FILE, NULL);
	if (!CheckFilePath(output))
		error(CMPACK_ERR_INVALID_OUT_FILE, 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_mfind_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_geti(&cmd, "aperture", &aperture)) {
		aper.id = aperture;
		cmpack_fset_add_aperture(fc, CMPACK_PA_ID, &aper);
		cmpack_mfind_set_aperture(lc, aperture);
		ap_valid = 1;
	}
	if (cfgfile_geti(&cmd, "comparison-star", &i))
		cmpack_mfind_set_comparison(lc, i);
	if (cfgfile_geti(&cmd, "threshold", &threshold))
		cmpack_mfind_set_threshold(lc, threshold);
	
	if (cmdline_geti(&cmd, "aperture", &aperture)) {
		aper.id = aperture;
		cmpack_fset_add_aperture(fc, CMPACK_PA_ID, &aper);
		cmpack_mfind_set_aperture(lc, aperture);
		ap_valid = 1;
	}
	if (cmdline_geti(&cmd, "comparison-stars",  &i))
		cmpack_mfind_set_comparison(lc, i);
	if (cmdline_geti(&cmd, "threshold", &threshold))
		cmpack_mfind_set_threshold(lc, threshold);

	if (!ap_valid) {
		fprintf(stderr, "Missing aperture selection.");
		return CMPACK_ERR_AP_NOT_FOUND;
	}

	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);
		}
		while (fgets(buf1, MAXLINE, din)) {
			if (sscanf(buf1, "%1023s", line) == 1 && CheckFilePath(line)) {
				in_files++;
				mfind(fc, line, in_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);
								mfind(fc, line, in_files);
							}
						} while (_findnext(fh, &fd)==0);
						_findclose(fh);
					}
#else
					in_files++;
					mfind(fc, files[i], in_files);
#endif
				}
			}
		}
	}

	res = cmpack_mfind(lc, fc, &tc, CMPACK_MFIND_DEFAULT);
	if (res!=0) 
		error(res, output);

	/* Write table to file */
	res = cmpack_tab_save(tc, output, 0, NULL, 0);
	if (res!=0) 
		error(res, output);

	PrintEpilogue(&cmd, in_files);

	cmpack_mfind_destroy(lc);
	cmpack_fset_destroy(fc);
	cmpack_tab_destroy(tc);
	cmpack_con_destroy(con);
	Clean(&cmd);
	return 0;
}
