#include "sopnamsp.h"
#include "pmixer.h"
/*! \ingroup PMixer
 *  \file extractRS.cc 
 * \brief  \b PROGRAM \b extractRS  
 * Program to create a map (SphereHEALPix) with point source
 * from small map (matrix) and convolving their radiation spectrum
 * RadSpectra
 * with a given filter response SpectralResponse
 */
// -----------------------------------------------------------------
// ------------- Function declaration ------------------------------
int CheckCards(DataCards & dc, string & msg);
char * BuildFITSFileName(string const & fname);
SpectralResponse * getSpectralResponse(DataCards & dc);
float ComputeFrequency(DataCards &,string&);
// -----------------------------------------------------------------
//  ----- Global (static) variables ------------
static bool rdmap = false;    // true -> Read map first 
static char mapPath[256];     // Path for input maps
static int  hp_nside = 32;    // HealPix NSide
static int  nskycomp = 0;     // Number of sky components
static int  debuglev = 0;     // Debug Level
static int  printlev = 0;     // Print Level
static POutPersist * so = NULL;  // Debug PPFOut file
// -------------------------------------------------------------------------
//                             main program 
// -------------------------------------------------------------------------
int main(int narg, char * arg[])
{
  if ((narg < 3) || ((narg > 1) && (strcmp(arg[1], "-h") == 0) )) {
    cout << "  Usage: extractRS parameterFile outputfitsnameformaps  [outppfname]" << endl;
    exit(0);
  }
  
  InitTim();
  
  string msg;
  int rc = 0;
  RadSpectra * es = NULL;
  SpectralResponse * sr = NULL;
  double moy, sig;
  
  DataCards dc;
  so = NULL;
  
  try {
    string dcard = arg[1];
    cout << " Decoding parameters from file " << dcard << endl;
    dc.ReadFile(dcard);
    
    rc = CheckCards(dc, msg);
    if (rc) { 
      cerr << " Error condition -> Rc= " << rc << endl;
      cerr << " Msg= " << msg << endl;
      return(rc);
    }
  }
  catch (PException exc) {
    msg = exc.Msg();
    cerr << " !!!! extractRS/ Readcard - Catched exception - Msg= " << exc.Msg() << endl;
    return(90);
  }   
  
  
  cout << " extractRS/Info : NComp = " <<  nskycomp << " SphereHEALPix_NSide= " << hp_nside << endl;
  cout << "  ... MapPath = " << (string)mapPath << "  DebugLev= " << debuglev 
       << "  PrintLev= " << printlev << endl;
  
  // We create an output persist file for writing debug objects
  if (debuglev > 0) so = new POutPersist("extrRSdbg.ppf");
  SphereHEALPix SourceMap(hp_nside);
  SphereHEALPix OutputMap(hp_nside);
  bool okout = true;
  
  try {
    
    //    FitsIoServer fios; // Our FITS IO Server
    char * flnm, buff[90];
    string key;
    string key2;
   
    double K = 1.;
    
    // Loop over sky frequencies components
    int maxOfSkyComp = nskycomp;
    int nbOfPix;
    int sk;
    Vector freq(maxOfSkyComp);
    TMatrix spectrum;
    TMatrix fdenu; //par freq et par pixel
    int nb_source;
    TMatrix rareSource; //par freq et par numero de source
    
    for(sk = 0; sk ings;	
	// Opening the file containing the map
	cout << "-------------------" << endl;
	cout << " Processing map's frequency component No " << sk+1 << endl;
	sprintf(buff, "%d", sk+1);
	key = (string)"RADSPECMAP" + buff;
	
	flnm = BuildFITSFileName(dc.SParam(key,0));
	cout << " Reading Input FITS map " << (string)flnm << endl;
	FITS_TArray read_input(flnm); 
	ings = (TArray)read_input;
	if (printlev > 2) 
	  {
	    double min = 9.e99;
	    double max = -9.e99;
	    for(int x=0;xings(x,y)) min = ings(x,y);
		    if(max 2)  cout << "filling spectrum for freq = " << freq(sk) << endl;
	
	// Opening the file containing the point source
	sprintf(buff, "%d", sk+1);
	key2 = (string)"SOURCEPTMAP" + buff;
	flnm = BuildFITSFileName(dc.SParam(key2,0));
	const char* nameOfFile = flnm ;
	if (printlev > 2) cout << " Reading Input FITS map " << nameOfFile << endl;
	ifstream from(nameOfFile);
	char ch;
	string dum;
	from >> nb_source >> dum;
	if(sk==0) rareSource.ReSize(maxOfSkyComp,nb_source);
	for (int ii=0; ii< nb_source; ii++)
	  {
	    double value = 0;
	    from >> value;
	    rareSource(sk,ii) = value*1.e-26; //for Jansky->W
	  }
	from.close();
	nbOfPix = ings.NRows()*ings.NCols();
	spectrum.ReSize(ings.NRows(),ings.NCols());
	if(sk==0) fdenu.ReSize(maxOfSkyComp,nbOfPix);
	int xy=0;
	for(int x=0;xW
		fdenu(sk,xy) = spectrum(x,y);  
		xy += 1;
	      }
	  }
	if (printlev > 2) 
	  {
	    MeanSig(spectrum.DataBlock(), moy, sig );
	    cout << " MeanSig for spectrum  map - Mean= " << moy << " Sigma= " << sig << endl;
	  }
	
	
	K = dc.DParam(key, 1, 1.);
	if (debuglev > 4) {  // Writing the input map to the outppf
	  FIO_TArray fiog;
	  fiog.Write(*so, key);
	}
	
	if(printlev>2) 
	  {	
	    sprintf(buff, "End of Proc. Comp. %d ", sk+1);
	    cout << " --------------------------------------- \n" << endl;    
	    PrtTim(buff);
	  }
      }   // End of sky component loop 
    
    // ---------------------------------------------------------------------
    //      Integration in the detector band of the maps
    // ---------------------------------------------------------------------
    SpectralResponse* sr = NULL;
    sr = getSpectralResponse(dc);
  
    if (printlev > 2)  cout  << "SpectralResponse!" << *sr << endl;
    TVector outCoeff(nbOfPix);
    for(int pix=0;pix 10)  cout << "RadiationSpectra" << radSV << endl;
	outCoeff(pix) = radSV.filteredIntegratedFlux(*sr);
      }
    int i;    
    for(i=0;i sourceCoeff(nb_source);
    for(int nsource=0;nsource) written to FITS file " 
      // 	     << (string)(arg[3]) << endl;
      //       }
      {
	 FITS_SphereHEALPix fios2(OutputMap);
	 fios2.Write(arg[2]);
	 double moy,sig;
	 MeanSig(OutputMap.DataBlock(),moy,sig);
	 cout << " MeanSig for Output Map - Mean= " << moy << " Sigma= " << sig << endl;
	 cout << "Output Map (SphereHEALPix) written to FITS file " 
	      << (string)(arg[2]) << endl;
      }
      if(printlev>2) PrtTim("End of WriteFITS ");
      // Saving the output map in PPF format 
      if (narg > 2) {
	POutPersist s(arg[3]); 
	FIO_SphereHEALPix fiog(OutputMap);
	fiog.Write(s);
	cout << "Output Map (SphereHEALPix) written to POutPersist file "  
	     << (string)(arg[3]) << endl;
	if(printlev>2) PrtTim("End of WritePPF ");
      }
    }
  if (so) delete so;  //  Closing the debug ppf file 
  return(rc);
}
/* Nouvelle-Fonction */
int CheckCards(DataCards & dc, string & msg)
  //   Function to check datacards
{
  rdmap = false;
  mapPath[0] = '\0';
  nskycomp = 0;
  debuglev  = 0;
  printlev = 0;
  
  int rc = 0;
  string key, key2;
  
  //  Checking datacards
  if (dc.NbParam("EXT_RS") < 2)   {
     rc = 71; 
     msg = "Invalid parameters  - Check @EXT_RS card ";
     return(rc);
  }
  int kc;
  char buff[256];
  bool pb = false;
  string key3;
  int ncomp = 0;
  ncomp = dc.IParam("EXT_RS", 0);
  int nside = 32;
  nside = dc.IParam("EXT_RS", 1);
  
  for(kc=0; kc mtx(2,10);
    FITS_TArray read_input(ifnm); 
    mtx = (TMatrix)read_input;
    double numin = dc.DParam(key, 2, 1.);
    double numax = dc.DParam(key, 3, 9999.);
    Vector nu(mtx.NCols());
    Vector fnu(mtx.NCols());
    for(int k=0; k 1)  SpectralResponse2Nt(*filt, *so, ppfname);
  return(filt);
}
float ComputeFrequency(DataCards & dc,string& key)
{
  ofstream filename("temp_filename");
  filename << dc.SParam(key,0) << '\n';
  filename.close();
  
  ifstream fromtempfile("temp_filename");
  char chtemp;
  string temp_str;
  int count = 0;
  do { 
    fromtempfile.get(chtemp);    
    if(count> 12 && count < 20)
      {
	temp_str+= chtemp; 
      }
    count+=1;
  } while(chtemp!='\n'); 
  fromtempfile.close();
  
  ofstream filename2("temp_filename");
  filename2 << temp_str << '\n';
  filename2.close();
  
  int frequency;
  ifstream fromtempfile2("temp_filename");
  fromtempfile2 >> frequency;
  fromtempfile2.close();
  return ((float)frequency/1000.);
}