#include "pmixer.h"
/*!
 * \defgroup PMixer PMixer module
 * This module contains programs which:
 * 
 * -  add several sky components, taking into account their
 * radiation spectra and convoluting them with a given filter
 * response : skymixer
 * 
-  create a map with point source : extractRS
 * 
-  generate sky components, radiation spectra and spectral 
 * response (small generator of maps) : tgsky and tgrsr
 * 
* A detailed description may be found at:
 */
/*!
 * \ingroup PMixer
 * \file skymixer.cc
 *\brief   \b PROGRAM    \b skyMixer
 *   add several sky components, taking into account their
 *radiation spectra and convoluting them with a given filter
 *response
 */
// -----------------------------------------------------------------
// ------------- Function declaration ------------------------------
int CheckCards(DataCards & dc, string & msg);
char * BuildFITSFileName(string const & fname);
SpectralResponse * getSpectralResponse(DataCards & dc);
RadSpectra * getEmissionSpectra(DataCards & dc, int nc);
void RadSpec2Nt(RadSpectra & rs, POutPersist & so, string name);
void SpectralResponse2Nt(SpectralResponse& sr, POutPersist & so, string name);
// to add different sky components and corresponding tools
//----------------------------------------------------------
template  
void addComponent(SpectralResponse&  sr, 
				     PixelMap& finalMap, 
				     PixelMap& mapToAdd, 
				     RadSpectra& rs, double K=1.);
//
template 
void addComponentBeta(SphereHEALPix& finalMap, 
		      SphereHEALPix& mapToAdd,SpectralResponse& sr, 
		      SphereHEALPix& betaMap, double normFreq, double K);
//
template 
void integratedMap(SpectralResponse&  sr,   
		   SphereHEALPix& betaMap, double normFreq, SphereHEALPix& intBetaMap);
//
template 
void addComponentBeta(SphereHEALPix& finalMap, 
		      SphereHEALPix& mapToAdd,
		      SphereHEALPix& intBetaMap, double K);
//
template  
void addDipole(SpectralResponse&  sr,  PixelMap& finalMap, 
	       double theta,double phi,double amp,double temp);
//
// -----------------------------------------------------------------
//  ----- 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: skymixer parameterFile outputfitsname [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];
    if(printlev > 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 << " !!!! skymixer/ Readcard - Catched exception - Msg= " << exc.Msg() << endl;
    return(90);
  }   
  
  
  cout << " skymix/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("skymixdbg.ppf");
  
  SphereHEALPix outgs(hp_nside);
  try{
    if (rdmap) {  // Reading map from FITS file
      char ifnm[256];
      strncpy(ifnm, dc.SParam("READMAP", 0).c_str(), 255);
      ifnm[255] = '\0';
      cout << " Reading output HealPix map from FITS file " << (string)ifnm << endl;
      {
	FITS_SphereHEALPix fios(&outgs);
	fios.ReadF(ifnm,2);
      }
      if(printlev>0)
	cout << " Output HealPIx Map read - NbPixels= " << 
	  outgs.NbPixels() << endl;
      if (printlev > 0) {
	MeanSig(outgs.DataBlock(), moy, sig );
	cout << " MeanSig for outpout map - Mean= " << 
	  moy << " Sigma= " << sig << endl;
      }
    }
    else {
      if(printlev>0)
	cout << " Output HealPix Map  created - NbPixels= " << 
	  outgs.NbPixels() << endl;
      outgs.SetPixels(0.);
    }
    
    // Decoding detection pass-band filter 
    sr = getSpectralResponse(dc);
    PrtTim(" After FilterCreation ");
    
    char * flnm, buff[90];
    string key;
    
    double K = 1.;
    double freqOfMap = 1.;
    // Loop over sky component 
    int sk;
    for(sk = 0; sk3) 
	    {
	      temp =  dc.DParam(key,4,1.);
	    }
	  cout << " creating dipole " << temp << " " << amp << " " << phi << " " << theta << " " << endl;
	  addDipole(*sr, outgs,theta,phi,amp,temp);
	}
      else
	{
	  sprintf(buff, "%d", sk+1);
	  key = (string)"MAPFITSFILE" + buff;
	  flnm = BuildFITSFileName(dc.SParam(key, 0));
	  
	  K = dc.DParam(key, 1, 1.);
	  
	  cout << " Reading Input FITS map " << (string)flnm << endl;
	  SphereHEALPix ings(hp_nside);
	  {
	    FITS_SphereHEALPix fiosIn(&ings);
	    fiosIn.ReadF(flnm,2);
	  }
	  if (debuglev > 4) {  // Writing the input map to the outppf
	    FIO_SphereHEALPix fiog(ings);
	    fiog.Write(*so, key);
	  }
	  if (printlev > 2) {
	    MeanSig(ings.DataBlock(), moy, sig );
	    cout << " MeanSig for input map - Mean= " << moy << " Sigma= " << sig << endl;
	  }
	  bool mapDependentOfFreq = false;
	  key = (string)"BETAFITSFILE"+ buff;
	  if(dc.HasKey(key)) 
	    {
	      mapDependentOfFreq = true;
	    }
	  
	  // getting Emission spectra  
	  if(!mapDependentOfFreq)
	    {
	      if (es) { delete es; es = NULL; }
	      es = getEmissionSpectra(dc, sk);
	      addComponent(*sr, outgs, ings, *es, K);
	    }
	  else
	    {
	      key = (string)"BETAFITSFILE"+ buff;
	      //SphereHEALPix betaMap;
	      flnm = BuildFITSFileName(dc.SParam(key, 0));
	      double normFreq = dc.DParam(key, 1, 1.);
	      if (printlev > 4) cout << "....BetaFits... normalization Freq = " << normFreq << endl;
	      int nSideForInt = dc.DParam(key, 2, 1.);
	      if (printlev > 4) cout << "....BetaFits... NSide for Integration map = " << nSideForInt << endl;
	      cout << "....BetaFits...  Reading Beta FITS map " << (string)flnm << endl;
	      SphereHEALPix betaMap(hp_nside);
	      {
		FITS_SphereHEALPix fiosBM(&betaMap);
		fiosBM.ReadF(flnm,2);
	      }
	      if (printlev > 2) {
		MeanSig(betaMap.DataBlock(), moy, sig );
		cout << " MeanSig for Beta map - Mean= " << moy << " Sigma= " << sig << endl;
	      }
	      if (debuglev > 4) {  // Writing the input map to the outppf
		FIO_SphereHEALPix fiogs(betaMap);
		fiogs.Write(*so, key);
	      }
	      
	      if(nSideForInt<0) nSideForInt = sqrt((double)betaMap.NbPixels()/12);
	      bool bydefault = true;
	      if(!bydefault)
		addComponentBeta(outgs,ings,*sr,betaMap,normFreq, K);
	      else
		{
		  // integrate the betamap over the SpectralResponse
		  SphereHEALPix intBetaMap(nSideForInt);
		  integratedMap(*sr, betaMap, normFreq, intBetaMap);
		  if (debuglev > 4) {  // Writing the input map to the outppf
		    FIO_SphereHEALPix fiogs2(intBetaMap);
		    fiogs2.Write(*so, "INTBETAMAP");
		  }
		  
		  betaMap.Resize(8);
		  if (printlev > 4)
		    {
		      MeanSig(intBetaMap.DataBlock(), moy, sig );
		      cout << "....BetaFits... MeanSig for intBetaMap - Mean= " 
			   << moy << " Sigma= " << sig << endl;
		    }
		  // add the integrated beta map 
		  addComponentBeta(outgs,ings,intBetaMap, K);
		}
	    }
	  
	  MeanSig(outgs.DataBlock(), moy, sig );
	  cout << " MeanSig for Sum map - Mean= " << moy << " Sigma= " << sig << endl;
	  cout << "-------------------------------------------------" << endl;
	  
	  sprintf(buff, "End of Processing Component %d ", sk+1);
	  PrtTim(buff);
	} 
    }
  }
  catch(PException exc) 
    {
      cout << "catched PException" << endl;
      msg = exc.Msg();
      cerr << " !!!! skymixer - Catched exception - Msg= " << exc.Msg() << endl;
      rc = 50;
      return(50);
    } 
  
 // Saving the output map in FITS format 
 cout << "Output Map (SphereHEALPix) written to FITS file " 
      << (string)(arg[2]) << endl;
 {
   FITS_SphereHEALPix fios2(outgs);
   fios2.Write(arg[2]);
 }
 PrtTim("End of WriteFITS ");
 // Saving the output map in PPF format 
 if (narg > 3) {
   POutPersist s(arg[3]); 
   FIO_SphereHEALPix fiog(&outgs) ;
   fiog.Write(s);
   cout << "Output Map (SphereHEALPix) written to POutPersist file "  
  	<< (string)(arg[3]) << endl;
   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';
hp_nside = 32;
nskycomp = 0;
debuglev  = 0;
printlev = 0;
int rc = 0;
string key, key2,key3;
  //  Cheking datacards
  if (dc.NbParam("SKYMIX") < 2)   {
     rc = 71; 
     msg = "Invalid parameters  - Check @SKYMIX card ";
     return(rc);
  }
  key = "READMAP";
  if (dc.HasKey(key)) {
    if (dc.NbParam(key) < 1) {
     rc = 72; 
     msg = "Invalid parameters  - Check @READMAP card ";
     return(rc);
    }
   else rdmap = true;
  }
//  Checking detection filter specification 
  key = "GAUSSFILTER";
  key2 = "FILTERFITSFILE";
  key3 = "DIPOLE";
  if ( (dc.NbParam(key) < 5) && (dc.NbParam(key2) < 3) && (dc.NbParam(key3) < 3)) { 
    msg = "Missing card or parameters : Check @GAUSSFILTER or @FILTERFITSFILE or @DIPOLE";
    rc = 73;  return(rc); 
    }
  // Decoding number of component and pixelisation parameter
  int mg = 32;
  int ncomp = 0;
  ncomp = dc.IParam("SKYMIX", 0, 0);
  mg = dc.IParam("SKYMIX", 1, 32);
  if (ncomp < 1)  {
    msg = "Invalid parameters  - Check datacards @SKYMIX ";
    rc = 74;
    return(rc);
  }
  // Checking detection filter specification
  //  Checking input FITS file specifications 
  int kc;
  char buff[256];
  bool pb = false;
  string key4;
  string key5;
  string key6;
  for(kc=0; kc0)
    {
      cout << endl;
      cout << " Filter decoded - Created " << endl;
      cout << *filt << endl;
    }
  // for debug
  if (debuglev > 1)  SpectralResponse2Nt(*filt, *so, ppfname);
  return(filt);
}
/* Nouvelle-Fonction */
RadSpectra * getEmissionSpectra(DataCards & dc, int nc)
{
  char numb[16];
  sprintf(numb, "%d", nc+1);
  string key = (string)"SPECTRAFITSFILE" + numb;
  string key2 = (string)"BLACKBODY" + numb;
  string key5 = (string)"DERIVBB" + numb;
  string key3 = (string)"POWERLAWSPECTRA" + numb;
  string ppfname = "espectra";
  RadSpectra * rs = NULL;
  if (dc.HasKey(key) ) {    // Reading emission spectra from file
    char * ifnm = BuildFITSFileName(dc.SParam(key, 0));
    cout << " Reading Input FITS spectra file " << (string)ifnm << endl;
    FitsIoServer fios;
    Matrix mtx(2,10);
    fios.load(mtx, ifnm);
    double numin = dc.DParam(key, 2, 1.);
    double numax = dc.DParam(key, 3, 9999.);
    Vector nu(mtx.NCols());
    Vector tnu(mtx.NCols());
    for(int k=0; k 2)  RadSpec2Nt(*rs, *so, ppfname);
  return(rs);
}
template  
void addDipole(SpectralResponse&  sr,  PixelMap& finalMap, 
	       double theta,double phi,double amp,double temp)
{
  DerivBlackBody dbb;
  if(temp>0) dbb.setTemperature(temp);
  double coeff = dbb.filteredIntegratedFlux(sr) * amp;
  UnitVector vd(theta,phi);
  UnitVector vc(theta,phi);
  
  for(int i=0; i 4) {  // Writing the input map to the outppf
    SphereHEALPix ings(sqrt((double)finalMap.NbPixels()/12));
    for(int i=0; i fiog(ings);
    fiog.Write(*so, "dipole");
    cout << "Debug the dipole map....saved in debug file !" << endl;
  }
}
/* Nouvelle-Fonction */
template  
void addComponent(SpectralResponse&  sr, PixelMap& finalMap, 
                  PixelMap& mapToAdd, RadSpectra& rs, double K)
{
  // finalMap = finalMap + coeff* mapToAdd
  // coeff    =  convolution of sr and rs 
  // compute the coefficient corresponding to mapToAdd
  if (finalMap.NbPixels() != mapToAdd.NbPixels())   
    throw SzMismatchError("addComponent()/Error: Unequal number of Input/Output map pixels");
  double coeff = rs.filteredIntegratedFlux(sr) * K;
  if (printlev > 1) 
    cout << " addComponent - Coeff= " << coeff << " (K= " << K << ")" << endl; 
  for(int i=0; i 
void addComponentBeta(SphereHEALPix& finalMap, 
		      SphereHEALPix& mapToAdd,SpectralResponse& sr, 
		      SphereHEALPix& betaMap, double normFreq, double K)
{
  // finalMap = finalMap + coeff* mapToAdd
  // coeff    =  convolution of sr and rs 
  // compute the coefficient corresponding to mapToAdd
  // betaMap is the map of (beta(theta,phi)) 
  int nbpix = finalMap.NbPixels();
  if (nbpix != mapToAdd.NbPixels())   
    throw SzMismatchError("addComponentBeta()/Error: Unequal number of Input/Output map pixels");
  if (printlev > 1) 
    {
      cout << "addComponentBeta - Coeff= "  << K  << endl; 
      cout << "nb pixels: " << finalMap.NbPixels() << endl;
    }
  SphereHEALPix bigBetaMap(sqrt((double)nbpix/12));
  if(nbpix != betaMap.NbPixels())
    {
       Sph2Sph(betaMap,bigBetaMap);
     }
  for(int i=0; ifilteredIntegratedFlux(sr);
      finalMap(i) += coeff*K*mapToAdd(i);
    }
}
template 
void integratedMap(SpectralResponse&  sr,   
		   SphereHEALPix& betaMap, 
		   double normFreq, 
		   SphereHEALPix& intBetaMap)
{
  PowerLawSpectra rs(1.,-2., 0., normFreq);
  
  if(betaMap.NbPixels()!=intBetaMap.NbPixels()) 
    {
      Sph2Sph(betaMap,intBetaMap);
      for(int i=0; i
void addComponentBeta(SphereHEALPix& finalMap, 
		      SphereHEALPix& mapToAdd,SphereHEALPix& intBetaMap, double K)
{
  // finalMap = finalMap + coeff* mapToAdd
  // coeff    =  convolution of sr and rs 
  // compute the coefficient corresponding to mapToAdd
  // integBetaMap is the map of the integration (nu/normFreq)^(-beta(theta,phi)) over
  // the spectralResponse
  // different from addComponentBeta(PixelMap& finalMap, 
  //    PixelMap& mapToAdd,SpectralResponse& sr, PixelMap& betaMap, double normFreq, double K)
  //   since it permits to use a intBetaMap with a different number of pixels than
  //   the other maps
  int nbpix = finalMap.NbPixels();
  if (nbpix != mapToAdd.NbPixels())   
    throw SzMismatchError("addComponentBeta(PixelMap&,PixelMap&,PixelMap&,double)/Error: Unequal number of Input/Output map pixels");
  double coeff = K;
  if(nbpix != intBetaMap.NbPixels())
    {
      for(int i=0; i 1) 
    {
      cout << "addComponentBeta(SG,SG,SG,double) - Coeff= "  << K  << endl;     
    }
}
/* Nouvelle-Fonction */
/* Nouvelle-Fonction */
void RadSpec2Nt(RadSpectra & rs, POutPersist & so, string name)
{
  char *ntn[2] = {"nu","fnu"};
  NTuple nt(2,ntn);  // Creation NTuple (AVEC new )
  float xnt[2];
  double nu;
  double numin = rs.minFreq();
  double numax = rs.maxFreq();
  int nmax = 500;
  double dnu = (numax-numin)/nmax;
  for(int k=0; k oiont(nt);
  oiont.Write(so, name);
  return;
}
/* Nouvelle-Fonction */
void SpectralResponse2Nt(SpectralResponse& sr, POutPersist & so, string name)
{
  char *ntn[2] = {"nu","tnu"};
  NTuple nt(2,ntn);  // Creation NTuple (AVEC new )
  float xnt[2];
  double nu;
  double numin = sr.minFreq();
  double numax = sr.maxFreq();
  int nmax = 500;
  double dnu = (numax-numin)/nmax;
  for(int k=0; k oiont(nt);
  oiont.Write(so, name);
  return;
}