#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, FitsOutFile& fios);
char * BuildFITSFileName(string const & fname);
SpectralResponse * getSpectralResponse(DataCards & dc, FitsOutFile& fios);
RadSpectra * getEmissionSpectra(DataCards & dc, int nc, FitsOutFile& fios);
void SKM_MergeFITSKeywords(char * flnm);
void SKM_MergeFITSKeywords2(DVList & dvl);
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
static DVList * dvl_fitskw = NULL; // Global DVList for all FITS Keywords 
bool checkpdmtype=false;
bool dvliston= false;
// --------- SkyMixer Version --------------
static double skm_version = 1.5;
// -------------------------------------------------------------------------
//                             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();
  FitsOutFile fios(arg[2]);
     
  cout << " skymixer Version= " << skm_version << " SophyaVersion= " 
       << SophyaVersion() << endl;
  
  string msg;
  int rc = 0;
  RadSpectra * es = NULL;
  SpectralResponse * sr = NULL;
  double moy, sig;
  
  DataCards dc;
  so = NULL;
  // DVList for merging all FITS keywords and datacards
  dvl_fitskw = new DVList;
  
  try {
    string dcard = arg[1];
    if(printlev > 1) cout << " Decoding parameters from file " << dcard << endl;
    dc.ReadFile(dcard);
    
    rc = CheckCards(dc, msg,fios);
    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");
  int countHead = 2;
  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;
      {
	FitsInFile fitsin(ifnm);
	fitsin >> outgs;
	//  Getting FITS keywords in primary header
	//	SKM_MergeFITSKeywords(ifnm); 
	//  Getting FITS keywords in data object header
	if(checkpdmtype)
	  {
	    int status = 1;
	    string whatsup=fitsin.getStringKeyword(2,"PDMTYPE",status);
	    if(!(status==0&&whatsup=="COMPMAP")) 
	      {
		cerr << " !!!! skymixer - file" << ifnm << " is not a COMPMAP " << endl;
		throw ParmError("Error");
	      }
	    else cout << "read the comment COMPMAP from " << ifnm << endl;
	  }
	if(dvliston) SKM_MergeFITSKeywords2(outgs.Info());
	else 
	  {
	    fios.appendInputHeader(fitsin, countHead);
	  }
      }
      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,fios);
    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);
	  {
	    FitsInFile fiosIn(flnm);
	    fiosIn >> ings;
	    //  Getting FITS keywords in primary header
	    //  SKM_MergeFITSKeywords(flnm); 
	    //  Getting FITS keywords in data object header
	    //if(fiosIn.hasKeyword(string("PDMTYPE"), 1)) cout << "read the comment COMPMAP from " << flnm << endl;
	    if(checkpdmtype)
	      {
		int status = 1;
		string ch = "PDMTYPE";
		string whatsup=fiosIn.getStringKeyword(2,ch,status);
		if(!(status==0&&whatsup=="COMPMAP")) 
		  {
		    cerr << " !!!! skymixer - file" << flnm << " is not a COMPMAP " << endl;
		    throw ParmError("Error");
		  }
		else cout << "read the comment COMPMAP from " << flnm << endl;
	      }
	    if(dvliston) SKM_MergeFITSKeywords2(ings.Info());
	    else 
	      {
		fios.appendInputHeader(fiosIn, countHead);
	      }
	  }
	  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,fios);
	      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);
	      {
		FitsInFile fiosBM(flnm);
		fiosBM >> betaMap;
		//  Getting FITS keywords in primary header
		// SKM_MergeFITSKeywords(flnm); 
		//  Getting FITS keywords in data object header
		//if(fiosBM.hasKeyword(string("COMPMAP"), 1)) cout << "read the comment COMPMAP from " << flnm << endl;
		if(checkpdmtype)
		  {
		    int status = 1;
		    string whatsup=fiosBM.getStringKeyword(2,"PDMTYPE",status);
		    if(!(status==0&&whatsup=="INDEXMAP")) 
		      {
			cerr << " !!!! skymixer - file" << flnm << " is not an INDEXMAP " << endl;
			throw ParmError("Error");
		      }
		    else cout << "read the comment INDEXMAP from " << flnm << endl;
		  }
		if(dvliston) SKM_MergeFITSKeywords2(betaMap.Info()); 
		else 
		  {
		    fios.appendInputHeader(fiosBM, countHead);
		  }
	      }
	      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);
    } 
  
 try {
 // Saving the output map in FITS format 
   cout << "Output Map (SphereHEALPix) written to FITS file " 
	<< (string)(arg[2]) << endl;
   {
     //     FitsOutFile fios(arg[2]);
     fios.firstImageOnPrimaryHeader(false); // Use secondary header 
     DVList& dvl = (*dvl_fitskw);
     dvl["PDMTYPE"] = "COMPMAP";
     dvl.SetComment("PDMTYPE", "Planck Data Model Type"); 
     dvl["SOPHYVER"] =  SophyaVersion();
     dvl.SetComment("SOPHYVER", "Sophya Version number"); 
     dvl["SKYMVER"] =  skm_version;
     dvl.SetComment("SKYMVER", "skymixer Version number"); 
     //     fios.DVListIntoPrimaryHeader(dvl);  
     dvl["CREATOR"] = "SkyMixer";
     outgs.Info() = dvl;
     fios << outgs ;
   }
   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 ");
   }
 }
 catch(PException exc) 
   {
     cout << "catched PException (2)" << endl;
     msg = exc.Msg();
     cerr << " !!!! skymixer(2) - Catched exception - Msg= " << exc.Msg() << endl;
     rc = 55;
     return(55);
   } 
 if (so) delete so;  //  Closing the debug ppf file 
 return(rc);
}
/* Nouvelle-Fonction */
int CheckCards(DataCards & dc, string & msg, FitsOutFile& fios)
//   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;
 DVList & dvl = *dvl_fitskw; 
  //  Cheking datacards
  if (dc.NbParam("SKYMIX") < 2)   {
     rc = 71; 
     msg = "Invalid parameters  - Check @SKYMIX card ";
     return(rc);
  }
  if(dvliston)
    dvl.SetS("SKYMIX", dc.GetParams("SKYMIX"));
  else
    {
      fios.insertCommentLineOnHeader("--------------------");
      fios.insertCommentLineOnHeader("SkyMixer DataCard");
      fios.insertCommentLineOnHeader("--------------------");
 
       string key = "SKYMIX"+ (string)dc.GetParams("SKYMIX");
       fios.insertCommentLineOnHeader(key);
    }
  key = "CHECKPDMTYPE";
  if (dc.HasKey(key)) {
    checkpdmtype=true;
  }
  
  key = "READMAP";
  if (dc.HasKey(key)) {
    if (dc.NbParam(key) < 1) {
     rc = 72; 
     msg = "Invalid parameters  - Check @READMAP card ";
     return(rc);
    }
    else rdmap = true;
    
    if(dvliston) dvl.SetS(key, dc.GetParams(key));
    else 
      {
	string keynew = key + (string)dc.GetParams(key);
	fios.insertCommentLineOnHeader(keynew);
      }
  }
//  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); 
    }
  if (dc.HasKey(key))   
    { 
      if(dvliston) dvl.SetS("GAUSFILT", dc.GetParams(key));
      else 
	{
	  string keynew = key + (string)dc.GetParams(key);
	  fios.insertCommentLineOnHeader(keynew);
	}
    }
  if (dc.HasKey(key2))
    {
      if(dvliston) dvl.SetS("FILTFILE", dc.GetParams(key2));
      else
	{
	  string keynew = key2 + (string)dc.GetParams(key2);
	  fios.insertCommentLineOnHeader(keynew);
	}
    }
  if (dc.HasKey(key3))  
    {
      if(dvliston) dvl.SetS("DIPOLE", dc.GetParams(key3));
      else
	{
	  string keynew = key3 + (string)dc.GetParams(key3);
	  fios.insertCommentLineOnHeader(keynew);
	}
    }
  // 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; kc> mtx ; 
    //  Getting FITS keywords in primary header
    //    SKM_MergeFITSKeywords(ifnm); 
    //  Getting FITS keywords in data object header
    if(checkpdmtype)
      {
	int status = 1;
	string whatsup=fiis.getStringKeyword(2,"PDMTYPE",status);
	if(!(status==0&&whatsup=="COMPMAP")) 
	  {
	    cerr << " !!!! skymixer - file" << ifnm << " is not a COMPMAP " << endl;
	    throw ParmError("Error");
	  }
	else cout << "read the comment COMPMAP from " << ifnm << endl;
      }
    if(dvliston) SKM_MergeFITSKeywords2(mtx.Info()); 
    else 
      {
	fios.appendInputHeader(fiis, 2);
      }
    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; k0)
    {
      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, FitsOutFile& fios)
{
  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;
    Matrix mtx;
    FitsInFile fiis(ifnm);
    fiis.firstImageOnPrimaryHeader(false); // Use secondary header HDU=2
    fiis >> mtx ; 
    //  Getting FITS keywords in primary header
    //    SKM_MergeFITSKeywords(ifnm); 
    //  Getting FITS keywords in data object header
    //if(fiis.hasKeyword(string("PDMTYPE"), 1)) cout << "read the comment COMPMAP from " << ifnm << endl;
    if(checkpdmtype)
      {
	int status = 1;
	string whatsup=fiis.getStringKeyword(2,"PDMTYPE",status);
	if(!(status==0&&whatsup=="FGRSPEC")) 
	  {
	    cerr << " !!!! skymixer - file" << ifnm << " is not a  FGRSPEC" << endl;
	    throw ParmError("Error");
	  }
	else cout << "read the comment FGRSPEC from " << ifnm << endl;
      }
    if(dvliston) SKM_MergeFITSKeywords2(mtx.Info()); 
    else 
      {
	fios.appendInputHeader(fiis, 2);
      }
    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 */
void SKM_MergeFITSKeywords(char * flnm)
{
  DVList dvl;
  FitsFile::FitsExtensionType typeOfExtension;
  int naxis;
  vector naxisn;
  FitsFile::FitsDataType dataType;
  FitsInFile::GetBlockType(flnm, 1, typeOfExtension, naxis, naxisn, dataType, dvl);
  // Cleaning the keywords 
#define SZexlst 21
  char *exlst[SZexlst]=
  {"SIMPLE","BITPIX" ,"NAXIS" ,"NAXIS#" ,"PCOUNT","GCOUNT",
     "EXTEND","ORIGIN" ,"DATE*" ,"TFIELDS","TTYPE#","TFORM#",
     "TUNIT#","EXTNAME","CTYPE#","CRVAL#" ,"CRPIX#","CDELT#",
     "XTENSION","INSTRUME","TELESCOP"};
  char  kwex[32];
  int i,l;
  for (i=0; i lstsup;
      kwex[l] = '\0';
      DVList::ValList::const_iterator it;
      for (it = dvl.Begin(); it != dvl.End(); it++) {
	if ((*it).first.substr(0,l) != kwex) continue;
	if (fgd && !isdigit((*it).first[l])) continue;
	lstsup.push_back((*it).first);
      }
      list::iterator it2;
      for (it2 = lstsup.begin(); it2 != lstsup.end(); it2++)
	dvl.DeleteKey(*it2);
    }
  }
  dvl_fitskw->Merge(dvl);
}
/* Nouvelle-Fonction */
void SKM_MergeFITSKeywords2(DVList & dvl)
{
  // Cleaning the keywords 
#define SZexlst 21
  char *exlst[SZexlst]=
  {"SIMPLE","BITPIX" ,"NAXIS" ,"NAXIS#" ,"PCOUNT","GCOUNT",
     "EXTEND","ORIGIN" ,"DATE*" ,"TFIELDS","TTYPE#","TFORM#",
     "TUNIT#","EXTNAME","CTYPE#","CRVAL#" ,"CRPIX#","CDELT#",
     "XTENSION","INSTRUME","TELESCOP"};
  char  kwex[32];
  int i,l;
  for (i=0; i lstsup;
      kwex[l] = '\0';
      DVList::ValList::const_iterator it;
      for (it = dvl.Begin(); it != dvl.End(); it++) {
	if ((*it).first.substr(0,l) != kwex) continue;
	if (fgd && !isdigit((*it).first[l])) continue;
	lstsup.push_back((*it).first);
      }
      list::iterator it2;
      for (it2 = lstsup.begin(); it2 != lstsup.end(); it2++)
	dvl.DeleteKey(*it2);
    }
  }
  dvl_fitskw->Merge(dvl);
}
/* 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;
}