#include "sopnamsp.h"
#include "pexceptions.h"
#include "fitsxntuple.h"
///////////////////////////////////////////////////////////
//   Les objets delegues pour la gestion de persistance sur fichiers fits 
//    pout XNTuple
///////////////////////////////////////////////////////////

/*!
  \class SOPHYA::FITS_XNTuple
  \ingroup FitsIOServer
  FITS format I/O handler for SOPHYA::XNTuple objects.
*/


#define LONNOM 31 


FITS_XNTuple::FITS_XNTuple()
{
  dobj_ = new XNTuple;
  InitNull();
  ownobj_ = true;
}

FITS_XNTuple::FITS_XNTuple(char inputfile[],int hdunum)
{
  dobj_ = new XNTuple;
  InitNull();
  ownobj_ = true; 

  Read(inputfile,hdunum);
}


FITS_XNTuple::FITS_XNTuple(const XNTuple & obj) 
{ 
  dobj_ = new XNTuple(obj);
  InitNull();
  ownobj_ = true; 
}
FITS_XNTuple::FITS_XNTuple(XNTuple* obj) 
{ 
  dobj_ = obj;
  InitNull();
  ownobj_ = false; 
}
FITS_XNTuple::~FITS_XNTuple()
{
  if (ownobj_ && dobj_ != NULL) delete dobj_;
}


void FITS_XNTuple::ReadLines(char inputfile[],int firstLine, int numberOfLines,int hdunum)
{
  fistLineToBeRead_ = firstLine;
  numberOfLinesToBeRead_ = numberOfLines;
  Read(inputfile,hdunum);
}


 
void FITS_XNTuple::ReadFromFits(FitsInFile& is)
{   
  if (!is.IsFitsTable())
    {
      throw PException("ReadFromFits: the fits file seems not to be a bintable nor ASCII table");
    }
  int nbcols, nbentries;
  nbcols = is.NbColsFromFits();
  nbentries = 0;
  int k;
  for (k=0; k<nbcols; k++) nbentries=max( nbentries, is.NentriesFromFits(k) );

  //
  // pour mettre les colonnes dans l'ordre double, float, int, char :
  // tableau de correspondance 
  // DfitsCol(j)= numero dans le fichier fits de la  jeme variable double du 
  // xntuple;
  // FfitsCol(j)= numero dans le fichier fits de la  jeme variable float du 
  // xntuple;
  // etc.
  vector<int> DfitsCol;
  vector<int> FfitsCol;
  vector<int> IfitsCol;
  vector<int> SfitsCol;
  for (k=0; k<nbcols;k++)
    {

      FitsFile::FitsDataType ss= is.ColTypeFromFits(k);
      switch (ss) 
	{
	case  FitsFile::FitsDataType_double :
	  {
	    DfitsCol.push_back(k);
	    break;
	  }
	case FitsFile::FitsDataType_float :
	  {
	    FfitsCol.push_back(k);
	    break;
	  }
	case FitsFile::FitsDataType_int :
	  {
	    IfitsCol.push_back(k);
	    break;
	  }
	case FitsFile::FitsDataType_long :
	  {
	    IfitsCol.push_back(k);
	    break;
	  }
	case FitsFile::FitsDataType_byte :
	  {
	    IfitsCol.push_back(k);
	    break;
	  }
	case FitsFile::FitsDataType_char :
	  {
	    SfitsCol.push_back(k);
	    break;
	  }
	default :
	  {
	    cout << " FITS_XNTuple: colonne fits " << k << " type= " << (int) ss << endl;
	    throw  IOExc("type de champ inconnu");
	  }
	}
    }
  char ** ColName = new char*[nbcols];
  int compt=0;
  for (k=0; k<DfitsCol.size(); k++)
    {
      ColName[compt] = new char[LONNOM+1]; 
      strncpy(ColName[compt], is.ColNameFromFits(DfitsCol[k]).c_str(), LONNOM);
      ColName[compt++][ LONNOM] =  '\0';
    }
  for (k=0; k<FfitsCol.size(); k++)
    {
      ColName[compt] = new char[LONNOM+1]; 
      strncpy(ColName[compt], is.ColNameFromFits(FfitsCol[k]).c_str(), LONNOM);
      ColName[compt++][ LONNOM] =  '\0';
    }
  for (k=0; k<IfitsCol.size(); k++)
    {
      ColName[compt] = new char[LONNOM+1]; 
      strncpy(ColName[compt], is.ColNameFromFits(IfitsCol[k]).c_str(), LONNOM);
      ColName[compt++][ LONNOM] =  '\0';
    }
  for (k=0; k<SfitsCol.size(); k++)
    {
      ColName[compt] = new char[LONNOM+1]; 
      strncpy(ColName[compt], is.ColNameFromFits(SfitsCol[k]).c_str(), LONNOM);
      ColName[compt++][LONNOM] =  '\0';
    }
  int ND = DfitsCol.size();
  int NF = FfitsCol.size();
  int NI = IfitsCol.size();
  int NS = SfitsCol.size();
  if(dobj_ == NULL) 
    { 
      dobj_= new XNTuple(ND, NF, NI, NS,ColName);
      ownobj_ = true;      
    }
  else 
    {
      if (ownobj_)
	{
	  (*dobj_)= XNTuple(ND, NF, NI, NS,ColName);
	}
      else
	{
	  if (ND != dobj_->NDVar() || NF != dobj_->NFVar() ||  NI != dobj_->NIVar() || NS != dobj_->NSVar())
	    {
	      //	      cout << " WARNING : FITS_XNTuple : XNTuple reconfigured " << endl;
	      (*dobj_)= XNTuple(ND, NF, NI, NS,ColName);
	    }
	}
    }

  for (k=0; k<nbcols;k++) 
    {
      delete [] ColName[k];
    }
  delete [] ColName;

    r_8* dligne;
    r_4* fligne;
    int_4* iligne;
    char** cligne;

  if (ND>0) dligne = new double[ND];
  else dligne=NULL;
  if (NF>0) fligne = new float[NF];
  else fligne=NULL;
  if (NI) iligne = new int[NI];
  else iligne=NULL;
  if (NS) 
    {
      cligne = new char*[NS];
      int  taille_des_chaines=0;
      for (k=0; k< NS; k++)  taille_des_chaines = max( taille_des_chaines, is.ColStringLengthFromFits(SfitsCol[k]) );
      for (k=0; k<NS; k++) cligne[k]=new char[taille_des_chaines+1];
    }
  else cligne=NULL;
  int firstln, lastln;
  if (numberOfLinesToBeRead_ > 0) 
    {
      firstln = fistLineToBeRead_;
      lastln = firstln + numberOfLinesToBeRead_;
    }
  else
    {
      firstln = 0;
      lastln  = nbentries;
    }
  int numLigne;
  for (numLigne=firstln; numLigne < lastln; numLigne++)
    {
      const FitsFile::BufferLine& bfligne = is.GetBufferLine(numLigne);
      int k;
      int rang;
      int dcount =0;
      int fcount =0;
      int icount =0;
      int ccount = 0;
      for (k=0; k<nbcols;k++)
	{
	  rang = bfligne.identificateur()[k].second;
	  switch (bfligne.identificateur()[k].first)
	    {
	    case  FitsFile::FitsDataType_double :
	      {
		dligne[dcount++] =  bfligne.r_8Array(rang);
		break;
	      }
	    case  FitsFile::FitsDataType_float :
	      {
		fligne[fcount++] =  bfligne.r_4Array(rang);
		break;
	      }
	    case  FitsFile::FitsDataType_short :
	      {
		iligne[icount++] =  bfligne.int_2Array(rang);
		break;
	      }
	    case  FitsFile::FitsDataType_int :
	      {
		iligne[icount++] =  bfligne.int_4Array(rang);
		break;
	      }
	    case  FitsFile::FitsDataType_long :
	      {
		iligne[icount++] =  (int_4)bfligne.int_8Array(rang);
		break;
	      }
	    case  FitsFile::FitsDataType_byte :
	      {
		iligne[icount++] =  (int_4)bfligne.u_charArray(rang);
		break;
	      }
	    case FitsFile::FitsDataType_char :
	      {
		strncpy( cligne[ccount++], bfligne.stringArray(rang).c_str(),bfligne.stringArray(rang).length());
		break;
	      }

	    default:
	      {  
		throw PException(" FITS_XNTuple::ReadFromFits : unsupported FITS data type");
	      }
	    }
	
	}
      //      is.GetBinTabLine(numLigne, dligne, fligne, iligne, cligne );
      //      dobj_->Fill((r_8*)dligne, (r_4*)fligne, (int_4*)iligne, cligne);    
      dobj_->Fill(dligne, fligne, iligne, cligne);    
    }
    delete [] dligne;
    delete [] fligne;
    delete [] iligne;
    for (k=0; k< SfitsCol.size(); k++) delete []  cligne[k];
    delete [] cligne; 
  dobj_->Info()=is.DVListFromFits();

}
void FITS_XNTuple::WriteToFits(FitsOutFile& os) 
{

  if(dobj_ == NULL) 
    {
      cout << " WriteToFits:: dobj_= null " << endl;
      return;
    }

  // table will have 'ncols'  columns
  int ncols = dobj_->NVar(); 
  // table will have 'nrows' rows
  int nrows = dobj_->NEntry();
  //  cout << " FITS_XNTuple::WriteToFits : nombre de lignes a ecrire " << nrows << endl;
  // get names and values from the join DVList object
  DVList dvl= dobj_->Info();
  // extension name
  string extname("XNTuple_Binary_tbl"); 
  vector<string> Noms(ncols);   
  int k;
  for (k=0; k< ncols; k++)
    {
      Noms[k] = dobj_->NomIndex(k) ;
    }
  string types;
  for (k=0; k<dobj_->NDVar();k++)
    {
      types+='D';
    }
  for (k=0; k<dobj_->NFVar();k++)
    {
      types+='E';
    }
  for (k=0; k<dobj_->NIVar();k++)
    {
      types+='J';
    }
  for (k=0; k<dobj_->NSVar();k++)
    {
      types+='A';
    }            
  vector<int> StringSizes(dobj_->NSVar());
  for (k=0; k< StringSizes.size(); k++) StringSizes[k]=dobj_->mStrSz;
  dvl["Content"]= "XNTuple";
  dvl.SetComment("Content", "name of SOPHYA object");
  os.makeHeaderBntblOnFits(types, Noms, nrows, ncols, &dvl, extname,StringSizes); 
   
  int compt=0; 
   if (dobj_->NDVar() > 0) 
     {
       double* dcolumn = new double[nrows];
       for (k=0; k<dobj_->NDVar();k++)
	 {
           int j;
	   for(j = 0; j < nrows; j++) dcolumn[j]= dobj_->GetDVal(j,compt);
	   os.PutColToFits(compt, nrows, dcolumn);
	   compt++;
	 }
       delete [] dcolumn;
     }

   if (dobj_->NFVar() > 0)
     {
       float* fcolumn = new float[nrows];
       for (k=0; k<dobj_->NFVar();k++)
	 {
           int j;
	   for(j = 0; j < nrows; j++) fcolumn[j]= dobj_->GetFVal(j,compt);
	   os.PutColToFits(compt, nrows, fcolumn);
	   compt++;
	 }
       delete [] fcolumn;
     }

   if (dobj_->NIVar() > 0)
     { 
       int_4* icolumn = new int_4[nrows];
       for (k=0; k<dobj_->NIVar();k++)
	 {
           int j; 
	   for(j = 0; j < nrows; j++) icolumn[j]= dobj_->GetIVal(j,compt);
	   //	   for(j = 0; j < nrows; j++) cout << icolumn[j] << endl;;

	   os.PutColToFits(compt, nrows, icolumn);
	   compt++;
	 }
       delete [] icolumn;
     }

   if (dobj_->NSVar() > 0)
     {
      char**  ccolumn = new char*[nrows];
      for (k=0; k<dobj_->NSVar();k++)
	{
	  int j;
	  for(j = 0; j < nrows; j++)
	    {
	      string s= dobj_->GetSVal(j,compt);
	      ccolumn[j] = new char[dobj_->mStrSz+1];
	      strcpy(ccolumn[j],s.c_str());
	    }
	  os.PutColToFits(compt, nrows, ccolumn);
	  compt++;
	  for(j = 0; j < nrows; j++)
	    {
	      delete [] ccolumn[j];
	      ccolumn[j] = NULL;
	    }

	}
      delete [] ccolumn;
     }
}
