#include <stdio.h>
#include <stdlib.h>
#include <math.h>
#include <iostream>

#include "sopnamsp.h"
#include "histinit.h"
#include "dvlist.h"
#include "ntuple.h"
#include "fitsntuple.h"
#include "fitstarray.h"
#include "array.h"

int main(int narg, char *arg[])
{
  if (narg < 3) {
    cout << "obj_fits/Erreur arg - Usage obj_fits r/r2/w/w2 fitsfilename " << endl;
    cout << "  w : Create a FITS file with a matrix and an NTuple " << endl;
    cout << "  r : Read a matrix and an NTuple from a Fits File " << endl;
    cout << "  2 : Image on secondary header " << endl;  
    exit(1);
  }
  try {
    SophyaInit();
    string flnm = arg[2];
    bool imgonph = true;
    if (*(arg[1]+1) == '2')  imgonph = false;
    if (*arg[1] == 'r') {
      cout << " obj_fits/Info: Opening input FitsFile " << endl;
      FitsInFile fiis(flnm);
      fiis.firstImageOnPrimaryHeader(imgonph);

      cout << " Reading Matrix m from FITS " << endl;
      Matrix m;
      fiis >> m;
      cout << m << endl;

      cout << " Reading NTuple from FITS " << endl;
      NTuple nt;
      fiis >> nt ;
      nt.Show();
    }
    else {
      cout << " obj_fits/Info: Opening output FitsFile " << endl;
      FitsOutFile fios(flnm);
      fios.firstImageOnPrimaryHeader(imgonph);

      cout << " Creating Matrix m " << endl;
      Matrix m(50,70);
      m = RegularSequence(35., 0.2);
      m.Info()["SVERSION"] = SophyaVersion();
      m.Info().SetComment("SVERSIO", "Sophya Version");
      m.Info()["OBJ_FITS"] = "Test Matrix" ;
      cout << m << endl;
      
      cout << " Writing Matrix m to FITS " << endl;
      fios << m ;
      
      cout << " Creating NTuple " << endl;
      const char * names[3] = {"XPos", "YPos", "Val"};
      int i,j, k;
      float xnt[3];
      
      NTuple  nt1(3, names, 20);
      
      k = 0;
      for(j=0; j<8; j++)
	for(i=0; i<12; i++)
	  { xnt[0] = i+0.5;  xnt[1] = j+0.5;  xnt[2] = k;
	  nt1.Fill(xnt); k++; }
      
      nt1.Info().Comment() = "NTuple de Test - Cree par obj_fits.cc";
      nt1.Info()["Version"] = SophyaVersion();
      nt1.Show();
      
      cout << " Writing NTuple to FITS " << endl;
      fios << nt1 ;
    }
  }
  catch (PThrowable & exc) {
    cerr << " Catched Exception " << (string)typeid(exc).name()
         << " - Msg= " << exc.Msg() << endl;
  }
  catch (...) {
    cerr << " some other exception was caught ! " << endl;
  }

}
