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

//////////////////////////////////////////////////////////////
//////////////////////////////////////////////////////////////
//////////////////////////////////////////////////////////////
//////////////////////////////////////////////////////////////
/*!
  \class SOPHYA::FitsWriter
  \ingroup FitsIOServer
  Class for writing into a FITS file (DO NOT USE)
*/

/*! Constructor  (DO NOT USE). */
FitsWriter::FitsWriter(string fname,int lp)
{
  cr_or_upd_fits(fname.c_str(),false,lp);
}

/*! Constructor (DO NOT USE). */
FitsWriter::FitsWriter(const char* cfname,int lp)
{
  cr_or_upd_fits(cfname,false,lp);
}

/*! Constructor (DO NOT USE). */
FitsWriter::FitsWriter(string fname,bool update,int lp)
{
  cr_or_upd_fits(fname.c_str(),update,lp);
}

/*! Constructor (DO NOT USE). */
FitsWriter::FitsWriter(const char* cfname,bool update,int lp)
{
  cr_or_upd_fits(cfname,update,lp);
}

/*! See FitsWriter() */
void FitsWriter::cr_or_upd_fits(const char *cfname,bool update,int lp)
{
 FitsPtr = NULL;
 HduType = 0;
 SetDebug(lp);
 FitsFN = cfname;
 NOverFlow = 0;
 Update = update;
 // Init key structure
 DoubleKey.resize(0);
 LongKey.resize(0);
 StringKey.resize(0);

 if(DbgLevel)
   cout<<"FitsWriter::cr_or_upd_fits FitsFN="<<FitsFN<<endl;

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

 // create or update FITS file
 int sta=0;
 if(Update) {
   if(fits_open_file(&FitsPtr,FitsFN.c_str(),READWRITE,&sta)) {
     printerror(sta);
     throw NullPtrError("FitsWriter::cr_or_upd_fits: Error opening Fits file for update\n");
   }
   if(DbgLevel) cout<<"FitsWriter::cr_or_upd_fits: fits file has been opened for update"<<endl;
 } else {
   if(fits_create_file(&FitsPtr,FitsFN.c_str(),&sta)) {
     printerror(sta);
     throw NullPtrError("FitsWriter::cr_or_upd_fits: Error creating new Fits file\n");
   }
   if(DbgLevel) cout<<"FitsWriter::cr_or_upd_fits: a new fits file has been created"<<endl;
 }

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

/*! Destructor */
FitsWriter::~FitsWriter()
{
 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 FitsWriter::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 FitsWriter::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 FitsWriter::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);
}

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

void FitsWriter::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);
   }
 if(StringKey.size()>0)
   for(unsigned int i=0;i<StringKey.size();i++) {
     char* key = const_cast<char*>(StringKey[i].keyname.c_str());
     char* com = const_cast<char*>(StringKey[i].comment.c_str());
     char* val = const_cast<char*>(StringKey[i].val.c_str());
     if(fits_update_key(FitsPtr,TSTRING,key,val,com,&sta))
       printerror(sta);
   }
 DoubleKey.resize(0);
 LongKey.resize(0);
 StringKey.resize(0);
}

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

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

//////////////////////////////////////////////////////////////////
//////////////////////////////////////////////////////////////////
//////////////////////////////////////////////////////////////////
//////////////////////////////////////////////////////////////////
/*!
  \class SOPHYA::FitsABTWriter
  \ingroup FitsIOServer
  Class for writing a FITS ASCII or BINARY table
  \verbatim
  //-----------------------------------------------------------
  OPENING A NEW FILE AND WRITING INTO
  -- Exemple 1: Writing element by element
  FitsABTWriter fbtw(fitswrit,BINARY_TBL);
  fbtw.SetExtName("MY_OWN_EXTENSION");
  int c1 = fbtw.AddCol("vars",NULL,"km",TSHORT);       // col=0
  int c2 = fbtw.AddCol("vars2",NULL,"km",TSHORT);      // col=1
  int c3 = fbtw.AddCol("varl",NULL,"Degre",TLONG);     // col=2
  int c4 = fbtw.AddCol("varf",NULL,"",TFLOAT);         // col=3
  int c5 = fbtw.AddCol("vard","","arcmin",TDOUBLE);    // col=4
  fbtw.SetDebug(3);
  for(long i=0;i<1000;i++) {
    double x = i;
    fbtw.Write(c1,i,1000.*x); // if overflow, managed by cfitsio
                             // Write(int,long,double) is called
    fbtw.Write(c2,i,(short)(1000.*x));
                             // if overflow, managed by language
                             // Write(int,long,short) is called
    fbtw.Write(c3,i,x);
    fbtw.Write(c4,i,x);
    fbtw.Write(c5,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
  \verbatim
  //-----------------------------------------------------------
  //-----------------------------------------------------------
  //-----------------------------------------------------------
  OPENING A NEW FILE AND WRITING 2 TABLE EXTENSIONS SIMULTANEOUSLY INTO
 try {

   cout<<">>>>> Creating a new fits file with FitsABTWriter"<<endl;
   FitsABTWriter fbtw("!cmvtstfits3.fits",BINARY_TBL,3);
   //FitsABTWriter fbtw("!cmvtstfits3.fits",false,BINARY_TBL,3);
   fbtw.SetExtName("Test fits table 1");
   cout<<"Writing Keys"<<endl;
   fbtw.WriteKey("MYKEYL",(long)123456789,"my LONG key");
   fbtw.WriteKey("MYKEYD",1.9999999,"my DOUBLE key");
   fbtw.WriteKey("MYKEYC","how are you ?","my CHAR* key");
   dum="do you feel better ?";
   fbtw.WriteKey("MYKEYS",dum,"my STRING key");
   i1 = fbtw.AddCol("x1",NULL,"unit1",TDOUBLE);
   i2 = fbtw.AddCol("x2",NULL,"unit2",TDOUBLE);
   i3 = fbtw.AddCol("x3",NULL,"unit3",TDOUBLE);
   fbtw.Print();

   cout<<">>>>> Another extension fits table with FitsABTWriter"<<endl;
   FitsABTWriter fbtw2("cmvtstfits3.fits",true,BINARY_TBL,3);
   fbtw2.SetExtName("Test fits table 2");
   cout<<"Writing Keys"<<endl;
   fbtw2.WriteKey("MYKEYL",(long)-123456789,"my new LONG key");
   fbtw2.WriteKey("MYKEYD",-1.9999999,"my new clef DOUBLE key");
   fbtw2.WriteKey("MYKEYC","how are you NOW ?","my new CHAR* key");
   dum="do you feel better NOW ?";
   fbtw2.WriteKey("MYKEYS",dum,"my new STRING key");
   i11 = fbtw2.AddCol("x11",NULL,"unit11",TDOUBLE);
   i12 = fbtw2.AddCol("x12",NULL,"unit12",TDOUBLE);
   i13 = fbtw2.AddCol("x13",NULL,"unit13",TDOUBLE);
   fbtw2.Print();

   cout<<">>>>> Write into the 2 tables simultaneously"<<endl;
   for(int i=0;i<NNN;i++) {
     fbtw.Write(i1,i,i+1.);
     fbtw.Write(i2,i,i+11.);
     fbtw.Write(i3,i,i+101.);
     fbtw2.Write(i11,i,-(i+1.));
     fbtw2.Write(i12,i,-(i+11.));
     fbtw2.Write(i13,i,-(i+101.));
   }

 } catch (PThrowable & exc) {
   cout<<"Exception : "<<(string)typeid(exc).name()
       <<" - Msg= "<<exc.Msg()<<endl;
   return -2;
 } catch (...) {
   cout<<" some other exception was caught !"<<endl;
   return -2;
 }
  \endverbatim
*/

//////////////////////////////////////////////////////////////
/*!
  Constructor.
  \param fname : FITS file name to be written (a new fits file is created)
  \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)
: FitsWriter(fname,lp)
{
 FirstTime = true;
 HduType = hdutype;
 if(HduType!=BINARY_TBL && HduType!=ASCII_TBL)
   throw
     TypeMismatchExc("FitsABTWriter::FitsABTWriter: Only BINARY or ASCII table permitted\n");
}

/*!
  Constructor.
  \param cfname : FITS file name to be written (a new fits file is created)
  \param hdutype : type of extension to be created (BINARY_TBL or ASCII_TBL)
  \param lp : debug level
*/
FitsABTWriter::FitsABTWriter(const char* cfname,int hdutype,int lp)
: FitsWriter(cfname,lp)
{
 FirstTime = true;
 HduType = hdutype;
 if(HduType!=BINARY_TBL && HduType!=ASCII_TBL)
   throw
     TypeMismatchExc("FitsABTWriter::FitsABTWriter: Only BINARY or ASCII table permitted\n");
}

/*!
  Constructor.
  \param fname : FITS file name to be written (created or updated)
  \param update : file is created if FALSE, open for update if TRUE
  \param hdutype : type of extension to be created (BINARY_TBL or ASCII_TBL)
  \param lp : debug level
*/
FitsABTWriter::FitsABTWriter(string fname,bool update,int hdutype,int lp)
: FitsWriter(fname,update,lp)
{
 FirstTime = true;
 HduType = hdutype;
 if(HduType!=BINARY_TBL && HduType!=ASCII_TBL)
   throw
     TypeMismatchExc("FitsABTWriter::FitsABTWriter: Only BINARY or ASCII table permitted\n");
}

/*!
  Constructor.
  \param cfname : FITS file name to be written (created or updated)
  \param update : file is created if FALSE, open for update if TRUE
  \param hdutype : type of extension to be created (BINARY_TBL or ASCII_TBL)
  \param lp : debug level
*/
FitsABTWriter::FitsABTWriter(const char* cfname,bool update,int hdutype,int lp)
: FitsWriter(cfname,update,lp)
{
 FirstTime = true;
 HduType = hdutype;
 if(HduType!=BINARY_TBL && HduType!=ASCII_TBL)
   throw
     TypeMismatchExc("FitsABTWriter::FitsABTWriter: Only BINARY or ASCII table permitted\n");
}

/*! Destructor */
FitsABTWriter::~FitsABTWriter()
{
}

//////////////////////////////////////////////////////////////
/*!
  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 TSBYTE. 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");
#ifdef TSBYTE
   else if(datatype==TSBYTE)    strcpy(str,"1S");
#endif
   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");
#ifdef TSBYTE
   else if(datatype==TSBYTE)    strcpy(str,"I5");
#endif
   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");
 }

 // 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 signed char (1 Byte) data to FITS file (see below) */
void FitsABTWriter::Write(int col,long row,int_1 val)
{
#ifdef TSBYTE
  if(FirstTime) createtbl();
  int sta=0;
  if(fits_write_col(FitsPtr,TSBYTE,col+1,row+1,1,1,&val,&sta))
    printerrorwrite("signed char",col,row,sta);
#else
  throw PException("FitsABTWriter::Write(..,int_1) Not in that cfitsio version");
#endif
}

/*! 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::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;
}

//////////////////////////////////////////////////////////////////
//////////////////////////////////////////////////////////////////
//////////////////////////////////////////////////////////////////
//////////////////////////////////////////////////////////////////
/*!
  \class SOPHYA::FitsImg2DWriter
  \ingroup FitsIOServer
  Class for writing an image into FITS file
*/

/*!
  Constructor.
  \param fname : FITS file name to be written (a new fits file is created)
  \param bitpix : image type (BYTE_IMG,USHORT_IMG,SHORT_IMG,LONG_IMG,FLOAT_IMG,DOUBLE_IMG)
  \param lp : debug level
*/
FitsImg2DWriter::FitsImg2DWriter(string fname,int bitpix,int lp)
: FitsWriter(fname,lp)
{
 BitPix = bitpix;
 HduType = IMAGE_HDU;
 FirstTime = true;
 Naxis[0] = Naxis[1] = 0;
}

/*!
  Constructor.
  \param cfname : FITS file name to be written (a new fits file is created)
  \param bitpix : image type (BYTE_IMG,USHORT_IMG,SHORT_IMG,LONG_IMG,FLOAT_IMG,DOUBLE_IMG)
  \param lp : debug level
*/
FitsImg2DWriter::FitsImg2DWriter(const char* cfname,int bitpix,int lp)
: FitsWriter(cfname,lp)
{
 BitPix = bitpix;
 HduType = IMAGE_HDU;
 FirstTime = true;
 Naxis[0] = Naxis[1] = 0;
}

/*!
  Constructor.
  \param fname : FITS file name to be written (created or updated)
  \param update : file is created if FALSE, open for update if TRUE
  \param bitpix : image type (BYTE_IMG,USHORT_IMG,SHORT_IMG,LONG_IMG,FLOAT_IMG,DOUBLE_IMG)
  \param lp : debug level
*/
FitsImg2DWriter::FitsImg2DWriter(string fname,bool update,int bitpix,int lp)
: FitsWriter(fname,update,lp)
{
 BitPix = bitpix;
 HduType = IMAGE_HDU;
 FirstTime = true;
 Naxis[0] = Naxis[1] = 0;
}

/*!
  Constructor.
  \param cfname : FITS file name to be written (created or updated)
  \param update : file is created if FALSE, open for update if TRUE
  \param bitpix : image type (BYTE_IMG,USHORT_IMG,SHORT_IMG,LONG_IMG,FLOAT_IMG,DOUBLE_IMG)
  \param lp : debug level
*/
FitsImg2DWriter::FitsImg2DWriter(const char* cfname,bool update,int bitpix,int lp)
: FitsWriter(cfname,update,lp)
{
 BitPix = bitpix;
 HduType = IMAGE_HDU;
 FirstTime = true;
 Naxis[0] = Naxis[1] = 0;
}

/*! Destructor */
FitsImg2DWriter::~FitsImg2DWriter()
{
}

/*! Create the image. Done at the first write request. */
void FitsImg2DWriter::createimg(void)
{
 if(!FirstTime)
   throw NotAvailableOperation("FitsImg2DWriter::createimg: already created image\n");
 if(Naxis[0]<=0 || Naxis[1]<=0)
   throw ParmError("FitsImg2DWriter::createimg: bad Naxis 1 or 2 value\n");

 int sta=0;
 if(fits_create_img(FitsPtr,BitPix,2,Naxis,&sta)) {
   printerror(sta);
   throw NullPtrError("FitsImg2DWriter::createimg: Error creating image extension\n");
 }

 FirstTime = false;
}

/*!
  Write an unsigned short image to FITS file.
  \warning TMatrix data(Naxis2,Naxis1) means Data(row,column)
*/
void FitsImg2DWriter::Write(TMatrix<uint_2>& data)
{
 Naxis[0]=data.NCols(); Naxis[1]=data.NRows(); createimg();
 uint_2* arr = new uint_2[Naxis[0]];

 for(int l=0;l<Naxis[1];l++) {
   for(int c=0;c<Naxis[0];c++) arr[c] = data(l,c);
   long deb = l*Naxis[0]+1, nel = Naxis[0]; int sta=0;
   fits_write_img(FitsPtr,TUSHORT,deb,nel,arr,&sta);
   if(sta) {
     printerrorwrite("uint_2",0,l,sta); delete [] arr;
     throw
       NotAvailableOperation("FitsImg2DRd::Write(TMatrix<uint_2>): Error Writing Fits file\n");
   }
 }

 delete [] arr;
}

/*! Write a long image to FITS file. */
void FitsImg2DWriter::Write(TMatrix<int_4>& data)
{
 int T = (sizeof(long)==4) ? TLONG: TINT;
 Naxis[0]=data.NCols(); Naxis[1]=data.NRows(); createimg();
 int_4* arr = new int_4[Naxis[0]];

 for(int l=0;l<Naxis[1];l++) {
   for(int c=0;c<Naxis[0];c++) arr[c] = data(l,c);
   long deb = l*Naxis[0]+1, nel = Naxis[0]; int sta=0;
   fits_write_img(FitsPtr,T,deb,nel,arr,&sta);
   if(sta) {
     printerrorwrite("int_4",0,l,sta); delete [] arr;
     throw
       NotAvailableOperation("FitsImg2DRd::Write(TMatrix<int_4>): Error Writing Fits file\n");
   }
 }

 delete [] arr;
}

/*! Write a float image to FITS file. */
void FitsImg2DWriter::Write(TMatrix<float>& data)
{
 Naxis[0]=data.NCols(); Naxis[1]=data.NRows(); createimg();
 float* arr = new float[Naxis[0]];

 for(int l=0;l<Naxis[1];l++) {
   for(int c=0;c<Naxis[0];c++) arr[c] = data(l,c);
   long deb = l*Naxis[0]+1, nel = Naxis[0]; int sta=0;
   fits_write_img(FitsPtr,TFLOAT,deb,nel,arr,&sta);
   if(sta) {
     printerrorwrite("float",0,l,sta); delete [] arr;
     throw
       NotAvailableOperation("FitsImg2DRd::Write(TMatrix<float>): Error Writing Fits file\n");
   }
 }

 delete [] arr;
}

/*! Write a double image to FITS file. */
void FitsImg2DWriter::Write(TMatrix<double>& data)
{
 Naxis[0]=data.NCols(); Naxis[1]=data.NRows(); createimg();
 double* arr = new double[Naxis[0]];

 for(int l=0;l<Naxis[1];l++) {
   for(int c=0;c<Naxis[0];c++) arr[c] = data(l,c);
   long deb = l*Naxis[0]+1, nel = Naxis[0]; int sta=0;
   fits_write_img(FitsPtr,TDOUBLE,deb,nel,arr,&sta);
   if(sta) {
     printerrorwrite("double",0,l,sta); delete [] arr;
     throw
       NotAvailableOperation("FitsImg2DRd::Write(TMatrix<double>): Error Writing Fits file\n");
   }
 }

 delete [] arr;
}

/*! Print infos. */
void FitsImg2DWriter::Print(ostream& os) const
{
os<<"FitsImg2DWriter::Print: FitsFN "<<FitsFN<<endl
  <<"  HduType "<<HduType<<"  NOverFlow "<<NOverFlow<<"  BitPix "<<BitPix
  <<"  Naxis1 "<<Naxis[0]<<"  Naxis2 "<<Naxis[1]<<endl;
}
