# include "relphot.h"
void GetConfig (char *config, char *field, char *format, int N, void *ptr);

void ConfigInit (int *argc, char **argv) {

  double ZERO_POINT;
  char  *config, *file;
  char   PhotCodeFile[256];

  /*** load configuration info ***/
  file = SelectConfigFile (argc, argv, "ptolemy");
  config = LoadConfigFile (file);
  if (config == (char *) NULL) {
    fprintf (stderr, "ERROR: can't find configuration file %s\n", file);
    if (file != (char *) NULL) free (file);
    exit (0);
  }
  if (VERBOSE) fprintf (stderr, "loaded config file: %s\n", file);

  GetConfig (config, "MAG_LIM",                "%lf", 0, &MAG_LIM);
  GetConfig (config, "SIGMA_LIM",              "%lf", 0, &SIGMA_LIM);
  GetConfig (config, "STAR_SCATTER",           "%lf", 0, &STAR_SCATTER);
  GetConfig (config, "IMAGE_SCATTER",          "%lf", 0, &IMAGE_SCATTER);
  GetConfig (config, "IMAGE_OFFSET",           "%lf", 0, &IMAGE_OFFSET);
  MAG_LIM *= 1000;
  SIGMA_LIM *= 1000;
  STAR_SCATTER *= 1000;
  IMAGE_SCATTER *= 1000;
  IMAGE_OFFSET *= 1000;

  GetConfig (config, "STAR_CHISQ",             "%lf", 0, &STAR_CHISQ);
  GetConfig (config, "STAR_TOOFEW",            "%d",  0, &STAR_TOOFEW);
  GetConfig (config, "IMAGE_TOOFEW",           "%d",  0, &IMAGE_TOOFEW);
  GetConfig (config, "IMAGE_GOOD_FRACTION",    "%lf", 0, &IMAGE_GOOD_FRACTION);

  GetConfig (config, "IMAGE_CATALOG",          "%s",  0, ImageCat);
  GetConfig (config, "IMAGE_CATALOG_TEMPLATE", "%s",  0, ImageTemplate);
  GetConfig (config, "CATALOG_TEMPLATE",       "%s",  0, CatTemplate);
  GetConfig (config, "GSCFILE",                "%s",  0, GSCFILE);
  GetConfig (config, "CATDIR",                 "%s",  0, CATDIR);
  GetConfig (config, "PHOTCODE_FILE",          "%s",  0, PhotCodeFile);
  GetConfig (config, "ZERO_PT",                "%lf", 0, &ZERO_POINT);

  GetConfig (config, "RELPHOT_GRID_X",         "%d",  0, &RELPHOT_GRID_X);
  GetConfig (config, "RELPHOT_GRID_Y",         "%d",  0, &RELPHOT_GRID_Y);
  GetConfig (config, "RELPHOT_GRID_BINNING",   "%d",  0, &RELPHOT_GRID_BINNING);
  GetConfig (config, "CAMERA_CONFIG",          "%s",  0, CameraConfig);

  if (!LoadPhotcodes (PhotCodeFile)) {
    fprintf (stderr, "error loading photcodes\n");
    exit (1);
  }
  SetZeroPoint (ZERO_POINT);

  free (config);
  free (file);

}

void GetConfig (char *config, char *field, char *format, int N, void *ptr) {

  int status;

  status = ScanConfig (config, field, format, N, ptr);
  if (!status) {
    fprintf (stderr, "error in config, cannot find %s\n", field);
    exit (1);
  }
  return;
}
