/*===========================================================================
  Copyright (C) 1995,2003 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 Massachusetss Ave, Cambridge, 
  MA 02139, USA.
 
  Corresponding 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
===========================================================================*/

/*++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++
.COPYRIGHT  (c)  1994,2003   European Southern Observatory
.IDENT      fitsrat.c
.LAUGUAGE   C
.AUTHOR     P.Grosbol   ESO/IPG
.KEYWORDS   FITS ASCII table extension, decode, read
.COMMENT    read the ASCII table extension of FITS file
.VERSION    1.0  1988-Oct-16 : Creation,   PJG 
.VERSION    1.1  1989-May-26 : Correct NULL test,   PJG 
.VERSION    1.2  1989-Jul-05 : Include I*4 types,   PJG 
.VERSION    1.3  1990-Nov-09 : Correct scaling of columns,   PJG 
.VERSION    2.0  1991-Feb-15 : Change calling seq. and structures, PJG 
.VERSION    2.1  1991-Mar-23 : Change scaling for I-fields, PJG 
.VERSION    2.2  1993-Oct-26 : Update to new ST/TC + prototypes, PJG 
.VERSION    2.3  1994-Mar-31 : Insert '\0' after strings, PJG 
.VERSION    2.4  1997-Jan-08 : Only warning on wrong record size, PJG

 031002		last modif
---------------------------------------------------------------------*/
#include   <fitsfmt.h>
#include   <fitsdef.h>
#include   <fitskwt.h>
#include   <midas_def.h>

int fitsrat(mfd,bfdef,size,Midas_flag)
/*+++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++
.PURPOSE       Read ASCII table extension in FITS
.RETURN        error code - 0: OK, -1: error
---------------------------------------------------------------------*/
int       mfd;                 /* IN: MIDAS file descriptor          */
BFDEF     *bfdef;              /* IN: pointer to FITS parm's         */
int       size;                /* IN: size of data matrix (bytes)    */
int       Midas_flag;          /* IN: 0 = from intape,
				      1 = for intl FITS table        */
{
  register  char   *pc, *pf;
  register  FDEF   *fd;
  register  int    nc, n, m;
  char             *pb, *line, *pn, *buf;
  int              i, iv, nf, nr, nor, nof, nbr;
  float            f;
  double           d;
  TXDEF            *txdef;

  txdef = (TXDEF *) bfdef->extd;
  nf = txdef->tfields;
  nbr = bfdef->data[0].naxis;
  iv = 0;                           /* length of longest string field  */
  fd = txdef->col;
  for (nof=1; nof<=nf; nof++,fd++)
    if (fd->tdfmt=='A' && iv<fd->twdth) iv = fd->twdth;


  line = (char *) osmmget(nbr+iv+1);     /* get buffer whole line      */
  if (!line) {
     SCTPUT("Error: cannot allocate line buffer");
     TCTCLO(mfd); mfd = -1;
     return -1;
  }
  buf = line + nbr;                      /* bufer for string fields    */

  n  = 0;                                /* bytes in read buffer       */
  nr = bfdef->data[1].naxis;             /* no. of rows to read        */
  for (nor=1; nor<=nr; nor++) {          /* read row by row            */
    pc = line; nc = nbr;
    size -= nc;                          /* decrement remaining bytes  */
    while (n<nc) {                       /* line across record limit   */
        nc -= n;
        while (n--) *pc++ = *pb++;       /* copy bytes to line buffer  */
        if ((n=dread(&pb,FITSLR))!=FITSLR) {
	  if (!size) {
	    SCTPUT("Warning: incomplete FITS record read!");
	  }
	  else {
            SCTPUT("Error: unexpected EOF!");
            TCSINI(mfd);
            TCTCLO(mfd); mfd = -1;
            return NOFITS;
	  }
	}
    }
    n -= nc;
    while (nc--) *pc++ = *pb++;          /* copy bytes to line buffer  */
    fd = txdef->col;
    for (nof=1; nof<=nf; nof++,fd++) {   /* transfer entry by entry    */
       pf = line + fd->tbcol;
       if (*(pn=fd->tnull)) {            /* check for NULL value       */
          m = fd->twdth;
	  while (m && *pf == *pn) { pn++; pf++; m--; }
	  if (m && !(*pn)) while (m && *pf++ == ' ') m--;
	  if (!m) continue;              /* NULL field goto next       */
          pf = line + fd->tbcol;
       }
       switch (fd->tdfmt) {              /* convert data if needed     */
	  case  'A' : pc = buf;          /* transfer string to buf     */
                      m = fd->twdth;
	              while (m--) *pc++ = *pf++;
	              *pc = '\0';               /* terminate with NUL  */
	              TCEWRC(mfd,nor,nof,buf);
		      break;
	  case  'I' : getint(pf,fd->twdth,&i,&iv);
		      if (fd->sflag) {
			 f = fd->tscal*iv + fd->tzero;
			 TCEWRR(mfd,nor,nof,&f);
		       }
	              else if (i) TCEWRI(mfd,nor,nof,&iv);
		      break;
	  case  'E' : getval(pf,fd->twdth,&i,&d);
		      if (i) {           /* implicit decimal point     */
			 i = fd->tdfdd; while (i--) d /= 10.0;
                      }
		      f = (fd->sflag) ? fd->tscal*d+fd->tzero : d;
		      TCEWRR(mfd,nor,nof,&f);
		      break;
	  case  'D' : getval(pf,fd->twdth,&i,&d);
		      if (i) {           /* implicit decimal point     */
			 i = fd->tdfdd; while (i--) d /= 10.0;
                      }
		      if (fd->sflag) d = fd->tscal*d + fd->tzero;
		      TCEWRD(mfd,nor,nof,&d);
		      break;
       }
    }
  }
  osmmfree(line);                          /* free line buffer and return */
  if ((0 <= mfd) && (Midas_flag == 0))
     TCTCLO(mfd);		/* close MIDAS table file (no TCSINI!) */

  mfd = -1;
  return 0;
}
