# include "relastro.h"

int main (int argc, char **argv) {

  int i, status, Ncatalog;
  Catalog *catalog;
  FITS_DB db;

  SkyList *skylist = NULL;

  /* get configuration info, args */
  initialize (argc, argv);

  /* register database handle with shutdown procedure */
  set_db (&db);

  /* lock and load the image db table */
  status = dvo_image_lock (&db, ImageCat, 60.0, (UPDATE ? LCK_XCLD : LCK_SOFT));
  if (!status) Shutdown ("ERROR: failure to lock image catalog %s", db.filename);
  if (db.dbstate == LCK_EMPTY) Shutdown ("ERROR: No images in catalog %s (1)", db.filename);
  if (!dvo_image_load (&db, VERBOSE, FALSE)) Shutdown ("can't read image catalog %s", db.filename);

  /* load regions and images based on specified sky patch */
  // XXX need to mimic old-style load by passing patch name
  // XXX need to reduce number of global variables in use.
  // XXX this is fairly lame: argv[1] is photcode if UserPatchSelect is true
  skylist = load_images (&db, argv[1], &UserPatch, UserPatchSelect);

  /* unlock, if we can (else, unlocked below) */
  if (!UPDATE) dvo_image_unlock (&db); 

  /* load catalog data from region files */
  catalog = load_catalogs (skylist, &Ncatalog);

  /* match measurements with images, mosaics */
  initImageBins  (catalog, Ncatalog);
  initMosaicBins (catalog, Ncatalog);
  initGridBins   (catalog, Ncatalog);
  initMrel (catalog, Ncatalog);

  findImages (catalog, Ncatalog);
  findMosaics (catalog, Ncatalog);  /* also sets Grid values */
  SAVEPLOT = FALSE;

  setExclusions (catalog, Ncatalog);

  if (PLOTSTUFF) {
    plot_star_coords (catalog, Ncatalog);
    plot_mosaic_fields (catalog);
  }

  /* major modes */
  if (UpdateObjects) {
    UpdateObjects (catalog, Ncatalog);
  }
  if (UpdateImages) {
    UpdateImages (catalog, Ncatalog);
  }

  /* put these types of functions inside the update functions
      plot_scatter (catalog, Ncatalog); 
      plot_grid (catalog); 
      plot_mosaics ();
      plot_images ();
      plot_stars (catalog, Ncatalog);
      plot_chisq (catalog, Ncatalog);
  */

  if (!UPDATE) exit (0);

  /* need to figure out how to update images, etc */
  dvo_image_update (&db, VERBOSE);
  dvo_image_unlock (&db); 

  exit (0);
}

