/*===========================================================================
  Copyright (C) 1995-2009 European Southern Observatory (ESO)
 
  This program is free software; you can redistribute it and/or 
  modify it under the terms of the GNU General Public License as 
  published by the Free Software Foundation; either version 2 of 
  the License, or (at your option) any later version.
 
  This program is distributed in the hope that it will be useful,
  but WITHOUT ANY WARRANTY; without even the implied warranty of
  MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
  GNU General Public License for more details.
 
  You should have received a copy of the GNU General Public 
  License along with this program; if not, write to the Free 
  Software Foundation, Inc., 675 Massachusetts Ave, Cambridge, 
  MA 02139, USA.
 
  Correspondence concerning ESO-MIDAS should be addressed as follows:
	Internet e-mail: midas@eso.org
	Postal address: European Southern Observatory
			Data Management Division 
			Karl-Schwarzschild-Strasse 2
			D 85748 Garching bei Muenchen 
			GERMANY
===========================================================================*/

/*++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++
.IDENT        fheader.c
.LANGUAGE     C
.AUTHOR       K. Banse   ESO/IPG
.KEYWORDS     FITS header
.PURPOSE      isolate FITS primary header in an ascii file
.VERSION      1.00  021115:   Creation 

 090710		last modif
---------------------------------------------------------------------*/

#include <sys/types.h>
#include <sys/stat.h>

#include <stdio.h>
#include <stdlib.h>
#include <fcntl.h>

#include   <fileexts.h>
#include <fsydef.h>

#define MAXREC 2880
/*

*/

int main(argc,argv)
int argc;
char *argv[];

{
int   inMidas, stat, nval, uni, linco, extco;
int   mfd, info;
int   get_fhead();

char  tbuf[120], ffile[120], txtfile[120], extname[24];



if (argc > 1)				/* we're with command line args. */
   {
   SCSPRO("-1");
   (void) strcpy(ffile,argv[1]);
   extname[0] = '?';
   if (argc > 2) (void) strcpy(extname,argv[2]);
   inMidas = 0;
   }
else
   {
   SCSPRO("header");
   (void) SCKGETC("IN_A",1,80,&nval,ffile);	
   (void) SCKGETC("IN_B",1,20,&nval,extname);	
   inMidas = 1;
   uni = 0;
   }

/* 2nd param decides which command to execute */

/* for GET/FEXTENS the extname is in IN_B */
if (*extname != '?')
   {	
   stat = MID_fitsin(-2,ffile,-1,"FITZdummy.xyz",extname,&mfd,&info);
   if (stat == 0)
      {
      (void) SCKWRI("OUTPUTI",&info,1,1,&uni);
      (void) 
      sprintf(tbuf,"EXTNAME %s found in extension no. %d",extname,info);
      SCTPUT(tbuf);
      }
   else
      SCTPUT("FITS extension not found...!");
   }

/* for GET/FHEADER pass FITS file name to get_fhead */
else
   {
   stat = get_fhead(ffile,txtfile,&linco,&extco);
   if (stat != 0)
      (void) sprintf(tbuf,"extracting FITS header from %s failed",ffile);
   else
      {
      (void) sprintf(tbuf,"FITS header stored in %s",txtfile);
      SCTPUT(tbuf);
      (void) sprintf(tbuf,
      "%d extensions, %d lines of FITS keywords in FITS header(s)",extco,linco);
      }
   SCTPUT(tbuf);


   /* inside Midas we save some info for the wrapper procedure (fheader.prg) */

   if (inMidas == 1)
      {
      int   flags[3];

      flags[0] = stat; flags[1] = extco; flags[2] = linco;
      (void) SCKWRI("OUTPUTI",flags,1,3,&uni);
      nval = (int) strlen(txtfile);
      if (nval < 80) 
         {
         (void) strcat(txtfile,"                    ");
         nval += 20;
         }
      (void) SCKWRC("OUT_A",1,txtfile,1,nval+20,&uni);
      }
   }

SCSEPI();
return (0);
}
/*

*/
int get_fhead(fitsfile,txtfile,ico,eco)
char  *fitsfile;
char  *txtfile;
int   *ico;		/* OUT: no. of lines copied */
int   *eco;		/* OUT: no. of extensions in FITS file */

{
int  n, m, count, retstat, endy;
int  bline, skip, td, fd, nbytes;

char  myrec[MAXREC+2],endmask[24], ascbuf[88];
char  *myptr;



m = CGN_JNDEXC(fitsfile,FSY_TYPMARK);
if (m > 0)
   {
   fitsfile[m] = '\0';
   (void) strcpy(txtfile,fitsfile);
   (void) strcat(txtfile,".fhead");
   fitsfile[m] = FSY_TYPMARK;
   }
else
   {
   (void) strcpy(txtfile,fitsfile);
   (void) strcat(txtfile,".fhead");
   }

td = 0;
*ico = *eco = 0;

fd = open(fitsfile,O_RDONLY);
if (fd == -1)
   {
   (void) printf("could not access %s\n",fitsfile);
   retstat = 1;
   goto byebye;
   }

td = osaopen(txtfile,1);		/* create ascii file */
if (td < 0)
   {
   (void) printf("could not create %s ...\n",txtfile);
   retstat = 2;
   goto byebye;
   }

(void) strcpy(endmask,"END");
retstat = 0, endy = 0, bline = 0;


/* FITS records are usually 2880 bytes long (MAXREC set to that value) */

nbytes = read(fd,(void *)myrec,(size_t)MAXREC);		/* first read */
if (nbytes < 0) 
   {
   (void) printf("could not read anything ...\n");
      retstat = 5;
      goto byebye;
      }

/* check if really FITS format */

if (strncmp(myrec,"SIMPLE",6) != 0)
   {
   (void) printf("not a FITS file ...\n");
   retstat = 4;
   goto byebye;
   }

*eco = 1;
count = 0;
myptr = myrec;                          /* point to header buffer */
goto copy_header;


/* here we read a full record (36 lines) */

read_loop:
nbytes = read(fd,(void *)myrec,(size_t)MAXREC);
if (nbytes < 0) goto byebye;			/* EOF reached */
count = 0;
myptr = myrec;				/* point to header buffer */


/* analyze the record, line by line */

copy_header:
while (count < nbytes)
   {					/* copy records of 80 bytes */
   (void) strncpy(ascbuf,myptr,80);
   ascbuf[80] = '\0';

   if (strncmp(ascbuf,"END",3) == 0)	/* check for end of header */
      {
      endy = 1;
      ascbuf[3] = '\0';
      }

   if (strncmp(ascbuf,"          ",10) == 0)
      bline++;					/* omit blank lines */
   else
      {
      n = (int)strlen(ascbuf);
      m = osawrite(td,ascbuf,n);
      if ((m-1) != n)
         {
         (void) printf("problems in writing FITS header to text file ...\n");
         (void) printf("m,n = %d, %d, ascbuf = %s\n",m,n,ascbuf);
         retstat = 5;
         goto byebye;
         }
      }

   (*ico) ++;
   myptr += 80;				/* point to next line */
   count += 80;

   if (endy == 1) 
      {
      endy = 0;
      if (bline > 0) 
         {
         printf("%d blank lines in this extension\n",bline);
         bline = 0;
         }
      skip = 0;
      goto xtens_check;
      }
   }
goto read_loop;


/* here we look for the extensions */

xtens_check:				/* check for FITS extensions */
while (count < nbytes)
   {
   if (strncmp(myptr,"XTENSION=",9) == 0)
      {						/* mark it visually */
      char trenn[24];

      (void) strcpy(trenn,"         ");
      (void) osawrite(td,trenn,(int)strlen(trenn));
      (void) strcpy(trenn,"--------------------");
      (void) osawrite(td,trenn,(int)strlen(trenn));
      (void) strcpy(trenn,"         ");
      (void) osawrite(td,trenn,(int)strlen(trenn));
      (*eco) ++;				/* update extension count */

      printf("%d data records skipped\n",skip);
      goto copy_header;
      }

   myptr += 80;
   count += 80;
   }

nbytes = read(fd,(void *)myrec,(size_t)MAXREC);
if (nbytes > 0) 
   {
   skip ++;
   count = 0;
   myptr = myrec;
   goto xtens_check;
   }
printf("%d data records skipped\n",skip);


byebye:
(void) close(fd);
(void) osaclose(td);
return retstat;
}

