# include "photdbc.h"

int success = TRUE;

void WarnConfig (char *config, char *key, char * mode, int N, void *var) {
  if (!ScanConfig (config, key, mode, N, var)) {
    fprintf (stderr, "missing config variable %s\n", key);
    success = FALSE;
  }
}

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

  char *config, *file;
  char CatdirPhotcodeFile[256];
  char MasterPhotcodeFile[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);

  WarnConfig (config, "PHOTDBC_JOIN_RADIUS",       "%lf", 0, &JOIN_RADIUS);
  // WarnConfig (config, "UNIQ_RADIUS",            "%lf", 0, &UNIQ_RADIUS);

  // WarnConfig (config, "XMIN",                   "%lf", 0, &XMIN);
  // WarnConfig (config, "XMAX",                   "%lf", 0, &XMAX);
  // WarnConfig (config, "YMIN",                   "%lf", 0, &YMIN);
  // WarnConfig (config, "YMAX",                   "%lf", 0, &YMAX);
  
  // WarnConfig (config, "DMCAL_MIN",              "%lf", 0, &tmp);  DMCAL_MIN = 1000*tmp;
  // WarnConfig (config, "MMIN",                   "%lf", 0, &tmp);  MMIN      = 1000*tmp;
  // WarnConfig (config, "MMAX",                   "%lf", 0, &tmp);  MMAX      = 1000*tmp;
  // WarnConfig (config, "DMSYS",                  "%lf", 0, &tmp);  DMSYS     = SQ(1000*tmp);
  // WarnConfig (config, "DMGAIN",                 "%lf", 0, &DMGAIN); 
  // WarnConfig (config, "CHISQ_MAX",              "%lf", 0, &CHISQ_MAX);

  ScanConfig (config, "SIGMA_MAX",              "%lf", 0, &SIGMA_MAX);
  ScanConfig (config, "AVE_SIGMA_LIM",          "%lf", 0, &AVE_SIGMA_LIM);
  ScanConfig (config, "NMEAS_MIN",              "%d",  0, &NMEAS_MIN);

  WarnConfig (config, "GSCFILE",                "%s",  0, GSCFILE);
  WarnConfig (config, "CATDIR",                 "%s",  0, CATDIR);
  ScanConfig (config, "CATMODE",                "%s",  0, CATMODE);
  ScanConfig (config, "CATFORMAT",              "%s",  0, CATFORMAT);
  ScanConfig (config, "PHOTCODE_FILE",         	"%s",  0, MasterPhotcodeFile);

  sprintf (ImageCat, "%s/Images.dat", CATDIR);

  WarnConfig (config, "ZERO_PT",                "%lf", 0, &ZERO_POINT);

  if (!success) { 
    fprintf (stderr, "missing config parameter\n");
    exit (1);
  }

  if (*CATMODE == 0) strcpy (CATMODE, "RAW");
  if (*CATFORMAT == 0) strcpy (CATFORMAT, "ELIXIR");

  /* XXX this does not yet write out the master photcode table */
  sprintf (CatdirPhotcodeFile, "%s/Photcodes.dat", CATDIR);
  if (!LoadPhotcodes (CatdirPhotcodeFile, MasterPhotcodeFile, TRUE)) {
    fprintf (stderr, "error loading photcode table %s or master file %s\n", CatdirPhotcodeFile, MasterPhotcodeFile);
    exit (1);
  }
  SetZeroPoint (ZERO_POINT);

  free (config);
  free (file);
}
