/*===========================================================================
  Copyright (C) 1998-2209 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        outfits.c
.LANGUAGE     C
.AUTHOR       P.Grosbol   ESO/DPG
.KEYWORDS     Encode data to FITS 
.PURPOSE      Convert set of disk files in internal MIDAS format to a
              single disk file in FITS format
.VERSION      1.0  1998-May-15 : Creation,   PJG 

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

#ifndef _XOPEN_SOURCE
#define _XOPEN_SOURCE 1
#endif

#include   <ctype.h>
#include   <stdio.h>
#include   <string.h>
#include   <osfile.h>
#include   <osparms.h>
#include   <fitsfmt.h>
#include   <fitsdef.h>
#include   <midas_def.h>

#define    MXFILE            400   /* Max. no. of input files        */
#define    MXPARM            4000  /* Max. char's in input file list */
/*

*/

int main()

{
char     *cs, *cp, *fin, *wext;
char     ffmt, copt, ctype;
char     name[MXPARM+1], oname[MXPARM+1], iname[MXPARM+1];
char     *pname[MXFILE], opt[4], line[128];
char     tmpnam[16];

int      iparm[5];
int      did, err, mfd, mft, mff,  bf, popt, fid;
int      max_lines,no, n, nval, mr, nf, mf;

float    tmbyte;




(void) SCSPRO("OUTFITS");

wext = ".fits";
ctype = '\0';
mr = 0;

/* get max. no. of input lines - must be sync'd with MID_PROC:outsfits.prg! */

(void) SCKRDI("SNAM_COUNTER",1,1,&nval,&max_lines,&n,&n);
for (mr=0; mr<max_lines; mr++)
   {
   (void)sprintf(tmpnam,"SNAMES%d",mr+1);
   (void) SCKGETC(tmpnam,1,MXPARM,&nval,name);	/* read input file list */
   if (mr > 0) 
      {
      (void) strcat(iname,",");
      (void) strcat(iname,name);
      }
   else
      (void) strcpy(iname,name);
   }


mf = 0;
pname[mf++] = strtok(iname, ",");
while ((pname[mf]=strtok(NULL, ","))!=NULL && mf<MXFILE) mf++;

(void) strcpy(oname,pname[0]);
cp = strrchr(oname,'.');              /* find last '.' in output file */
cs = strrchr(oname,'/');              /* find last '/' in output file */
if (cp && cs<cp) *cp = '\0'; 

(void) SCKGETC("P2",1,MXPARM,&nval,name);        /* read output file name    */
if (name[0]!='.') 
   {             /* extension only is given  */
   (void) strcpy(oname,name);
   cp = strrchr(oname,'.');              /* find last '.' in output file */
   cs = strrchr(oname,'/');              /* find last '/' in output file */
   if (!cp || cp<cs) strcat(oname, wext);
   }
else 
   (void) strcat(oname,name);

(void) sprintf(name,"FITS file %s will have %d extensions",oname,mf);
SCTPUT(name);

opt[0] = 'O';                   /* format flag : Original, Basic      */
opt[1] = 'S';                   /* print  flag : No, Short, Full      */
opt[2] = 'N';                   /* cut    flag : No cuts, Cuts used   */
(void) SCKGETC("P3",1,3,&nval,opt);                /* read options           */
ffmt = opt[0];                        /* set FITS format type   */     
if ((opt[1] == 'N') || (opt[1] == 'n'))
   popt = 0;
else
   popt = 1;				/* set  print option */
copt = opt[2];                        /* set cut flag           */

did = dopen(oname,WRITE,'S',0);
if (did < 0) 
   {					/* open output FITS file */
   SCTPUT(osmsg());
   SCETER(1,"Error: cannot open output FITS file");
   }

bf = 1;
dwinit(bf);

no = 1; nval = 0;
SCECNT("PUT",&no,&nval,&nval);              /* disable SC errors      */


/* go through input list  */

for (nf=0; nf<mf; nf++) 
   {				
   fin = pname[nf];
   mft = -1;
   err = SCFINF(fin,1,iparm);                /* get type of MIDAS file */
   if (err == ERR_NORMAL) 
      {
      mft = iparm[1];
      mff = D_R4_FORMAT;
      err = SCFINF(fin,4,iparm);              /* check if FITS format   */
      if (iparm[2]!=0) 
         {
	 sprintf(line,"Warning: >%s< skipped as already in FITS format",fin);
	 SCTPUT(line); continue;
         }
      }
   else if (ctype=='A') 
      {
      fid = osaopen(fin,READ);                     /* open text file    */
      n = osaread(fid,line,80);
      osaclose(fid);
      if (!strncmp(line,"SIMPLE  =",9)) 
         {
	 (void) sprintf(line,
                        "Warning: >%s< skipped as already in FITS format",fin);
         SCTPUT(line); continue;
         }
      mft = F_ASC_TYPE;
      }
   else 
      {
      (void) sprintf(line,"Warning: Cannot open or find type of file >%s<",fin);
      SCTPUT(line); continue;
      }

   if (mft==F_IMA_TYPE) 
      {						/* if image get data format */
      (void) SCFINF(fin,2,iparm);
      mff = iparm[1];
      }

   err = 0;
   if (nf==0)
      {
      if (mft==F_TBL_TYPE) 
         {
         TCTOPN(fin,F_I_MODE,&mfd);			/* open table file */
         err = fitswhd(mfd,mft,mff,fin,ffmt,copt,BFITSE);	/* prime hdr.*/
         }
      else
         {
         SCFOPN(fin,mff,0,mft,&mfd);			/* open image file  */
         err = fitswhd(mfd,mft,mff,fin,ffmt,copt,BFITS);	/* prime hdr.*/
         }
      if (err) SCETER(2,"Error: cannot write prime FITS header");
      }

   err = 0;
   switch (mft) 
      {                              /* check which format        */
     case F_IMA_TYPE :                        /* file is an image          */
      if (nf) 
               {
               SCFOPN(fin,mff,0,mft,&mfd);	/* open image file           */
               err = fitswhd(mfd,mft,mff,fin,ffmt,copt,IMAGE);	/* extension */
	       if (err) break;
               }
      err = fitswdm(mfd,mff,ffmt);        /* write prime data          */
      SCFCLO(mfd);                        /* close image file          */
      break;
     case F_TBL_TYPE :                        /* file is a table           */
      if (nf) TCTOPN(fin,F_I_MODE,&mfd);  /* open table file           */
      err = fitswhd(mfd,mft,mff,fin,ffmt,copt,ATABLE);   /* extension  */
      if (err) break;
      if (ffmt=='B') 
         err = fitswat(mfd);  /* write ASCII table         */
      else 
         err = fitswbt(mfd);            /* write Binary table        */
      TCTCLO(mfd);                        /* close table file          */
      break;
     case F_FIT_TYPE :                       /* file is a fit-format       */
      if (nf)
         {
         SCFOPN(fin,mff,0,mft,&mfd);        /* open fit file           */
         err = fitswhd(mfd,mft,mff,fin,ffmt,copt,BFITSE);   /* extens. */
         }
      SCFCLO(mfd);                       /* close fit file             */
      break;
     case F_ASC_TYPE :                       /* file is ASCII char.        */
      text_open(fin,READ);
      err = fitswhd(mfd,mft,mff,fin,ffmt,copt,BFITSE);   /* prime hdr. */
      text_close();
      break;
     default   :
      sprintf(line,"Warning: file %-16s unknown type>%d<",fin,mft);
      SCTPUT(line);
      continue;
      }
   if (err) 
      {
      (void) sprintf(line,
                     "Warning: file %-16s NOT completed - device error",fin);
      SCTPUT(line); break;
      }
   }

n = dweof();
if (n<=0) SCETER(3,"Error: cannot close FITS file correctly");
dclose(did);

if (1<popt) 
   {
   tmbyte = (2880.0/1048576.0) * n;
   if (tmbyte<0.01) tmbyte = 0.01;
   (void) sprintf(line,
                  "Disk FITS file >%-16s< written with %4.2f Mb",oname,tmbyte);
   SCTPUT(line);
   }

SCSEPI();

return 0;
}
