# include "relastro.h"

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

  char  *config, *file;
  char CatdirPhotcodeFile[256];
  char MasterPhotcodeFile[256];
  struct stat filestat;
  int status;

  /*** 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, "RELASTRO_SIGMA_LIM",     "%lf", 0, &SIGMA_LIM);

  // XXX these are used in relphot to identify poor stars / images -- define
  // an equivalent concept here?
  // GetConfig (config, "STAR_SCATTER",           "%lf", 0, &STAR_SCATTER);
  // GetConfig (config, "IMAGE_SCATTER",          "%lf", 0, &IMAGE_SCATTER);
  // GetConfig (config, "IMAGE_OFFSET",           "%lf", 0, &IMAGE_OFFSET);
  // GetConfig (config, "STAR_CHISQ",             "%lf", 0, &STAR_CHISQ);

  GetConfig (config, "PM_DT_MIN",              "%lf", 0, &PM_DT_MIN);
  GetConfig (config, "PM_TOOFEW",              "%d",  0, &PM_TOOFEW);
  GetConfig (config, "POS_TOOFEW",             "%d",  0, &POS_TOOFEW);

  GetConfig (config, "GSCFILE",                "%s",  0, GSCFILE);
  GetConfig (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);

  if (!ScanConfig (config, "SKY_DEPTH",         "%d",  0, &SKY_DEPTH)) {
    SKY_DEPTH = 2;
  }
  if (!ScanConfig (config, "SKY_TABLE",         "%s",  0, SKY_TABLE)) {
    SKY_TABLE[0] = 0;
  }

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

  // check for existence of CATDIR
  status = stat (CATDIR, &filestat);
  if (status == -1) {
    fprintf (stderr, "directory %s does not exist, giving up\n", CATDIR);
    exit (1);
  } 

  /* update master photcode table if not defined */
  sprintf (CatdirPhotcodeFile, "%s/Photcodes.dat", CATDIR);
  if (!LoadPhotcodes (CatdirPhotcodeFile, MasterPhotcodeFile)) {
    fprintf (stderr, "error loading photcode table %s or master file %s\n", CatdirPhotcodeFile, MasterPhotcodeFile);
    exit (1);
  }
  SetZeroPoint (25.0);

  free (config);
  free (file);

}

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

  char *status;

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