#ifdef HAVE_CONFIG_H
#include "config.h"
#endif

#include <savant.h>
#include <savutil.h>
#include <template.h>
#include <savantio.h>
#include <main.h>

void instructions(void);

int SavantVerbose = 0, SavantDebug = 0;

FILE *TITLE_FILE=NULL, *TOFF_FILE=NULL;
FILE *DOCLOC_FILE=NULL, *DLOFF_FILE=NULL;
FILE *WMAP_FILE=NULL, *LOG_FILE=NULL, *BIAS_FILE=NULL;

void instructions(void)  
{
  fprintf(stderr,"\nusage:\n");
  fprintf(stderr,"   ra-retrieve [-v] [-c <config-file>] <base-dir>\n");
  fprintf(stderr,"   -v invokes savant retrieval verbosely;  -d provides debugging messages.\n");
  fflush(stderr);
}

void main(int argc,
	  char *argv[])
{
  int i;
  char *config_name=NULL, *db_name=NULL, db_dir[1024];

  for (i=1; i < argc; i++)
    if (argv[i][0] == '-')
      switch (argv[i][1]) {
      case 'c':
	if (config_name == NULL) {
	  config_name = argv[++i];
	}
	else {
	  instructions();
	  exit(-1);
	}
	break;
      case 'v':
	SavantVerbose = 1;
	break;
      case 'd':
	SavantDebug = 1;
	break;
      default:
	instructions();
	exit(-1);
      }
    else if (db_name == NULL) {
      db_name = argv[i];
    }
    else {
      instructions();
      exit(-1);
    }

  if(SavantVerbose || SavantDebug) {
    printf("%s\n",VERSION);
  }

  if (db_name == NULL) {
    instructions();
    exit(-1);
  }

  if(db_name[0] != '/') {  /* if not absolute pathname, tack it onto cwd */
    getcwd(db_dir, 510);
    strcat(db_dir, "/");
    strcat(db_dir, db_name);
  }
  else { /* use the absolute pathname */
    strcpy(db_dir, db_name);
  }

  load_config(config_name);
  core_comm_local();
  
  TITLE_FILE = open_or_die(db_dir, TITLE_FNAME, "r");
  TOFF_FILE = open_or_die(db_dir, TOFF_FNAME, "r");
  DOCLOC_FILE = open_or_die(db_dir, DOCLOC_FNAME, "r");
  DLOFF_FILE = open_or_die(db_dir, DLOFF_FNAME, "r");
  WMAP_FILE = open_or_die(db_dir, WMAP_FNAME, "r");
  BIAS_FILE = open_or_die(db_dir, BIAS_FNAME, "r");
  savant_retrieve(init_read(db_dir));

  exit(0);

}
