# include "addusno.h"

main (int argc, char **argv) {

  int i, N, Nusno;
  Catalog catalog;
  CatStats catstats;
  USNOstats usnostats;
  USNOdata *usno, *getusno();
  struct timeval now, then;  
  PhotCodeData photcodes;
  
  gettimeofday (&then, (void *) NULL);
  ConfigInit (argc, argv);

  VERBOSE = FALSE;
  if ((i = get_argument (argc, argv, "-v"))) {
    VERBOSE = TRUE;
    remove_argument (i, &argc, argv);
  }
  FORCE_RUN = FALSE;
  if ((i = get_argument (argc, argv, "-f"))) {
    FORCE_RUN = TRUE;
    remove_argument (i, &argc, argv);
  }
  RESET = FALSE;
  if ((i = get_argument (argc, argv, "-reset"))) {
    RESET = TRUE;
    remove_argument (i, &argc, argv);
  }
  if (argc < 2) {
    fprintf (stderr, "ERROR: Usage: addusno (region)\n");
    exit (0);
  }

  if (!LoadPhotcodes (PhotCodeFile)) {
    fprintf (stderr, "error loading photcodes\n");
    exit (0);
  }
  
  USNO_RED = GetPhotcodebyName ("USNO_RED");
  if (!USNO_RED) {
    fprintf (stderr, "ERROR: USNO_RED photcode not found in photcode table\n");
    exit (0);
  }
  USNO_BLUE = GetPhotcodebyName ("USNO_BLUE");
  if (!USNO_BLUE) {
    fprintf (stderr, "ERROR: USNO_BLUE photcode not found in photcode table\n");
    exit (0);
  }

  /* if lockfile exists, program will complain and quit */
  check_lockfile (); 
  check_permissions (argv[1]);

  gcatalog (argv[1], &catalog);

  if (RESET) reset_catalog (&catalog);

  gcatstats (&catalog, &catstats);

  usno = getusno (&usnostats, &catstats, &Nusno);

  find_matches (&catstats, &catalog, &usnostats, usno, Nusno);

  find_proper (&catstats, &catalog, &usnostats, usno, Nusno);

  wcatalog (argv[1], &catalog);

  if (VERBOSE) {
    gettimeofday (&now, (void *) NULL);
    fprintf (stderr, "%s: elapsed time = %.2f sec\n", argv[1], 
	     (now.tv_sec - then.tv_sec) + 1e-6*(now.tv_usec - then.tv_usec));
  }
  clear_lockfile (); 
  fprintf (stderr, "SUCCESS\n");
}
