# include "dvo.h"

int avextract (int argc, char **argv) {
  
  Catalog catalog;
  Graphdata graphsky;
  RegionFile *regions;
  PhotCode *code;
  Vector *vec;

  char filename[256], catdir[256], *p;
  int i, j, m, N, NPTS, param;
  int Ngraph, Nsec, Nregions, mode;

  regions = NULL;
  catalog.average = NULL; 
  catalog.secfilt = NULL;
  catalog.measure = NULL;

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

  /* load data about plot windows */
  Ngraph = 0;
  if (!GetGraphData (&graphsky, NULL, &Ngraph)) goto escape;
 
  /* find CATDIR in config system */
  VarConfig ("CATDIR", "%s", catdir);

  /* grab value of photcode, if available */
  code = NULL;
  mode = MAG_AVE;
  if (N = get_argument (argc, argv, "-photcode")) {
    remove_argument (N, &argc, argv);
    code = GetPhotcodebyName (argv[N]);
    if (code == NULL) {
      fprintf (stderr, "photcode not found in photcode table\n");
      goto usage;
    }
    remove_argument (N, &argc, argv);
  }

  /* interpret command-line options */
  if (!SetPhotSelections (&argc, argv)) goto usage;
  if (argc != 3) { goto usage; }

  /* identify selection */
  param = GetAverageParam (argv[2]);
  if (param == AVE_ZERO) {
    if (!GetPhotcodeInfo (argv[2], &code, &mode)) {
      GetAverageParam ("help");
      fprintf (stderr, "value may also be a valid photcode\n");
      fprintf (stderr, "photcodes or 'mag' may have optional magnitude mode: mag,[Mave, Mref]\n");
      goto escape;
    }
    param = AVE_MAG;
    for (p = argv[2]; *p != 0; p++) { 
      if (*p == '.') *p = ':';
    }
  } 
  if ((vec = SelectVector (argv[2], ANYVECTOR, TRUE)) == NULL) goto escape;

  /* need valid code for some params: */
  switch (param) {
    case AVE_MAG:
    case AVE_dMAG:
    case AVE_Xm:
    case AVE_TYPE:
    case AVE_NCODE:
    case AVE_NPHOT: 
      if (code == NULL) goto escape;
      if (code[0].type == PHOT_DEP) goto escape;
      if (code[0].type == PHOT_REF) goto escape;
      break;
    default:
      break;
  }

  /* determine region-file names */
  if (!strcmp (argv[1], "all")) {
    float Radius;
    Radius = MAX (fabs(graphsky.xmax), fabs(graphsky.ymax));
    regions = find_regions (graphsky.coords.crval1, graphsky.coords.crval2, Radius, &Nregions);
    if (!SetImageSelection (param, &graphsky, TRUE)) goto escape;
  } else {
    Nregions = 1;
    ALLOCATE (regions, RegionFile, 1);
    strcpy (regions[0].name, argv[1]);
    if (!SetImageSelection (param, NULL, FALSE)) goto escape;
  }

  /* create storage vector */
  N = 0;
  NPTS = 1000;
  REALLOCATE (vec[0].elements, float, NPTS);

  for (i = 0; i < Nregions; i++) {
    /* lock, load, unlock catalog */
    sprintf (filename, "%s/%s", catdir, regions[i].name);
    catalog.filename = filename;
    switch (lock_catalog (&catalog, LCK_SOFT)) {
    case 2:
      unlock_catalog (&catalog);
    case 0:
      continue;
    }
    if (!load_catalog (&catalog, LOAD_AVES | LOAD_MEAS | LOAD_SECF, FALSE)) {
      unlock_catalog (&catalog);
      continue;
    }
    unlock_catalog (&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*Nsec], &catalog.measure[m], param);
      N++;
      if (N == NPTS - 1) {
	NPTS += 2000;
	REALLOCATE (vec[0].elements, float, NPTS);
      }
    }
    if (catalog.average != NULL) free (catalog.average);
    if (catalog.secfilt != NULL) free (catalog.secfilt);
    if (catalog.measure != NULL) free (catalog.measure);
    catalog.average = (Average *) NULL; 
    catalog.secfilt = (SecFilt *) NULL;
    catalog.measure = (Measure *) NULL;
  }
  vec[0].Nelements = N;
  REALLOCATE (vec[0].elements, float, MAX(1,N));

  if (regions != NULL) free (regions);
  FreeImageSelection ();
  return (TRUE);

usage:
  fprintf (stderr, "USAGE: avextract (from) (value) [options]\n");
  fprintf (stderr, "  from: cpt name or 'all'\n");
  fprintf (stderr, "  value: average.parameter or photcode\n");
  return (FALSE);

escape:
  fprintf (stderr, "error in avextract\n");
  if (regions != NULL) free (regions);
  FreeImageSelection ();
  if (catalog.average != NULL) free (catalog.average);
  if (catalog.secfilt != NULL) free (catalog.secfilt);
  if (catalog.measure != NULL) free (catalog.measure);
  return (FALSE);
}
