/**
	\file
	\brief Functions for reading and writing photometry files.

	Photometry files contain photometry result for a single CCD frame.
	The file is valid standalone XML document. This format was introduced
	in the version 1.2
	
	\author David Motl <dmotl@volny.cz>
	
	\par Copying
	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, version 2.
	
	$Id: cmpack_phtfile.h,v 1.3 2016/05/19 20:47:18 dmotl Exp $
*/

#ifndef _CMPACK_PHFILE_H_INCLUDED
#define _CMPACK_PHFILE_H_INCLUDED

#include "cmpack_common.h"
#include "cmpack_wcs.h"
#include "cmpack_table.h"

/*****************    Private data structures    ***************************/

/** 
	\brief Photometry file context
	\details This private structure holds the content of the read-all file.
*/
typedef struct _CmpackPhtFile CmpackPhtFile;

/** \brief Photometry file parameters */
typedef struct _CmpackPhtInfo
{
	int width;							/**< Width of frame in pixels */
	int height;							/**< Height of frame in pixels */
	double jd;							/**< Julian date of observation */
	char *filter;						/**< Color filter name */
	double exptime;						/**< Exposure duration in seconds */
	double ccdtemp;						/**< CCD temperature in deg. C */
	char *origin;						/**< Origin of the file (photometry software) */
	struct tm crtime;					/**< Creation time */
	double range[2];					/**< Low and high cutoff of pixel values */
	double gain;						/**< ADC gain */
	double rnoise;						/**< Readout noise */
	double fwhm_exp;					/**< Expected FWHM of objects */
	double fwhm_mean;					/**< Measured mean FWHM of objects */
	double fwhm_err;					/**< Standard deviation of FHWM of objects */
	double threshold;					/**< Detection threshold */
	double sharpness[2];				/**< Allowed range of roundness of objects */
	double roundness[2];				/**< Allowed range of sharpness of objects */
	int	matched;						/**< Non-zero if the frame has been matched */
	int match_rstars;					/**< Maximum number of stars used in Solve procedure */
	int match_istars;					/**< Number of vertices of polygons */
	int match_mstars;					/**< Number of stars that were successfully matched */
	double match_clip;					/**< Clipping threshold for matching */
	double offset[2];					/**< Frame offset in pixels */
	CmpackObjCoords object;				/**< Object's designation and coordinates */
	CmpackLocation location;			/**< Observer's location and coordinates */
	CmpackMatrix trafo;					/**< Trasformation matrix between the frame and the reference frame */
} CmpackPhtInfo;

/**	\brief Frame property flags */
typedef enum _CmpackPhtInfoMask
{
	CMPACK_PI_FRAME_PARAMS	= (1<<0),	/**< Fields: width, height, jd, filter, exptime, ccdtemp */
	CMPACK_PI_ORIGIN_CRDATE	= (1<<1),	/**< Fields: origin, crtime */
	CMPACK_PI_PHOT_PARAMS	= (1<<2),	/**< Fields: range, gain, rnoise, fwhm_*, threshold, sharpness, roundness */
	CMPACK_PI_MATCH_PARAMS	= (1<<3),	/**< Fields: matched, match_*, offset */
	CMPACK_PI_OBJECT		= (1<<4),	/**< Fields: object.* */
	CMPACK_PI_LOCATION		= (1<<5),	/**< Fields: location.* */
	CMPACK_PI_TRAFO			= (1<<6),	/**< Fields: trafo */
	CMPACK_PI_JD			= (1<<7)	/**< Fields: jd */
} CmpackPhtInfoMask;

/**	\brief Object properties */
typedef struct _CmpackPhtObject
{
	int id;								/**< Object identifier */
	int ref_id;							/**< Reference identifier */
	double x;							/**< Center - X coordinate */
	double y;							/**< Center - Y coordinate */
	double skymed;						/**< Background mean level in ADU */
	double skysig;						/**< Background noise level in ADU */
	double fwhm;						/**< Full width at half maximum in pixels */
} CmpackPhtObject;

/**	\brief Frame property flags */
typedef enum _CmpackPhtObjectMask
{
	CMPACK_PO_ID		= (1<<0),		/**< Fields: id (read only) */
	CMPACK_PO_REF_ID	= (1<<1),		/**< Fields: ref_id */
	CMPACK_PO_CENTER	= (1<<2),		/**< Fields: x, y */
	CMPACK_PO_SKY		= (1<<3),		/**< Fields: skymed, skysig */
	CMPACK_PO_FWHM		= (1<<4)		/**< Fields: fwhm */
} CmpackPhtObjectMask;

/**	\brief Aperture properties */
typedef struct _CmpackPhtAperture
{
	int id;								/**< Aperture identifier */
	double radius;						/**< Radius in pixels */
} CmpackPhtAperture;

/** \brief Aperture property flags */
typedef enum _CmpackPhtApertureFlags
{
	CMPACK_PA_ID		= (1<<0),		/**< Fields: id (read only) */
	CMPACK_PA_RADIUS	= (1<<1)		/**< Fields: radius */
} CmpackPhtApertureFlags;

/** \brief Measurement of an object for an aperture */
typedef struct _CmpackPhtData
{
	int		mag_valid;					/**< Is the magnitude valid? */
	double	magnitude;					/**< Instrumental magnitude */
	double	mag_error;					/**< Error estimation of brightness (0 = not available) */
} CmpackPhtData;

/********************   Public functions   **************************/

#ifdef __cplusplus
extern "C" {
#endif

/**
	\brief Create a new photometry file context
	\details The function creates a new photometry file and returns a new 
	reference to it. This file is designed to store data temporarily
	in the memory. To open a file from the disk or create a permanent
	file, use cmpack_pht_open() function instead. The reference counter 
	is set to one. The caller is responsible to call cmpack_pht_close() 
	or cmpack_pht_destroy() when it is no longer needed.
	\return pointer to a new reference
*/
	CMPACK_EXPORT(CmpackPhtFile*, cmpack_pht_init, (void));

/**
	\brief Make a new reference to the catalog file
	\details The function makes a new reference to the file and returns a 
	pointer to it. The reference counter is incremented by one. The caller 
	is responsible to call cmpack_pht_destroy() when the reference is 
	no longer needed.
	\param[in]	file		file context
	\return pointer to a new reference
*/
	CMPACK_EXPORT(CmpackPhtFile*, cmpack_pht_reference, (CmpackPhtFile* file));

/**
	\brief Release a reference to the photometry file.
	\details The function releases a reference to the file. The reference 
	counter is decreased by one and when it was the last reference to the 
	file, the content of the disk file is updated and it is closed. The data
	are freed from the memory.
	\param[in]	file		file context
*/
	CMPACK_EXPORT(void, cmpack_pht_destroy, (CmpackPhtFile* file));

/**
	\brief Open or create a photometry file stored on the disk.
	\details The function opens an existing photometry file stored on the
	disk or creates a new file. 
	\param[out]	file			new file context
	\param[in] 	filename		path + file name
	\param[in]	mode			opening mode (see CMPACK_OPEN_xxx constants)
	\param[in] 	flags 			not used, should be 0
	\return zero on success, error code on failure
*/
	CMPACK_EXPORT(int, cmpack_pht_open, (CmpackPhtFile** file, const char* filename,
		CmpackOpenMode mode, unsigned flags));

/**
	\brief Close photometry file and release the reference
	\details The function updates the content of the disk file and 
	closes the file. The context is then switched to the read-only
	mode, so it is possible in some cases to retrieve the information, 
	but the file cannot be modified. The function also decrements the 
	reference counter and when it was the last reference, the memory 
	is freed. In that case, the context is no longer valid and it is 
	not possible to retrieve the information from it.
	\param[in]	file			file context
	\return zero on success, error code on failure
*/
	CMPACK_EXPORT(int, cmpack_pht_close, (CmpackPhtFile* file));

/**
	\brief Copy content of the photometry file 
	\details The function makes copy of the source photometry file
	and to the target photometry file. If the target file contains
	any information, it is overwritten.
	\param[in] dstfile			target file
	\param[in] srcfile			source file
	\return zero on success, error code on failure
*/
	CMPACK_EXPORT(int, cmpack_pht_copy, (CmpackPhtFile* dstfile, CmpackPhtFile* srcfile));

/**
	\brief Clear the photometry file
	\details The function deletes all defined objects and sets all header
	fields to default values.
	\param[in]	file			catalog file 
*/
	CMPACK_EXPORT(void, cmpack_pht_clear, (CmpackPhtFile* file));

/** 
	\brief Test if given file seems to be a valid photometry file
	\details The function reads the beginning of the file and
	examines them to check if the file is a valid catalogue file or not.
	This function is used for file format autodetection.
	\param[in] 	filename		path + file name
	\return nonzero if the file is a valid photometry file, zero otherwise
*/
	CMPACK_EXPORT(int, cmpack_pht_test, (const char* filename));

/** 
	\brief Test memory buffer if it seems to be a valid photometry file
	\details The function examines the given memory buffer to check
	if the buffer contains a beginning of a valid photometry file or not.
	This function is used for file format autodetection.
	\param[in] 	buffer			data to be examined
	\param[in]	buflen			number of bytes in the buffer
	\param[in]	filesize		real size of the complete file in bytes
	\return nonzero if the file is a valid catalog file, zero otherwise
*/
	CMPACK_EXPORT(int, cmpack_pht_test_buffer, (const char* buffer, int buflen, int filesize));

/**
	\brief Dump content of the photometry file to a file
	\details The function makes a table of objects and their positions.
	If a valid aperture index is specified, the function dumps also
	magnitudes and their error. If aperture is not specified, the first aperture
	is used as a default.
	\param[in] file				file context
	\param[out] table			new table with the light curve
	\param[in] aperture			aperture index (-1 = use first aperture)
	\param[in] con				where debug messages are printed to
	\param[in] flags			reserved for future use, set to zero
	\return zero on success or error code on failure
*/
	CMPACK_EXPORT(int, cmpack_pht_dump, (CmpackPhtFile* file, CmpackTable** table, int aperture, 
		CmpackConsole* con, unsigned flags));

/******************* File header ***************************/

/**
	\brief Set frame parameters to the photometry file
	\details The function sets the parameters that are stored in the
	header of the photometry file.
	\param[in] file 		file context
	\param[in] mask			which fields shall be changed
	\param[in] info			frame properties
	\return zero on success or error code on failure
*/
	CMPACK_EXPORT(int, cmpack_pht_set_info, (CmpackPhtFile* file, unsigned mask, const CmpackPhtInfo* info));

/**
	\brief Get frame parameters from the photometry file
	\details 
	\param[in] file 		file context
	\param[in] mask			which fields shall be retrieved
	\param[out] info		frame properties
	\return zero on success or error code on failure
*/
	CMPACK_EXPORT(int, cmpack_pht_get_info, (CmpackPhtFile* file, unsigned mask, CmpackPhtInfo* info));

/************************* Table of apertures ********************************/

/**
	\brief Get number of apertures stored in a photometry file
	\details The function returns the number of apertures that
	are defined in the photometry file.
	\param[in]	file 		file context
	\return number of apertures or zero on failure.
*/
	CMPACK_EXPORT(int, cmpack_pht_aperture_count, (CmpackPhtFile* file));

/**
	\brief Find aperture in the photometry file by identifier
	\details The function finds an aperture record with specified
	aperture identifier and returns its index. When such record does
	not exist, the function returns -1.
	\param[in] file			file context
	\param[in] aper_id		aperture identifier
	\return aperture index or negative value on failure
*/
	CMPACK_EXPORT(int, cmpack_pht_find_aperture, (CmpackPhtFile* file, int aper_id));

/** 
	\brief Add new aperture to a file
	\details The function adds a new aperture to the photometry file. The
	aperture is appended to the end of the table.
	\param[in] file			file context
	\param[in] mask			which fields shall be initialized
	\param[in] data			initial parameters
	\returns aperture index or negative value on failure
*/
	CMPACK_EXPORT(int, cmpack_pht_add_aperture, (CmpackPhtFile* file, unsigned mask,
		const CmpackPhtAperture* data));

/** 
	\brief Get aperture parameters
	\details The function reads aperture parameters. The caller specify
	by a bitmask which parameters shall be retrieved.
	\param[in] file			file context
	\param[in] index		aperture index
	\param[in] mask			which fields shall be retieved
	\param[out] data		aperture parameters
	\return returns zero on success or error code on failure
*/
	CMPACK_EXPORT(int, cmpack_pht_get_aperture, (CmpackPhtFile* file, int index, unsigned mask,
		CmpackPhtAperture* data));

/** 
	\brief Get radius of an aperture
	\details The function returns radius of the aperture
	from the table of apertures. The item is specified by an index
	to the table.
	\param[in] file			file context
	\param[in] index		aperture index
	\param[in] mask			which fields shall be modified
	\param[in] data			aperture parameters
	\return returns zero on success or error code on failure
*/
	CMPACK_EXPORT(int, cmpack_pht_set_aperture, (CmpackPhtFile* file, int index, unsigned mask,
		const CmpackPhtAperture* data));

/*************************** Table of stars **********************************/

/**
	\brief Get number of stars stored in a photometry file
	\details The function returns number of objects that are
	defined in the photometry file.
	\param[in]	file 		file context
	\return zero on success, error code on failure
*/
	CMPACK_EXPORT(int, cmpack_pht_object_count, (CmpackPhtFile* file));

/**
	\brief Add new star to a file
	\details The function creates a new record in the table 
	of objects and assigns its properties. The new record is
	appended to the end of the table.
	\param[in] file			file context
	\param[in] mask			which fields shall be initialized
	\param[in] info			object properties
	\return star index or negative value on failure
*/
	CMPACK_EXPORT(int, cmpack_pht_add_object, (CmpackPhtFile* file, unsigned mask,
		const CmpackPhtObject* info));

/**
	\brief Get star context by object identifier or reference identifier
	\details The function finds an object record with specified
	object/reference identifier and returns its index. When such record does
	not exist, the function returns -1.
	\param[in] file			file context
	\param[in] id			identifier
	\param[in] ref_id		0 = object id, 1 = reference id
	\return star index or negative value on failure
*/
	CMPACK_EXPORT(int, cmpack_pht_find_object, (CmpackPhtFile* file, int id, int ref_id));

/**
	\brief Get object parameters
	\details The function retrieves object properties from 
	the record that is indicated by its index. When such record 
	does not exist, an error code is returned.
	\param[in] file			file context
	\param[in] index		object index
	\param[in] mask			which fields shall be retrieved?
	\param[out] info		object properties
	\return zero on success or error code on failure
*/
	CMPACK_EXPORT(int, cmpack_pht_get_object, (CmpackPhtFile* file, int index, unsigned mask,
		CmpackPhtObject* info));

/**
	\brief Set object parameters
	\details The function changes object properties in the record
	that is indicated by its index. 
	\param[in] file			file context
	\param[in] index		record index
	\param[in] mask			which fields shall be modified?
	\param[in] info			object properties
	\return zero on success or error code on failure
*/
	CMPACK_EXPORT(int, cmpack_pht_set_object, (CmpackPhtFile* file, int index, unsigned mask,
		const CmpackPhtObject* info));

/*************************** Measurements **********************************/

/**
	\brief Set measurement to the photometry file
	\details The function sets measurement data for specified
	object and aperture. 
	\param[in] file			photometry file
	\param[in] object		object index
	\param[in] aperture		aperture index
	\param[in] data			measurement data
	\return zero on success or error code on failure
*/
	CMPACK_EXPORT(int, cmpack_pht_set_data, (CmpackPhtFile* file, int object, int aperture,
		const CmpackPhtData* data));

/**
	\brief Set measurement to the photometry file
	\details The function sets measurement data for specified
	object and aperture. 
	\param[in] file			photometry file
	\param[in] object		object index
	\param[in] aperture		aperture index
	\param[in] data			measurement data
	\param[in] code			code indicating a reason why the brightness was not measured
	\return zero on success or error code on failure
*/
	CMPACK_EXPORT(int, cmpack_pht_set_data_with_code, (CmpackPhtFile* file, int object, int aperture,
		const CmpackPhtData* data, CmpackError code));

/**
	\brief Get measurement from the photometry file
	\details The function retrieves measurement data for specified
	object and aperture. 
	Please note: The function returns zero if it has found the record
	for the indicated star and aperture. It may happen, that the brightness
	was not measured. The function returns zero and clears the data.mag_valid flag.
	\param[in] file			photometry file
	\param[in] object		object index
	\param[in] aperture		aperture index
	\param[out] data		measurement data
	\return zero on success or error code on failure.
*/
	CMPACK_EXPORT(int, cmpack_pht_get_data, (CmpackPhtFile* file, int object, int aperture,
		CmpackPhtData* data));

/**
	\brief Get measurement from the photometry file
	\details The function retrieves measurement data for specified
	object and aperture. 
	Please note: The function returns zero if it has found the record
	for the indicated star and aperture. It may happen, that the brightness
	was not measured. The function returns zero and clears the data.mag_valid flag.
	\param[in] file			photometry file
	\param[in] object		object index
	\param[in] aperture		aperture index
	\param[out] data		measurement data
	\param[out] code		code indicating reason why the brightness was not measured
	\return zero on success or error code on failure
*/
	CMPACK_EXPORT(int, cmpack_pht_get_data_with_code, (CmpackPhtFile* file, int object, int aperture,
		CmpackPhtData* data, CmpackError* code));

/**
	\brief Get code indicating reason why the brightness was not measured
	\details The function retrieves error code for specified object and aperture. 
	\param[in] file			photometry file
	\param[in] object		object index
	\param[in] aperture		aperture index
	\param[out] code		code indicating reason why the brightness was not measured
	\return zero on success or error code on failure
*/
	CMPACK_EXPORT(int, cmpack_pht_get_code, (CmpackPhtFile* file, int object, int aperture,
		CmpackError* code));

/*************************** World Coordinate System **********************************/

/**
	\brief Update World Coordinate System (WCS) data in the file
	\details The function updates the WCS data stored in the file. 
	\param[in] file			photometry file
	\param[in] wcs			WCS data to be saved to the file
	\returns zero on success, error code on failure
*/
	CMPACK_EXPORT(int, cmpack_pht_set_wcs, (CmpackPhtFile* file, const CmpackWcs* wcs));

/**
	\brief Read World Coordinate System (WCS) data from the file
	\details The function retrieves WCS data stored in the file. The data
	are returned as a new CmpackWcs object. If the file contains several 
	WCS data sets, all of them are retrieved. The returned object is a pointer
	to internal data, the caller should not modify or free it.
	\param[in] file			photometry file
	\param[out] wcs			WCS data retrieved from the file
	\returns zero on success, error code on failure
*/
	CMPACK_EXPORT(int, cmpack_pht_get_wcs, (CmpackPhtFile* file, CmpackWcs** wcs));

#ifdef __cplusplus
}
#endif

#endif
