# include "relphot.h"
/** I'm not currently setting the lockfiles.  this should be fixed! **/

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

  char c;
  int i, Ncatalog;
  Catalog *catalog, tcatalog;
  GSCRegion fullregion, *region;

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

  /* load regions and images based on seed region */
  region = load_images (argv[1], &Ncatalog, &fullregion);

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

  /* 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);
  }

  /* determine fit values */
  for (i = 0; i < NLOOP; i++) {
    setMrel  (catalog, Ncatalog);
    setMcal  (catalog, FALSE);
    setMmos  (catalog, FALSE);
    setMgrid (catalog);
    
    if (PLOTSTUFF) {
      plot_scatter (catalog, Ncatalog); 
      plot_grid (catalog); 
      plot_mosaics ();
      plot_images ();
      plot_stars (catalog, Ncatalog);
      plot_chisq (catalog, Ncatalog);
    }
    if ((i == 1) || (i == 5) || (i ==  9) || (i == 13)) clean_measures (catalog, Ncatalog, FALSE); 
    if ((i == 2) || (i == 6) || (i == 10) || (i == 14)) clean_stars (catalog, Ncatalog);
    if ((i == 4) || (i == 8) || (i == 12) || (i == 16)) clean_mosaics (catalog, Ncatalog);
    if ((i == 4) || (i == 8) || (i == 12) || (i == 16)) clean_images ();
    global_stats (catalog, Ncatalog);
  }

  SAVEPLOT = TRUE;
  plot_scatter (catalog, Ncatalog); 
  plot_grid (catalog); 
  plot_mosaics ();
  plot_images ();
  plot_stars (catalog, Ncatalog);
  plot_chisq (catalog, Ncatalog);

  if (USE_GRID) dump_grid ();
  if (!UPDATE) exit (0);

  /* set Mcal & Mmos for bad images */
  setMcal  (catalog, TRUE);
  setMmos  (catalog, TRUE);

  /* at this point, we have correct cal coeffs in the image/mosaic structures */
  free_catalogs (catalog, Ncatalog);
  freeImageBins (Ncatalog);
  freeMosaicBins (Ncatalog);
  freeGridBins (Ncatalog);

  /* load catalog data from region files, update Mrel include all data */
  reload_catalogs (region, Ncatalog, &fullregion);
  wimages (); 

}

