# include "dvo.h"

int imlist (int argc, char **argv) {
  
  int i, j, N, Nimage, *subset, Nsubset, TimeSelect, RegionSelect, TimeFormat, NameSelect;
  int PhotcodeSelect;
  time_t tzero, TimeReference;
  double r, d, trange, t;
  char *name;
  int Ngraph;
  Image *image;
  Graphdata graphmode;
  PhotCode *PhotcodeValue;

  Ngraph = 0;
  if (!GetGraphData (&graphmode, NULL, &Ngraph)) return (FALSE);

  TimeSelect = FALSE;
  if (N = get_argument (argc, argv, "-time")) {
    remove_argument (N, &argc, argv);
    if (!str_to_time (argv[N], &tzero)) { 
      fprintf (stderr, "syntax error\n");
      return (FALSE);
    }
    remove_argument (N, &argc, argv);
    if (!str_to_dtime (argv[N], &trange)) { 
      fprintf (stderr, "syntax error\n");
      return (FALSE);
    }
    remove_argument (N, &argc, argv);
    TimeSelect = TRUE;
    fprintf (stderr, "plotting in range %ds - %ds (%f seconds)\n", (int)tzero, (int)(tzero + trange), trange);
  }

  RegionSelect = FALSE;
  if (N = get_argument (argc, argv, "-region")) {
    remove_argument (N, &argc, argv);
    RegionSelect = TRUE;
  }

  PhotcodeSelect = FALSE;
  if (N = get_argument (argc, argv, "-photcode")) {
    PhotcodeSelect = TRUE;
    remove_argument (N, &argc, argv);
    PhotcodeValue = GetPhotcodebyName (argv[N]);
    if (PhotcodeValue == NULL) {
      fprintf (stderr, "photcode not found in photcode table\n");
      return (FALSE);
    }
    remove_argument (N, &argc, argv);
  }

  NameSelect = FALSE;
  if (N = get_argument (argc, argv, "-name")) {
    remove_argument (N, &argc, argv);
    name = strcreate (argv[N]);
    remove_argument (N, &argc, argv);
    NameSelect = TRUE;
  }

  if (argc != 1) {
    fprintf (stderr, "USAGE: image [-time start range] [-region] [-name string]\n");
    return (FALSE);
  }
  
  image = LoadImages (&Nimage);
  if (Nimage == 0) {
    return (FALSE);
  }
  image_subset (image, Nimage, &subset, &Nsubset, &graphmode, RegionSelect, tzero, trange, TimeSelect);

  GetTimeFormat (&TimeReference, &TimeFormat);

  for (j = 0; j < Nsubset; j++) {
    i = subset[j];
    if (NameSelect && (strstr (image[i].name, name) == (char *) NULL)) continue;
    if (PhotcodeSelect) {
      if (PhotcodeValue[0].type == PHOT_DEP) {
	if (PhotcodeValue[0].code != image[i].source) continue;
      } else {
	if (PhotcodeValue[0].code != GetPhotcodeEquivCodebyCode (image[i].source)) continue;
      }
    }
    t = TimeValue (image[i].tzero, TimeReference, TimeFormat);
    XY_to_RD (&r, &d, 0.5*image[i].NX, 0.5*image[i].NY, &image[i].coords);
    fprintf (GetOutfile(), "%3d %s %8.4f %8.4f %f %5d %2d %4.2f %5.3f %5.3f\n", 
	     i, image[i].name, r, d, t, image[i].nstar, image[i].source, 0.001*image[i].secz, 0.001*image[i].Mcal, 0.001*image[i].dMcal);
  }

  free (subset);
  free (image);
  return (TRUE);
}
