/* Writer de table Fits (binaire ou ASCII) */
#include "machdefs.h"
#include <stdlib.h>
#include <stdio.h>
#include "pexceptions.h"
#include "fabtwriter.h"

/*!
  \class SOPHYA::FitsABTWriter
  \ingroup FitsIOServer
  Class for writing a FITS ASCII or BINARY table
  \verbatim
  //-----------------------------------------------------------
  -- Exemple 1: Writing element by element
  FitsABTWriter fbtw(fitswrit,BINARY_TBL);
  fbtw.SetExtName("MY_OWN_EXTENSION");
  fbtw.AddCol("vars",NULL,"km",TSHORT);       // col=0
  fbtw.AddCol("vars2",NULL,"km",TSHORT);      // col=1
  fbtw.AddCol("varl",NULL,"Degre",TLONG);     // col=2
  fbtw.AddCol("varf",NULL,"",TFLOAT);         // col=3
  fbtw.AddCol("vard","","arcmin",TDOUBLE);    // col=4
  fbtw.SetDebug(3);
  for(long i=0;i<1000;i++) {
    double x = i;
    fbtw.Write(0,i,1000.*x); // if overflow, managed by cfitsio
                             // Write(int,long,double) is called
    fbtw.Write(1,i,(short)(1000.*x));
                             // if overflow, managed by language
                             // Write(int,long,short) is called
    fbtw.Write(2,i,x);
    fbtw.Write(3,i,x);
    fbtw.Write(4,i,x);
  }
  cout<<"Number of Overflows when writing: "
      <<fbtw.GetNOverFlow()<<endl;

  //-----------------------------------------------------------
  -- Exemple 2: Writing into TVector
  ...
  TVector<double> datad(100);
  TVector<float>  dataf(100);
  TVector<int_4>  datal(100);
  for(long i=0;i<9990;i+=100) {
    long i2=i+100-1; if(i2>=9990) i2=9990-1;
    for(long j=0;j<100;j++) datad(i) =  ...;
    for(long j=0;j<100;j++) dataf(i) =  ...;
    for(long j=0;j<100;j++) datal(i) =  ...;
    fbtw.Write(1,i,datal);
    fbtw.Write(2,i,dataf);
    fbtw.Write(3,i,datad);
  }
  \endverbatim
*/

//////////////////////////////////////////////////////////////
/*!
  Constructor.
  \param fname : FITS file name to be written
  \param hdutype : type of extension to be created (BINARY_TBL or ASCII_TBL)
  \param lp : debug level
*/
FitsABTWriter::FitsABTWriter(string fname,int hdutype,int lp)
{
  createfits(fname.c_str(),hdutype,lp);
}

/*! See FitsABTWriter() */
FitsABTWriter::FitsABTWriter(const char* cfname,int hdutype,int lp)
{
  createfits(cfname,hdutype,lp);
}

/*! See FitsABTWriter() */
void FitsABTWriter::createfits(const char *cfname,int hdutype,int lp)
{
 FirstTime = true;
 FitsPtr = NULL;
 HduType = hdutype;
 SetDebug(lp);
 FitsFN = cfname;
 NOverFlow = 0;

 if(DbgLevel)
   cout<<"FitsABTWriter::createfits FitsFN="<<FitsFN
       <<" HduType="<<HduType<<endl;

 if(FitsFN.size() <= 0 )
   throw ParmError("FitsABTWriter::createfits: Fits file name error\n");

 if(HduType!=BINARY_TBL && HduType!=ASCII_TBL)
   throw TypeMismatchExc("FitsABTWriter::createfits: Only BINARY or ASCII table permitted\n");

 // create new FITS file
 int sta=0;
 if(fits_create_file(&FitsPtr,FitsFN.c_str(),&sta)) {
   printerror(sta);
   throw NullPtrError("FitsABTWriter::createfits: Error creating Fits file\n");
 }

 // create d'un Primary HDU
 //long naxes[1] = {0};
 //if(fits_create_img(FitsPtr,BYTE_IMG,0,naxes,&sta)) {
 //  printerror(sta);
 //  throw NullPtrError("FitsABTWriter::createfits: Error creating Primary extension\n");
 //}

}

/*! Destructor */
FitsABTWriter::~FitsABTWriter()
{
 int sta = 0;
 writekeys();
 if(fits_close_file(FitsPtr,&sta)) printerror(sta);
 FitsPtr = NULL;
}

/*! Flush the FitsIO buffer to set good Fits file in case of problems */
void FitsABTWriter::Flush(void)
{
 if(FitsPtr==NULL) return;
 int sta = 0;
 if(fits_flush_file(FitsPtr,&sta)) printerror(sta);
}

/*! Write a double value into Fits Header */
void FitsABTWriter::WriteKey(const char *keyname,double val,char* comment)
{
 if(keyname==NULL || strlen(keyname)<=0) return;
 KeyDouble k;
 k.keyname=keyname;
 k.val=val;
 if(comment) k.comment=comment; else k.comment="";
 DoubleKey.push_back(k);
}

/*! Write a long value into Fits Header */
void FitsABTWriter::WriteKey(const char *keyname,long val,char* comment)
{
 if(keyname==NULL || strlen(keyname)<=0) return;
 KeyLong k;
 k.keyname=keyname;
 k.val=val;
 if(comment) k.comment=comment; else k.comment="";
 LongKey.push_back(k);
}

void FitsABTWriter::writekeys(void)
// Ecriture effective des clefs
{
 if(FitsPtr==NULL) return;
 int sta=0;
 if(DoubleKey.size()>0)
   for(unsigned int i=0;i<DoubleKey.size();i++) {
     char* key = const_cast<char*>(DoubleKey[i].keyname.c_str());
     char* com = const_cast<char*>(DoubleKey[i].comment.c_str());
     double val = DoubleKey[i].val;
     if(fits_update_key(FitsPtr,TDOUBLE,key,&val,com,&sta))
       printerror(sta);
   }
 if(LongKey.size()>0)
   for(unsigned int i=0;i<LongKey.size();i++) {
     char* key = const_cast<char*>(LongKey[i].keyname.c_str());
     char* com = const_cast<char*>(LongKey[i].comment.c_str());
     long val = LongKey[i].val;
     if(fits_update_key(FitsPtr,TLONG,key,&val,com,&sta))
       printerror(sta);
   }
 DoubleKey.resize(0);
 LongKey.resize(0);
}

//////////////////////////////////////////////////////////////
/*!
  Add a new column to the FITS table
  \param label : column label
  \param tform : fits tform definition ("1I","1J","1E","1J",...)
         (can be automatically set as "datatype"
          if BINARY_TBL and tform="" or tform=NULL)
  \param tunit : fits tunit definition (optional)
  \param datatype : TBYTE TSHORT TLONG (TINT32BIT) TLONGLONG TFLOAT TDOUBLE
                    TUSHORT TULONG. That parameter is only use in case
                    of a BINARY_TBL table when tform is not defined).
  \return The number of the new added column in the table.
  \warning col = [0,ncol-1]
*/
int FitsABTWriter::addcol(const char* label,const char* tform
                         ,const char* tunit,int datatype)
{
  if(!FirstTime)
    throw AllocationError("FitsABTWriter::addcol: table already created\n");
 
 // Gestion auto du tform pour les tables binaires avec le datatype (si non-definie)
 bool tformauto = false;
 if(HduType==BINARY_TBL || HduType==ASCII_TBL) {
   if(tform==NULL)           tformauto = true;
   else if(strlen(tform)<=0) tformauto = true;
 }
 if(tformauto && HduType==BINARY_TBL) {
   char str[8];
   if(datatype==TBYTE)          strcpy(str,"1B");
   else if(datatype==TSHORT)    strcpy(str,"1I");
   else if(datatype==TLONG)     strcpy(str,"1J");
#ifdef TINT32BIT
   else if(datatype==TINT32BIT) strcpy(str,"1J");
#endif
#ifdef TLONGLONG
   else if(datatype==TLONGLONG) strcpy(str,"1K");
#endif
   else if(datatype==TFLOAT)    strcpy(str,"1E");
   else if(datatype==TDOUBLE)   strcpy(str,"1D");
   else if(datatype==TUSHORT)   strcpy(str,"1U");
   else if(datatype==TULONG)    strcpy(str,"1V");
   else
     throw ParmError("FitsABTWriter::addcol: datatype not allowed\n");
   TForm.push_back(str);
 } else if(tformauto && HduType==ASCII_TBL) {
   char str[8];
   if(datatype==TBYTE)          strcpy(str,"I5");
   else if(datatype==TSHORT)    strcpy(str,"I7");
   else if(datatype==TLONG)     strcpy(str,"I11");
#ifdef TINT32BIT
   else if(datatype==TINT32BIT) strcpy(str,"I11");
#endif
#ifdef TLONGLONG
   else if(datatype==TLONGLONG) strcpy(str,"I21");
#endif
   else if(datatype==TFLOAT)    strcpy(str,"E29.20");
   else if(datatype==TDOUBLE)   strcpy(str,"E29.20");
   else if(datatype==TUSHORT)   strcpy(str,"I7");
   else if(datatype==TULONG)    strcpy(str,"I11");
   else
     throw ParmError("FitsABTWriter::addcol: datatype not allowed\n");
   TForm.push_back(str);
 } else {
   if(tform) TForm.push_back(tform); else TForm.push_back("");
   datatype = 0;
 }
 Label.push_back(label);
 if(tunit) TUnit.push_back(tunit); else TUnit.push_back("");

 int n = (int) Label.size() -1;

 if(DbgLevel)
   cout<<"FitsABTWriter::addcol["<<n<<"] Label="<<Label[n]
       <<" TForm="<<TForm[n]
       <<" TUnit="<<TUnit[n]
       <<" datatype="<<datatype<<endl;

 return n;
}

/*! Create the table. Done at the first write request. */
void FitsABTWriter::createtbl(void)
{
  if(!FirstTime) return;

 int tfields = Label.size();
 if(tfields<=0)
   throw ParmError("FitsABTWriter::createtbl: Zero column asked !\n");

 long nrows = 0;
 char *extname = NULL;
 char **ttype   = (char **) malloc(tfields*sizeof(char *));
 char **tform   = (char **) malloc(tfields*sizeof(char *));
 char **tunit   = (char **) malloc(tfields*sizeof(char *));

 if(ExtName.size()>0) {
   extname = (char *) malloc((strlen(ExtName.c_str())+1)*sizeof(char));
   strcpy(extname,ExtName.c_str());
 }
 int i;
 for(i=0;i<tfields;i++) {
   ttype[i] = (char *) malloc((strlen(Label[i].c_str())+1)*sizeof(char));
     strcpy(ttype[i],Label[i].c_str());
   tform[i] = (char *) malloc((strlen(TForm[i].c_str())+1)*sizeof(char));
     strcpy(tform[i],TForm[i].c_str());
   tunit[i] = (char *) malloc((strlen(TUnit[i].c_str())+1)*sizeof(char));
     strcpy(tunit[i],TUnit[i].c_str());
 }

 // append a new empty binary/ascii table onto the FITS file
 int sta=0;
 if(fits_create_tbl(FitsPtr,HduType,nrows,tfields,ttype,tform,tunit,extname,&sta)) {
   printerror(sta);
   throw NullPtrError("FitsABTWriter::createtbl: Error creating Table extension\n");
 }

 // Append Fits key
 writekeys();

 // menage
 if(extname) delete [] extname;
 for(i=0;i<tfields;i++) {
   if(ttype[i]) delete [] ttype[i];
   if(tform[i]) delete [] tform[i];
   if(tunit[i]) delete [] tunit[i];
 }
 if(ttype) delete [] ttype;
 if(tform) delete [] tform;
 if(tunit) delete [] tunit;

 FirstTime = false;
}

//////////////////////////////////////////////////////////////
/*!
  Write a data to FITS file.
  \param col : column number [0,ncol[
  \param row : row number    [0,nrow[
  \param val : value to be written
  \warning that routine write a SHORT value into column "col"
           which could have been defined with an other type.
           Cast is performed by the cfitsio package.
  \verbatim
  WARNING: suppose that the column has be defined to be TSHORT
           and suppose that you wanted to write a double value "val"
   - If you write dummy.Write(col,row,(short)(val))
       the Write(int,long,short) routine is called and
       the cast is performed by the C++ language.
   - If you write dummy.Write(col,row,val) where val is double
       the Write(int,long,double) routine is called and
       the cast is performed by the cfistio package.
  \endverbatim
*/

/*! Write unsigned char (1 Byte) data to FITS file (see below) */
void FitsABTWriter::Write(int col,long row,uint_1 val)
{
  if(FirstTime) createtbl();
  int sta=0;
  if(fits_write_col(FitsPtr,TBYTE,col+1,row+1,1,1,&val,&sta))
    printerrorwrite("unsigned char",col,row,sta);
}

/*! Write short (2 Bytes) data to FITS file (see below) */
void FitsABTWriter::Write(int col,long row,int_2 val)
{
  if(FirstTime) createtbl();
  int sta=0;
  if(fits_write_col(FitsPtr,TSHORT,col+1,row+1,1,1,&val,&sta))
    printerrorwrite("short",col,row,sta);
}

/*! Write unsigned short (2 Bytes) data to FITS file (see below) */
void FitsABTWriter::Write(int col,long row,uint_2 val)
{
  if(FirstTime) createtbl();
  int sta=0;
  if(fits_write_col(FitsPtr,TUSHORT,col+1,row+1,1,1,&val,&sta))
    printerrorwrite("unsigned short",col,row,sta);
}

/*! Write long (4 Bytes) data to FITS file (see below) */
void FitsABTWriter::Write(int col,long row,int_4 val)
{
  if(FirstTime) createtbl();
  int sta=0;
  // Bug ou inconsistence cfitsio sur machine ou long=8Bytes ?
  int T = (sizeof(long)==4) ? TLONG: TINT;
  if(fits_write_col(FitsPtr,T,col+1,row+1,1,1,&val,&sta))
    printerrorwrite("long",col,row,sta);
}

/*! Write unsigned long (4 Bytes) data to FITS file (see below) */
void FitsABTWriter::Write(int col,long row,uint_4 val)
{
  if(FirstTime) createtbl();
  int sta=0;
  // Bug ou inconsistence cfitsio sur machine ou long=8Bytes ?
  int T = (sizeof(unsigned long)==4) ? TULONG: TUINT;
  if(fits_write_col(FitsPtr,T,col+1,row+1,1,1,&val,&sta))
    printerrorwrite("long",col,row,sta);
}

/*! Write long long (8 Bytes) data to FITS file (see below) */
void FitsABTWriter::Write(int col,long row,int_8 val)
{
#ifdef TLONGLONG
  if(FirstTime) createtbl();
  int sta=0;
  if(fits_write_col(FitsPtr,TLONGLONG,col+1,row+1,1,1,&val,&sta))
    printerrorwrite("long long",col,row,sta);
#else
  throw PException("FitsABTWriter::Write(..,int_8) Not in that cfitsio version");
#endif
}

/*! Write float data to FITS file (see below) */
void FitsABTWriter::Write(int col,long row,float val)
{
  if(FirstTime) createtbl();
  int sta=0;
  if(fits_write_col(FitsPtr,TFLOAT,col+1,row+1,1,1,&val,&sta))
    printerrorwrite("float",col,row,sta);
}

/*! Write double data to FITS file (see below) */
void FitsABTWriter::Write(int col,long row,double val)
{
  if(FirstTime) createtbl();
  int sta=0;
  if(fits_write_col(FitsPtr,TDOUBLE,col+1,row+1,1,1,&val,&sta))
    printerrorwrite("double",col,row,sta);
}

//////////////////////////////////////////////////////////////
/*!
  Write a vector of data to FITS file.
  \param col : column number [0,ncol[
  \param row : starting row number    [0,nrow[
  \param val : vector to be written
  \return "N" = number of the next row to be written,
      that is "N-1" is the number of the last row written.
*/

/*! Write a vector of unsigned short (2 Bytes) data to FITS file (see below) */
long FitsABTWriter::Write(int col,long row,TVector<uint_2>& val)
{
  if(FirstTime) createtbl();
  long nel = val.Size();
  int sta=0;
  if(fits_write_col(FitsPtr,TUSHORT,col+1,row+1,1,nel,val.Data(),&sta))
    printerrorwrite("long",col,row,sta);
  return row+nel;
}

/*! Write a vector of long (4 Bytes) data to FITS file (see below) */
long FitsABTWriter::Write(int col,long row,TVector<int_4>& val)
{
  if(FirstTime) createtbl();
  long nel = val.Size();
  int sta=0;
  // Bug ou inconsistence cfitsio sur machine ou long=8Bytes ?
  int T = (sizeof(long)==4) ? TLONG: TINT;
  if(fits_write_col(FitsPtr,T,col+1,row+1,1,nel,val.Data(),&sta))
    printerrorwrite("long",col,row,sta);
  return row+nel;
}

/*! Write a vector of long long (8 Bytes) data to FITS file (see below) */
long FitsABTWriter::Write(int col,long row,TVector<int_8>& val)
{
#ifdef TLONGLONG
  if(FirstTime) createtbl();
  long nel = val.Size();
  int sta=0;
  if(fits_write_col(FitsPtr,TLONGLONG,col+1,row+1,1,nel,val.Data(),&sta))
    printerrorwrite("long long",col,row,sta);
  return row+nel;
#else
  throw PException("FitsABTWriter::Write(..,TVector<int_8>&) Not in that cfitsio version");
#endif
}

/*! Write a vector of float data to FITS file (see below) */
long FitsABTWriter::Write(int col,long row,TVector<float>&  val)
{
  if(FirstTime) createtbl();
  long nel = val.Size();
  int sta=0;
  if(fits_write_col(FitsPtr,TFLOAT,col+1,row+1,1,nel,val.Data(),&sta))
    printerrorwrite("float",col,row,sta);
  return row+nel;
}

/*! Write a vector of double data to FITS file (see below) */
long FitsABTWriter::Write(int col,long row,TVector<double>& val)
{
  if(FirstTime) createtbl();
  long nel = val.Size();
  int sta=0;
  if(fits_write_col(FitsPtr,TDOUBLE,col+1,row+1,1,nel,val.Data(),&sta))
    printerrorwrite("double",col,row,sta);
  return row+nel;
}

//////////////////////////////////////////////////////////////
void FitsABTWriter::printerrorwrite(const char* type,int col,long row,int sta)
{
 if(sta==NUM_OVERFLOW) {NOverFlow++; return;}
 printerror(sta);
 char str[256];
 sprintf(str,"FitsABTWriter::Write_%s: Error Writing Fits c=%d r=%ld sta=%d"
        ,type,col,row,sta);
 throw NotAvailableOperation(str);
}

/////////////////////////////////////////////////
void FitsABTWriter::printerror(int sta) const
{
 int stat = sta;
 fits_report_error(stdout,stat);
 fflush(stdout);
 return;
}

/////////////////////////////////////////////////
void FitsABTWriter::Print(ostream& os,int lp) const
{
os<<"FitsABTWriter::Print: FitsFN "<<FitsFN<<endl
  <<"                      HduType "<<HduType<<"  NOverFlow "<<NOverFlow
  <<"  NCol "<<Label.size()<<endl;
if(Label.size()>0 && lp>=1)
  for(int i=0;i<(int)Label.size();i++)
    os<<i<<"... Label="<<Label[i]<<" TForm="<<TForm[i]<<" TUnit="<<TUnit[i]<<endl;
}
