/**
	\file
	\brief Miscellaneous data types, definitions, functions, &c.

	Set of functions, data types for general use.
	
	\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_common.h,v 1.7 2016/05/01 16:15:05 dmotl Exp $
*/

#ifndef _CMPACK_COMMON_H_INCLUDED
#define _CMPACK_COMMON_H_INCLUDED

#include <time.h>

#include "cmpack_config.h"

#ifdef __cplusplus
extern "C" {
#endif

/********************   Public data types   ********************************/

/** \brief Date in full format */
typedef struct _CmpackDate
{
	int year;				/**< year in 4-digit format */
	int month;				/**< month (1-12) */
	int day;				/**< day (1-31) */
} CmpackDate;

/** \brief Time in full format */
typedef struct _CmpackTime
{
	int hour;				/**< hour (0-23) */
	int minute;				/**< minute (0-59) */
	int second;				/**< second (0-59) */
	int milisecond;			/**< milisecond (0-999) */
} CmpackTime;

/** \brief Date and time in full format */
typedef struct _CmpackDateTime
{
	CmpackDate date;		/**< date, see CmpackDate structure */
	CmpackTime time;		/**< time, see CmpackTime structure */
} CmpackDateTime;

/** \brief Border size */
typedef struct _CmpackBorder
{
	int left;				/**< Left border */
	int top;				/**< Top border */
	int right;				/**< Right border */
	int bottom;				/**< Bottom border */
} CmpackBorder;

/**
	\brief Transformation matrix
	\details A CmpackMatrix holds an affine transformation, such as a scale, rotation, 
	shear, or a combination of those. The transformation of a point (x, y) is given by:
    x_new = xx * x + xy * y + x0;
    y_new = yx * x + yy * y + y0;
*/
typedef struct _CmpackMatrix {
    double xx;				/**< xx component of the affine transformation */
	double yx;				/**< yx component of the affine transformation */
    double xy;				/**< xy component of the affine transformation */
	double yy;				/**< yy component of the affine transformation */
    double x0;				/**< x translation component of the affine transformation */
	double y0;				/**< y translation component of the affine transformation */
} CmpackMatrix;

/** \brief Object designation and coordinates */
typedef struct _CmpackObjCoords
{
	char	*designation;	/**< Object's designation */
	int		ra_valid;		/**< Is right ascension valid? */
	int		dec_valid;		/**< Is declination valid? */
	double	ra;				/**< Right ascension (hours) */
	double	dec;			/**< Declination (degrees) */
} CmpackObjCoords;

/** \brief Location name and coordinates */
typedef struct _CmpackLocation
{
	char	*designation;	/**< Location name */
	int		lon_valid;		/**< Is longitude valid? */
	int		lat_valid;		/**< Is latitude valid? */
	double	lon;			/**< Longitude (degrees, E positive, W negative)*/
	double	lat;			/**< Latitude (degrees, N positive, S negative) */
} CmpackLocation;

/** \brief Open flags */
typedef enum _CmpackOpenMode
{
	CMPACK_OPEN_READONLY,	/**< The file does not allow modifications */
	CMPACK_OPEN_READWRITE,	/**< The file allows modifications */
	CMPACK_OPEN_CREATE		/**< Create a new file */
} CmpackOpenMode;

/** \brief Load flags */
typedef enum _CmpackLoadFlags
{
	CMPACK_LOAD_HEADONLY    = (1<<0)	/**< Load only header if possible */
} CmpackLoadFlags;

typedef enum _CmpackSaveFlags
{
	CMPACK_SAVE_BIN_FORMAT			= (1<<0),	/**< Save in binary format */
	CMPACK_SAVE_XML_FORMAT			= (1<<1),	/**< Save as XML document */
	CMPACK_SAVE_DAO_FORMAT			= (1<<2),	/**< Save in DAOPHOT compatible format */
	CMPACK_SAVE_NO_HEADER			= (1<<3)	/**< Do not save header when writing tables */
} CmpackSaveFlags;

/** \brief Sort keys */
typedef enum _CmpackSortKey
{
	CMPACK_SORT_ID,						/**< Sort by object id */
	CMPACK_SORT_REF_ID,					/**< Sort by reference id */
	CMPACK_SORT_MAGNITUDE				/**< Sort by magnitude */
} CmpackSortKey;

/** \brief Image data types */
typedef enum _CmpackBitpix
{
	CMPACK_BITPIX_UNKNOWN = 0,			/**< Unknown or invalid data format */
	CMPACK_BITPIX_SSHORT = 16,			/**< Signed short int (2 bytes) */
	CMPACK_BITPIX_USHORT = 20,			/**< Unsigned short int (2 bytes) */
	CMPACK_BITPIX_SLONG = 32,			/**< Signed long int (4 bytes) */
	CMPACK_BITPIX_ULONG = 40,			/**< Unsigned long int (4 bytes) */
	CMPACK_BITPIX_FLOAT = -32,			/**< Single precision FP (4 bytes) */
	CMPACK_BITPIX_DOUBLE = -64			/**< Double precision FP (8 bytes) */
} CmpackBitpix;

#define CMPACK_BITPIX_AUTO CMPACK_BITPIX_UNKNOWN

/** \brief Parameter identifiers */
typedef enum _CmpackParam
{
	CMPACK_PARAM_JD_PRECISION		= 0,	/**< Number of decimal places for Julian dates and heliocentric correction */
	CMPACK_PARAM_POS_PRECISION		= 1,	/**< Number of decimal places for position in pixels */
	CMPACK_PARAM_EXP_PRECISION		= 2,	/**< Number of decimal places for exposure duration in seconds */
	CMPACK_PARAM_TEMP_PRECISION		= 3,	/**< Number of decimal places for CCD temperature */
	CMPACK_PARAM_AMASS_PRECISION	= 4,	/**< Number of decimal places for air mass coefficient */
	CMPACK_PARAM_ALT_PRECISION		= 5,	/**< Number of decimal places for altitude in degrees */
	CMPACK_PARAM_MAG_PRECISION      = 6,	/**< Number of decimal places for magnitudes */
	CMPACK_PARAM_WCS_SUPPORTED		= 7		/**< 1 if compiled with wcslib, 0 otherwise */
} CmpackParam;

/** \brief Error codes */
typedef enum _CmpackError
{
	CMPACK_ERR_OK				= 0,		/**< Operation finished successfully */
	CMPACK_ERR_MEMORY			= 1001,		/**< Insufficient memory */
	CMPACK_ERR_KEY_NOT_FOUND    = 1002,		/**< Key not found */
	CMPACK_ERR_COL_NOT_FOUND	= 1003,		/**< Column not found */
	CMPACK_ERR_ROW_NOT_FOUND	= 1004,		/**< Row not found */
	CMPACK_ERR_AP_NOT_FOUND		= 1005,		/**< Aperture not found */
	CMPACK_ERR_READ_ONLY		= 1006,		/**< File is open in read-only mode */
	CMPACK_ERR_CLOSED_FILE      = 1007,		/**< Operation not allowed on closed file */
	CMPACK_ERR_OPEN_ERROR		= 1008,		/**< Error while opening file */
	CMPACK_ERR_READ_ERROR		= 1009,		/**< Error while reading file */
	CMPACK_ERR_WRITE_ERROR		= 1010,		/**< Error while writing file */
	CMPACK_ERR_UNKNOWN_FORMAT	= 1011,		/**< Unsupported file format */
	CMPACK_ERR_BUFFER_TOO_SMALL = 1012,		/**< Buffer is too small */
	CMPACK_ERR_INVALID_CONTEXT  = 1013,     /**< Invalid context */
	CMPACK_ERR_OUT_OF_RANGE     = 1014,     /**< Index is out of range */
	CMPACK_ERR_UNDEF_VALUE      = 1015,     /**< Undefined value */
	CMPACK_ERR_MAG_NOT_FOUND    = 1016,		/**< Measurement not found */
	CMPACK_ERR_STAR_NOT_FOUND	= 1017,		/**< Star not found */
	CMPACK_ERR_NOT_IMPLEMENTED  = 1018,		/**< Unsupported operation */
	CMPACK_ERR_ACCESS_DENIED	= 1019,		/**< Access denied - the file is already in use */
	CMPACK_ERR_FILE_NOT_FOUND	= 1020,		/**< The file does not exist */
	CMPACK_ERR_INVALID_SIZE     = 1100,		/**< Invalid dimensions of image */
	CMPACK_ERR_INVALID_DATE     = 1101,		/**< Invalid date/time format */
	CMPACK_ERR_INVALID_PAR      = 1102,		/**< Invalid value of parameter */
	CMPACK_ERR_INVALID_RA		= 1103,		/**< Invalid RA format */
	CMPACK_ERR_INVALID_DEC		= 1104,		/**< Invalid DEC format */
	CMPACK_ERR_INVALID_EXPTIME	= 1105,		/**< Invalid exposure duration */
	CMPACK_ERR_INVALID_BITPIX   = 1106,     /**< Image image data format */
	CMPACK_ERR_INVALID_LON		= 1107,		/**< Invalid format of longitude */
	CMPACK_ERR_INVALID_LAT		= 1108,		/**< Invalid format of latitude */
	CMPACK_ERR_INVALID_JULDAT	= 1109,		/**< Invalid date/time of observation */
	CMPACK_ERR_INVALID_WCS		= 1110,		/**< No valid WCS data found */
	CMPACK_ERR_CANT_OPEN_SRC	= 1200,		/**< Cannot open the source file */
	CMPACK_ERR_CANT_OPEN_OUT	= 1201,		/**< Cannot open the destination file */
	CMPACK_ERR_CANT_OPEN_BIAS	= 1202,		/**< Bias frame not found */
	CMPACK_ERR_CANT_OPEN_DARK	= 1203,		/**< Dark frame not found */
	CMPACK_ERR_CANT_OPEN_FLAT	= 1204,		/**< Flat frame not found */
	CMPACK_ERR_CANT_OPEN_REF	= 1205,		/**< Reference file not found */
	CMPACK_ERR_CANT_OPEN_PHT	= 1206,		/**< Cannot open photometry file */
	CMPACK_ERR_DIFF_SIZE_SRC	= 1300,		/**< Input frames are not compatible (different sizes) */
	CMPACK_ERR_DIFF_SIZE_BIAS   = 1301,		/**< Bias frame is not compatible (different sizes) */
	CMPACK_ERR_DIFF_SIZE_DARK  	= 1302,		/**< Dimensions of dark-frame and scientific image are different */
	CMPACK_ERR_DIFF_SIZE_FLAT   = 1303,		/**< Dimensions of flat-frame and scientific image are different */ 
	CMPACK_ERR_DIFF_BITPIX_SRC	= 1304,		/**< Input frames are not compatible (different image data type) */
	CMPACK_ERR_NO_INPUT_FILES	= 1400,		/**< No input files */
	CMPACK_ERR_NO_BIAS_FRAME	= 1401,		/**< Missing bias frame */
	CMPACK_ERR_NO_DARK_FRAME	= 1402,		/**< Missing dark frame */
	CMPACK_ERR_NO_FLAT_FRAME	= 1403,		/**< Missing flat frame */
	CMPACK_ERR_NO_OBS_COORDS	= 1404,		/**< Missing observer's coordinates */
	CMPACK_ERR_NO_OBJ_COORDS	= 1405,		/**< Missing object's coordinates */
	CMPACK_ERR_NO_OUTPUT_FILE	= 1406,		/**< Missing name of output frame */
	CMPACK_ERR_NO_REF_FILE		= 1407,		/**< Missing name of reference frame */
	CMPACK_ERR_MEAN_ZERO    	= 1500,		/**< Mean value of flat frame is zero (can't divide by zero) */
	CMPACK_ERR_REF_NOT_FOUND	= 1501,		/**< Refererence star was not found */
	CMPACK_ERR_FEW_POINTS_REF	= 1502,		/**< Too few stars in the reference file */
	CMPACK_ERR_FEW_POINTS_SRC	= 1503,		/**< Too few stars in the source file */
	CMPACK_ERR_MATCH_NOT_FOUND	= 1504,		/**< Coincidences not found  */
	CMPACK_ERR_MANY_BAD_PXLS	= 1505,		/**< Too many bad pixels in the correction frame */
	CMPACK_ERR_TARGET_NOT_FOUND = 1506,		/**< Moving target was not identified */
	CMPACK_ERR_ZERO_INTENSITY	= 1600,		/**< The net intensity is zero or negative */
	CMPACK_ERR_INVALID_AP_SIZE	= 1601,		/**< The aperture has invalid size */
	CMPACK_ERR_CLOSE_TO_BORDER	= 1602,		/**< The object is too close to the frame border */
	CMPACK_ERR_OVEREXPOSED_PXLS = 1603,		/**< There are overexposed pixels in the aperture */
	CMPACK_ERR_BAD_PIXELS		= 1604,		/**< There are bad pixels in the aperture */
	CMPACK_ERR_SKY_NOT_MEASURED = 1605		/**< Not enough valid pixels in the sky annulus */
} CmpackError;

/** \brief Data type identifiers */
typedef enum _CmpackType 
{
	CMPACK_TYPE_VOID,		/**< Nothing */
	CMPACK_TYPE_INT,		/**< Integer number */
	CMPACK_TYPE_DBL,		/**< Floating point number */
	CMPACK_TYPE_STR			/**< String */
} CmpackType;

/** \brief Selection types */
typedef enum _CmpackSelectionType
{
	CMPACK_SELECT_NONE,		/**< Ordinary star */
	CMPACK_SELECT_VAR,		/**< Variable star */
	CMPACK_SELECT_COMP,		/**< Comparison star */
	CMPACK_SELECT_CHECK,	/**< Check star */
	CMPACK_SELECT_COUNT		/**< Number of types */
} CmpackSelectionType;

/********************   Intialization/clean-up   ********************************/

/**
	\brief Initialize library
	\details The function initializes internal variables in the library. The
	application must call this function before any other function from the 
	C-Munipack library is called.
	\warning Any call to a function from the C-Munipack library preceding execution
	of this function can lead to unpredictable results!
*/
CMPACK_EXPORT(void, cmpack_init, (void));

/**
	\brief Clean-up library
	\details The function frees memory allocated in the internal variables
	in the library. It is recommended to call this function before the application
	is finished. When the library is compiled with the CMPACK_DEBUG_HEAP flag on, the function
	prints a table of unreleased memory blocks to the stderr stream.
	\warning Any call to a function from the C-Munipack library succeeding execution
	of this function can lead to unpredictable results!
*/	
CMPACK_EXPORT(void, cmpack_cleanup, (void));

/********************   Common functions   ********************************/

/**
	\brief Translates error code to its human readable representation.
	\details The function returns a nul-terminated string with human-readable
	description of the specified error code. The caller is responsible
	to release the returned string by calling the cmpack_free() function.
	\param[in] code			error code
	\return pointer to newly allocated string or zero on failure.
*/
CMPACK_EXPORT(char*, cmpack_formaterror, (int code));

/**
	\brief Get C-Munipack package name
	\details The function returns pointer to a nul-terminated string which
	indicates name of the library. The caller must not modify or free the
	string.
	\return pointer to nul-terminated string or zero on failure.
*/
CMPACK_EXPORT(const char*, cmpack_packagename, (void));

/**
	\brief Get configuration parameter
	\param[in] param		parameter identifier (see CMPACK_PARAM_xxx)
	\return parameter value or zero on failure 
*/
CMPACK_EXPORT(int, cmpack_get_param_int, (CmpackParam param));

/**
	\brief Get configuration parameter
	\param[in] param		parameter identifier (see CMPACK_PARAM_xxx)
	\return parameter value or zero on failure 
*/
CMPACK_EXPORT(long, cmpack_get_param_long, (CmpackParam param));

/******************   Memory management   ***************************/

/**
	\brief Allocate memory.
	\details The function allocates specified amount of memory on heap
	and returns pointer to the beginning of the memory block. The 
	content of the memory block is undefined. All blocks allocated by 
	means of this function must be released by calling the cmpack_free() 
	function. If there is not enough memory, the function returns NULL.
	\param[in] size				size in bytes
	\return pointer to the first byte of the memory block
*/
CMPACK_EXPORT(void*, cmpack_malloc, (size_t size));

/**
	\brief Allocate and clear memory block.
	\details The function allocates specified amount of memory on heap
	and returns pointer to the beginning of the memory block. The content
	of the new memory block is set to zeros. All blocks allocated by means 
	of this function must be released by calling the cmpack_free() function.
	If there is not enough memory, the function returns NULL.
	\param[in] num				number of items
	\param[in] size				size of single item
	\return pointer to the first byte of the memory block
*/
CMPACK_EXPORT(void*, cmpack_calloc, (size_t num, size_t size));

/**
	\brief Change size of the memory block or make new one.
	\details The function changes the size of allocated memory block. When
	a NULL value is given as the first parameter, a new memory block 
	is allocated. Content of the original memory block is preserved, but the 
	content of the new area is undefined.
	If there is not enough memory, the function returns NULL and the old
	memory block remains valid and allocated.
	\param[in] ptr				pointer to existing block (or NULL)
	\param[in] size				new size in bytes
*/
CMPACK_EXPORT(void*, cmpack_realloc, (void* ptr, size_t size));

/**
	\brief Makes copy of a null-terminated string
	\details The function makes a new copy of a nul-terminated string 
	and returns pointer to the new string. If the input is NULL or there 
	is not enough memory, it returns NULL. Use cmpack_free() function to 
	release the memory.
	\param[in] src				source string
*/
CMPACK_EXPORT(char*, cmpack_strdup, (const char* src));

/**
	\brief Release allocated memory
	\details The function releases the memory block allocated inside the
	library. If the NULL pointer is passed, it does nothing
	\param[in] ptr				pointer to memory (can be NULL)
*/
CMPACK_EXPORT(void, cmpack_free, (void* ptr));

/******************   Debug heap functions   ******************************/

/**
	\brief Allocate memory (debug version)
	\details The function allocates specified amount of memory on heap
	and returns pointer to the beginning of the memory block. All
	blocks allocated by means of this function must be released by
	calling the cmpack_free() function. Unlike cmpack_malloc(), this
	function stores the given name of the source file and line number.
	The content of the memory block is undefined.
	\param[in] size				size in bytes
	\param[in] file				source file name
	\param[in] line				source line index
	\returns pointer to the first byte of the memory block
*/
CMPACK_EXPORT(void*, cmpack_malloc_dbg, (size_t size, const char* file, int line));

/**
	\brief Change size of the memory block or make new one.
	\details The function changes the size of allocated memory block. When
	a NULL value is given as the first parameter, a new memory block 
	is allocated. Content of the original memory block is preserved, but the 
	content of the new area is undefined.
	If there is not enough memory, the function returns NULL and the old
	memory block remains valid and allocated.
	Unline cmpack_realloc() this function stores the given name of the source 
	file and line number.
	\param[in] ptr				pointer to existing block (or NULL)
	\param[in] size				new size in bytes
	\param[in] file				source file name
	\param[in] line				source line index
*/
CMPACK_EXPORT(void*, cmpack_realloc_dbg, (void* ptr, size_t size, const char* file, int line));

/**
	\brief Allocate and clear memory block (debug version)
	\details The function allocates specified amount of memory on heap
	and returns pointer to the beginning of the memory block and sets
	the content to zeros. All blocks allocated by means of this function 
	must be released by	calling the cmpack_free() function. Unlike 
	cmpack_calloc(), this function stores the given name of the source 
	file and line number.
	\param[in] num				number of items
	\param[in] size				size of single item
	\param[in] file				source file name
	\param[in] line				source line index
	\return pointer to the first byte of the memory block
*/
CMPACK_EXPORT(void*, cmpack_calloc_dbg, (size_t num, size_t size, const char* file, int line));

/**
	\brief Makes copy of a null-terminated string
	\details The function makes a new copy of a nul-terminated string 
	and returns pointer to the new string. If the input is NULL or there 
	is not enough memory, it returns NULL. Use cmpack_free() function to 
	release the memory. Unlike cmpack_realloc() this function stores the 
	given name of the source file and line number.
	\param[in] src				source string
	\param[in] file				source file name
	\param[in] line				source line index
*/
CMPACK_EXPORT(char*, cmpack_strdup_dbg, (const char* src, const char* file, int line));

#ifdef CMPACK_DEBUG_HEAP
#ifndef CMPACK_MEM_DO_NOT_USE_DEFINES
#define cmpack_malloc(size)			cmpack_malloc_dbg((size), __FILE__, __LINE__)
#define cmpack_calloc(num, size)	cmpack_calloc_dbg((num), (size), __FILE__, __LINE__)
#define cmpack_realloc(ptr, size)	cmpack_realloc_dbg((ptr), (size), __FILE__, __LINE__)
#define cmpack_strdup(src)			cmpack_strdup_dbg((src), __FILE__, __LINE__)
#endif
#endif

/**
	\brief Get number of bytes allocated on the heap (debug only)
	\details If the library was compiled with CMPACK_DEBUG_HEAP preprocessor macro,
	the function returns a number of bytes that were allocated by cmpack_xxx
	functions and not freed. You can use it to find out how much memory was
	consumed between two checkpoints. Without the CMPACK_DEBUG_HEAP macro, it returns zero.
	\return Size of allocated memory in bytes
*/
CMPACK_EXPORT(size_t, cmpack_allocsize, (void));

/********************** String utilities ***********************/

/**
	\brief Remove leading and trailing white spaces
	\details The function modifies the string inplace
	\param[in,out] str		a nul-terminated string
	\return Save value as 'str' parameter
*/
CMPACK_EXPORT(char*, cmpack_str_trim, (char* str));

/******************** Date & time utilities ********************/

/**
	\brief Fill date structure
	\param[out] date		date structure
	\param[in] year			year in 4-digit format
	\param[in] month		month (1-12)
	\param[in] day			day (1-31)
*/
CMPACK_EXPORT(void, cmpack_date_set, (CmpackDate* date, int year, int month, int day));

/**
	\brief Fill time structure
	\param[out] time		time structure
	\param[in] hour			hour (0-23)
	\param[in] minute		minute (0-59)
	\param[in] second		second (0-59)
	\param[in] milisecond	milisecond (0-999)
*/
CMPACK_EXPORT(void, cmpack_time_set, (CmpackTime* time, int hour, int minute, int second, int milisecond));

/**  
	\brief Fill date and time structure
	\param[out] datetime	date and time structure
	\param[in] year			year in 4-digit format
	\param[in] month		month (1-12)
	\param[in] day			day (1-31)
	\param[in] hour			hour (0-23)
	\param[in] minute		minute (0-59)
	\param[in] second		second (0-59)
	\param[in] milisecond	milisecond (0-999)
*/
CMPACK_EXPORT(void, cmpack_datetime_set, (CmpackDateTime* datetime, int year, int month, int day,
	int hour, int minute, int second, int milisecond));

/**
	\brief Parse string and return parts of the date
	\details The function decodes a date from a nul-terminated string.
	\param[in] datestr		date string (YYYY-MM-DD)
	\param[out] date		date parts
	\return zero on success or error code on failure
*/
CMPACK_EXPORT(int, cmpack_strtodate, (const char* datestr, CmpackDate* date));

/**
	\brief Parse string and return parts of the time
	\details The function decodes a time from a nul-terminated string.
	\param[in] timestr		time string (HH:MM:SS.SSS)
	\param[out] time		time parts
	\return zero on success or error code on failure
*/
CMPACK_EXPORT(int, cmpack_strtotime, (const char* timestr, CmpackTime* time));

/**
	\brief Print date to the string
	\details The function prints a date to given memory buffer
	\param[in] date			date parts
	\param[out] buf			output string
	\param[in] buflen		size of buffer in chars
	\return zero on success or error code on failure.
*/
CMPACK_EXPORT(int, cmpack_datetostr, (const CmpackDate* date, char* buf, int buflen));

/**
	\brief Print time to the string
	\details The function prints a time to given memory buffer
	\param[in] time			time parts
	\param[out] buf			output string
	\param[in] buflen		size of buffer in chars
	\return zero on success or error code on failure.
*/
CMPACK_EXPORT(int, cmpack_timetostr, (const CmpackTime* time, char* buf, int buflen));

/**
	\brief Convert date and time parts to Julian date
	\details The function converts given Gregorian date to Julian date
	\param[in] datetime		Gregorian date
	\return Julian date on success or zero on failure 
*/
CMPACK_EXPORT(double, cmpack_encodejd, (const CmpackDateTime* datetime));

/**
	\brief Convert Julian date to parts of date and time
	\details The function converts given Julian date to Gregorian date
	\param[in] jd			Julian date
	\param[out] datetime	Gregorian date
	\return zero on success or error code on failure.
*/
CMPACK_EXPORT(int, cmpack_decodejd, (double jd, CmpackDateTime* datetime));

/******************** Conversion of coordinates **********************/

/**
	\brief Convert the string to R.A.
	\details The function converts nul-terminated string to right ascension
	\param[in] buf			input string 
	\param[out] ra			right ascension in hours (0..24)
	\return zero on success or error code on failure.
*/
CMPACK_EXPORT(int, cmpack_strtora, (const char* buf, double* ra));

/**
	\brief Converts the string to DEC.
	\details The function converts nul-terminated string to declination
	\param[in] buf			input string
	\param[out] dec			declination in degrees (-90..90)
	\return zero on success or error code on failure.
*/
CMPACK_EXPORT(int, cmpack_strtodec, (const char* buf, double* dec));

/**
	\brief Converts the R.A. value to the string
	\details The function prints right ascension to memory buffer
	\param[in] ra			right ascension in hours
	\param[out] buf			output string (HH MM SS)
	\param[in] buflen		size of buffer in chars
	\return zero on success or error code on failure.
*/
CMPACK_EXPORT(int, cmpack_ratostr, (double ra, char* buf, int buflen));

/**
\brief Converts the R.A. value to the string (with optional number of decimal places)
\details The function prints right ascension to memory buffer
\param[in] ra			right ascension in hours
\param[out] buf			output string (HH MM SS.SSS)
\param[in] buflen		size of buffer in chars
\param[in] places		decimal places of arcseconds (0, 1, 2 or 3)
\return zero on success or error code on failure.
*/
CMPACK_EXPORT(int, cmpack_ratostr2, (double ra, char* buf, int buflen, int places));

/**
	\brief Converts the DEC. value to the string
	\details The function prints declination to memory buffer
	\param[in] dec			declination in degrees
	\param[out] buf			output string (+DDD MM SS)
	\param[in] buflen		size of buffer in chars
	\return pointer to allocated string or zero on failure
*/
CMPACK_EXPORT(int, cmpack_dectostr, (double dec, char* buf, int buflen));

/**
\brief Converts the DEC. value to the string (with optional number of decimal places)
\details The function prints declination to memory buffer
\param[in] dec			declination in degrees
\param[out] buf			output string (+DDD MM SS.SSS)
\param[in] buflen		size of buffer in chars
\param[in] places		decimal places of arcseconds (0, 1, 2 or 3)
\return pointer to allocated string or zero on failure
*/
CMPACK_EXPORT(int, cmpack_dectostr2, (double dec, char* buf, int buflen, int places));

/**
	\brief Converts string to latitude.
	\details The function converts nul-terminated string to latitude
	\param[in] buf			input string
	\param[out] lat			latitude in degrees (-90..90)
	\return zero on success or error code on failure.
*/
CMPACK_EXPORT(int, cmpack_strtolat, (const char* buf, double* lat));

/**
	\brief Converts string to longitude.
	\details The function converts nul-terminated string to longitude
	\param[in] buf			input string
	\param[out] lon			longitude in degrees (-180..180)
	\return zero on success or error code on failure.
*/
CMPACK_EXPORT(int, cmpack_strtolon, (const char* buf, double* lon));

/**
	\brief Converts the latitude to the string
	\details The function prints longitude to memory buffer
	\param[in] lat			latitude in degrees
	\param[out] buf			output string (N DDD MM SS)
	\param[in] buflen		size of buffer in chars
	\return zero on success or error code on failure.
*/
CMPACK_EXPORT(int, cmpack_lattostr, (double lat, char* buf, int buflen));

/**
	\brief Converts the longitude to the string
	\details The function prints longitude to memory buffer
	\param[in] lon			longitude in degrees
	\param[out] buf			output string (E DDD MM SS)
	\param[in] buflen		size of buffer in chars
	\return zero on success or error code on failure.
*/
CMPACK_EXPORT(int, cmpack_lontostr, (double lon, char* buf, int buflen));

/************************ Math functions **********************************/

/**
	\brief Computes robust mean and standard deviation
	\details The function computes the robust mean and standard deviation
	for given set of values.
	\param[in] n			number of elements
	\param[in] A			array of elements
	\param[out] mean		robust mean
	\param[out] sig			standard deviation
	\return zero on success or error code on failure.
*/
CMPACK_EXPORT(int, cmpack_robustmean, (int n, double* A, double* mean, double* sig));

/******************************   CmpackBorder methods   ********************************/

/**
	\brief Initialize borders
	\details Sets border structure to given components
	\param[in] border		border structure to be initialized
	\param[in] left			left border 
	\param[in] top			top border 
	\param[in] right		right border 
	\param[in] bottom		bottom border 
*/
CMPACK_EXPORT(void, cmpack_border_set, (CmpackBorder* border, int left, int top, int right, int bottom));

/**
	\brief Clear borders
	\details Sets border components to zero
	\param[in] border		border structure to be initialized
*/
CMPACK_EXPORT(void, cmpack_border_clear, (CmpackBorder* border));

/******************************   CmpackMatrix methods   ********************************/

/**
	\brief Initialize the affine transformation
	\details Sets matrix to given components
	\param[in] matrix		a matrix to be initialized
    \param[in] xx			xx component of the affine transformation
	\param[in] yx			yx component of the affine transformation
    \param[in] xy			xy component of the affine transformation
	\param[in] yy			yy component of the affine transformation
    \param[in] x0			x translation component of the affine transformation
	\param[in] y0			y translation component of the affine transformation
*/
CMPACK_EXPORT(void, cmpack_matrix_init, (CmpackMatrix* matrix, double xx, double yx, double xy, double yy,
	double x0, double y0));

/**
	\brief Set matrix to identity transformation
	\details Sets matrix to identity transformation
	\param[in] matrix		a matrix to be initialized
*/
CMPACK_EXPORT(void, cmpack_matrix_identity, (CmpackMatrix* matrix));

/**
	\brief Copy matrix 
	\details Makes copy of the transformation matrix
	\param[out] dst			target matrix
	\param[in] src			source matrix
*/
CMPACK_EXPORT(void, cmpack_matrix_copy, (CmpackMatrix* dst, const CmpackMatrix* src));

/**
	\brief Transform a point using given affine transformation
	\details Transforms given point (x, y) using the affine transformation
	specified by given matrix.
	\param[in] matrix		a transformation matrix
	\param[in,out] x		x coordinate of the source and the target point
	\param[in,out] y		y coordinate of the source and the target point
*/
CMPACK_EXPORT(void, cmpack_matrix_transform_point, (const CmpackMatrix* matrix, double* x, double* y));

/**
	\brief Reverse transform of a point using given affine transformation
	\details Transforms given point (x, y) using the affine transformation
	specified by inverse matrix to a given matrix. The get good performance
	in terms of speed and precision, the inverse matrix is not created.
	\param[in] matrix		a transformation matrix
	\param[in,out] x		x coordinate of the source and the target point
	\param[in,out] y		y coordinate of the source and the target point
*/
CMPACK_EXPORT(void, cmpack_matrix_reverse_transform, (const CmpackMatrix* matrix, double* x, double* y));

/**
	\brief Left multiply a matrix by another matrix
	\details The function modifies the matrix by left multiplying it by A.
	\param[in,out] matrix	a matrix (right operand, product)
	\param[in] a			matrix A (left operand)
*/
CMPACK_EXPORT(void, cmpack_matrix_left_multiply, (CmpackMatrix* matrix, const CmpackMatrix* a));

/******************************   Regressions   ********************************/

CMPACK_EXPORT(void, cmpack_quadratic_fit, (int length, const double* jd, const double* yval, double* coeff));

#ifdef __cplusplus
}
#endif

#endif
