# include "data.h"

int header (int argc, char **argv) {
  
  int j, N, nlines, nbytes, Nbytes, LOADHEAD, status, bitpix, unsign;
  char *p, filename[128];
  FILE *f;
  double bscale, bzero;
  Buffer *buf;

  LOADHEAD = FALSE;
  if (N = get_argument (argc, argv, "-w")) {
    remove_argument (N, &argc, argv);
    strcpy (filename, argv[N]);
    remove_argument (N, &argc, argv);
    LOADHEAD = TRUE;
  }

  if (argc != 2) {
    fprintf (stderr, "USAGE: header <buffer> [-w filename]\n");
    return (FALSE);
  }

  if ((buf = SelectBuffer (argv[1], OLDBUFFER, TRUE)) == NULL) return (FALSE);

  if (LOADHEAD) {
    f = fopen (filename, "r");
    if (f == (FILE *) NULL) {
      fprintf (stderr, "file %s not found\n", filename);
      return (FALSE);
    }
    fclose (f);
    
    bitpix = buf[0].header.bitpix;
    bzero  = buf[0].header.bzero;
    bscale = buf[0].header.bscale;
    unsign = buf[0].header.unsign;
    fits_free_header (&buf[0].header);
    
    strcpy (filename, buf[0].file);
    strcpy (buf[0].file, "*");
    strcat (buf[0].file, filename);
    status = fits_read_header (argv[2], &buf[0].header);
    buf[0].header.bitpix = bitpix;     
    buf[0].header.bzero  = bzero;      
    buf[0].header.bscale = bscale;     
    buf[0].header.unsign = unsign;     
    fits_modify (&buf[0].header, "BITPIX", "%d",  1, bitpix);
    fits_modify (&buf[0].header, "BSCALE", "%lf", 1, bscale);
    fits_modify (&buf[0].header, "BZERO",  "%lf", 1, bzero);
    fits_modify (&buf[0].header, "UNSIGN", "%t",  1, unsign);
    
  } else {

    f = popen ("more", "w");
    
    p = fits_header_field (&buf[0].header, "END", 1);
    nlines = (p - buf[0].header.buffer) / 80;
    nbytes = 81*nlines;

    /* duplicate the header, add in the <return> chars, send to more */
    ALLOCATE (p, char, nbytes);
    for (j = 0; j < nlines; j++) {
      memcpy (&p[81*j], &buf[0].header.buffer[80*j], 80);
      p[81*j+80] = 10;
    }
    Nbytes = fwrite (p, sizeof(char), nbytes, f);
    if (Nbytes != nbytes) {
      fprintf (stderr, "warning: not all printed...\n");
    }
    free (p);

    pclose (f);

  }

  return (TRUE);

}
