# include "dvoshell.h"

int avextract (int argc, char **argv) {
  
  int i, j, m, N, NPTS, param;
  int Nsecfilt, mode;
  char *RegionName, *RegionList, *p;

  Catalog catalog;
  SkyList *skylist;
  PhotCode *code;
  Vector *vec;

  /* defaults */
  skylist = NULL;
  RegionName = NULL;
  RegionList = NULL;
  code = NULL;
  mode = MAG_AVE;
  dvo_catalog_init (&catalog, TRUE);

  /* load photcode information */
  if (!InitPhotcodes ()) goto escape;
  Nsecfilt = GetPhotcodeNsecfilt ();

  /* interpret command-line options */
  SetSelectionParam (0);
  if (!SetRegionSelection (&argc, argv, &RegionName, &RegionList)) goto escape;
  if (!SetPhotSelections (&argc, argv, 1)) goto usage;

  /* interpret required command-line arguments: mextract (value) */
  if (argc != 2) { goto usage; }
  param = GetAverageParam (argv[1]);
  if (param == AVE_ZERO) {
    if (!GetPhotcodeInfo (argv[1], &code, &mode)) {
      GetAverageParamHelp ();
      goto escape;
    }
    param = AVE_MAG;
    for (p = argv[1]; *p != 0; p++) { 
      if (*p == '.') *p = ':';
    }
  } 
  if (!TestPhotSelections (&code, &mode, param)) goto escape;

  /* load region corresponding to selection above */
  if ((skylist = SelectRegions (RegionName, RegionList)) == NULL) goto escape;

  /* create storage vector */
  N = 0;
  NPTS = 1;
  if ((vec = SelectVector (argv[1], ANYVECTOR, TRUE)) == NULL) goto escape;

  // XXX need to add interrupt test to this loop
  for (i = 0; i < skylist[0].Nregions; i++) {
    /* lock, load, unlock catalog */
    catalog.filename = skylist[0].filename[i];
    catalog.catflags = LOAD_AVES | LOAD_MEAS | LOAD_SECF;
    catalog.Nsecfilt = 0;

    // an error exit status here is a significant error
    if (!dvo_catalog_open (&catalog, NULL, FALSE, "r")) {
      fprintf (stderr, "ERROR: failure to open catalog file %s\n", catalog.filename);
      exit (2);
    }
    dvo_catalog_unlock (&catalog);

    for (j = 0; j < catalog.Naverage; j++) {
      m = catalog.average[j].offset;
      vec[0].elements[N] = ExtractAverages (code, mode, &catalog.average[j], &catalog.secfilt[j*Nsecfilt], &catalog.measure[m], param);
      N++;
      CHECK_REALLOCATE (vec[0].elements, float, NPTS, N, 2000);
    }
    dvo_catalog_free (&catalog);
  }
  vec[0].Nelements = N;
  REALLOCATE (vec[0].elements, float, MAX(1,N));

  SkyListFree (skylist, ((RegionName != NULL) || (RegionList != NULL)));
  return (TRUE);

usage:
  gprint (GP_ERR, "USAGE: avextract (value) [options]\n");
  gprint (GP_ERR, "  value: average.parameter or photcode\n");

escape:
  SkyListFree (skylist, ((RegionName != NULL) || (RegionList != NULL)));
  dvo_catalog_free (&catalog);
  if (RegionName != NULL) free (RegionName);
  if (RegionList != NULL) free (RegionList);
  return (FALSE);
}
