# include "markrock.h"

main (int argc, char **argv) {
  
  int i, Nrocks1, Nrocks2;
  Catalog catalog;
  CatStats catstats;
  Rocks *rocks1, *rocks2, *find_rocks(), *find_slow_rocks();
  struct timeval now, then;  
  
  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: markstar (catalog)\n");
    exit (0);
  }

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

  catalog.filename = argv[1];
  switch (lock_catalog (&catalog, LCK_XCLD)) {
  case 0:
    fprintf (stderr, "ERROR: can't lock file\n");
    exit (1);
  case 1:
    gcatalog (&catalog); /* load from disk */
    break;
  case 2:
    fprintf (stderr, "no data in %s, skipping\n", catalog.filename);
    catalog.Naverage = 0;
    catalog.Nmeasure = 0;
    unlock_catalog (&catalog);
    exit (0);
  default:
    fprintf (stderr, "weird lock_catalog exit state\n");
    exit (1);
  }

  gcatstats (&catalog, &catstats);

  find_bright_stars (&catalog, &catstats); 

  rocks1 = find_rocks (&catalog, &catstats, &Nrocks1); 
  count_neighbors (rocks1, Nrocks1, &catalog, &catstats);

  /* rocks2 = find_slow_rocks (&catalog, &catstats, &Nrocks2);  */

  wcatalog (&catalog);
  wrocks (rocks1, Nrocks1);

  unlock_catalog (&catalog);
  /* wrocks (rocks2, Nrocks2); */

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

  fprintf (stderr, "SUCCESS\n");
}

