# include "imregister.h"
# include "spreg.h"

Spectrum *spinfo (char *filename) {

  Spectrum *spectrum;
  Header header;
  int Naxes, Nextend;
  char Imagetype[80], line[80];
  struct timeval now;
  char *name, *cwd, *tempname;
  double tmp;
  float *dtime;

  ALLOCATE (spectrum, Spectrum, 1);
  bzero (spectrum, sizeof (Spectrum));

  /* load in FITS header from image */
  if (!fits_read_header (filename, &header)) {
    fprintf (stderr, "ERROR: can't find image file %s\n", filename);
    exit (1);
  }

  /* get filename */
  name = filebasename (filename);
  snprintf (spectrum[0].filename, 32, "%s", name);
  free (name);

  /* get pathname (add cwd if not absolute) */
  name = pathname (filename);
  if (name[0] != '/') {
    cwd = getcwd (NULL, 64 - strlen(name) - 2);
    if (cwd == (char *) NULL) {
      cwd = strcreate ("longpath");
      /* pathname is limited to 64 chars.  if it is toolong, 
	 we put in the word 'longpath'.  no other useful solution. */
    }
    ALLOCATE (tempname, char, strlen (cwd) + strlen (name) + 2);
    if (!strcmp (name, ".")) {
      sprintf (tempname, "%s", cwd);
    } else {
      sprintf (tempname, "%s/%s", cwd, name);
    }      
    free (name);
    free (cwd);
    name = tempname;
  }    
  snprintf (spectrum[0].pathname, 64, "%s", name);
  free (name);

  /* find the important header keyword values */
  spectrum[0].obstime = parse_time (&header);

  gettimeofday (&now, (void *) NULL);
  spectrum[0].regtime = now.tv_sec;

  fits_scan_nchar (&header, 15, ObjectKeyword,    1, spectrum[0].objname);
  fits_scan_nchar (&header, 15, CameraKeyword,    1, spectrum[0].instrument);
  fits_scan_nchar (&header, 15, TelescopeKeyword, 1, spectrum[0].telescope);

  fits_scan (&header, ExptimeKeyword,    "%f", 1, &spectrum[0].exptime);
  fits_scan (&header, AirmassKeyword,    "%f", 1, &spectrum[0].airmass);

  /* grab coordinates from header */
  if (RADecDegKeyword[0] & DECDecDegKeyword[0]) {
    /* expect RA & DEC in decimal degrees */
    fits_scan (&header, RADecDegKeyword,  "%f", 1, &spectrum[0].ra);
    fits_scan (&header, DECDecDegKeyword, "%f", 1, &spectrum[0].dec);
  } else {
    if (RASexigKeyword[0] & DECSexigKeyword[0]) {
      /* expect RA & DEC in hh:mm:ss, dd:mm:ss */
      fits_scan (&header, RASexigKeyword,  "%s", 1, line);
      dms_to_ddd (&tmp, line);
      spectrum[0].ra = 15*tmp;
      fits_scan (&header, DECSexigKeyword, "%s", 1, &line);
      dms_to_ddd (&tmp, line);
      spectrum[0].dec = tmp;
    }
  }

  /* for now we will not try to determine the mode, state, or 
     wavelength ranges from the header.  set these with -modify
     or on the command line on insert.  later on, we can add the logic */
  
  spectrum[0].mode  = SPMODE_UKN;
  spectrum[0].state = SPSTATE_UKN;
  spectrum[0].Nspec = 1;
  spectrum[0].flag  = 0;
  
  spectrum[0].Ws = 0;
  spectrum[0].We = 0;
  spectrum[0].dW = 0;
  
  strcpy (spectrum[0].extname, "PHU");
  
  return (spectrum);

}

