# include <ohana.h>
# include <loneos.h>
# include <signal.h>

typedef struct {
  double X;
  double Y;
  double R;
  double D;
  double M, dM;
  char   dophot;
  double sky;
  double fx, fy, df;
  double Mgal, Map;
  int found;
} Stars;

/* global variables set in parameter file */
char   ImageCat[256];
char   ImageTemplate[256];
char   CatTemplate[256];
char   GSCFILE[256];
char   CATDIR[256];
double DEFAULT_RADIUS, NSIGMA, SNLIMIT;
double ALPHA, ZeroPt;
double Latitude, SiderealTime;
int    VERBOSE, FORCE;
int    XOVERSCAN, YOVERSCAN;
int    ACCEPT_ASTROM;

PhotCode *thiscode;

char DateKeyword[64];
char DateMode[64];
char UTKeyword[64];
char MJDKeyword[64];
char JDKeyword[64];
char ExptimeKeyword[64];
char AirmassKeyword[64];
char CCDNumKeyword[64];
char STKeyword[64];
char SubpixDatafile[256];

int CalReference;
int CalColor;
int CALIBRATE;
int DUMP_MATCHES;
int ONLY_IMAGES;
int SKIP_MISSED;

double get_subpix (double x, double y);
void load_subpix ();
double scat_subpix (double x, double y);

int Shutdown ();  
void TrapSignal (int sig);
int main (int argc, char **argv);
int SetSignals ();
int gcatalog (Catalog *catalog);
GSCRegion *gregions (Image *image, int *Nregions);
Image *gimages (FILE *f, Image *image, int *Npimage);
int edge_check (double *x1, double *y1, double *x2, double *y2);
double opening_angle (double x1, double y1, double x2, double y2, double x3, double y3);
void wimage (FILE *f, int dbstate, Image *image, int Nstars);
Stars *gstars (char *file, int *NSTARS, Image *image);
void find_matches (GSCRegion *region, Stars *stars, int Nstars, Catalog *catalog, Image *image, Image *pimage, int Nimage);
int in_image (double r, double d, Image *image);
void wcatalog (Catalog *catalog);
void ConfigInit (int *argc, char **argv);
int hms_to_deg (double *h0, double *h1, double *d0, double *d1, char *string);
void aregion (GSCRegion *region, FILE *f, double ra, double dec);
void wimage (FILE *f, int dbstate, Image *image, int Nstars);
void check_permissions (char *basefile);
void make_backup (char *filename);
void help ();
int args (int argc, char **argv);
int parse_time (Header *header);
void uppercase (char *string);
void mkcatalog (GSCRegion *region, Catalog *catalog);
double airmass (double ra, double dec, double st, double latitude);

void SaveCalibration (float M, float dM, float Mr, float dMr, float Mc, float A, int N, float ra, float dec, float x, float y);
void InitCalibration ();
void FindCalibration (Image *image);
void fsort (float *X, int N);
void sort_lists (float *X, float *Y, int *S, int N);
void fsort2 (float *X, float *Y, int N);
