diff --git a/MatrixElement/Matchbox/Base/MatchboxMEBase.cc b/MatrixElement/Matchbox/Base/MatchboxMEBase.cc
--- a/MatrixElement/Matchbox/Base/MatchboxMEBase.cc
+++ b/MatrixElement/Matchbox/Base/MatchboxMEBase.cc
@@ -1,1647 +1,1658 @@
 // -*- C++ -*-
 //
 // MatchboxMEBase.cc is a part of Herwig - A multi-purpose Monte Carlo event generator
 // Copyright (C) 2002-2017 The Herwig Collaboration
 //
 // Herwig is licenced under version 3 of the GPL, see COPYING for details.
 // Please respect the MCnet academic guidelines, see GUIDELINES for details.
 //
 //
 // This is the implementation of the non-inlined, non-templated member
 // functions of the MatchboxMEBase class.
 //
 
 #include "MatchboxMEBase.h"
 #include "ThePEG/Utilities/DescribeClass.h"
 #include "ThePEG/Interface/ClassDocumentation.h"
 #include "ThePEG/Persistency/PersistentOStream.h"
 #include "ThePEG/Persistency/PersistentIStream.h"
 #include "ThePEG/PDF/PDF.h"
 #include "ThePEG/PDT/PDT.h"
 #include "ThePEG/StandardModel/StandardModelBase.h"
 #include "ThePEG/Cuts/Cuts.h"
 #include "ThePEG/Handlers/StdXCombGroup.h"
 #include "ThePEG/EventRecord/SubProcess.h"
 #include "Herwig/MatrixElement/Matchbox/Dipoles/SubtractionDipole.h"
 #include "Herwig/MatrixElement/Matchbox/Utility/DiagramDrawer.h"
 #include "Herwig/MatrixElement/Matchbox/MatchboxFactory.h"
 #include "Herwig/MatrixElement/Matchbox/Base/MergerBase.h"
 #include "Herwig/API/RunDirectories.h"
 #include "Herwig/MatrixElement/ProductionMatrixElement.h"
 #include "Herwig/MatrixElement/HardVertex.h"
 
 #include <cctype>
 
 #include <iterator>
 using std::ostream_iterator;
 
 using namespace Herwig;
 
 MatchboxMEBase::MatchboxMEBase() 
   : MEBase(), 
     theOneLoop(false),
     theOneLoopNoBorn(false),
     theOneLoopNoLoops(false),
     theNoCorrelations(false),
     theHavePDFs(false,false), checkedPDFs(false) {}
 
 MatchboxMEBase::~MatchboxMEBase() {}
 
 Ptr<MatchboxFactory>::tptr MatchboxMEBase::factory() const {
   return MatchboxFactory::currentFactory();
 }
 
 Ptr<Tree2toNGenerator>::tptr MatchboxMEBase::diagramGenerator() const { return factory()->diagramGenerator(); }
 
 Ptr<ProcessData>::tptr MatchboxMEBase::processData() const { return factory()->processData(); }
 
 unsigned int MatchboxMEBase::getNLight() const { return factory()->nLight(); }
 
 vector<long> MatchboxMEBase::getNLightJetVec() const { return factory()->nLightJetVec(); }
 
 vector<long> MatchboxMEBase::getNHeavyJetVec() const { return factory()->nHeavyJetVec(); }
 
 vector<long> MatchboxMEBase::getNLightProtonVec() const { return factory()->nLightProtonVec(); }
 
 double MatchboxMEBase::factorizationScaleFactor() const { return factory()->factorizationScaleFactor(); }
 
 double MatchboxMEBase::renormalizationScaleFactor() const { return factory()->renormalizationScaleFactor(); }
 
 bool MatchboxMEBase::fixedCouplings() const { return factory()->fixedCouplings(); }
 
 bool MatchboxMEBase::fixedQEDCouplings() const { return factory()->fixedQEDCouplings(); }
 
 bool MatchboxMEBase::checkPoles() const { return factory()->checkPoles(); }
 
 bool MatchboxMEBase::verbose() const { return factory()->verbose(); }
 
 bool MatchboxMEBase::initVerbose() const { return factory()->initVerbose(); }
 
 void MatchboxMEBase::getDiagrams() const {
 
   if ( diagramGenerator() && processData() ) {
 
     vector<Ptr<Tree2toNDiagram>::ptr> diags;
 
     vector<Ptr<Tree2toNDiagram>::ptr>& res =
       processData()->diagramMap()[subProcess().legs];
     if ( res.empty() ) {
       res = diagramGenerator()->generate(subProcess().legs,orderInAlphaS(),orderInAlphaEW());
     }
     copy(res.begin(),res.end(),back_inserter(diags));
     processData()->fillMassGenerators(subProcess().legs);
 
     if ( diags.empty() )
       return;
 
     for (auto const & d :  diags )
       add(d);
     
     return;
 
   }
 
   throw Exception()
     << "MatchboxMEBase::getDiagrams() expects a Tree2toNGenerator and ProcessData object.\n"
     << "Please check your setup." << Exception::runerror;
 
 }
 
 Selector<MEBase::DiagramIndex> 
 MatchboxMEBase::diagrams(const DiagramVector & diags) const {
 
   if ( phasespace() ) {
     return phasespace()->selectDiagrams(diags);
   }
 
   throw Exception()
     << "MatchboxMEBase::diagrams() expects a MatchboxPhasespace object.\n"
     << "Please check your setup." << Exception::runerror;
   return Selector<MEBase::DiagramIndex>();
 
 }
 
 Selector<const ColourLines *>
 MatchboxMEBase::colourGeometries(tcDiagPtr diag) const {
 
   if ( matchboxAmplitude() ) {
     if ( matchboxAmplitude()->haveColourFlows() ) {
       if ( matchboxAmplitude()->treeAmplitudes() )
 	matchboxAmplitude()->prepareAmplitudes(this);
       return matchboxAmplitude()->colourGeometries(diag);
     }
   }
 
   Ptr<Tree2toNDiagram>::tcptr tdiag =
     dynamic_ptr_cast<Ptr<Tree2toNDiagram>::tcptr>(diag);
   assert(diag && processData());
 
   vector<ColourLines*>& flows = processData()->colourFlowMap()[tdiag];
 
   if ( flows.empty() ) {
 
     list<list<list<pair<int,bool> > > > cflows =
       ColourBasis::colourFlows(tdiag);
 
     for ( auto const & fit : cflows)
       flows.push_back(new ColourLines(ColourBasis::cfstring(fit)));
 
   }
 
   Selector<const ColourLines *> res;
   for ( auto const & f : flows ) res.insert(1.0,f);
 
   return res;
 
 }
 
 void MatchboxMEBase::constructVertex(tSubProPtr sub, const ColourLines* cl) {
 
   if ( !canFillRhoMatrix() || !factory()->spinCorrelations() )
     return;
 
   assert(matchboxAmplitude());
   assert(matchboxAmplitude()->colourBasis());
 
   // get the colour structure for the selected colour flow
   size_t cStructure = 
     matchboxAmplitude()->colourBasis()->tensorIdFromFlow(lastXComb().lastDiagram(),cl);
 
   // hard process for processing the spin info
   tPVector hard;
   hard.push_back(sub->incoming().first);
   hard.push_back(sub->incoming().second);
   
   vector<PDT::Spin> out;
   for ( auto const & p  : sub->outgoing() ) {
     out.push_back(p->data().iSpin());
     hard.push_back(p);
   }
 
   // calculate dummy wave functions to fill the spin info
   static vector<VectorWaveFunction> dummyPolarizations;
   static vector<SpinorWaveFunction> dummySpinors;
   static vector<SpinorBarWaveFunction> dummyBarSpinors;
   for ( size_t k = 0; k < hard.size(); ++k ) {
     if ( hard[k]->data().iSpin() == PDT::Spin1Half ) {
       if ( hard[k]->id() > 0 && k > 1 ) {
 	SpinorBarWaveFunction(dummyBarSpinors,hard[k],
 			      outgoing, true);
       } else if ( hard[k]->id() < 0 && k > 1 ) {
 	SpinorWaveFunction(dummySpinors,hard[k],
 			   outgoing, true);
       } else if ( hard[k]->id() > 0 && k < 2 ) {
 	SpinorWaveFunction(dummySpinors,hard[k],
 			   incoming, false);
       } else if ( hard[k]->id() < 0 && k < 2 ) {
 	SpinorBarWaveFunction(dummyBarSpinors,hard[k],
 			      incoming, false);
       }
     } 
     else if ( hard[k]->data().iSpin() == PDT::Spin1 ) {
       VectorWaveFunction(dummyPolarizations,hard[k],
 			 k > 1 ? outgoing : incoming,
 			 k > 1 ? true : false,
 			 hard[k]->data().hardProcessMass() == ZERO);
     }
     else if (hard[k]->data().iSpin() == PDT::Spin0 ) {
       ScalarWaveFunction(hard[k],k > 1 ? outgoing : incoming,
 			 k > 1 ? true : false);
     }
     else
       assert(false);
   }
 
   // fill the production matrix element
   ProductionMatrixElement pMe(mePartonData()[0]->iSpin(),
 			      mePartonData()[1]->iSpin(),
 			      out);
   for ( map<vector<int>,CVector>::const_iterator lamp = lastLargeNAmplitudes().begin();
 	lamp != lastLargeNAmplitudes().end(); ++lamp ) {
     vector<unsigned int> pMeHelicities
       = matchboxAmplitude()->physicalHelicities(lamp->first);
     pMe(pMeHelicities) = lamp->second[cStructure];
   }
 
   // set the spin information
   HardVertexPtr hardvertex = new_ptr(HardVertex());
   hardvertex->ME(pMe);
   if ( sub->incoming().first->spinInfo() )
     sub->incoming().first->spinInfo()->productionVertex(hardvertex);
   if ( sub->incoming().second->spinInfo() )
     sub->incoming().second->spinInfo()->productionVertex(hardvertex);
   for ( auto const & p : sub->outgoing() )
     if ( p->spinInfo() )
       p->spinInfo()->productionVertex(hardvertex);
   
 
 }
 
 unsigned int MatchboxMEBase::orderInAlphaS() const {
   return subProcess().orderInAlphaS;
 }
 
 unsigned int MatchboxMEBase::orderInAlphaEW() const {
   return subProcess().orderInAlphaEW;
 }
 
 void MatchboxMEBase::setXComb(tStdXCombPtr xc) {
 
   MEBase::setXComb(xc);
   lastMatchboxXComb(xc);
   if ( phasespace() )
     phasespace()->setXComb(xc);
   if ( scaleChoice() )
     scaleChoice()->setXComb(xc);
   if ( matchboxAmplitude() )
     matchboxAmplitude()->setXComb(xc);
   if (theMerger){
     theMerger->setME(this);
     theMerger->setXComb( xc );
   }
 
 }
 
 double MatchboxMEBase::generateIncomingPartons(const double* r1, const double* r2) {
   
   // shamelessly stolen from PartonExtractor.cc
 
   Energy2 shmax = lastCuts().sHatMax();
   Energy2 shmin = lastCuts().sHatMin();
   Energy2 sh = shmin*pow(shmax/shmin, *r1);
   double ymax = lastCuts().yHatMax();
   double ymin = lastCuts().yHatMin();
   double km = log(shmax/shmin);
   ymax = min(ymax, log(lastCuts().x1Max()*sqrt(lastS()/sh)));
   ymin = max(ymin, -log(lastCuts().x2Max()*sqrt(lastS()/sh)));
 
   double y = ymin + (*r2)*(ymax - ymin);
   double x1 = exp(-0.5*log(lastS()/sh) + y);
   double x2 = exp(-0.5*log(lastS()/sh) - y);
 
   Lorentz5Momentum P1 = lastParticles().first->momentum();
   LorentzMomentum p1 = lightCone((P1.rho() + P1.e())*x1, Energy());
   p1.rotateY(P1.theta());
   p1.rotateZ(P1.phi());
   meMomenta()[0] = p1;
 
   Lorentz5Momentum P2 = lastParticles().second->momentum();
   LorentzMomentum p2 = lightCone((P2.rho() + P2.e())*x2, Energy());
   p2.rotateY(P2.theta());
   p2.rotateZ(P2.phi());
   meMomenta()[1] = p2;
 
   lastXCombPtr()->lastX1X2(make_pair(x1,x2));
   lastXCombPtr()->lastSHat((meMomenta()[0]+meMomenta()[1]).m2());
 
   return km*(ymax - ymin);
 
 }
 
 bool MatchboxMEBase::generateKinematics(const double * r) {
 
   if ( phasespace() ) {
 
     jacobian(phasespace()->generateKinematics(r,meMomenta()));
     if ( jacobian() == 0.0 )
       return false;
 
     setScale();
     if (theMerger&&!theMerger->generateKinematics(r)){
       return false;
     }
 
     logGenerateKinematics(r);
 
     assert(lastMatchboxXComb());
 
     if ( nDimAmplitude() > 0 ) {
       amplitudeRandomNumbers().resize(nDimAmplitude());
       copy(r + nDimPhasespace(), 
 	   r + nDimPhasespace() + nDimAmplitude(),
 	   amplitudeRandomNumbers().begin());
     }
 
     if ( nDimInsertions() > 0 ) {
       insertionRandomNumbers().resize(nDimInsertions());
       copy(r + nDimPhasespace() + nDimAmplitude(), 
 	   r + nDimPhasespace() + nDimAmplitude() + nDimInsertions(),
 	   insertionRandomNumbers().begin());
     }
 
     return true;
 
   }
 
   throw Exception()
     << "MatchboxMEBase::generateKinematics() expects a MatchboxPhasespace object.\n"
     << "Please check your setup." << Exception::runerror;
 
   return false;
 
 }
 
 int MatchboxMEBase::nDim() const { 
 
   if ( lastMatchboxXComb() )
     return nDimPhasespace() + nDimAmplitude() + nDimInsertions();
 
   int ampAdd = 0;
   if ( matchboxAmplitude() ) {
     ampAdd = matchboxAmplitude()->nDimAdditional();
   }
 
   int insertionAdd = 0;
   for ( auto const & v : virtuals() ) {
     insertionAdd = max(insertionAdd,v->nDimAdditional());
   }
 
   return nDimBorn() + ampAdd + insertionAdd;
 
 }
 
 int MatchboxMEBase::nDimBorn() const { 
 
   if ( lastMatchboxXComb() )
     return nDimPhasespace();
 
   if ( phasespace() )
     return phasespace()->nDim(diagrams().front()->partons());
 
   throw Exception()
     << "MatchboxMEBase::nDim() expects a MatchboxPhasespace object.\n"
     << "Please check your setup." << Exception::runerror;
 
   return 0;
 
 }
 
 void MatchboxMEBase::setScale(Energy2 ren, Energy2 fac) const {
   if ( haveX1X2() ) {
     lastXCombPtr()->lastSHat((meMomenta()[0]+meMomenta()[1]).m2());
   }
   Energy2 fcscale = (fac == ZERO) ? factorizationScale() : fac;
   Energy2 fscale = fcscale*sqr(factorizationScaleFactor());
   Energy2 rscale = (ren == ZERO ? renormalizationScale() : ren)*sqr(renormalizationScaleFactor());
   Energy2 ewrscale = renormalizationScaleQED();
   lastXCombPtr()->lastScale(fscale);
   lastXCombPtr()->lastCentralScale(fcscale);
   lastXCombPtr()->lastShowerScale(showerScale());
   lastMatchboxXComb()->lastRenormalizationScale(rscale);
   if ( !fixedCouplings() ) {
     if ( rscale > lastCuts().scaleMin() )
       lastXCombPtr()->lastAlphaS(SM().alphaS(rscale));
     else
       lastXCombPtr()->lastAlphaS(SM().alphaS(lastCuts().scaleMin()));
   } else {
     lastXCombPtr()->lastAlphaS(SM().alphaS());
   }
   if ( !fixedQEDCouplings() ) {
     lastXCombPtr()->lastAlphaEM(SM().alphaEMME(ewrscale));
   } else {
     lastXCombPtr()->lastAlphaEM(SM().alphaEMMZ());
   }
   logSetScale();
 }
 
 Energy2 MatchboxMEBase::factorizationScale() const {
   if ( scaleChoice() ) {
     return scaleChoice()->factorizationScale();
   }
 
   throw Exception()
     << "MatchboxMEBase::factorizationScale() expects a MatchboxScaleChoice object.\n"
     << "Please check your setup." << Exception::runerror;
 
   return ZERO;
 
 }
 
 Energy2 MatchboxMEBase::renormalizationScale() const {
   if ( scaleChoice() ) {
     return scaleChoice()->renormalizationScale();
   }
 
   throw Exception()
     << "MatchboxMEBase::renormalizationScale() expects a MatchboxScaleChoice object.\n"
     << "Please check your setup." << Exception::runerror;
 
   return ZERO;
 
 }
 
 Energy2 MatchboxMEBase::renormalizationScaleQED() const {
   if ( scaleChoice() ) {
     return scaleChoice()->renormalizationScaleQED();
   }
   return renormalizationScale();
 }
 
 Energy2 MatchboxMEBase::showerScale() const {
   if ( scaleChoice() ) {
     return scaleChoice()->showerScale();
   }
 
   throw Exception()
     << "MatchboxMEBase::showerScale() expects a MatchboxScaleChoice object.\n"
     << "Please check your setup." << Exception::runerror;
 
   return ZERO;
 
 }
 
 void MatchboxMEBase::setVetoScales(tSubProPtr) const {}
 
 bool MatchboxMEBase::havePDFWeight1() const {
   if ( checkedPDFs )
     return theHavePDFs.first;
   theHavePDFs.first = 
     factory()->isIncoming(mePartonData()[0]) && 
     lastXCombPtr()->partonBins().first->pdf();
   theHavePDFs.second = 
     factory()->isIncoming(mePartonData()[1]) &&
     lastXCombPtr()->partonBins().second->pdf();
   checkedPDFs = true;
   return theHavePDFs.first;
 }
 
 bool MatchboxMEBase::havePDFWeight2() const {
   if ( checkedPDFs )
     return theHavePDFs.second;
   theHavePDFs.first = 
     factory()->isIncoming(mePartonData()[0]) && 
     lastXCombPtr()->partonBins().first->pdf();
   theHavePDFs.second = 
     factory()->isIncoming(mePartonData()[1]) &&
     lastXCombPtr()->partonBins().second->pdf();
   checkedPDFs = true;
   return theHavePDFs.second;
 }
 
 void MatchboxMEBase::getPDFWeight(Energy2 factorizationScale) const {
 
   if ( !havePDFWeight1() && !havePDFWeight2() ) {
     lastMEPDFWeight(1.0);
     logPDFWeight();
     return;
   }
 
   double w = 1.;
 
   if ( havePDFWeight1() )
     w *= pdf1(factorizationScale);
 
   if ( havePDFWeight2() )
     w *= pdf2(factorizationScale);
 
   lastMEPDFWeight(w);
 
   logPDFWeight();
 
 }
 
 double MatchboxMEBase::pdf1(Energy2 fscale, double xEx, double xFactor) const {
 
   assert(lastXCombPtr()->partonBins().first->pdf());
 
   if ( xEx < 1. && lastX1()*xFactor >= xEx ) {
     return
       ( ( 1. - lastX1()*xFactor ) / ( 1. - xEx ) ) *
       lastXCombPtr()->partonBins().first->pdf()->xfx(lastParticles().first->dataPtr(),
 						     lastPartons().first->dataPtr(),
 						     fscale == ZERO ? lastScale() : fscale,
 						     xEx)/xEx;
   }
 
   return lastXCombPtr()->partonBins().first->pdf()->xfx(lastParticles().first->dataPtr(),
 							lastPartons().first->dataPtr(),
 							fscale == ZERO ? lastScale() : fscale,
 							lastX1()*xFactor)/lastX1()/xFactor;
 }
 
 double MatchboxMEBase::pdf2(Energy2 fscale, double xEx, double xFactor) const {
 
   assert(lastXCombPtr()->partonBins().second->pdf());
 
   if ( xEx < 1. && lastX2()*xFactor >= xEx ) {
     return
       ( ( 1. - lastX2()*xFactor ) / ( 1. - xEx ) ) *
       lastXCombPtr()->partonBins().second->pdf()->xfx(lastParticles().second->dataPtr(),
 						      lastPartons().second->dataPtr(),
 						      fscale == ZERO ? lastScale() : fscale,
 						      xEx)/xEx;
   }
 
   return lastXCombPtr()->partonBins().second->pdf()->xfx(lastParticles().second->dataPtr(),
 							 lastPartons().second->dataPtr(),
 							 fscale == ZERO ? lastScale() : fscale,
 							 lastX2()*xFactor)/lastX2()/xFactor;
 
 }
 
 double MatchboxMEBase::me2() const {
 
   if ( matchboxAmplitude() ) {
 
     if ( matchboxAmplitude()->treeAmplitudes() )
       matchboxAmplitude()->prepareAmplitudes(this);
 
     double res = 
       matchboxAmplitude()->me2()*
       me2Norm();
 
     return res;
 
   }
 
   throw Exception()
     << "MatchboxMEBase::me2() expects a MatchboxAmplitude object.\n"
     << "Please check your setup." << Exception::runerror;
   return 0.;
 
 }
 
 double MatchboxMEBase::largeNME2(Ptr<ColourBasis>::tptr largeNBasis) const {
 
   if ( matchboxAmplitude() ) {
 
     if ( matchboxAmplitude()->treeAmplitudes() ) {
       largeNBasis->prepare(mePartonData(),false);
       matchboxAmplitude()->prepareAmplitudes(this);
     }
 
     double res = 
       matchboxAmplitude()->largeNME2(largeNBasis)*
       me2Norm();
 
     return res;
 
   }
 
   throw Exception()
     << "MatchboxMEBase::largeNME2() expects a MatchboxAmplitude object.\n"
     << "Please check your setup." << Exception::runerror;
   return 0.;
 
 }
 
 double MatchboxMEBase::finalStateSymmetry() const {
 
   if ( symmetryFactor() > 0.0 )
     return symmetryFactor();
 
   double sFactor = 1.;
 
   map<long,int> counts;
 
   cPDVector checkData;
   copy(mePartonData().begin()+2,mePartonData().end(),back_inserter(checkData));
 
   cPDVector::iterator p = checkData.begin();
   while ( !checkData.empty() ) {
     if ( counts.find((**p).id()) != counts.end() ) {
       counts[(**p).id()] += 1;
     } else {
       counts[(**p).id()] = 1;
     }
     checkData.erase(p);
     p = checkData.begin();
     continue;
   }
 
   for ( auto const & c : counts) {
     if ( c.second == 1 )
       continue;
     if ( c.second == 2 )
       sFactor /= 2.;
     else if ( c.second == 3 )
       sFactor /= 6.;
     else if ( c.second == 4 )
       sFactor /= 24.;
   }
 
   symmetryFactor(sFactor);
 
   return symmetryFactor();
 
 }
 
 double MatchboxMEBase::me2Norm(unsigned int addAlphaS) const {
 
   // assume that we always have incoming
   // spin-1/2 or massless spin-1 particles
   double fac = 1./4.;
 
   if ( hasInitialAverage() )
     fac = 1.;
 
   double couplings = 1.0;
   if ( (orderInAlphaS() > 0 || addAlphaS != 0) && !hasRunningAlphaS() ) {
     fac *= pow(lastAlphaS()/SM().alphaS(),double(orderInAlphaS()+addAlphaS));
     couplings *= pow(lastAlphaS(),double(orderInAlphaS()+addAlphaS));
   }
   if ( orderInAlphaEW() > 0 && !hasRunningAlphaEW() ) {
     fac *= pow(lastAlphaEM()/SM().alphaEMMZ(),double(orderInAlphaEW()));
     couplings *= pow(lastAlphaEM(),double(orderInAlphaEW()));
   }
   lastMECouplings(couplings);
 
   if ( !hasInitialAverage() ) {
     if ( mePartonData()[0]->iColour() == PDT::Colour3 || 
 	 mePartonData()[0]->iColour() == PDT::Colour3bar )
       fac /= SM().Nc();
     else if ( mePartonData()[0]->iColour() == PDT::Colour8 )
       fac /= (SM().Nc()*SM().Nc()-1.);
 
     if ( mePartonData()[1]->iColour() == PDT::Colour3 || 
 	 mePartonData()[1]->iColour() == PDT::Colour3bar )
       fac /= SM().Nc();
     else if ( mePartonData()[1]->iColour() == PDT::Colour8 )
       fac /= (SM().Nc()*SM().Nc()-1.);
   }
 
   return !hasFinalStateSymmetry() ? finalStateSymmetry()*fac : fac;
 
 }
 
 
 CrossSection MatchboxMEBase::prefactor()const{
   return (sqr(hbarc)/(2.*lastSHat())) *jacobian()* lastMEPDFWeight();
 }
 
 CrossSection MatchboxMEBase::dSigHatDRB() const {
   getPDFWeight();
   lastME2(me2());
   return oneLoopNoBorn()?ZERO:prefactor() * lastME2();
 }
 
 CrossSection MatchboxMEBase::dSigHatDRV() const {
   getPDFWeight();
   lastME2(me2());
   return ( oneLoop() && !oneLoopNoLoops() )?(prefactor() * oneLoopInterference()):ZERO;
 }
 
 CrossSection MatchboxMEBase::dSigHatDRI() const {
   getPDFWeight();
   lastME2(me2());
   CrossSection res=ZERO;
   if  (oneLoop() &&!onlyOneLoop())  {
     for ( auto const & v : virtuals()) {
       v->setXComb(lastXCombPtr());
       res += v->dSigHatDR();
     }
     if ( checkPoles() && oneLoop() )
       logPoles();
   }
   return res;
 }
 
 CrossSection MatchboxMEBase::dSigHatDRAlphaDiff(double alpha) const {
   getPDFWeight();
   lastME2(me2());
   CrossSection res=ZERO;
   for ( auto const & v: virtuals() ) {
     v->setXComb(lastXCombPtr());
     res+=v->dSigHatDRAlphaDiff( alpha);
   }
   return res;
 }
 
-
-
-
-
-
 CrossSection MatchboxMEBase::dSigHatDR() const {
   getPDFWeight();
   
   if (theMerger){
     lastMECrossSection(theMerger->MergingDSigDR());
     return lastMECrossSection();
-  }else if (lastXCombPtr()->willPassCuts() ) {
-    lastMECrossSection(dSigHatDRB()+
-                       dSigHatDRV()+
-                       dSigHatDRI());
+  }
+  else if (lastXCombPtr()->willPassCuts() ) {
+	lastME2(me2());
+	CrossSection _dSigHatDRB, _dSigHatDRV, _dSigHatDRI, res = ZERO;
+	// ----- dSigHatDRB -----
+	_dSigHatDRB = oneLoopNoBorn()?ZERO:prefactor() * lastME2();
+	// ----- dSigHatDRV -----
+	_dSigHatDRV = ( oneLoop() && !oneLoopNoLoops() )?(prefactor() * oneLoopInterference()):ZERO;
+	// ----- dSigHatDRI -----
+    if  (oneLoop() &&!onlyOneLoop())  {
+    for ( auto const & v : virtuals()) {
+      v->setXComb(lastXCombPtr());
+      res += v->dSigHatDR();
+    }
+    if ( checkPoles() && oneLoop() )
+      logPoles();
+  }
+	_dSigHatDRI = res;
+	// ----- finalizing -----
+    lastMECrossSection(_dSigHatDRB + _dSigHatDRV + _dSigHatDRI);
     return lastMECrossSection();
   }
-
+  else
+  {
   lastME2(ZERO);
   lastMECrossSection(ZERO);
-
   return lastMECrossSection();
-
+  }
 }
 
 double MatchboxMEBase::oneLoopInterference() const {
 
   if ( matchboxAmplitude() ) {
 
     if ( matchboxAmplitude()->oneLoopAmplitudes() )
       matchboxAmplitude()->prepareOneLoopAmplitudes(this);
 
     double res = 
       matchboxAmplitude()->oneLoopInterference()*
       me2Norm(1);
 
     return res;
 
   }
 
   throw Exception()
     << "MatchboxMEBase::oneLoopInterference() expects a MatchboxAmplitude object.\n"
     << "Please check your setup." << Exception::runerror;
   return 0.;
 
 }
 
 MatchboxMEBase::AccuracyHistogram::AccuracyHistogram(double low,
 						     double up,
 						     unsigned int nbins) 
   : lower(low), upper(up), 
     sameSign(0), oppositeSign(0), nans(0),
     overflow(0), underflow(0) {
 
   double step = (up-low)/nbins;
 
   for ( unsigned int k = 1; k <= nbins; ++k )
     bins[lower + k*step] = 0.0;
 
 }
 
 void MatchboxMEBase::AccuracyHistogram::book(double a, double b) {
   if ( ! (isfinite(a) && isfinite(b)) ) {
     ++nans;
     return;
   }
   if ( a*b >= 0. )
     ++sameSign;
   if ( a*b < 0. )
     ++oppositeSign;
   double r = 1.;
   if ( abs(a) != 0.0 )
     r = abs(1.-abs(b/a));
   else if ( abs(b) != 0.0 )
     r = abs(b);
   if ( log10(r) < lower || r == 0.0 ) {
     ++underflow;
     return;
   }
   if ( log10(r) > upper ) {
     ++overflow;
     return;
   }
   map<double,double>::iterator bin =
     bins.upper_bound(log10(r));
   if ( bin == bins.end() )
     return;
   bin->second += 1.;
 }
 
 void MatchboxMEBase::AccuracyHistogram::dump(const std::string& folder, const std::string& prefix,
 					     const cPDVector& proc) const {
   ostringstream fname("");
   for ( cPDVector::const_iterator p = proc.begin();
 	p != proc.end(); ++p )
     fname << (**p).PDGName();
   ofstream out((folder+"/"+prefix+fname.str()+".dat").c_str());
   out << "# same sign : " << sameSign << " opposite sign : "
       << oppositeSign << " nans : " << nans 
       << " overflow : " << overflow
       << " underflow : " << underflow << "\n";
   for ( map<double,double>::const_iterator b = bins.begin();
 	b != bins.end(); ++b ) {
     map<double,double>::const_iterator bp = b; --bp;
     if ( b->second != 0. ) {
       if ( b != bins.begin() )
 	out << bp->first;
       else
 	out << lower;
       out << " " << b->first
 	  << " " << b->second
 	  << "\n" << flush;
     }
   }
   ofstream gpout((folder+"/"+prefix+fname.str()+".gp").c_str());
   gpout << "set terminal png\n"
       << "set xlabel 'accuracy of pole cancellation [decimal places]'\n"
       << "set ylabel 'counts\n"
       << "set xrange [-20:0]\n"
       << "set output '" << prefix << fname.str() << ".png'\n"
       << "plot '" << prefix << fname.str() << ".dat' using (0.5*($1+$2)):3 with linespoints pt 7 ps 1 not";
 }
 
 void MatchboxMEBase::AccuracyHistogram::persistentOutput(PersistentOStream& os) const {
   os << lower << upper << bins
      << sameSign << oppositeSign << nans
      << overflow << underflow;
 }
 
 void MatchboxMEBase::AccuracyHistogram::persistentInput(PersistentIStream& is) {
   is >> lower >> upper >> bins
      >> sameSign >> oppositeSign >> nans
      >> overflow >> underflow;
 }
 
 void MatchboxMEBase::logPoles() const {
   double res2me = oneLoopDoublePole();
   double res1me = oneLoopSinglePole();
   double res2i = 0.;
   double res1i = 0.;
   for ( auto const & v : virtuals()) {
     res2i += v->oneLoopDoublePole();
     res1i += v->oneLoopSinglePole();
   }
   if (res2me != 0.0 || res2i != 0.0) epsilonSquarePoleHistograms[mePartonData()].book(res2me,res2i);
   if (res1me != 0.0 || res1i != 0.0) epsilonPoleHistograms[mePartonData()].book(res1me,res1i);
 }
 
 bool MatchboxMEBase::haveOneLoop() const {
   if ( matchboxAmplitude() )
     return matchboxAmplitude()->haveOneLoop();
   return false;
 }
 
 bool MatchboxMEBase::onlyOneLoop() const {
   if ( matchboxAmplitude() )
     return matchboxAmplitude()->onlyOneLoop();
   return false;
 }
 
 bool MatchboxMEBase::isDRbar() const {
   if ( matchboxAmplitude() )
     return matchboxAmplitude()->isDRbar();
   return false;
 }
 
 bool MatchboxMEBase::isDR() const {
   if ( matchboxAmplitude() )
     return matchboxAmplitude()->isDR();
   return false;
 }
 
 bool MatchboxMEBase::isCS() const {
   if ( matchboxAmplitude() )
     return matchboxAmplitude()->isCS();
   return false;
 }
 
 bool MatchboxMEBase::isBDK() const {
   if ( matchboxAmplitude() )
     return matchboxAmplitude()->isBDK();
   return false;
 }
 
 bool MatchboxMEBase::isExpanded() const {
   if ( matchboxAmplitude() )
     return matchboxAmplitude()->isExpanded();
   return false;
 }
 
 Energy2 MatchboxMEBase::mu2() const {
   if ( matchboxAmplitude() )
     return matchboxAmplitude()->mu2();
   return 0*GeV2;
 }
 
 double MatchboxMEBase::oneLoopDoublePole() const {
 
   if ( matchboxAmplitude() ) {
 
     return
       matchboxAmplitude()->oneLoopDoublePole()*
       me2Norm(1);
 
   }
 
   return 0.;
 
 }
 
 double MatchboxMEBase::oneLoopSinglePole() const {
 
   if ( matchboxAmplitude() ) {
 
     return 
       matchboxAmplitude()->oneLoopSinglePole()*
       me2Norm(1);
 
   }
 
   return 0.;
 
 }
 
 vector<SubtractionDipolePtr> 
 MatchboxMEBase::getDipoles(const vector<SubtractionDipolePtr>& dipoles,
 			   const vector<MatchboxMEBasePtr> & borns,bool slim) const {
 
   vector<SubtractionDipolePtr> res;
 
   // keep track of the dipoles we already did set up
   set<pair<pair<pair<int,int>,int>,pair<Ptr<MatchboxMEBase>::tptr,Ptr<SubtractionDipole>::tptr> > > done;
 
   cPDVector rep = diagrams().front()->partons();
   int nreal = rep.size();
 
   // now loop over configs
   for ( int emitter = 0; emitter < nreal; ++emitter ) {
 
     list<SubtractionDipolePtr> matchDipoles;
     for ( auto const & d : dipoles ) {
       if ( ! d->canHandleEmitter(rep,emitter) )
 	continue;
       matchDipoles.push_back(d);
     }
     if ( matchDipoles.empty() )
       continue;
 
     for ( int emission = 2; emission < nreal; ++emission ) {
       if ( emission == emitter )
 	continue;
 
       list<SubtractionDipolePtr> matchDipoles2;
       for ( auto const & d : matchDipoles ) {
 	if ( !d->canHandleSplitting(rep,emitter,emission) )
 	  continue;
 	matchDipoles2.push_back(d);
       }
       if ( matchDipoles2.empty() )
 	continue;
 
       map<Ptr<DiagramBase>::ptr,SubtractionDipole::MergeInfo> mergeInfo;
 
       for ( auto const & d : diagrams() ) {
 
 	Ptr<Tree2toNDiagram>::ptr check =
         new_ptr(Tree2toNDiagram(*dynamic_ptr_cast<Ptr<Tree2toNDiagram>::ptr>(d)));
 
 	map<int,int> theMergeLegs;
 
 	for ( unsigned int i = 0; i < check->external().size(); ++i )
 	  theMergeLegs[i] = -1;
 	int theEmitter = check->mergeEmission(emitter,emission,theMergeLegs);
 
 	// no underlying Born
 	if ( theEmitter == -1 )
 	  continue;
 
 	SubtractionDipole::MergeInfo info;
 	info.diagram = check;
 	info.emitter = theEmitter;
 	info.mergeLegs = theMergeLegs;
 	mergeInfo[d] = info;
 
       }
 
       if ( mergeInfo.empty() )
 	continue;
 
       for ( int spectator = 0; spectator < nreal; ++spectator ) {
 	if ( spectator == emitter || spectator == emission )
 	  continue;
 
 	list<SubtractionDipolePtr> matchDipoles3;
     for ( auto const & d : matchDipoles2 ) {
 	  if ( ! d->canHandleSpectator(rep,spectator) )
 	    continue;
 	  matchDipoles3.push_back(d);
 	}
 	if ( matchDipoles3.empty() )
 	  continue;
 
 	if ( noDipole(emitter,emission,spectator) )
 	  continue;
 
         for ( auto const & d : matchDipoles3 ) {
 
 	  if ( !d->canHandle(rep,emitter,emission,spectator) )
 	    continue;
 
           for ( auto const & b : borns ) {
 	    if ( b->onlyOneLoop() )
 	      continue;
 	    if ( done.find(make_pair(make_pair(make_pair(emitter,emission),spectator),make_pair(b,d)))
 		 != done.end() )
 	      continue;
 	    // now get to work
 	    d->clearBookkeeping();
 	    d->realEmitter(emitter);
 	    d->realEmission(emission);
 	    d->realSpectator(spectator);
 	    d->realEmissionME(const_cast<MatchboxMEBase*>(this));
 	    d->underlyingBornME(b);
 	    d->setupBookkeeping(mergeInfo,slim);
 	    if ( ! d->empty() )  {
 	      res.push_back( d->cloneMe() );
 	      Ptr<SubtractionDipole>::tptr nDipole = res.back();
 	      done.insert(make_pair(make_pair(make_pair(emitter,emission),spectator),make_pair(b,d)));
 	      if ( nDipole->isSymmetric() )
 		done.insert(make_pair(make_pair(make_pair(emission,emitter),spectator),make_pair(b,d)));
 	      ostringstream dname;
               if ( theMerger) {
                 dname << fullName();
                 if (theOneLoopNoBorn)  dname <<  ".virtual" << "." ;
                 dname   << b->name() << "."
                         << d->name() << ".[("
                         << emitter << "," << emission << ")," << spectator << "]";
               } else {
                 dname << fullName() << "." << b->name() << "."
 		    << d->name() << ".[("
 		    << emitter << "," << emission << ")," << spectator << "]";
               }
 	      if ( ! (generator()->preinitRegister(nDipole,dname.str()) ) )
 		throw Exception() << "MatchboxMEBase::getDipoles(): Dipole " << dname.str() << " already existing." << Exception::runerror;
 	      if ( !factory()->reweighters().empty() ) {
             for ( auto const & rw : factory()->reweighters())
 		  nDipole->addReweighter(rw);
 	      }
 	      if ( !factory()->preweighters().empty() ) {
             for ( auto const & rw : factory()->preweighters() )
 		  nDipole->addPreweighter(rw);
 	      }
 	      nDipole->cloneDependencies(dname.str(),slim);
 	    }
 	  }
 	}
       }
     }
   }
 
   vector<Ptr<SubtractionDipole>::tptr> partners;
   copy(res.begin(),res.end(),back_inserter(partners));
   for ( auto const & d : res )
     d->partnerDipoles(partners);
 
   return res;
 
 }
 
 double MatchboxMEBase::colourCorrelatedME2(pair<int,int> ij) const {
 
   if ( matchboxAmplitude() ) {
 
     if ( matchboxAmplitude()->treeAmplitudes() )
       matchboxAmplitude()->prepareAmplitudes(this);
 
     double res = 
       matchboxAmplitude()->colourCorrelatedME2(ij)*
       me2Norm();
 
     return res;
 
   }
 
   throw Exception()
     << "MatchboxMEBase::colourCorrelatedME2() expects a MatchboxAmplitude object.\n"
     << "Please check your setup." << Exception::runerror;
   return 0.;
 
 }
 
 double MatchboxMEBase::largeNColourCorrelatedME2(pair<int,int> ij,
 						 Ptr<ColourBasis>::tptr largeNBasis) const {
 
   if ( matchboxAmplitude() ) {
 
     if ( matchboxAmplitude()->treeAmplitudes() ) {
       largeNBasis->prepare(mePartonData(),false);
       matchboxAmplitude()->prepareAmplitudes(this);
     }
 
     double res = 
       matchboxAmplitude()->largeNColourCorrelatedME2(ij,largeNBasis)*
       me2Norm();
 
     return res;
 
   }
 
   throw Exception()
     << "MatchboxMEBase::largeNColourCorrelatedME2() expects a MatchboxAmplitude object.\n"
     << "Please check your setup." << Exception::runerror;
   return 0.;
 
 }
 
 double MatchboxMEBase::spinColourCorrelatedME2(pair<int,int> ij,
 					       const SpinCorrelationTensor& c) const {
 
   if ( matchboxAmplitude() ) {
 
     if ( matchboxAmplitude()->treeAmplitudes() )
       matchboxAmplitude()->prepareAmplitudes(this);
 
     double res = 
       matchboxAmplitude()->spinColourCorrelatedME2(ij,c)*
       me2Norm();
 
     return res;
 
   }
 
   throw Exception()
     << "MatchboxMEBase::spinColourCorrelatedME2() expects a MatchboxAmplitude object.\n"
     << "Please check your setup." << Exception::runerror;
   return 0.;
 
 }
 
 double MatchboxMEBase::spinCorrelatedME2(pair<int,int> ij,
 					 const SpinCorrelationTensor& c) const {
 
   if ( matchboxAmplitude() ) {
 
     if ( matchboxAmplitude()->treeAmplitudes() )
       matchboxAmplitude()->prepareAmplitudes(this);
 
     double res = 
       matchboxAmplitude()->spinCorrelatedME2(ij,c)*
       me2Norm();
 
     return res;
 
   }
 
   throw Exception()
     << "MatchboxMEBase::spinCorrelatedME2() expects a MatchboxAmplitude object.\n"
     << "Please check your setup." << Exception::runerror;
   return 0.;
 
 }
 
 
 void MatchboxMEBase::flushCaches() {
   if ( theMerger )theMerger->flushCaches(); 
   MEBase::flushCaches();
   if ( matchboxAmplitude() )
     matchboxAmplitude()->flushCaches();
   for ( auto const & r : reweights() ) 
     r->flushCaches();
   for ( auto const &  v : virtuals()) 
     v->flushCaches();
 }
 
 
 void MatchboxMEBase::setKinematics() {
   MEBase::setKinematics();
   if ( theMerger ) 
     theMerger->setKinematics();
 }
 
 void MatchboxMEBase::clearKinematics() {
   MEBase::clearKinematics();
   if ( theMerger )
     theMerger->clearKinematics();
 }
 
 const MergerBasePtr MatchboxMEBase::merger() const {
   return theMerger;
 }
 
 MergerBasePtr MatchboxMEBase::merger() {
   return theMerger;
 }
 
 void MatchboxMEBase::merger(MergerBasePtr v) {
   theMerger = v;
 }
 
 
 
 
 void MatchboxMEBase::print(ostream& os) const {
 
   os << "--- MatchboxMEBase setup -------------------------------------------------------\n";
 
   os << " '" << name() << "' for subprocess:\n";
 
   os << "  ";
   for ( PDVector::const_iterator pp = subProcess().legs.begin();
 	pp != subProcess().legs.end(); ++pp ) {
     os << (**pp).PDGName() << " ";
     if ( pp == subProcess().legs.begin() + 1 )
       os << "-> ";
   }
   os << "\n";
 
   os << " including " << (oneLoop() ? "" : "no ") << "virtual corrections";
   if ( oneLoopNoBorn() )
     os << " without Born contributions";
   if ( oneLoopNoLoops() )
     os << " without loop contributions";
   os << "\n";
 
   if ( oneLoop() && !onlyOneLoop() ) {
     os << " using insertion operators\n";
     for ( vector<Ptr<MatchboxInsertionOperator>::ptr>::const_iterator v =
 	    virtuals().begin(); v != virtuals().end(); ++v ) {
       os << " '" << (**v).name() << "' with " 
 	 << ((**v).isDR() ? "" : "C") << "DR/";
       if ( (**v).isCS() )
 	os << "CS";
       if ( (**v).isBDK() )
 	os << "BDK";
       if ( (**v).isExpanded() )
 	os << "expanded";
       os << " conventions\n";
     }
   }
 
   os << "--------------------------------------------------------------------------------\n";
 
   os << flush;
 
 }
 
 void MatchboxMEBase::printLastEvent(ostream& os) const {
 
   os << "--- MatchboxMEBase last event information --------------------------------------\n";
 
   os << " for matrix element '" << name() << "'\n";
 
   os << " process considered:\n ";
 
   int in = 0;
   for ( cPDVector::const_iterator p = mePartonData().begin();
 	p != mePartonData().end(); ++p ) {
     os << (**p).PDGName() << " ";
     if ( ++in == 2 )
       os << " -> ";
   }
 
   os << " kinematic environment as set by the XComb " << lastXCombPtr() << ":\n"
      << " sqrt(shat)/GeV = " << sqrt(lastSHat()/GeV2)
      << " x1 = " << lastX1() << " x2 = " << lastX2() 
      << " alphaS = " << lastAlphaS() << "\n";
 
   os << " momenta/GeV generated from random numbers\n ";
   copy(lastXComb().lastRandomNumbers().begin(),
        lastXComb().lastRandomNumbers().end(),ostream_iterator<double>(os," "));
   os << ":\n ";
 
   for ( vector<Lorentz5Momentum>::const_iterator p = meMomenta().begin();
 	p != meMomenta().end(); ++p ) {
     os << (*p/GeV) << "\n ";
   }
 
   os << "last cross section/nb calculated was:\n "
      << (lastMECrossSection()/nanobarn) << " (pdf weight " << lastMEPDFWeight() << ")\n";
 
   os << "--------------------------------------------------------------------------------\n";
 
   os << flush;
 
 }
 
 void MatchboxMEBase::logGenerateKinematics(const double * r) const {
 
   if ( !verbose() )
     return;
 
   generator()->log() << "'" << name() << "' generated kinematics\nfrom "
 		     << nDim() << " random numbers:\n";
   copy(r,r+nDim(),ostream_iterator<double>(generator()->log()," "));
   generator()->log() << "\n";
 
   generator()->log() << "storing phase space information in XComb "
 		     << lastXCombPtr() << "\n";
 
   generator()->log() << "generated phase space point (in GeV):\n";
 
   vector<Lorentz5Momentum>::const_iterator pit = meMomenta().begin();
   cPDVector::const_iterator dit = mePartonData().begin();
 
   for ( ; pit != meMomenta().end() ; ++pit, ++dit )
     generator()->log() << (**dit).PDGName() << " : "
 		       << (*pit/GeV) << "\n";
 
   generator()->log() << "with x1 = " << lastX1() << " x2 = " << lastX2() << "\n"
 		     << "and Jacobian = " << jacobian() << " sHat/GeV2 = "
 		     << (lastSHat()/GeV2) << "\n" << flush;
 
 }
 
 void MatchboxMEBase::logSetScale() const {
 
   if ( !verbose() )
     return;
 
   generator()->log() << "'" << name() << "' set scales using XComb " << lastXCombPtr() << ":\n"
 		     << "scale/GeV2 = " << (scale()/GeV2) << " xi_R = "
 		     << renormalizationScaleFactor() << " xi_F = "
 		     << factorizationScaleFactor() << "\n"
 		     << "alpha_s = " << lastAlphaS() << "\n" << flush;
 
 }
 
 void MatchboxMEBase::logPDFWeight() const {
 
   if ( !verbose() )
     return;
 
   generator()->log() << "'" << name() << "' calculated pdf weight = "
 		     << lastMEPDFWeight() << " from XComb "
 		     << lastXCombPtr() << "\n"
 		     << "x1 = " << lastX1() << " (" << (mePartonData()[0]->coloured() ? "" : "not ") << "used) "
 		     << "x2 = " << lastX2() << " (" << (mePartonData()[1]->coloured() ? "" : "not ") << "used)\n"
 		     << flush;
 
 }
 
 void MatchboxMEBase::logME2() const {
 
   if ( !verbose() )
     return;
 
   generator()->log() << "'" << name() << "' evaluated me2 using XComb "
 		     << lastXCombPtr() << "\n"
 		     << "and phase space point (in GeV):\n";
 
   vector<Lorentz5Momentum>::const_iterator pit = meMomenta().begin();
   cPDVector::const_iterator dit = mePartonData().begin();
 
   for ( ; pit != meMomenta().end() ; ++pit, ++dit )
     generator()->log() << (**dit).PDGName() << " : "
 		       << (*pit/GeV) << "\n";
 
   generator()->log() << "with x1 = " << lastX1() << " x2 = " << lastX2() << "\n"
 		     << "sHat/GeV2 = " << (lastSHat()/GeV2) << "\n" << flush;
 
 }
 
 void MatchboxMEBase::logDSigHatDR() const {
 
   if ( !verbose() )
     return;
 
   generator()->log() << "'" << name() << "' evaluated cross section using XComb "
 		     << lastXCombPtr() << "\n"
 		     << "Jacobian = " << jacobian() << " sHat/GeV2 = "
 		     << (lastSHat()/GeV2) << " dsig/nb = "
 		     << (lastMECrossSection()/nanobarn) << "\n" << flush;
 
 }
 
 void MatchboxMEBase::cloneDependencies(const std::string& prefix,bool slim) {
 
   if ( phasespace() && !slim ) {
     Ptr<MatchboxPhasespace>::ptr myPhasespace = phasespace()->cloneMe();
     ostringstream pname;
     pname << (prefix == "" ? fullName() : prefix) << "/" << myPhasespace->name();
     if ( ! (generator()->preinitRegister(myPhasespace,pname.str()) ) )
       throw Exception() << "MatchboxMEBase::cloneDependencies(): Phasespace generator " << pname.str() << " already existing." << Exception::runerror;
     myPhasespace->cloneDependencies(pname.str());
     phasespace(myPhasespace);
   }
 
   theAmplitude = dynamic_ptr_cast<Ptr<MatchboxAmplitude>::ptr>(amplitude());
 
   if ( matchboxAmplitude() ) {
     Ptr<MatchboxAmplitude>::ptr myAmplitude = matchboxAmplitude()->cloneMe();
     ostringstream pname;
     pname << (prefix == "" ? fullName() : prefix) << "/" << myAmplitude->name();
     if ( ! (generator()->preinitRegister(myAmplitude,pname.str()) ) ){
       throw Exception() << "MatchboxMEBase::cloneDependencies(): Amplitude " << pname.str() << " already existing." << Exception::runerror;
     }
     myAmplitude->cloneDependencies(pname.str(),slim);
     matchboxAmplitude(myAmplitude);
     amplitude(myAmplitude);
     matchboxAmplitude()->orderInGs(orderInAlphaS());
     matchboxAmplitude()->orderInGem(orderInAlphaEW());
   }
 
   if ( scaleChoice() &&!slim ) {
     Ptr<MatchboxScaleChoice>::ptr myScaleChoice = scaleChoice()->cloneMe();
     ostringstream pname;
     pname << (prefix == "" ? fullName() : prefix) << "/" << myScaleChoice->name();
     if ( ! (generator()->preinitRegister(myScaleChoice,pname.str()) ) )
       throw Exception() << "MatchboxMEBase::cloneDependencies(): Scale choice " << pname.str() << " already existing." << Exception::runerror;
     scaleChoice(myScaleChoice);
   }
 
   for ( auto &  rw : theReweights ) {
     Ptr<MatchboxReweightBase>::ptr myReweight = rw->cloneMe();
     ostringstream pname;
     pname << (prefix == "" ? fullName() : prefix) << "/" << rw->name();
     if ( ! (generator()->preinitRegister(myReweight,pname.str()) ) )
       throw Exception() << "MatchboxMEBase::cloneDependencies(): Reweight " << pname.str() << " already existing." << Exception::runerror;
     myReweight->cloneDependencies(pname.str());
     rw = myReweight;
   }
 
   for ( auto & v : virtuals()) {
     Ptr<MatchboxInsertionOperator>::ptr myIOP = v->cloneMe();
     ostringstream pname;
     pname << (prefix == "" ? fullName() : prefix) << "/" << v->name();
     if ( ! (generator()->preinitRegister(myIOP,pname.str()) ) )
       throw Exception() << "MatchboxMEBase::cloneDependencies(): Insertion operator " << pname.str() << " already existing." << Exception::runerror;
     v = myIOP;
   }
 
 }
 
 void MatchboxMEBase::prepareXComb(MatchboxXCombData& xc) const {
 
   // fixme We need to pass on the partons from the xcmob here, not
   // assuming one subprocess per matrix element
 
   if ( phasespace() )
     xc.nDimPhasespace(phasespace()->nDim(diagrams().front()->partons()));
 
   if ( matchboxAmplitude() ) {
     xc.nDimAmplitude(matchboxAmplitude()->nDimAdditional());
     if ( matchboxAmplitude()->colourBasis() ) {
       size_t cdim = 
  	matchboxAmplitude()->colourBasis()->prepare(diagrams(),noCorrelations());
       xc.colourBasisDim(cdim);
     }
     if ( matchboxAmplitude()->isExternal() ) {
       xc.externalId(matchboxAmplitude()->externalId(diagrams().front()->partons()));
     }
   }
 
   int insertionAdd = 0;
   for ( auto const &  v : virtuals() )
     insertionAdd = max(insertionAdd,v->nDimAdditional());
   
   xc.nDimInsertions(insertionAdd);
 
   xc.nLight(getNLight());
   if(xc.nLightJetVec().empty())
   for (auto const & id : getNLightJetVec())
     xc.nLightJetVec( id );
   
   if(xc.nHeavyJetVec().empty())
   for (auto const & id :getNHeavyJetVec())
     xc.nHeavyJetVec(id);
 
   if(xc.nLightProtonVec().empty())
   for (auto const & id : getNLightProtonVec())
     xc.nLightProtonVec(id);
 
   xc.olpId(olpProcess());
 
   if ( initVerbose() ) {
     ostringstream fname_strm;
     // only allow alphanumeric, / and _ in filename
     for (const char c : name()) {
         switch (c) {
           case '+' : fname_strm << "+"; break;
           case '-' : fname_strm << "-"; break;
           case '~' : fname_strm << "_tilde"; break;
           case ']' : break;
           case ',' : fname_strm << "__"; break;
           default  : fname_strm << (isalnum(c) ? c : '_'); break;
         }
     }
     fname_strm << ".diagrams";
     const string fname = fname_strm.str();
     ifstream test(fname.c_str());
     if ( !test ) {
       test.close();
       ofstream out(fname.c_str());
       for ( vector<Ptr<DiagramBase>::ptr>::const_iterator d = diagrams().begin();
 	    d != diagrams().end(); ++d ) {
 	DiagramDrawer::drawDiag(out,dynamic_cast<const Tree2toNDiagram&>(**d));
 	out << "\n";
       }
     }
   }
 
 }
 
 StdXCombPtr MatchboxMEBase::makeXComb(Energy newMaxEnergy, const cPDPair & inc,
 				      tEHPtr newEventHandler,tSubHdlPtr newSubProcessHandler,
 				      tPExtrPtr newExtractor,	tCascHdlPtr newCKKW,
 				      const PBPair & newPartonBins, tCutsPtr newCuts,
 				      const DiagramVector & newDiagrams, bool mir,
 				      const PartonPairVec&,
 				      tStdXCombPtr newHead,
 				      tMEPtr newME) {
 
   if ( !newME )
     newME = this;
 
   Ptr<MatchboxXComb>::ptr xc =
     new_ptr(MatchboxXComb(newMaxEnergy, inc,
 			  newEventHandler, newSubProcessHandler,
 			  newExtractor, newCKKW,
 			  newPartonBins, newCuts, newME,
 			  newDiagrams, mir,
 			  newHead));
 
   prepareXComb(*xc);
 
   return xc;
 
 }
 
 StdXCombPtr MatchboxMEBase::makeXComb(tStdXCombPtr newHead,
 				      const PBPair & newPartonBins,
 				      const DiagramVector & newDiagrams,
 				      tMEPtr newME) {
   if ( !newME )
     newME = this;
 
   Ptr<MatchboxXComb>::ptr xc = 
     new_ptr(MatchboxXComb(newHead, newPartonBins, newME, newDiagrams));
 
   prepareXComb(*xc);
 
   return xc;
 }
 
 void MatchboxMEBase::persistentOutput(PersistentOStream & os) const {
   os << theLastXComb << thePhasespace 
      << theAmplitude << theScaleChoice << theVirtuals 
      << theReweights << theSubprocess << theOneLoop 
      << theOneLoopNoBorn << theOneLoopNoLoops
      << epsilonSquarePoleHistograms << epsilonPoleHistograms
      << theMerger
      << theOLPProcess << theNoCorrelations
      << theHavePDFs << checkedPDFs;
 }
 
 void MatchboxMEBase::persistentInput(PersistentIStream & is, int) {
   is >> theLastXComb >> thePhasespace 
      >> theAmplitude >> theScaleChoice >> theVirtuals 
      >> theReweights >> theSubprocess >> theOneLoop 
      >> theOneLoopNoBorn >> theOneLoopNoLoops
      >> epsilonSquarePoleHistograms >> epsilonPoleHistograms
      >> theMerger
      >> theOLPProcess >> theNoCorrelations
      >> theHavePDFs >> checkedPDFs;
   lastMatchboxXComb(theLastXComb);
 }
 
 void MatchboxMEBase::Init() {
 
   static ClassDocumentation<MatchboxMEBase> documentation
     ("MatchboxMEBase is the base class for matrix elements "
      "in the context of the matchbox NLO interface.");
 
 }
 
 IBPtr MatchboxMEBase::clone() const {
   return new_ptr(*this);
 }
 
 IBPtr MatchboxMEBase::fullclone() const {
   return new_ptr(*this);
 }
 
 void MatchboxMEBase::doinit() {
   MEBase::doinit();
   if ( !theAmplitude )
     theAmplitude = dynamic_ptr_cast<Ptr<MatchboxAmplitude>::ptr>(amplitude());
   if ( matchboxAmplitude() )
     matchboxAmplitude()->init();
   if ( phasespace() ) {
     phasespace()->init();
     matchboxAmplitude()->checkReshuffling(phasespace());
   }
   if ( scaleChoice() ) {
     scaleChoice()->init();
   }
   for (auto const & rw : theReweights)
     rw->init();
   for (auto const & v :  virtuals() )
     v->init();
 }
 
 
 void MatchboxMEBase::doinitrun() {
   MEBase::doinitrun();
   if ( matchboxAmplitude() )
     matchboxAmplitude()->initrun();
   
   if ( phasespace() )
     phasespace()->initrun();
   
   if ( scaleChoice() )
     scaleChoice()->initrun();
   
   for (auto const & rw : theReweights)
     rw->initrun();
   for (auto const & v :  virtuals() )
     v->initrun();
 }
   
 void MatchboxMEBase::dofinish() {
   MEBase::dofinish();
   for (auto const & b : epsilonSquarePoleHistograms ) {
     b.second.dump(factory()->poleData(),"epsilonSquarePoles-",b.first);
   }
   for (auto const & b :  epsilonPoleHistograms ) {
     b.second.dump(factory()->poleData(),"epsilonPoles-",b.first);
   }
 }
 
 // *** Attention *** The following static variable is needed for the type
 // description system in ThePEG. Please check that the template arguments
 // are correct (the class and its base class), and that the constructor
 // arguments are correct (the class name and the name of the dynamically
 // loadable library where the class implementation can be found).
 DescribeClass<MatchboxMEBase,MEBase>
 describeHerwigMatchboxMEBase("Herwig::MatchboxMEBase", "Herwig.so");
 
diff --git a/MatrixElement/Matchbox/Matching/QTildeMatching.cc b/MatrixElement/Matchbox/Matching/QTildeMatching.cc
--- a/MatrixElement/Matchbox/Matching/QTildeMatching.cc
+++ b/MatrixElement/Matchbox/Matching/QTildeMatching.cc
@@ -1,538 +1,538 @@
 // -*- C++ -*-
 //
 // QTildeMatching.cc is a part of Herwig - A multi-purpose Monte Carlo event generator
 // Copyright (C) 2002-2017 The Herwig Collaboration
 //
 // Herwig is licenced under version 3 of the GPL, see COPYING for details.
 // Please respect the MCnet academic guidelines, see GUIDELINES for details.
 //
 //
 // This is the implementation of the non-inlined, non-templated member
 // functions of the QTildeMatching class.
 //
 
 #include "QTildeMatching.h"
 #include "ThePEG/Interface/ClassDocumentation.h"
 #include "ThePEG/Interface/Switch.h"
 #include "ThePEG/Interface/Reference.h"
 #include "ThePEG/EventRecord/Particle.h"
 #include "ThePEG/Repository/UseRandom.h"
 #include "ThePEG/Repository/EventGenerator.h"
 #include "ThePEG/Utilities/DescribeClass.h"
 
 
 #include "ThePEG/Persistency/PersistentOStream.h"
 #include "ThePEG/Persistency/PersistentIStream.h"
 
 #include "Herwig/MatrixElement/Matchbox/Dipoles/SubtractionDipole.h"
 #include "Herwig/MatrixElement/Matchbox/Phasespace/TildeKinematics.h"
 #include "Herwig/Shower/QTilde/Kinematics/KinematicHelpers.h"
 
 using namespace Herwig;
 
 QTildeMatching::QTildeMatching() 
   : theCorrectForXZMismatch(true) {}
 
 QTildeMatching::~QTildeMatching() {}
 
 IBPtr QTildeMatching::clone() const {
   return new_ptr(*this);
 }
 
 IBPtr QTildeMatching::fullclone() const {
   return new_ptr(*this);
 }
 
 void QTildeMatching::checkCutoff() {
   if ( showerTildeKinematics() ) {
     showerTildeKinematics()->
       prepare(realCXComb(),bornCXComb());
     showerTildeKinematics()->dipole(dipole());
     showerTildeKinematics()->getShowerVariables();
   }
 }
 
 void QTildeMatching::getShowerVariables() {
 
   // already filled from checkCutoff in this case
   if ( showerTildeKinematics() )
     return;
 
   // get the shower variables
   calculateShowerVariables();
 
   // check for the cutoff
   dipole()->isAboveCutoff(isAboveCutoff());
 
   // get the hard scale
   dipole()->showerHardScale(hardScale());
 
   // check for phase space
   dipole()->isInShowerPhasespace(isInShowerPhasespace());
 
 }
 
 bool QTildeMatching::isInShowerPhasespace() const {
 
   Energy qtildeHard = ZERO;
 
   Energy qtilde = dipole()->showerScale();
   assert(!dipole()->showerParameters().empty());
   double z = dipole()->showerParameters()[0];
 
   // FF
   if ( dipole()->bornEmitter() > 1 && dipole()->bornSpectator() > 1 ) {
     qtildeHard = 
       theQTildeFinder->
       calculateFinalFinalScales(bornCXComb()->meMomenta()[dipole()->bornEmitter()],
 				bornCXComb()->meMomenta()[dipole()->bornSpectator()]).first;
   }
 
   // FI
   if ( dipole()->bornEmitter() > 1 && dipole()->bornSpectator() < 2 ) {
     qtildeHard = 
       theQTildeFinder->
       calculateInitialFinalScales(bornCXComb()->meMomenta()[dipole()->bornSpectator()],
 				  bornCXComb()->meMomenta()[dipole()->bornEmitter()],false).second;
   }
 
   // IF
   if ( dipole()->bornEmitter() < 2 && dipole()->bornSpectator() > 1 ) {
     qtildeHard = 
       theQTildeFinder->
       calculateInitialFinalScales(bornCXComb()->meMomenta()[dipole()->bornEmitter()],
 				  bornCXComb()->meMomenta()[dipole()->bornSpectator()],false).first;
     if ( z < (dipole()->bornEmitter() == 0 ? bornCXComb()->lastX1() : bornCXComb()->lastX2()) )
       return false;
   }
 
   // II
   if ( dipole()->bornEmitter() < 2 && dipole()->bornSpectator() < 2 ) {
     qtildeHard = 
       theQTildeFinder->
       calculateInitialInitialScales(bornCXComb()->meMomenta()[dipole()->bornEmitter()],
 				    bornCXComb()->meMomenta()[dipole()->bornSpectator()]).first;
     if ( z < (dipole()->bornEmitter() == 0 ? bornCXComb()->lastX1() : bornCXComb()->lastX2()) )
       return false;
   }
 
 
   Energy2 pt2 = ZERO;
 
   const vector<Energy> & masses = theQTildeSudakov->virtualMasses({{
     bornCXComb()->mePartonData()[dipole()->bornEmitter() ],
     realCXComb()->mePartonData()[dipole()->realEmitter() ],
     realCXComb()->mePartonData()[dipole()->realEmission()]
   }});
 
   const Energy2 m22 = sqr(masses[2]);
 
   if ( dipole()->bornEmitter() > 1 ) {
     const Energy2 m02 = sqr(masses[0]);
     const Energy2 m12 = sqr(masses[1]);
 
-    pt2 = QTildeKinematics::pT2_FSR(sqr(qtilde),z,m02,m12,m22);
+    pt2 = QTildeKinematics::pT2_FSR(sqr(qtilde),z,m02,m12,m22,m12,m22);
   }
   else {
     pt2 = QTildeKinematics::pT2_ISR(sqr(qtilde),z,m22);
   }
 
   if ( pt2 < max(theQTildeSudakov->pT2min(),sqr(safeCut()) ))
     return false;
 
   bool hardVeto = restrictPhasespace() && sqrt(pt2) >= dipole()->showerHardScale();
   return qtilde <= qtildeHard && !hardVeto;
 
 }
 
 bool QTildeMatching::isAboveCutoff() const {
   Energy qtilde = dipole()->showerScale();
   assert(!dipole()->showerParameters().empty());
   double z = dipole()->showerParameters()[0];
 
 
   const vector<Energy> & masses = theQTildeSudakov->virtualMasses({{
     bornCXComb()->mePartonData()[dipole()->bornEmitter() ],
     realCXComb()->mePartonData()[dipole()->realEmitter() ],
     realCXComb()->mePartonData()[dipole()->realEmission()]
   }});
 
   const Energy2 m22 = sqr(masses[2]);
 
   if ( dipole()->bornEmitter() > 1 ) {
     const Energy2 m02 = sqr(masses[0]);
     const Energy2 m12 = sqr(masses[1]);
 
-    const Energy2 pt2 = QTildeKinematics::pT2_FSR(sqr(qtilde),z,m02,m12,m22);
+    const Energy2 pt2 = QTildeKinematics::pT2_FSR(sqr(qtilde),z,m02,m12,m22,m12,m22);
 
     return pt2 >= max(theQTildeSudakov->pT2min(),sqr(safeCut()));
   }
   else {
     const Energy2 pt2 = QTildeKinematics::pT2_ISR(sqr(qtilde),z,m22);
     return pt2 >= max(theQTildeSudakov->pT2min(),sqr(safeCut()));
   }
   return false;
 }
 
 CrossSection QTildeMatching::dSigHatDR() const {
 
   assert(!dipole()->showerParameters().empty());
   pair<Energy2,double> vars = 
     make_pair(sqr(dipole()->showerScale()),
 	      dipole()->showerParameters()[0]);
 
   pair<int,int> ij(dipole()->bornEmitter(),
 		   dipole()->bornSpectator());
   double ccme2 =
      dipole()->underlyingBornME()->largeNColourCorrelatedME2(ij,theLargeNBasis);
    
    if(ccme2==0.)return 0.*nanobarn;
       
    double lnme2=dipole()->underlyingBornME()->largeNME2(theLargeNBasis);
    if(lnme2==0){
      generator()->log() <<"\nQTildeMatching: ";
      generator()->log() <<"\n  largeNME2 is ZERO, while largeNColourCorrelatedME2 is not ZERO." ;
      generator()->log() <<"\n  This is too seriuos.\n" ;
      generator()->log() << Exception::runerror;
    }
   
    ccme2 *=
      dipole()->underlyingBornME()->me2() /lnme2;
      
 
   Energy2 prop = ZERO;
   if ( dipole()->bornEmitter() > 1 ) {
     prop =
       (realCXComb()->meMomenta()[dipole()->realEmitter()] +
        realCXComb()->meMomenta()[dipole()->realEmission()]).m2()
       - bornCXComb()->meMomenta()[dipole()->bornEmitter()].m2();
   } else {
     prop = 
       2.*vars.second*(realCXComb()->meMomenta()[dipole()->realEmitter()]*
 		      realCXComb()->meMomenta()[dipole()->realEmission()]);
   }
 
   // note alphas included downstream from subtractionScaleWeight()
   double xme2 = -8.*Constants::pi*ccme2*splitFn(vars)*realXComb()->lastSHat()/prop;
   xme2 *= 
     pow(realCXComb()->lastSHat() / bornCXComb()->lastSHat(),
 	bornCXComb()->mePartonData().size()-4.);
 
   double bornPDF = bornPDFWeight(dipole()->underlyingBornME()->lastScale());
   if ( bornPDF == 0.0 )
     return ZERO;
 
   xme2 *= bornPDF;
   
   xme2 *= dipole()->realEmissionME()->finalStateSymmetry() /
     dipole()->underlyingBornME()->finalStateSymmetry(); 
 
   // take care of mismatch between z and x as we are approaching the
   // hard phase space boundary
   // TODO get rid of this useless scale option business and simplify PDF handling in here
   if ( dipole()->bornEmitter() < 2 && theCorrectForXZMismatch ) {
     Energy2 emissionScale = ZERO;
     if ( emissionScaleInSubtraction() == showerScale ) {
       emissionScale = showerFactorizationScale();
     } else if ( emissionScaleInSubtraction() == realScale ) {
       emissionScale = dipole()->realEmissionME()->lastScale();
     } else if ( emissionScaleInSubtraction() == bornScale ) {
       emissionScale = dipole()->underlyingBornME()->lastScale();
     }
     double xzMismatch = 
       dipole()->subtractionParameters()[0] / dipole()->showerParameters()[0];
     double realCorrectedPDF = 
       dipole()->bornEmitter() == 0 ?
       dipole()->realEmissionME()->pdf1(emissionScale,theExtrapolationX,
 				       xzMismatch) :
       dipole()->realEmissionME()->pdf2(emissionScale,theExtrapolationX,
 				       xzMismatch);
     double realPDF = 
       dipole()->bornEmitter() == 0 ?
       dipole()->realEmissionME()->pdf1(emissionScale,theExtrapolationX,1.0) :
       dipole()->realEmissionME()->pdf2(emissionScale,theExtrapolationX,1.0);
     if ( realPDF == 0.0 || realCorrectedPDF == 0.0 )
       return ZERO;
     xme2 *= realCorrectedPDF / realPDF;
   }
 
   Energy qtilde = sqrt(vars.first);
   double z = vars.second;
   Energy2 pt2 = ZERO;
 
   const vector<Energy> & masses = theQTildeSudakov->virtualMasses({{
     bornCXComb()->mePartonData()[dipole()->bornEmitter() ],
     realCXComb()->mePartonData()[dipole()->realEmitter() ],
     realCXComb()->mePartonData()[dipole()->realEmission()]
   }});
 
   const Energy2 m22 = sqr(masses[2]);
   if ( dipole()->bornEmitter() > 1 ) {
     const Energy2 m02 = sqr(masses[0]);
     const Energy2 m12 = sqr(masses[1]);
 
-    pt2 = QTildeKinematics::pT2_FSR(sqr(qtilde),z,m02,m12,m22);
+    pt2 = QTildeKinematics::pT2_FSR(sqr(qtilde),z,m02,m12,m22,m12,m22);
   }
   else {
     pt2 = QTildeKinematics::pT2_ISR(sqr(qtilde),z,m22);
   }
   assert(pt2 >= ZERO);
 
   if ( profileScales() )
     xme2 *= profileScales()->hardScaleProfile(dipole()->showerHardScale(),sqrt(pt2));
 
   CrossSection res = 
     sqr(hbarc) * 
     realXComb()->jacobian() * 
     subtractionScaleWeight() *
     xme2 /
     (2. * realXComb()->lastSHat());
 
   return res;
 
 }
 
 double QTildeMatching::me2() const {
   throw Exception() << "QTildeMatching::me2(): Not intented to use. Disable the ShowerApproximationGenerator."
 		    << Exception::runerror;
   return 0.;
 }
 
 void QTildeMatching::calculateShowerVariables() const {
 
   Lorentz5Momentum n;
   Energy2 Q2 = ZERO;
 
   const Lorentz5Momentum& pb = bornCXComb()->meMomenta()[dipole()->bornEmitter()];
   const Lorentz5Momentum& pc = bornCXComb()->meMomenta()[dipole()->bornSpectator()];
 
   if ( dipole()->bornEmitter() > 1 ) {
     Q2 = (pb+pc).m2();
   } else {
     Q2 = -(pb-pc).m2();
   }
 
   if ( dipole()->bornEmitter() > 1 && dipole()->bornSpectator() > 1 ) {
     double b = sqr(bornCXComb()->meMomenta()[dipole()->bornEmitter()].m())/Q2;
     double c = sqr(bornCXComb()->meMomenta()[dipole()->bornSpectator()].m())/Q2;
     double lambda = sqrt(1.+sqr(b)+sqr(c)-2.*b-2.*c-2.*b*c);
     n = (1.-0.5*(1.-b+c-lambda))*pc - 0.5*(1.-b+c-lambda)*pb;
   }
 
   if ( dipole()->bornEmitter() > 1 && dipole()->bornSpectator() < 2 ) {
     n = bornCXComb()->meMomenta()[dipole()->bornSpectator()];
   }
 
   if ( dipole()->bornEmitter() < 2 && dipole()->bornSpectator() > 1 ) {
     double c = sqr(bornCXComb()->meMomenta()[dipole()->bornSpectator()].m())/Q2;
     n = (1.+c)*pc - c*pb;
   }
 
   if ( dipole()->bornEmitter() < 2 && dipole()->bornSpectator() < 2 ) {
     n = bornCXComb()->meMomenta()[dipole()->bornSpectator()];
   }
 
   // the light-cone condition is numerically not very stable, so we
   // explicitly push it on the light-cone here
   n.setMass(ZERO);
   n.rescaleEnergy();
 
   double z = 0.0;
 
   if ( dipole()->bornEmitter() > 1 ) {
     z = 1. - 
     (n*realCXComb()->meMomenta()[dipole()->realEmission()])/
     (n*bornCXComb()->meMomenta()[dipole()->bornEmitter()]);
   } else {
     z = 1. - 
     (n*realCXComb()->meMomenta()[dipole()->realEmission()])/
     (n*realCXComb()->meMomenta()[dipole()->realEmitter()]);
   }
   // allow small violations (numerical inaccuracies)
   if ( z <= 0 && z >= -1e-6 ) {
     z = std::numeric_limits<double>::epsilon();
   } else if ( z >= 1 && z <= 1+1e-6 ) {
     z = 1-std::numeric_limits<double>::epsilon();
   }
 
   Energy2 qtilde2 = ZERO;
   Energy2 q2 = ZERO;
 
   if ( dipole()->bornEmitter() > 1 ) {
     q2 = 
       (realCXComb()->meMomenta()[dipole()->realEmitter()] + realCXComb()->meMomenta()[dipole()->realEmission()]).m2();
     qtilde2 = (q2 - bornCXComb()->meMomenta()[dipole()->bornEmitter()].m2())/(z*(1.-z));
   } else {
     q2 = 
       -(realCXComb()->meMomenta()[dipole()->realEmitter()] - realCXComb()->meMomenta()[dipole()->realEmission()]).m2();
     qtilde2 = (q2 + bornCXComb()->meMomenta()[dipole()->bornEmitter()].m2())/(1.-z);
   }
   if ( qtilde2 < ZERO ) {
     qtilde2 = ZERO;
   }
 
   assert(qtilde2 >= ZERO && z > 0.0 && z < 1.0);
 
   dipole()->showerScale(sqrt(qtilde2));
   dipole()->showerParameters().resize(1);
   dipole()->showerParameters()[0] = z;
 
 }
 
 double QTildeMatching::splitFn(const pair<Energy2,double>& vars) const {
   const Energy2& qtilde2 = vars.first;
   const double z = vars.second;
   double Nc = SM().Nc();
 
   // final state branching
   if ( dipole()->bornEmitter() > 1 ) {
     // final state quark quark branching
     if ( abs(bornCXComb()->mePartonData()[dipole()->bornEmitter()]->id()) < 7 ) {
       Energy m = bornCXComb()->mePartonData()[dipole()->bornEmitter()]->hardProcessMass();
       return
 	((sqr(Nc)-1.)/(2.*Nc))*(1+sqr(z)-2.*sqr(m)/(z*qtilde2))/(1.-z);
     }
     // final state gluon branching
     if ( bornCXComb()->mePartonData()[dipole()->bornEmitter()]->id() == ParticleID::g ) {
       if ( realCXComb()->mePartonData()[dipole()->realEmission()]->id() == ParticleID::g ) {
 	// ATTENTION the factor 2 here is intentional as it cancels to the 1/2
 	// stemming from the large-N colour correlator
 	return 2.*Nc*(z/(1.-z)+(1.-z)/z+z*(1.-z));
       }
       if ( abs(realCXComb()->mePartonData()[dipole()->realEmission()]->id()) < 7 ) {
 	Energy m = realCXComb()->mePartonData()[dipole()->realEmission()]->hardProcessMass();
 	return (1./2.)*(1.-2.*z*(1.-z)+2.*sqr(m)/(z*(1.-z)*qtilde2));
       }
     }
     // final state squark branching
     if ((abs(bornCXComb()->mePartonData()[dipole()->bornEmitter()]->id()) > 1000000 && 
 	 abs(bornCXComb()->mePartonData()[dipole()->bornEmitter()]->id()) < 1000007) ||
 	(abs(bornCXComb()->mePartonData()[dipole()->bornEmitter()]->id()) > 2000000 && 
 	 abs(bornCXComb()->mePartonData()[dipole()->bornEmitter()]->id()) < 2000007)){
       Energy m = bornCXComb()->mePartonData()[dipole()->bornEmitter()]->hardProcessMass();
       return ((sqr(Nc)-1.)/Nc)*(z-sqr(m)/(z*qtilde2))/(1.-z);
     }
     // final state gluino branching
     if (bornCXComb()->mePartonData()[dipole()->bornEmitter()]->id() == 1000021){
       Energy m = bornCXComb()->mePartonData()[dipole()->bornEmitter()]->hardProcessMass();
       return Nc*(1.+sqr(z)-2.*sqr(m)/(z*qtilde2))/(1.-z);
     }
   }
 
   // initial state branching
   if ( dipole()->bornEmitter() < 2 ) {
     // g/g
     if ( realCXComb()->mePartonData()[dipole()->realEmitter()]->id() == ParticleID::g &&
 	 realCXComb()->mePartonData()[dipole()->realEmission()]->id() == ParticleID::g ) {
       // see above for factor of 2
       return 2.*Nc*(z/(1.-z)+(1.-z)/z+z*(1.-z));
     }
     // q/q
     if ( abs(realCXComb()->mePartonData()[dipole()->realEmitter()]->id()) < 7 &&
 	 realCXComb()->mePartonData()[dipole()->realEmission()]->id() == ParticleID::g ) {
       return
 	((sqr(Nc)-1.)/(2.*Nc))*(1+sqr(z))/(1.-z);
     }
     // g/q
     if ( realCXComb()->mePartonData()[dipole()->realEmitter()]->id() == ParticleID::g &&
 	 abs(realCXComb()->mePartonData()[dipole()->realEmission()]->id()) < 7 ) {
       return (1./2.)*(1.-2.*z*(1.-z));
     }
     // q/g
     if ( abs(realCXComb()->mePartonData()[dipole()->realEmitter()]->id()) < 7 &&
 	 abs(realCXComb()->mePartonData()[dipole()->realEmission()]->id()) < 7 ) {
       return
 	((sqr(Nc)-1.)/(2.*Nc))*(1+sqr(1.-z))/z;
     }
   }
 
   return 0.0;
 
 }
 
 // If needed, insert default implementations of virtual function defined
 // in the InterfacedBase class here (using ThePEG-interfaced-impl in Emacs).
 
 void QTildeMatching::doinit() {
   assert(theShowerHandler && theQTildeFinder && theQTildeSudakov);
   theShowerHandler->init();
   theQTildeFinder->init();
   theQTildeSudakov->init();
   hardScaleFactor(theShowerHandler->hardScaleFactor());
   factorizationScaleFactor(theShowerHandler->factorizationScaleFactor());
   renormalizationScaleFactor(theShowerHandler->renormalizationScaleFactor());
   profileScales(theShowerHandler->profileScales());
   restrictPhasespace(theShowerHandler->restrictPhasespace());
   hardScaleIsMuF(theShowerHandler->hardScaleIsMuF());
   ShowerApproximation::doinit();
 }
 
 void QTildeMatching::doinitrun() {
   assert(theShowerHandler && theQTildeFinder && theQTildeSudakov);
   theShowerHandler->initrun();
   theQTildeFinder->initrun();
   theQTildeSudakov->initrun();
   ShowerApproximation::doinitrun();
 }
 
 
 void QTildeMatching::persistentOutput(PersistentOStream & os) const {
   os << theQTildeFinder << theQTildeSudakov
      << theShowerHandler << theCorrectForXZMismatch;
 }
 
 void QTildeMatching::persistentInput(PersistentIStream & is, int) {
   is >> theQTildeFinder >> theQTildeSudakov
      >> theShowerHandler >> theCorrectForXZMismatch;
 }
 
 
 // *** Attention *** The following static variable is needed for the type
 // description system in ThePEG. Please check that the template arguments
 // are correct (the class and its base class), and that the constructor
 // arguments are correct (the class name and the name of the dynamically
 // loadable library where the class implementation can be found).
 DescribeClass<QTildeMatching,Herwig::ShowerApproximation>
   describeHerwigQTildeMatching("Herwig::QTildeMatching", "HwShower.so HwQTildeMatching.so");
 
 void QTildeMatching::Init() {
 
   static ClassDocumentation<QTildeMatching> documentation
     ("QTildeMatching implements NLO matching with the default shower.");
 
   static Reference<QTildeMatching,PartnerFinder> interfaceQTildeFinder
     ("QTildeFinder",
      "Set the partner finder to calculate hard scales.",
      &QTildeMatching::theQTildeFinder, false, false, true, false, false);
   interfaceQTildeFinder.rank(-1);
 
   static Reference<QTildeMatching,SudakovFormFactor> interfaceQTildeSudakov
     ("QTildeSudakov",
      "Set the partner finder to calculate hard scales.",
      &QTildeMatching::theQTildeSudakov, false, false, true, false, false);
   interfaceQTildeSudakov.rank(-1);
 
   static Reference<QTildeMatching,ShowerHandler> interfaceShowerHandler
     ("ShowerHandler",
      "The QTilde shower handler to use.",
      &QTildeMatching::theShowerHandler, false, false, true, true, false);
   interfaceShowerHandler.rank(-1);
 
   static Switch<QTildeMatching,bool> interfaceCorrectForXZMismatch
     ("CorrectForXZMismatch",
      "Correct for x/z mismatch near hard phase space boundary.",
      &QTildeMatching::theCorrectForXZMismatch, true, false, false);
   static SwitchOption interfaceCorrectForXZMismatchYes
     (interfaceCorrectForXZMismatch,
      "Yes",
      "Include the correction factor.",
      true);
   static SwitchOption interfaceCorrectForXZMismatchNo
     (interfaceCorrectForXZMismatch,
      "No",
      "Do not include the correction factor.",
      false);
   interfaceCorrectForXZMismatch.rank(-1);
 
 }
 
diff --git a/Models/Feynrules/python/ufo2peg/converter.py b/Models/Feynrules/python/ufo2peg/converter.py
--- a/Models/Feynrules/python/ufo2peg/converter.py
+++ b/Models/Feynrules/python/ufo2peg/converter.py
@@ -1,189 +1,193 @@
 """
 AST visitor class to convert Python expressions into C++ as used by ThePEG
 """
 import ast
 
 convertHerwig=False
 
 def py2cpp(expr,con=False):
     """Convert expr to C++ form. Wraps the converter class."""
     global convertHerwig
     convertHerwig=con
     result = PyToCpp().parse(expr)
     return result
 
 
 class PyToCppException(Exception):
     """Base class for all PyToCpp exceptions."""
 
 
 class PyToCpp(ast.NodeVisitor):
     """Convert Python math expressions into C++.
 
     Returns a tuple (expr,syms):
     expr -- C++-compatible expression
     syms -- set of all free variables
 
     Usage:
     >>> expr = '3+2**a*b'
     >>> PyToCpp().parse(expr)
     ('(3.0+(pow(2.0,a)*b))', set(['a', 'b']))
 
     Note: 
     The converter is currently not generic, it relies on the
     conventions of Feynrules' UFO format on the one hand and ThePEG's
     C++ types on the other.
     """
 
     def parse(self,expression):
         """Convert expression to C++ format."""
         self.result = []
         self.symbols = set()
         expression=expression.replace("abs(","cmath.abs(")
         tree = ast.parse(expression)
         #print ast.dump(tree)
         return self.visit(tree)
 
     ##################################
 
     def visit_Module(self,node):
         self.generic_visit(node)
         return ''.join(self.result), self.symbols
 
     def generic_visit(self,node):
         typename = type(node).__name__
         harmless = ['Module','Expr']
         if typename not in harmless:
             raise PyToCppException('Missing implementation for %s' % typename)
         super(PyToCpp,self).generic_visit(node)
 
     def visit_UnaryOp(self,node):
         self.result.append('(')
         self.visit(node.op)
         self.visit(node.operand)
         self.result.append(')')
 
     def visit_BinOp(self,node):
         if type(node.op) == type(ast.Pow()):
             return self.pow_node(node)
     
         self.result.append('(')
         self.visit(node.left)
         self.visit(node.op)
         self.visit(node.right)
         self.result.append(')')
 
     def pow_node(self,node):
         if is_square(node):
             self.result.append('sqr(')
             self.visit(node.left)
             self.result.append(')')
         else:
             self.result.append('pow(')
             self.visit(node.left)
             self.result.append(',')
             self.visit(node.right)
             self.result.append(')')
 
     def visit_Call(self,node):
         if is_ii(node): 
             self.result.append('ii')
         else:
             self.visit(node.func)
             self.result.append('(')
             for a in node.args:
                 self.visit(a)
                 self.result.append(',')
             if self.result[-1] == ',':
                 del self.result[-1]
             self.result.append(')')
         
     def visit_Attribute(self,node):
         if node.value.id != 'cmath':
             err = "Don't know how to convert %s module." % node.value.id
             raise PyToCppException(err)
         self.result.append(node.attr)
 
     def visit_Num(self,node):
         # some zeros are encoded as 0j
         if node.n == 0: text = '0.0'
         elif (node.n==complex("1j") ) :
             text = "ii"
         elif (node.n==complex("-1j") ) :
             text = "-ii"
         elif (node.n==complex("2j") ) :
             text = "2.*ii"
         else:
             text = str(float(node.n))
         self.result.append(text)
 
     def visit_Name(self,node):
         text = str(node.id)
         if text == 'complex': 
             text = 'Complex'
         elif text == 'complexconjugate': 
             text = 'conj'
         elif text == 'im':
             text = 'imag'
         elif text == 're':
             text = 'real'
+        elif text == 'max':
+            text = 'max'
+        elif text == 'min':
+            text = 'min'
         elif convertHerwig :
             if text == 'I' :
                 text = "ii"
             elif ( text.find("UnitRemoval")==0) :
                 text = "%s::%s" % (text[:11],text[11:])
             elif(text[0]=="P" or text[0]=="E" or text[0] == "V") :
                 if text[-1] in ["x","y","z","t"] :
                     text = "%s.%s()" % (text[0:-1],text[-1])
             elif(text[0]=="R") :
                 text = "%s.%s()" % (text[:-3],text[-3:])
             elif(text[0]=="s") :
                 text = "%s.%s()" % (text[:-2],text[-2:])
         elif text not in []:
             self.symbols.add(text)
         self.result.append(text)
 
     def visit_Mult(self,node):
         self.result.append('*')
 
     def visit_Add(self,node):
         self.result.append('+')
 
     def visit_Sub(self,node):
         self.result.append('-')
 
     def visit_USub(self,node):
         self.result.append('-')
 
     def visit_UAdd(self,node):
         self.result.append('+')
 
     def visit_Div(self,node):
         self.result.append('/')
 
     def visit_Pow(self,node):
         err = "Shold never get here. BinaryOp catches Pow calls."
         raise PyToCppException(err)
 
 ### Helpers
 
 def is_square(node):
     """Check if a Pow object is just a square."""
     try:
         return node.right.n == 2.0
     except:
         return False
 
 def is_ii(node):
     """Check if a Call object is just the imaginary unit."""
     try:
         return ( node.func.id == 'complex' 
                  and node.args[0].n == 0
                  and node.args[1].n == 1 )
     except:
         return False
 
 
 if __name__ == "__main__":
     import doctest
     doctest.testmod()
diff --git a/Shower/QTilde/Kinematics/Decay_QTildeShowerKinematics1to2.cc b/Shower/QTilde/Kinematics/Decay_QTildeShowerKinematics1to2.cc
--- a/Shower/QTilde/Kinematics/Decay_QTildeShowerKinematics1to2.cc
+++ b/Shower/QTilde/Kinematics/Decay_QTildeShowerKinematics1to2.cc
@@ -1,114 +1,115 @@
 // -*- C++ -*-
 //
 // Decay_QTildeShowerKinematics1to2.cc is a part of Herwig - A multi-purpose Monte Carlo event generator
 // Copyright (C) 2002-2017 The Herwig Collaboration
 //
 // Herwig is licenced under version 3 of the GPL, see COPYING for details.
 // Please respect the MCnet academic guidelines, see GUIDELINES for details.
 //
 //
 // This is the implementation of the non-inlined, non-templated member
 // functions of the Decay_QTildeShowerKinematics1to2 class.
 //
 
 #include "Decay_QTildeShowerKinematics1to2.h"
 #include "ThePEG/PDT/EnumParticles.h"
 #include "Herwig/Shower/QTilde/SplittingFunctions/SplittingFunction.h"
 #include "Herwig/Shower/QTilde/Base/ShowerParticle.h"
 #include <cassert>
 #include "Herwig/Shower/ShowerHandler.h"
 #include "Herwig/Shower/QTilde/Base/ShowerVertex.h"
 
 using namespace Herwig;
 
 void Decay_QTildeShowerKinematics1to2::
 updateChildren(const tShowerParticlePtr parent, 
 	       const ShowerParticleVector & children,
 	       ShowerPartnerType partnerType) const {
   assert(children.size() == 2);
   // calculate the scales
   splittingFn()->evaluateDecayScales(partnerType,scale(),z(),parent,
 				     children[0],children[1]);
   // set the maximum virtual masses
   IdList ids(3);
   ids[0] = parent->dataPtr();
   ids[1] = children[0]->dataPtr();
   ids[2] = children[1]->dataPtr();
   const vector<Energy> & virtualMasses = SudakovFormFactor()->virtualMasses(ids);
   Energy2 q2 = sqr(virtualMasses[0])-(1.-z())*sqr(scale());
   children[0]->virtualMass(sqrt(q2));
   // determine alphas of children according to interpretation of z
   const ShowerParticle::Parameters & params = parent->showerParameters();
   ShowerParticle::Parameters & child0 = children[0]->showerParameters();
   ShowerParticle::Parameters & child1 = children[1]->showerParameters();
   child0.alpha =     z()  * params.alpha; 
   child1.alpha = (1.-z()) * params.alpha;
 
   child0.ptx =  pT() * cos(phi()) +     z()* params.ptx;
   child0.pty =  pT() * sin(phi()) +     z()* params.pty;
   child0.pt  = sqrt( sqr(child0.ptx) + sqr(child0.pty) );
 
   child1.ptx = -pT() * cos(phi()) + (1.-z()) * params.ptx;
   child1.pty = -pT() * sin(phi()) + (1.-z()) * params.pty;
   child1.pt  = sqrt( sqr(child1.ptx) + sqr(child1.pty) );
 
   // set up the colour connections
   splittingFn()->colourConnection(parent,children[0],children[1],partnerType,false);
   // make the products children of the parent
   parent->addChild(children[0]);
   parent->addChild(children[1]);
   // set the momenta of the children
   for(ShowerParticleVector::const_iterator pit=children.begin();
       pit!=children.end();++pit) {
     (**pit).showerBasis(parent->showerBasis(),true);
     (**pit).setShowerMomentum(true);
   }
 }
 
 void Decay_QTildeShowerKinematics1to2::
 reconstructParent( const tShowerParticlePtr, const ParticleVector &) const {
   throw Exception() << "Decay_QTildeShowerKinematics1to2::reconstructParent not implemented"
 		    << Exception::abortnow;
 }
 
 void Decay_QTildeShowerKinematics1to2::
 reconstructLast(const tShowerParticlePtr last, Energy mass) const {
   // set beta component and consequently all missing data from that,
   // using the nominal (i.e. PDT) mass.
   Energy theMass =ZERO;
   
   if(!(mass > ZERO) && ShowerHandler::currentHandler()->retConstituentMasses())
     theMass = last->data().constituentMass();
   else
     theMass = mass > ZERO ? mass : last->data().mass();
   last->showerParameters().beta=
     (sqr(theMass) + sqr(last->showerParameters().pt)
      - sqr( last->showerParameters().alpha )*last->showerBasis()->pVector().m2())
     / ( 2.*last->showerParameters().alpha*last->showerBasis()->p_dot_n() );
   // set that new momentum  
   last->set5Momentum( last->showerBasis()->sudakov2Momentum( last->showerParameters().alpha, 
 							     last->showerParameters().beta, 
 							     last->showerParameters().ptx,
 							     last->showerParameters().pty) );
 }
 
 void Decay_QTildeShowerKinematics1to2::updateParent(const tShowerParticlePtr parent, 
 						    const ShowerParticleVector & children,
+						    unsigned int ,
 						    ShowerPartnerType) const {
   IdList ids(3);
   ids[0] = parent->dataPtr();
   ids[1] = children[0]->dataPtr();
   ids[2] = children[1]->dataPtr();
   const vector<Energy> & virtualMasses = SudakovFormFactor()->virtualMasses(ids);
   children[0]->virtualMass(sqrt(sqr(virtualMasses[0])-(1.-z())*sqr(scale())));
   if(children[1]->children().empty()) children[1]->virtualMass(virtualMasses[2]);
   // compute the new pT of the branching
   Energy2 pt2=(1.-z())*(z()*sqr(virtualMasses[0])-sqr(children[0]->virtualMass()))
     -z()*sqr(children[1]->virtualMass());
   if(pt2>ZERO) {
     pT(sqrt(pt2));
   }
   else {
     parent->virtualMass(ZERO);
   }
 }
diff --git a/Shower/QTilde/Kinematics/Decay_QTildeShowerKinematics1to2.h b/Shower/QTilde/Kinematics/Decay_QTildeShowerKinematics1to2.h
--- a/Shower/QTilde/Kinematics/Decay_QTildeShowerKinematics1to2.h
+++ b/Shower/QTilde/Kinematics/Decay_QTildeShowerKinematics1to2.h
@@ -1,113 +1,114 @@
 // -*- C++ -*-
 //
 // Decay_QTildeShowerKinematics1to2.h is a part of Herwig - A multi-purpose Monte Carlo event generator
 // Copyright (C) 2002-2017 The Herwig Collaboration
 //
 // Herwig is licenced under version 3 of the GPL, see COPYING for details.
 // Please respect the MCnet academic guidelines, see GUIDELINES for details.
 //
 #ifndef HERWIG_Decay_QTildeShowerKinematics1to2_H
 #define HERWIG_Decay_QTildeShowerKinematics1to2_H
 //
 // This is the declaration of the Decay_QTildeShowerKinematics1to2 class.
 //
 
 #include "Herwig/Shower/QTilde/Kinematics/ShowerKinematics.h"
 
 namespace Herwig {
 
 using namespace ThePEG;
 
 /** \ingroup Shower
  *
  *  This (concrete) class provides the specific decay shower
  *  kinematics information.
  *
  *  @see ShowerKinematics
  *  @see IS_QTildeShowerKinematics1to2
  *  @see FS_QTildeShowerKinematics1to2
  *  @see KinematicsReconstructor
  *
  */
 class Decay_QTildeShowerKinematics1to2: public ShowerKinematics {
 public:
 
   /**
    * Default constructor
    */
   Decay_QTildeShowerKinematics1to2() = default;
 
   /**
    * The constructor.
    */
   Decay_QTildeShowerKinematics1to2(Energy scale, double z, double phi, Energy pt, tSudakovPtr sud) 
     : ShowerKinematics(scale,z,phi,pt,sud) {}
   
 
 public:
 
   /**
    *  The updateChildren, updateParent and updateLast
    *  members to update the values of the \f$\alpha\f$ and 
    *  \f$p_\perp\f$ variables during the shower evolution.
    */
   //@{
 
   /**
    * Along with the showering evolution --- going forward for
    * time-like (forward) evolution, and going backward for space-like
    * (backward) evolution --- the kinematical variables of the
    * branching products are calculated and updated from the knowledge
    * of the parent kinematics.  This method is used by the
    * ForwardShowerEvolver.  
    * @param parent The branching particle
    * @param children The particles produced in the branching
    * @param partnerType The type of evolution partner
    */
   virtual void updateChildren( const tShowerParticlePtr parent, 
 			       const ShowerParticleVector & children,
 			       ShowerPartnerType partnerType) const;
 
   /**
    * Update the parent Kinematics from the knowledge of the kinematics
    * of the children. This method will be used by the 
    * KinematicsReconstructor.
    */
   virtual void reconstructParent( const tShowerParticlePtr parent, 
 				  const ParticleVector & children ) const;
 
   /**
    * Update the kinematical data of a particle when a reconstruction
    * fixpoint was found. This will highly depend on the kind of
    * kinematics chosen and will be defined in the inherited concrete
    * classes. This method will be used by the KinematicsReconstructor.
    * @param last The particle to update
    * @param mass The mass to be used, if less than zero on-shell
    */
   virtual void reconstructLast(const tShowerParticlePtr last, Energy mass=-1.*GeV) const;
 
   /**
    * Update the parent Kinematics from the knowledge of the kinematics
    * of the children. This method will be used by the KinematicsReconstructor.
    * @param parent   The parent
    * @param children The children
    * @param partnerType The type of evolution partner
    */
   virtual void updateParent(const tShowerParticlePtr parent,
 			    const ShowerParticleVector & children,
+			    unsigned int pTscheme,
 			    ShowerPartnerType partnerType) const;
 
   //@}
 
 private:
   /**
    * The assignment operator is private and must never be called.
    * In fact, it should not even be implemented.
    */
   Decay_QTildeShowerKinematics1to2 & operator=(const Decay_QTildeShowerKinematics1to2 &) = delete;
 
 };
 
 }
 
 #endif /* HERWIG_Decay_QTildeShowerKinematics1to2_H */
diff --git a/Shower/QTilde/Kinematics/FS_QTildeShowerKinematics1to2.cc b/Shower/QTilde/Kinematics/FS_QTildeShowerKinematics1to2.cc
--- a/Shower/QTilde/Kinematics/FS_QTildeShowerKinematics1to2.cc
+++ b/Shower/QTilde/Kinematics/FS_QTildeShowerKinematics1to2.cc
@@ -1,196 +1,211 @@
 // -*- C++ -*-
 //
 // FS_QTildeShowerKinematics1to2.cc is a part of Herwig - A multi-purpose Monte Carlo event generator
 // Copyright (C) 2002-2017 The Herwig Collaboration
 //
 // Herwig is licenced under version 3 of the GPL, see COPYING for details.
 // Please respect the MCnet academic guidelines, see GUIDELINES for details.
 //
 //
 // This is the implementation of the non-inlined, non-templated member
 // functions of the FS_QTildeShowerKinematics1to2 class.
 //
 
 #include "FS_QTildeShowerKinematics1to2.h"
 #include "ThePEG/PDT/EnumParticles.h"
 #include "Herwig/Shower/QTilde/SplittingFunctions/SplittingFunction.h"
 #include "Herwig/Shower/QTilde/Base/ShowerParticle.h"
 #include "ThePEG/Utilities/Debug.h"
 #include "Herwig/Shower/QTilde/QTildeShowerHandler.h"
 #include "Herwig/Shower/QTilde/Base/PartnerFinder.h"
 #include "Herwig/Shower/QTilde/Kinematics/KinematicsReconstructor.h"
 #include "Herwig/Shower/QTilde/Kinematics/KinematicHelpers.h"
 #include "Herwig/Shower/QTilde/Base/ShowerVertex.h"
 
 using namespace Herwig;
 
 void FS_QTildeShowerKinematics1to2::
 updateParameters(tShowerParticlePtr theParent,
 		 tShowerParticlePtr theChild0,
 		 tShowerParticlePtr theChild1,
 		 bool setAlpha) const {
   const ShowerParticle::Parameters & parent = theParent->showerParameters();
   ShowerParticle::Parameters & child0 = theChild0->showerParameters();
   ShowerParticle::Parameters & child1 = theChild1->showerParameters();
   // determine alphas of children according to interpretation of z
   if ( setAlpha ) {
     child0.alpha =      z() * parent.alpha;
     child1.alpha = (1.-z()) * parent.alpha;
   }
   // set the values
   double cphi = cos(phi());
   double sphi = sin(phi());
 
   child0.ptx =  pT() * cphi +     z() * parent.ptx;
   child0.pty =  pT() * sphi +     z() * parent.pty;
   child0.pt  = sqrt( sqr(child0.ptx) + sqr(child0.pty) );
 
   child1.ptx = -pT() * cphi + (1.-z())* parent.ptx;
   child1.pty = -pT() * sphi + (1.-z())* parent.pty;
   child1.pt  = sqrt( sqr(child1.ptx) + sqr(child1.pty) );
   
 }
 
 void FS_QTildeShowerKinematics1to2::
 updateChildren(const tShowerParticlePtr parent, 
 	       const ShowerParticleVector & children,
 	       ShowerPartnerType partnerType) const {
   assert(children.size()==2);
   // calculate the scales
   splittingFn()->evaluateFinalStateScales(partnerType,scale(),z(),parent,
 					  children[0],children[1]);
 
   // update the parameters
   updateParameters(parent, children[0], children[1], true);
   // set up the colour connections
   splittingFn()->colourConnection(parent,children[0],children[1],partnerType,false);
   // make the products children of the parent
   parent->addChild(children[0]);
   parent->addChild(children[1]);
   // set the momenta of the children
   for(ShowerParticleVector::const_iterator pit=children.begin();
       pit!=children.end();++pit) {
     (**pit).showerBasis(parent->showerBasis(),true);
     (**pit).setShowerMomentum(true);
   }
   // sort out the helicity stuff 
   if(! dynamic_ptr_cast<tcQTildeShowerHandlerPtr>(ShowerHandler::currentHandler())->correlations()) return;
   SpinPtr pspin(parent->spinInfo());
   if(!pspin ||  !dynamic_ptr_cast<tcQTildeShowerHandlerPtr>(ShowerHandler::currentHandler())->spinCorrelations() ) return;
   Energy2 t = sqr(scale())*z()*(1.-z());
   IdList ids;
   ids.push_back(parent->dataPtr());
   ids.push_back(children[0]->dataPtr());
   ids.push_back(children[1]->dataPtr());
   // create the vertex
   SVertexPtr vertex(new_ptr(ShowerVertex()));
   // set the matrix element
   vertex->ME(splittingFn()->matrixElement(z(),t,ids,phi(),true));
   RhoDMatrix mapping;
   SpinPtr inspin;
   bool needMapping = parent->getMapping(inspin,mapping);
   if(needMapping) vertex->incomingBasisTransform(mapping);
   // set the incoming particle for the vertex
   parent->spinInfo()->decayVertex(vertex);
   for(ShowerParticleVector::const_iterator pit=children.begin();
       pit!=children.end();++pit) {
     // construct the spin info for the children
     (**pit).constructSpinInfo(true);
     // connect the spinInfo object to the vertex
     (*pit)->spinInfo()->productionVertex(vertex);
   }
 }
 
 void FS_QTildeShowerKinematics1to2::
 reconstructParent(const tShowerParticlePtr parent, 
 		  const ParticleVector & children ) const {
   assert(children.size() == 2);
   ShowerParticlePtr c1 = dynamic_ptr_cast<ShowerParticlePtr>(children[0]);
   ShowerParticlePtr c2 = dynamic_ptr_cast<ShowerParticlePtr>(children[1]);
   parent->showerParameters().beta= 
     c1->showerParameters().beta + c2->showerParameters().beta; 
   Lorentz5Momentum pnew = c1->momentum() + c2->momentum();
   Energy2 m2 = sqr(pT())/z()/(1.-z()) + sqr(c1->mass())/z()
     + sqr(c2->mass())/(1.-z());
   pnew.setMass(sqrt(m2));
   parent->set5Momentum( pnew );
 }
 
 void FS_QTildeShowerKinematics1to2::reconstructLast(const tShowerParticlePtr last,
 						    Energy mass) const {
   // set beta component and consequently all missing data from that,
   // using the nominal (i.e. PDT) mass.
   Energy theMass =ZERO;
   if(!(mass > ZERO) && ShowerHandler::currentHandler()->retConstituentMasses())
     theMass = last->data().constituentMass();
   else
     theMass = mass > ZERO ? mass : last->data().mass();
   
   Lorentz5Momentum pVector = last->showerBasis()->pVector();
   ShowerParticle::Parameters & lastParam = last->showerParameters();
   Energy2 denom = 2. * lastParam.alpha * last->showerBasis()->p_dot_n();
   if(abs(denom)/(sqr(pVector.e())+pVector.rho2())<1e-10) {
     throw KinematicsReconstructionVeto();
   }
   lastParam.beta = ( sqr(theMass) + sqr(lastParam.pt)
 		     - sqr(lastParam.alpha) * pVector.m2() )
     / denom;
   // set that new momentum
   Lorentz5Momentum newMomentum = last->showerBasis()->
     sudakov2Momentum( lastParam.alpha, lastParam.beta,
 		      lastParam.ptx  , lastParam.pty);
   newMomentum.setMass(theMass);
   newMomentum.rescaleEnergy();
   if(last->data().stable()) {
     last->set5Momentum( newMomentum );
   }
   else {
     last->boost(last->momentum().findBoostToCM());
     last->boost(newMomentum.boostVector());
   }
 }
 
 void FS_QTildeShowerKinematics1to2::updateParent(const tShowerParticlePtr parent, 
 						 const ShowerParticleVector & children,
+						 unsigned int pTscheme,
 						 ShowerPartnerType) const {
   IdList ids(3);
   ids[0] = parent->dataPtr();
   ids[1] = children[0]->dataPtr();
   ids[2] = children[1]->dataPtr();
   const vector<Energy> & virtualMasses = SudakovFormFactor()->virtualMasses(ids);
   if(children[0]->children().empty()) children[0]->virtualMass(virtualMasses[1]);
   if(children[1]->children().empty()) children[1]->virtualMass(virtualMasses[2]);
   // compute the new pT of the branching
   Energy2 m02 = (ids[0]->id()!=ParticleID::g && ids[0]->id()!=ParticleID::gamma) ?
   	sqr(virtualMasses[0]) : Energy2();
-
-  Energy2 pt2 = QTildeKinematics::pT2_FSR(
-        sqr(scale()), z(), m02, sqr(children[0]->virtualMass()), sqr(children[1]->virtualMass())
-        );
-
+  Energy2 pt2;
+  if(pTscheme==0) {
+    pt2 = QTildeKinematics::pT2_FSR(sqr(scale()), z(), m02,
+				    sqr(virtualMasses[1])          ,sqr(virtualMasses[2]),
+				    sqr(virtualMasses[1])          ,sqr(virtualMasses[2]));
+  }
+  else if(pTscheme==1) {
+    pt2 = QTildeKinematics::pT2_FSR(sqr(scale()), z(), m02,
+				    sqr(virtualMasses[1])          ,sqr(virtualMasses[2]),
+				    sqr(children[0]->virtualMass()), sqr(children[1]->virtualMass()));
+  }
+  else if(pTscheme==2) {
+    pt2 = QTildeKinematics::pT2_FSR(sqr(scale()), z(), m02,
+				    sqr(children[0]->virtualMass()), sqr(children[1]->virtualMass()),
+				    sqr(children[0]->virtualMass()), sqr(children[1]->virtualMass()));
+  }
+  else
+    assert(false);
+  
   if(pt2>ZERO) {
     pT(sqrt(pt2));
   }
   else {
     pt2=ZERO;
     pT(ZERO);
   }
   Energy2 q2 = QTildeKinematics::q2_FSR(
       pt2, z(), sqr(children[0]->virtualMass()), sqr(children[1]->virtualMass())
     );
   parent->virtualMass(sqrt(q2));
 }
 
 void FS_QTildeShowerKinematics1to2::
 resetChildren(const tShowerParticlePtr parent, 
 	      const ShowerParticleVector & children) const {
   updateParameters(parent, children[0], children[1], false);
   for(unsigned int ix=0;ix<children.size();++ix) {
     if(children[ix]->children().empty()) continue;
     ShowerParticleVector newChildren;
     for(unsigned int iy=0;iy<children[ix]->children().size();++iy)
       newChildren.push_back(dynamic_ptr_cast<ShowerParticlePtr>
 			    (children[ix]->children()[iy]));
     children[ix]->showerKinematics()->resetChildren(children[ix],newChildren);
   }
 }
diff --git a/Shower/QTilde/Kinematics/FS_QTildeShowerKinematics1to2.h b/Shower/QTilde/Kinematics/FS_QTildeShowerKinematics1to2.h
--- a/Shower/QTilde/Kinematics/FS_QTildeShowerKinematics1to2.h
+++ b/Shower/QTilde/Kinematics/FS_QTildeShowerKinematics1to2.h
@@ -1,123 +1,124 @@
 // -*- C++ -*-
 //
 // FS_QTildeShowerKinematics1to2.h is a part of Herwig - A multi-purpose Monte Carlo event generator
 // Copyright (C) 2002-2017 The Herwig Collaboration
 //
 // Herwig is licenced under version 3 of the GPL, see COPYING for details.
 // Please respect the MCnet academic guidelines, see GUIDELINES for details.
 //
 #ifndef HERWIG_FS_QTildeShowerKinematics1to2_H
 #define HERWIG_FS_QTildeShowerKinematics1to2_H
 //
 // This is the declaration of the FS_QTildeShowerKinematics1to2 class.
 //
 
 #include "Herwig/Shower/QTilde/Kinematics/ShowerKinematics.h"
 
 namespace Herwig {
 
 using namespace ThePEG;
 
 /** \ingroup Shower
  *
  *  This (concrete) class provides the specific Final State shower
  *  kinematics information.
  *
  *  @see ShowerKinematics
  *  @see IS_QTildeShowerKinematics1to2
  *  @see Decay_QTildeShowerKinematics1to2
  *  @see KinematicsReconstructor
  */
 class FS_QTildeShowerKinematics1to2: public ShowerKinematics {
 
 public:
 
   /**
    * Default constructor
    */
   FS_QTildeShowerKinematics1to2() = default;
 
   /**
    * The constructor.
    */
   FS_QTildeShowerKinematics1to2(Energy scale, double z, double phi, Energy pt, tSudakovPtr sud) 
     : ShowerKinematics(scale,z,phi,pt,sud) {}
   
 
   /**
    *  The updateChildren, updateParent and updateLast
    *  members to update the values of the \f$\alpha\f$ and 
    *  \f$p_\perp\f$ variables during the shower evolution.
    */
   //@{
 
   /**
    * Along with the showering evolution --- going forward for
    * time-like (forward) evolution, and going backward for space-like
    * (backward) evolution --- the kinematical variables of the
    * branching products are calculated and updated from the knowledge
    * of the parent kinematics.  This method is used by the
    * ForwardShowerEvolver.  
    * @param parent The branching particle
    * @param children The particles produced in the branching
    * @param partnerType The type of evolution partner
    */
 private:
 
   void updateParameters(tShowerParticlePtr theParent,
 			tShowerParticlePtr theChild0,
 			tShowerParticlePtr theChild1,
 			bool setAlpha) const; 
 
 public:
   virtual void updateChildren( const tShowerParticlePtr parent, 
 			       const ShowerParticleVector & children,
 			       ShowerPartnerType partnerType) const;
 
   virtual void resetChildren( const tShowerParticlePtr parent, 
 			      const ShowerParticleVector & children) const;
 
 
   /**
    * Update the parent Kinematics from the knowledge of the kinematics
    * of the children. This method will be used by the KinematicsReconstructor.
    * @param parent   The parent
    * @param children The children
    * @param partnerType The type of evolution partner
    */
   virtual void updateParent(const tShowerParticlePtr parent,
 			    const ShowerParticleVector & children,
+			    unsigned int pTscheme,
 			    ShowerPartnerType partnerType) const;
 
   /**
    * Update the parent Kinematics from the knowledge of the kinematics
    * of the children. This method will be used by the 
    * KinematicsReconstructor.
    */
   virtual void reconstructParent( const tShowerParticlePtr parent, 
 				  const ParticleVector & children ) const;
 
   /**
    * Update the kinematical data of a particle when a reconstruction
    * fixpoint was found. This will highly depend on the kind of
    * kinematics chosen and will be defined in the inherited concrete
    * classes. This method will be used by the KinematicsReconstructor.
    * @param last The particle to update
    * @param mass The mass to be used, if less than zero on-shell
    */
   virtual void reconstructLast(const tShowerParticlePtr last, Energy mass=-1.*GeV) const;
   //@}
 
 private:
 
   /**
    * The assignment operator is private and must never be called.
    * In fact, it should not even be implemented.
    */
   FS_QTildeShowerKinematics1to2 & operator=(const FS_QTildeShowerKinematics1to2 &) = delete;
 
 };
 
 }
 
 #endif /* HERWIG_FS_QTildeShowerKinematics1to2_H */
diff --git a/Shower/QTilde/Kinematics/IS_QTildeShowerKinematics1to2.cc b/Shower/QTilde/Kinematics/IS_QTildeShowerKinematics1to2.cc
--- a/Shower/QTilde/Kinematics/IS_QTildeShowerKinematics1to2.cc
+++ b/Shower/QTilde/Kinematics/IS_QTildeShowerKinematics1to2.cc
@@ -1,149 +1,150 @@
 // -*- C++ -*-
 //
 // IS_QTildeShowerKinematics1to2.cc is a part of Herwig - A multi-purpose Monte Carlo event generator
 // Copyright (C) 2002-2017 The Herwig Collaboration
 //
 // Herwig is licenced under version 3 of the GPL, see COPYING for details.
 // Please respect the MCnet academic guidelines, see GUIDELINES for details.
 //
 //
 // This is the implementation of the non-inlined, non-templated member
 // functions of the IS_QTildeShowerKinematics1to2 class.
 //
 
 #include "IS_QTildeShowerKinematics1to2.h"
 #include "ThePEG/PDT/EnumParticles.h"
 #include "ThePEG/Interface/ClassDocumentation.h"
 #include "Herwig/Shower/QTilde/Base/ShowerParticle.h"
 #include "ThePEG/Utilities/Debug.h"
 #include "Herwig/Shower/QTilde/QTildeShowerHandler.h"
 #include "Herwig/Shower/QTilde/Base/PartnerFinder.h"
 #include "Herwig/Shower/QTilde/Kinematics/KinematicsReconstructor.h"
 #include "Herwig/Shower/QTilde/Base/ShowerVertex.h"
 #include <cassert>
 
 using namespace Herwig;
 
 void IS_QTildeShowerKinematics1to2::
 updateChildren( const tShowerParticlePtr theParent, 
 		const ShowerParticleVector & children,
 		ShowerPartnerType) const {
   const ShowerParticle::Parameters & parent = theParent->showerParameters();
   ShowerParticle::Parameters & child0 = children[0]->showerParameters();
   ShowerParticle::Parameters & child1 = children[1]->showerParameters();
   double cphi = cos(phi());
   double sphi = sin(phi());
 
   child1.alpha = (1.-z()) * parent.alpha;
 
   child1.ptx = (1.-z()) * parent.ptx - cphi * pT();
   child1.pty = (1.-z()) * parent.pty - sphi * pT();
   child1.pt  = sqrt( sqr(child1.ptx) + sqr(child1.pty) );
   // space-like child
   child0.alpha = parent.alpha - child1.alpha;
   child0.beta  = parent.beta  - child1.beta;
   child0.ptx   = parent.ptx   - child1.ptx;
   child0.pty   = parent.pty   - child1.pty;
 }
 
 
 void IS_QTildeShowerKinematics1to2::
 updateParent(const tShowerParticlePtr parent, 
 	     const ShowerParticleVector & children,
+	     unsigned int ,
 	     ShowerPartnerType partnerType) const {
   // calculate the scales
   splittingFn()->evaluateInitialStateScales(partnerType,scale(),z(),parent,
 					    children[0],children[1]);
   // set proper colour connections
   splittingFn()->colourConnection(parent,children[0],children[1],
 				  partnerType,true);
   // set proper parent/child relationships
   parent->addChild(children[0]);
   parent->addChild(children[1]);
   parent->x(children[0]->x()/z());
   // sort out the helicity stuff 
   // construct the spin info for parent and timelike child
   // temporary assignment of shower parameters to calculate correlations
   parent->showerParameters().alpha = parent->x();
   children[1]->showerParameters().alpha = (1.-z()) * parent->x();
   children[1]->showerParameters().ptx   = - cos(phi()) * pT();
   children[1]->showerParameters().pty   = - sin(phi()) * pT();
   children[1]->showerParameters().pt    = pT();
   parent     ->showerBasis(children[0]->showerBasis(),true);
   children[1]->showerBasis(children[0]->showerBasis(),true);
   parent     ->setShowerMomentum(false);
   children[1]->setShowerMomentum(true);
   if(! dynamic_ptr_cast<tcQTildeShowerHandlerPtr>(ShowerHandler::currentHandler())->correlations()) return;
   SpinPtr pspin(children[0]->spinInfo());
   if(!pspin ||  !dynamic_ptr_cast<tcQTildeShowerHandlerPtr>(ShowerHandler::currentHandler())->spinCorrelations() ) return;
   // compute the matrix element for spin correlations
   IdList ids;
   ids.push_back(parent->dataPtr());
   ids.push_back(children[0]->dataPtr());
   ids.push_back(children[1]->dataPtr());
   Energy2 t = (1.-z())*sqr(scale())/z();
   // create the vertex
   SVertexPtr vertex(new_ptr(ShowerVertex()));
   // set the matrix element
   vertex->ME(splittingFn()->matrixElement(z(),t,ids,phi(),false));
   // set the incoming particle for the vertex 
   // (in reality the first child as going backwards)
   pspin->decayVertex(vertex);
   // construct the spin infos
   parent     ->constructSpinInfo(false);
   children[1]->constructSpinInfo(true);
   // connect the spinInfo objects to the vertex
   parent     ->spinInfo()->productionVertex(vertex);
   children[1]->spinInfo()->productionVertex(vertex);
 }
 
 void IS_QTildeShowerKinematics1to2::
 reconstructParent(const tShowerParticlePtr parent, 
 		  const ParticleVector & children ) const {
   PPtr c1 = children[0];
   ShowerParticlePtr c2 = dynamic_ptr_cast<ShowerParticlePtr>(children[1]);
   ShowerParticle::Parameters & c2param = c2->showerParameters();
   // get shower variables from 1st child in order to keep notation
   // parent->(c1, c2) clean even though the splitting was initiated
   // from c1.  The name updateParent is still referring to the
   // timelike branching though.
   // on-shell child
   
   auto m=  ShowerHandler::currentHandler()->retConstituentMasses()?
            c2->data().constituentMass():
            c2->data().mass();
   
   c2param.beta = 0.5*( sqr(m) + sqr(c2param.pt) )
     / ( c2param.alpha * parent->showerBasis()->p_dot_n() );
   Lorentz5Momentum pnew = parent->showerBasis()->
     sudakov2Momentum(c2param.alpha, c2param.beta, 
 		     c2param.ptx  , c2param.pty);
   pnew.setMass(m);
   pnew.rescaleEnergy();
   c2->set5Momentum( pnew );
   // spacelike child
   Lorentz5Momentum pc1(parent->momentum() - c2->momentum());
   pc1.rescaleMass();
   c1->set5Momentum(pc1);
 }
 
 void IS_QTildeShowerKinematics1to2::
 updateLast( const tShowerParticlePtr theLast,Energy px,Energy py) const {
   if(theLast->isFinalState()) return; 
   Lorentz5Momentum pVector = theLast->showerBasis()->pVector();
   ShowerParticle::Parameters & last = theLast->showerParameters();
   Energy2 pt2 = sqr(px) + sqr(py);
   last.alpha = theLast->x();
   last.beta  = 0.5 * pt2 / last.alpha / theLast->showerBasis()->p_dot_n();
   last.ptx   = ZERO;
   last.pty   = ZERO;
   last.pt    = ZERO;
   // momentum
   Lorentz5Momentum ntemp = Lorentz5Momentum(ZERO,-pVector.vect());
   double beta = 0.5 * pt2 / last.alpha / ( pVector * ntemp);
   Lorentz5Momentum plast = 
     Lorentz5Momentum( (pVector.z()>ZERO ? px : -px), py, ZERO, ZERO)
     + theLast->x() * pVector + beta * ntemp;
   plast.rescaleMass();
   theLast->set5Momentum(plast);
 }
diff --git a/Shower/QTilde/Kinematics/IS_QTildeShowerKinematics1to2.h b/Shower/QTilde/Kinematics/IS_QTildeShowerKinematics1to2.h
--- a/Shower/QTilde/Kinematics/IS_QTildeShowerKinematics1to2.h
+++ b/Shower/QTilde/Kinematics/IS_QTildeShowerKinematics1to2.h
@@ -1,117 +1,118 @@
 // -*- C++ -*-
 //
 // IS_QTildeShowerKinematics1to2.h is a part of Herwig - A multi-purpose Monte Carlo event generator
 // Copyright (C) 2002-2017 The Herwig Collaboration
 //
 // Herwig is licenced under version 3 of the GPL, see COPYING for details.
 // Please respect the MCnet academic guidelines, see GUIDELINES for details.
 //
 #ifndef HERWIG_IS_QTildeShowerKinematics1to2_H
 #define HERWIG_IS_QTildeShowerKinematics1to2_H
 //
 // This is the declaration of the IS_QTildeShowerKinematics1to2 class.
 //
 
 #include "Herwig/Shower/QTilde/Kinematics/ShowerKinematics.h"
 
 namespace Herwig {
 
 using namespace ThePEG;
 
 /** \ingroup Shower
  *  
  *  This (concrete) class provides the specific Intial State shower
  *  kinematics information.
  *
  *  @see ShowerKinematics
  *  @see FS_QTildeShowerKinematics1to2
  *  @see Decay_QTildeShowerKinematics1to2
  *  @see KinematicsReconstructor
  */
 class IS_QTildeShowerKinematics1to2: public ShowerKinematics {
 
 public:
 
   /** @name Standard constructors and destructors. */
   //@{
   /**
    *  Construct in terms of the basis states
    */
   IS_QTildeShowerKinematics1to2()= default;
 
   /**
    * The default constructor.
    */
   IS_QTildeShowerKinematics1to2(Energy scale, double z, double phi, Energy pt, tSudakovPtr sud) 
     : ShowerKinematics(scale,z,phi,pt,sud) {}
   //@}
 
 public:
 
   /**
    *  The updateChildren, updateParent and updateLast
    *  members to update the values of the \f$\alpha\f$ and 
    *  \f$p_\perp\f$ variables during the shower evolution.
    */
   //@{
   /**
    * Along with the showering evolution --- going forward for
    * time-like (forward) evolution, and going backward for space-like
    * (backward) evolution --- the kinematical variables of the
    * branching products are calculated and updated from the knowledge
    * of the parent kinematics.  This method is used by the
    * ForwardShowerEvolver.  
    * @param parent The branching particle
    * @param children The particles produced in the branching
    * @param partnerType The type of evolution partner
    */
   virtual void updateChildren( const tShowerParticlePtr parent, 
 			       const ShowerParticleVector & children,
 			       ShowerPartnerType partnerType) const;
 
   /**
    * Update the parent Kinematics from the knowledge of the kinematics
    * of the children. This method will be used by the 
    * KinematicsReconstructor.
    * @param parent The branching particle
    * @param children The particles produced in the branching
    * @param partnerType The type of evolution partner
    */
   virtual void updateParent( const tShowerParticlePtr parent, 
 			     const ShowerParticleVector & children,
+			     unsigned int pTscheme,
 			     ShowerPartnerType partnerType) const;
 
   /**
    * Update the parent Kinematics from the knowledge of the kinematics
    * of the children. This method will be used by the 
    * KinematicsReconstructor.
    */
   virtual void reconstructParent( const tShowerParticlePtr parent, 
 				  const ParticleVector & children ) const;
 
   /**
    * Update the kinematical data of a particle when a reconstruction
    * fixpoint was found. This will highly depend on the kind of
    * kinematics chosen and will be defined in the inherited concrete
    * classes. This method will be used by the KinematicsReconstructor.
    * @param theLast The particle.
    * @param px The \f$x\f$ component of the \f$p_T\f$.
    * @param py The \f$y\f$ component of the \f$p_T\f$.
    */
   virtual void updateLast(const tShowerParticlePtr theLast,
 			  Energy px, Energy py) const;
   //@}
 
 private:
 
   /**
    * The assignment operator is private and must never be called.
    * In fact, it should not even be implemented.
    */
   IS_QTildeShowerKinematics1to2 & operator=(const IS_QTildeShowerKinematics1to2 &) = delete;
 
 };
 
 }
 
 #endif /* HERWIG_IS_QTildeShowerKinematics1to2_H */
diff --git a/Shower/QTilde/Kinematics/KinematicHelpers.h b/Shower/QTilde/Kinematics/KinematicHelpers.h
--- a/Shower/QTilde/Kinematics/KinematicHelpers.h
+++ b/Shower/QTilde/Kinematics/KinematicHelpers.h
@@ -1,56 +1,59 @@
 // -*- C++ -*-
 //
 // KinematicHelpers.h is a part of Herwig - A multi-purpose Monte Carlo event generator
 // Copyright (C) 2018 The Herwig Collaboration
 //
 // Herwig is licenced under version 3 of the GPL, see COPYING for details.
 // Please respect the MCnet academic guidelines, see GUIDELINES for details.
 //
 #ifndef HERWIG_KinematicHelpers_H
 #define HERWIG_KinematicHelpers_H
 
 namespace QTildeKinematics {
 
 
 
-inline Energy2 pT2_FSR(Energy2 qt2, double z, Energy2 m02, Energy2 m12, Energy2 m22) {
-	const double z1z = z*(1.-z);
-	return z1z*(z1z*qt2 + m02) - m12*(1.-z) - m22*z;
+inline Energy2 pT2_FSR(Energy2 qt2, double z, Energy2 m02, Energy2 m12, Energy2 m22,
+		       Energy2 q12, Energy2 q22) {
+  const double z1z = z*(1.-z);
+  return z1z*(z1z*qt2 + m02 -m12-m22) - q12*sqr(1.-z) - q22*sqr(z);
+  //return z1z*(z1z*qt2 + m02) - q12*(1.-z) - q22*z;
 }
 
 inline Energy2 pT2_ISR(Energy2 qt2, double z, Energy2 m22) {
-	return sqr(1.-z)*qt2 - m22*z;
+  return sqr(1.-z)*qt2 - m22*z;
 }
 
 inline Energy2 pT2_Decay(Energy2 qt2, double z, Energy2 m02, Energy2 m22) {
-	return sqr(1.-z)*(qt2 - m02) - m22*z;
+  return sqr(1.-z)*(qt2 - m02) - m22*z;
 }
 
 
 
-inline Energy pT_FSR(Energy2 qt2, double z, Energy2 m02, Energy2 m12, Energy2 m22) {
-	return sqrt( pT2_FSR(qt2,z,m02,m12,m22) );
+inline Energy pT_FSR(Energy2 qt2, double z, Energy2 m02, Energy2 m12, Energy2 m22,
+		       Energy2 q12, Energy2 q22) {
+  return sqrt( pT2_FSR(qt2,z,m02,m12,m22,q12,q22) );
 }
 
 
 inline Energy pT_ISR(Energy2 qt2, double z, Energy2 m22) {
-	return sqrt( pT2_ISR(qt2,z,m22) );
+  return sqrt( pT2_ISR(qt2,z,m22) );
 }
 
 inline Energy pT_Decay(Energy2 qt2, double z, Energy2 m02, Energy2 m22) {
-	return sqrt( pT2_Decay(qt2,z,m02,m22) );
+  return sqrt( pT2_Decay(qt2,z,m02,m22) );
 }
 
 
 inline Energy2 q2_FSR(Energy2 pt2, double z, Energy2 m12, Energy2 m22) {
   return m12/z + m22/(1.-z) + pt2/z/(1.-z);
 }
 
 // inline Energy2 q2_ISR(Energy2 pt2, double z, Energy2 m22) {
 //   return m22/(1.-z) + pt2/z/(1.-z);
 // }
 
 
 }
 
 #endif
diff --git a/Shower/QTilde/Kinematics/KinematicsReconstructor.cc b/Shower/QTilde/Kinematics/KinematicsReconstructor.cc
--- a/Shower/QTilde/Kinematics/KinematicsReconstructor.cc
+++ b/Shower/QTilde/Kinematics/KinematicsReconstructor.cc
@@ -1,2945 +1,2825 @@
 // -*- C++ -*-
 //
 // KinematicsReconstructor.cc is a part of Herwig - A multi-purpose Monte Carlo event generator
 // Copyright (C) 2002-2017 The Herwig Collaboration
 //
 // Herwig is licenced under version 3 of the GPL, see COPYING for details.
 // Please respect the MCnet academic guidelines, see GUIDELINES for details.
 //
 //
 // This is the implementation of the non-inlined, non-templated member
 // functions of the KinematicsReconstructor class.
 //
 
 #include "KinematicsReconstructor.h"
 #include "ThePEG/PDT/EnumParticles.h"
 #include "ThePEG/Repository/EventGenerator.h"
 #include "ThePEG/EventRecord/Event.h"
 #include "ThePEG/Interface/Parameter.h"
+#include "ThePEG/Interface/Deleted.h"
 #include "ThePEG/Interface/Switch.h"
 #include "ThePEG/Interface/ClassDocumentation.h"
 #include "ThePEG/Interface/RefVector.h"
 #include "Herwig/Shower/QTilde/Base/PartnerFinder.h"
 #include "ThePEG/Persistency/PersistentOStream.h"
 #include "ThePEG/Persistency/PersistentIStream.h"
 #include "Herwig/Shower/QTilde/SplittingFunctions/SplittingFunction.h"
 #include "ThePEG/Repository/UseRandom.h"
 #include "ThePEG/EventRecord/ColourLine.h"
 #include "ThePEG/Utilities/DescribeClass.h"
 #include "Herwig/Shower/QTilde/QTildeShowerHandler.h"
 #include <cassert>
 #include "KinematicsReconstructor.tcc"
 
 using namespace Herwig;
 
 DescribeClass<KinematicsReconstructor,Interfaced>
 describeKinematicsReconstructor("Herwig::KinematicsReconstructor", "HwShower.so");
 
 namespace {
 
 /**
  *  Struct to order the jets in off-shellness
  */
 struct JetOrdering {
 
   bool operator() (const JetKinStruct & j1, const JetKinStruct & j2) {
     Energy diff1 = j1.q.m()-j1.p.m();
     Energy diff2 = j2.q.m()-j2.p.m();
     if(diff1!=diff2) {
       return diff1>diff2;
     }
     else if( j1.q.e() != j2.q.e() )
       return j1.q.e()>j2.q.e();
     else
       return j1.parent->uniqueId>j2.parent->uniqueId;
   }
 };
 
 }
 
 void KinematicsReconstructor::persistentOutput(PersistentOStream & os) const {
   os << _reconopt << _initialBoost << ounit(_minQ,GeV) << _noRescale 
-     << _noRescaleVector << _finalStateReconOption
-     << _initialStateReconOption;
+     << _noRescaleVector << _initialStateReconOption << _finalFinalWeight;
 }
 
 void KinematicsReconstructor::persistentInput(PersistentIStream & is, int) {
   is >> _reconopt >> _initialBoost >> iunit(_minQ,GeV) >> _noRescale 
-     >> _noRescaleVector >> _finalStateReconOption
-     >> _initialStateReconOption;  
+     >> _noRescaleVector >> _initialStateReconOption >> _finalFinalWeight;
 }
 
 void KinematicsReconstructor::Init() {
 
   static ClassDocumentation<KinematicsReconstructor> documentation
     ( "This class is responsible for the kinematics reconstruction of the showering,",
       " including the kinematics reshuffling necessary to compensate for the recoil"
       "of the emissions." );
 
   static Switch<KinematicsReconstructor,unsigned int> interfaceReconstructionOption
     ("ReconstructionOption",
      "Option for the kinematics reconstruction",
      &KinematicsReconstructor::_reconopt, 0, false, false);
   static SwitchOption interfaceReconstructionOptionGeneral
     (interfaceReconstructionOption,
      "General",
      "Use the general solution which ignores the colour structure for all processes",
      0);
   static SwitchOption interfaceReconstructionOptionColour
     (interfaceReconstructionOption,
      "Colour",
      "Use the colour structure of the process to determine the reconstruction procedure.",
      1);
   static SwitchOption interfaceReconstructionOptionColour2
     (interfaceReconstructionOption,
      "Colour2",
      "Make the most use possible of the colour structure of the process to determine the reconstruction procedure. "
      "Start with FF, then IF then II colour connections",
      2);
   static SwitchOption interfaceReconstructionOptionColour3
     (interfaceReconstructionOption,
      "Colour3",
      "Make the most use possible of the colour structure of the process to determine the reconstruction procedure. "
      "Do the colour connections in order of the pT's emitted in the shower starting with the hardest."
      " The colour partner is fully reconstructed at the same time.",
      3);
   static SwitchOption interfaceReconstructionOptionColour4
     (interfaceReconstructionOption,
      "Colour4",
      "Make the most use possible of the colour structure of the process to determine the reconstruction procedure. "
      "Do the colour connections in order of the pT's emitted in the shower starting with the hardest, while leaving"
      " the colour partner on mass-shell",
      4);
 
   static Parameter<KinematicsReconstructor,Energy> interfaceMinimumQ2
     ("MinimumQ2",
      "The minimum Q2 for the reconstruction of initial-final systems",
      &KinematicsReconstructor::_minQ, GeV, 0.001*GeV, 1e-6*GeV, 10.0*GeV,
      false, false, Interface::limited);
 
   static RefVector<KinematicsReconstructor,ParticleData> interfaceNoRescale
     ("NoRescale",
      "Particles which shouldn't be rescaled to be on shell by the shower",
      &KinematicsReconstructor::_noRescaleVector, -1, false, false, true, false, false);
 
   static Switch<KinematicsReconstructor,unsigned int> interfaceInitialInitialBoostOption
     ("InitialInitialBoostOption",
      "Option for how the boost from the system before ISR to that after ISR is applied.",
      &KinematicsReconstructor::_initialBoost, 0, false, false);
   static SwitchOption interfaceInitialInitialBoostOptionOneBoost
     (interfaceInitialInitialBoostOption,
      "OneBoost",
      "Apply one boost from old CMS to new CMS",
      0);
   static SwitchOption interfaceInitialInitialBoostOptionLongTransBoost
     (interfaceInitialInitialBoostOption,
      "LongTransBoost",
      "First apply a longitudinal and then a transverse boost",
      1);
 
-  static Switch<KinematicsReconstructor,unsigned int> interfaceFinalStateReconOption
-    ("FinalStateReconOption",
-     "Option for how to reconstruct the momenta of the final-state system",
-     &KinematicsReconstructor::_finalStateReconOption, 0, false, false);
-  static SwitchOption interfaceFinalStateReconOptionDefault
-    (interfaceFinalStateReconOption,
-     "Default",
-     "All the momenta are rescaled in the rest frame",
-     0);
-  static SwitchOption interfaceFinalStateReconOptionMostOffShell
-    (interfaceFinalStateReconOption,
-     "MostOffShell",
-     "All particles put on the new-mass shell and then the most off-shell and"
-     " recoiling system are rescaled to ensure 4-momentum is conserved.",
-     1);
-  static SwitchOption interfaceFinalStateReconOptionRecursive
-    (interfaceFinalStateReconOption,
-     "Recursive",
-     "Recursively put on shell by putting the most off-shell particle which"
-     " hasn't been rescaled on-shell by rescaling the particles and the recoiling system. ",
-     2);
-  static SwitchOption interfaceFinalStateReconOptionRestMostOffShell
-    (interfaceFinalStateReconOption,
-     "RestMostOffShell",
-     "The most off-shell is put on shell by rescaling it and the recoiling system,"
-     " the recoiling system is then put on-shell in its rest frame.",
-     3);
-  static SwitchOption interfaceFinalStateReconOptionRestRecursive
-    (interfaceFinalStateReconOption,
-     "RestRecursive",
-     "As 3 but recursive treated the currently most-off shell,"
-     " only makes a difference if more than 3 partons.",
-     4);
-
+  static Deleted<KinematicsReconstructor> delFinalStateReconOption
+    ("FinalStateReconOption", "The old default (0) is now the only choice");
+  
   static Switch<KinematicsReconstructor,unsigned int> interfaceInitialStateReconOption
     ("InitialStateReconOption",
      "Option for the reconstruction of initial state radiation",
      &KinematicsReconstructor::_initialStateReconOption, 0, false, false);
   static SwitchOption interfaceInitialStateReconOptionRapidity
     (interfaceInitialStateReconOption,
      "Rapidity",
      "Preserve shat and rapidity",
      0);
   static SwitchOption interfaceInitialStateReconOptionLongitudinal
     (interfaceInitialStateReconOption,
      "Longitudinal",
      "Preserve longitudinal momentum",
      1);
   static SwitchOption interfaceInitialStateReconOptionSofterFraction
     (interfaceInitialStateReconOption,
      "SofterFraction",
      "Preserve the momentum fraction of the parton which has emitted softer.",
      2);
 
+  static Switch<KinematicsReconstructor,bool> interfaceFinalFinalWeight
+    ("FinalFinalWeight",
+     "Apply kinematic rejection weight for final-states",
+     &KinematicsReconstructor::_finalFinalWeight, false, false, false);
+  static SwitchOption interfaceFinalFinalWeightNo
+    (interfaceFinalFinalWeight,
+     "No",
+     "Don't apply the weight",
+     false);
+  static SwitchOption interfaceFinalFinalWeightYes
+    (interfaceFinalFinalWeight,
+     "Yes",
+     "Apply the weight",
+     true);
+
 }
 
 void KinematicsReconstructor::doinit() {
   Interfaced::doinit();
   _noRescale = set<cPDPtr>(_noRescaleVector.begin(),_noRescaleVector.end());
 }
 
 bool KinematicsReconstructor::
 reconstructTimeLikeJet(const tShowerParticlePtr particleJetParent) const {
   assert(particleJetParent);
   bool emitted=true;
   // if this is not a fixed point in the reconstruction
   if( !particleJetParent->children().empty() ) {
     // if not a reconstruction fixpoint, dig deeper for all children:
     for ( ParticleVector::const_iterator cit = 
 	    particleJetParent->children().begin();
 	  cit != particleJetParent->children().end(); ++cit )
       reconstructTimeLikeJet(dynamic_ptr_cast<ShowerParticlePtr>(*cit));
   }
   // it is a reconstruction fixpoint, ie kinematical data has to be available 
   else {
     // check if the parent was part of the shower
     ShowerParticlePtr jetGrandParent;
     if(!particleJetParent->parents().empty())
       jetGrandParent= dynamic_ptr_cast<ShowerParticlePtr>
 	(particleJetParent->parents()[0]);
     // update if so
     if (jetGrandParent) {
       if (jetGrandParent->showerKinematics()) {
 	if(particleJetParent->id()==_progenitor->id()&&
 	   !_progenitor->data().stable()&&abs(_progenitor->data().id())!=ParticleID::tauminus) {
 	  jetGrandParent->showerKinematics()->reconstructLast(particleJetParent,
 							      _progenitor->mass());
 	}
 	else {
 	  jetGrandParent->showerKinematics()->reconstructLast(particleJetParent);
 	}
       }
     }
     // otherwise
     else {
       Energy dm = ShowerHandler::currentHandler()->retConstituentMasses()?
 	particleJetParent->data().constituentMass():
 	particleJetParent->data().mass();
       if (abs(dm-particleJetParent->momentum().m())>0.001*MeV
 	  &&(particleJetParent->dataPtr()->stable() || abs(particleJetParent->id())==ParticleID::tauminus)
 	  &&particleJetParent->id()!=ParticleID::gamma
 	  &&_noRescale.find(particleJetParent->dataPtr())==_noRescale.end()) {
 	Lorentz5Momentum dum =  particleJetParent->momentum();
 	dum.setMass(dm);
 	dum.rescaleEnergy();
 	particleJetParent->set5Momentum(dum);
       } 
       else {
 	emitted=false;
       }
     }
   }
   // recursion has reached an endpoint once, ie we can reconstruct the
   // kinematics from the children.
   if( !particleJetParent->children().empty() ) 
     particleJetParent->showerKinematics()
       ->reconstructParent( particleJetParent, particleJetParent->children() );
   return emitted;
 }
 
 bool KinematicsReconstructor::
 reconstructHardJets(ShowerTreePtr hard,
 		    const map<tShowerProgenitorPtr,
 		    pair<Energy,double> > & intrinsic,
 		    ShowerInteraction type,
 		    bool switchRecon) const {
   _currentTree = hard;
   _intrinsic=intrinsic;
   // extract the particles from the ShowerTree
   vector<ShowerProgenitorPtr> ShowerHardJets=hard->extractProgenitors();
   for(unsigned int ix=0;ix<ShowerHardJets.size();++ix) {
     _boosts[ShowerHardJets[ix]->progenitor()] = vector<LorentzRotation>();
   }
   for(map<tShowerTreePtr,pair<tShowerProgenitorPtr,tShowerParticlePtr> >::const_iterator
 	tit  = _currentTree->treelinks().begin();
       tit != _currentTree->treelinks().end();++tit) {
     _treeBoosts[tit->first] = vector<LorentzRotation>();
   }
   try {
     // old recon method, using new member functions
     if(_reconopt == 0 || switchRecon ) {
       reconstructGeneralSystem(ShowerHardJets);
     }
     // reconstruction based on coloured systems
     else if( _reconopt == 1) {
       reconstructColourSinglets(ShowerHardJets,type);
     }
     // reconstruction of FF, then IF, then II
     else if( _reconopt == 2) {
       reconstructFinalFirst(ShowerHardJets);
     }
     // reconstruction based on coloured systems
     else if( _reconopt == 3 || _reconopt == 4) {
       reconstructColourPartner(ShowerHardJets);
     }
     else
       assert(false);
   }
   catch(KinematicsReconstructionVeto) {
     _progenitor=tShowerParticlePtr();
     _intrinsic.clear();
     for(map<tPPtr,vector<LorentzRotation> >::const_iterator bit=_boosts.begin();bit!=_boosts.end();++bit) {
       for(vector<LorentzRotation>::const_reverse_iterator rit=bit->second.rbegin();rit!=bit->second.rend();++rit) {
 	LorentzRotation rot = rit->inverse();
 	bit->first->transform(rot);
       }
     }
     _boosts.clear();
     for(map<tShowerTreePtr,vector<LorentzRotation> >::const_iterator bit=_treeBoosts.begin();bit!=_treeBoosts.end();++bit) {
       for(vector<LorentzRotation>::const_reverse_iterator rit=bit->second.rbegin();rit!=bit->second.rend();++rit) {
 	LorentzRotation rot = rit->inverse();
 	bit->first->transform(rot,false);
       }
     }
     _currentTree = tShowerTreePtr();
     _treeBoosts.clear();
     return false;
   }
   catch (Exception & ex) {
     _progenitor=tShowerParticlePtr();
     _intrinsic.clear();
     _currentTree = tShowerTreePtr();
     _boosts.clear();
     _treeBoosts.clear();
     throw ex;
   }
   _progenitor=tShowerParticlePtr();
   _intrinsic.clear();
   // ensure x<1
   for(map<ShowerProgenitorPtr,ShowerParticlePtr>::const_iterator 
 	cit=hard->incomingLines().begin();cit!=hard->incomingLines().end();++cit) {
     tPPtr parent = cit->first->progenitor();
     while (!parent->parents().empty()) {
       parent = parent->parents()[0];
     }
     tPPtr hadron;
     if ( cit->first->original()->parents().empty() ) {
       hadron = cit->first->original();
     } 
     else {
       hadron = cit->first->original()->parents()[0];
     }
     if( ! (hadron->id() == parent->id() && hadron->children().size() <= 1)
        && parent->momentum().rho() > hadron->momentum().rho()) {
       _progenitor=tShowerParticlePtr();
       _intrinsic.clear();
       for(map<tPPtr,vector<LorentzRotation> >::const_iterator bit=_boosts.begin();bit!=_boosts.end();++bit) {
 	for(vector<LorentzRotation>::const_reverse_iterator rit=bit->second.rbegin();rit!=bit->second.rend();++rit) {
 	  LorentzRotation rot = rit->inverse();
 	  bit->first->transform(rot);
 	}
       }
       _boosts.clear();
       for(map<tShowerTreePtr,vector<LorentzRotation> >::const_iterator bit=_treeBoosts.begin();bit!=_treeBoosts.end();++bit) {
 	for(vector<LorentzRotation>::const_reverse_iterator rit=bit->second.rbegin();rit!=bit->second.rend();++rit) {
 	  LorentzRotation rot = rit->inverse();
 	  bit->first->transform(rot,false);
 	}
       }
       _currentTree = tShowerTreePtr();
       _treeBoosts.clear();
       return false;
     }
   }
   _boosts.clear();
   _treeBoosts.clear();
   _currentTree = tShowerTreePtr();
   return true;
 }
 
 double 
 KinematicsReconstructor::solveKfactor(const Energy & root_s, 
-				  const JetKinVect & jets) const {
+				      const JetKinVect & jets) const {
   Energy2 s = sqr(root_s);
   // must be at least two jets
   if ( jets.size() < 2) throw KinematicsReconstructionVeto();
   // sum of jet masses must be less than roots
   if(momConsEq( 0.0, root_s, jets )>ZERO) throw KinematicsReconstructionVeto();
   // if two jets simple solution
   if ( jets.size() == 2 ) {
     static const Energy2 eps = 1.0e-4 * MeV2;
     if ( sqr(jets[0].p.x()+jets[1].p.x()) < eps &&
 	 sqr(jets[0].p.y()+jets[1].p.y()) < eps &&
 	 sqr(jets[0].p.z()+jets[1].p.z()) < eps ) {
       Energy test = (jets[0].p+jets[1].p).vect().mag();
       if(test > 1.0e-4 * MeV) throw KinematicsReconstructionVeto();
       if ( jets[0].p.vect().mag2() < eps ) throw KinematicsReconstructionVeto();
       Energy2 m1sq(jets[0].q.m2()),m2sq(jets[1].q.m2());
       return sqrt( ( sqr(s - m1sq - m2sq) - 4.*m1sq*m2sq )
 		   /(4.*s*jets[0].p.vect().mag2()) );
     } 
     else throw KinematicsReconstructionVeto();
   }
   // i.e. jets.size() > 2, numerically
   // check convergence, if it's a problem maybe use Newton iteration?
   else {
     double k1 = 0.,k2 = 1.,k = 0.; 
     if ( momConsEq( k1, root_s, jets ) < ZERO ) {
       while ( momConsEq( k2, root_s, jets ) < ZERO ) {
 	k1 = k2; 
 	k2 *= 2;       
       }
       while ( fabs( (k1 - k2)/(k1 + k2) ) > 1.e-10 ) { 
 	if( momConsEq( k2, root_s, jets ) == ZERO ) {
 	  return k2; 
 	} else {
 	  k = (k1+k2)/2.;
 	  if ( momConsEq( k, root_s, jets ) > ZERO ) {
 	    k2 = k;
 	  } else {
 	    k1 = k; 
 	  } 
 	}
       }
       return k1; 	  
     } else throw KinematicsReconstructionVeto();
   }
   throw KinematicsReconstructionVeto(); 
 }
 
 bool KinematicsReconstructor::
 reconstructSpaceLikeJet( const tShowerParticlePtr p) const {
   bool emitted = true;
   tShowerParticlePtr child;
   tShowerParticlePtr parent;
   if(!p->parents().empty())
     parent = dynamic_ptr_cast<ShowerParticlePtr>(p->parents()[0]);
   if(parent) {
     emitted=true;
     reconstructSpaceLikeJet(parent);
   }
   // if branching reconstruct time-like child
   if(p->children().size()==2)
     child = dynamic_ptr_cast<ShowerParticlePtr>(p->children()[1]);
   if(p->perturbative()==0 && child) {
     dynamic_ptr_cast<ShowerParticlePtr>(p->children()[0])->
       showerKinematics()->reconstructParent(p,p->children());
     if(!child->children().empty()) {
       _progenitor=child;
       reconstructTimeLikeJet(child);
       // calculate the momentum of the particle
       Lorentz5Momentum pnew=p->momentum()-child->momentum();
       pnew.rescaleMass();
       p->children()[0]->set5Momentum(pnew);
     }
   }
   return emitted;
 }
 
 Boost KinematicsReconstructor::
 solveBoostBeta( const double k, const Lorentz5Momentum & newq,
 		const Lorentz5Momentum & oldp ) {
   // try something different, purely numerical first: 
   // a) boost to rest frame of newq, b) boost with kp/E
   Energy q = newq.vect().mag(); 
   Energy2 qs = sqr(q); 
   Energy2 Q2 = newq.m2(); 
   Energy kp = k*(oldp.vect().mag()); 
   Energy2 kps = sqr(kp); 
 
   // usually we take the minus sign, since this boost will be smaller.
   // we only require |k \vec p| = |\vec q'| which leaves the sign of
   // the boost open but the 'minus' solution gives a smaller boost
   // parameter, i.e. the result should be closest to the previous
   // result. this is to be changed if we would get many momentum
   // conservation violations at the end of the shower from a hard
   // process.
   double betam = (q*sqrt(qs + Q2) - kp*sqrt(kps + Q2))/(kps + qs + Q2);
   // move directly to 'return' 
   Boost beta = -betam*(k/kp)*oldp.vect();
   // note that (k/kp)*oldp.vect() = oldp.vect()/oldp.vect().mag() but cheaper. 
   // leave this out if it's running properly! 
   if ( betam >= 0 ) return beta;
   else              return Boost(0., 0., 0.); 
 }
 
 bool KinematicsReconstructor::
 reconstructDecayJets(ShowerTreePtr decay,
 		     ShowerInteraction) const {
   _currentTree = decay;
   // extract the particles from the ShowerTree
   vector<ShowerProgenitorPtr> ShowerHardJets=decay->extractProgenitors();
   for(unsigned int ix=0;ix<ShowerHardJets.size();++ix) {
     _boosts[ShowerHardJets[ix]->progenitor()] = vector<LorentzRotation>();
   }
   for(map<tShowerTreePtr,pair<tShowerProgenitorPtr,tShowerParticlePtr> >::const_iterator
 	tit  = _currentTree->treelinks().begin();
       tit != _currentTree->treelinks().end();++tit) {
     _treeBoosts[tit->first] = vector<LorentzRotation>();
   }
   try {
     bool radiated[2]={false,false};
     // find the decaying particle and check if particles radiated
     ShowerProgenitorPtr initial;
     for(unsigned int ix=0;ix<ShowerHardJets.size();++ix) {
       // only consider initial-state jets
       if(ShowerHardJets[ix]->progenitor()->isFinalState()) {
 	radiated[1] |=ShowerHardJets[ix]->hasEmitted();
       }
       else {
 	initial=ShowerHardJets[ix];
 	radiated[0]|=ShowerHardJets[ix]->hasEmitted();
       }
     }
     // find boost to the rest frame if needed
     Boost boosttorest=-initial->progenitor()->momentum().boostVector();
     double gammarest =
       initial->progenitor()->momentum().e()/
       initial->progenitor()->momentum().mass();
     // check if need to boost to rest frame
     bool gottaBoost = (boosttorest.mag() > 1e-12);
     // if initial state radiation reconstruct the jet and set up the basis vectors
     Lorentz5Momentum pjet;
     Lorentz5Momentum nvect;
     // find the partner
     ShowerParticlePtr partner = initial->progenitor()->partner();
     Lorentz5Momentum ppartner[2];
     if(partner) ppartner[0]=partner->momentum();
     // get the n reference vector
     if(partner) {
       if(initial->progenitor()->showerKinematics()) {
 	nvect = initial->progenitor()->showerBasis()->getBasis()[1];
       }
       else {
 	Lorentz5Momentum ppartner=initial->progenitor()->partner()->momentum();
 	if(gottaBoost) ppartner.boost(boosttorest,gammarest);
 	nvect = Lorentz5Momentum( ZERO,0.5*initial->progenitor()->mass()*
 				  ppartner.vect().unit()); 
 	nvect.boost(-boosttorest,gammarest);
       }
     }
     // if ISR
     if(radiated[0]) {
       // reconstruct the decay jet
       reconstructDecayJet(initial->progenitor());
       // momentum of decaying particle after ISR
       pjet=initial->progenitor()->momentum()
 	-decay->incomingLines().begin()->second->momentum();
       pjet.rescaleMass();
     }
     // boost initial state jet and basis vector if needed
     if(gottaBoost) {
       pjet.boost(boosttorest,gammarest);
       nvect.boost(boosttorest,gammarest);
       ppartner[0].boost(boosttorest,gammarest);
     }
     // loop over the final-state particles and do the reconstruction
     JetKinVect possiblepartners;
     JetKinVect jetKinematics;
     bool atLeastOnce = radiated[0];
     LorentzRotation restboost(boosttorest,gammarest);
     Energy inmass(ZERO);
     for(unsigned int ix=0;ix<ShowerHardJets.size();++ix) {
       // only consider final-state jets
       if(!ShowerHardJets[ix]->progenitor()->isFinalState()) {
 	inmass=ShowerHardJets[ix]->progenitor()->mass();
 	continue;
       }
       // do the reconstruction
       JetKinStruct tempJetKin;      
       tempJetKin.parent = ShowerHardJets[ix]->progenitor();
       if(ShowerHardJets.size()==2) {
 	Lorentz5Momentum dum=ShowerHardJets[ix]->progenitor()->momentum();
 	dum.setMass(inmass);
 	dum.rescaleRho();
 	tempJetKin.parent->set5Momentum(dum);
       }
       tempJetKin.p = ShowerHardJets[ix]->progenitor()->momentum();
       if(gottaBoost) tempJetKin.p.boost(boosttorest,gammarest);
       _progenitor=tempJetKin.parent;
       if(ShowerHardJets[ix]->reconstructed()==ShowerProgenitor::notReconstructed) {
 	atLeastOnce |= reconstructTimeLikeJet(tempJetKin.parent);
 	ShowerHardJets[ix]->reconstructed(ShowerProgenitor::done);
       }
       if(gottaBoost) deepTransform(tempJetKin.parent,restboost);
       tempJetKin.q = ShowerHardJets[ix]->progenitor()->momentum();
       jetKinematics.push_back(tempJetKin);
     }
     if(partner) ppartner[1]=partner->momentum();
     // calculate the rescaling parameters
     double k1,k2;
     Lorentz5Momentum qt;
     if(!solveDecayKFactor(initial->progenitor()->mass(),nvect,pjet,
 			  jetKinematics,partner,ppartner,k1,k2,qt)) {
       for(map<tPPtr,vector<LorentzRotation> >::const_iterator bit=_boosts.begin();bit!=_boosts.end();++bit) {
 	for(vector<LorentzRotation>::const_reverse_iterator rit=bit->second.rbegin();rit!=bit->second.rend();++rit) {
 	  LorentzRotation rot = rit->inverse();
 	  bit->first->transform(rot);
 	}
       }
       _boosts.clear();
       for(map<tShowerTreePtr,vector<LorentzRotation> >::const_iterator bit=_treeBoosts.begin();bit!=_treeBoosts.end();++bit) {
 	for(vector<LorentzRotation>::const_reverse_iterator rit=bit->second.rbegin();rit!=bit->second.rend();++rit) {
 	  LorentzRotation rot = rit->inverse();
 	  bit->first->transform(rot,false);
 	}
       }
       _treeBoosts.clear();
       _currentTree = tShowerTreePtr();
       return false;
     }
     // apply boosts and rescalings to final-state jets
     for(JetKinVect::iterator it = jetKinematics.begin(); 
 	it != jetKinematics.end(); ++it) {
       LorentzRotation Trafo = LorentzRotation(); 
       if(it->parent!=partner) {
 	// boost for rescaling
 	if(atLeastOnce) {
 	  map<tShowerTreePtr,pair<tShowerProgenitorPtr,
 	    tShowerParticlePtr> >::const_iterator tit;
 	  for(tit  = _currentTree->treelinks().begin();
 	      tit != _currentTree->treelinks().end();++tit) {
 	    if(tit->second.first && tit->second.second==it->parent)
 	      break;
 	  }
 	  if(it->parent->children().empty()&&!it->parent->spinInfo() &&
 	     tit==_currentTree->treelinks().end()) {
 	    Lorentz5Momentum pnew(k2*it->p.vect(),
 				  sqrt(sqr(k2*it->p.vect().mag())+it->q.mass2()),
 				  it->q.mass());
 	    it->parent->set5Momentum(pnew);
 	  }
 	  else {
 	    // rescaling boost can't ever work in this case
 	    if(k2<0. && it->q.mass()==ZERO)
 	      throw KinematicsReconstructionVeto();
 	    Trafo = solveBoost(k2, it->q, it->p);
 	  }
 	}
 	if(gottaBoost)  Trafo.boost(-boosttorest,gammarest);
 	if(atLeastOnce || gottaBoost) deepTransform(it->parent,Trafo);
       }
       else {
 	Lorentz5Momentum pnew=ppartner[0];
 	pnew *=k1;
 	pnew-=qt;
 	pnew.setMass(ppartner[1].mass());
 	pnew.rescaleEnergy();
 	LorentzRotation Trafo=solveBoost(1.,ppartner[1],pnew);
 	if(gottaBoost) Trafo.boost(-boosttorest,gammarest);
 	deepTransform(partner,Trafo);
       }
     }
   }
   catch(KinematicsReconstructionVeto) {
     for(map<tPPtr,vector<LorentzRotation> >::const_iterator bit=_boosts.begin();bit!=_boosts.end();++bit) {
       for(vector<LorentzRotation>::const_reverse_iterator rit=bit->second.rbegin();rit!=bit->second.rend();++rit) {
 	LorentzRotation rot = rit->inverse();
 	bit->first->transform(rot);
       }
     }
     _boosts.clear();
     for(map<tShowerTreePtr,vector<LorentzRotation> >::const_iterator bit=_treeBoosts.begin();bit!=_treeBoosts.end();++bit) {
       for(vector<LorentzRotation>::const_reverse_iterator rit=bit->second.rbegin();rit!=bit->second.rend();++rit) {
 	LorentzRotation rot = rit->inverse();
 	bit->first->transform(rot,false);
       }
     }
     _treeBoosts.clear();
     _currentTree = tShowerTreePtr();
     return false;
   }
   catch (Exception & ex) {
     _currentTree = tShowerTreePtr();
     _boosts.clear();
     _treeBoosts.clear();
     throw ex;
   }
   _boosts.clear();
   _treeBoosts.clear();
   _currentTree = tShowerTreePtr();
   return true;
 }
 
 bool KinematicsReconstructor::
 reconstructDecayJet( const tShowerParticlePtr p) const {
   if(p->children().empty()) return false;
   tShowerParticlePtr child;
   // if branching reconstruct time-like child
   child = dynamic_ptr_cast<ShowerParticlePtr>(p->children()[1]);
   if(child) {
     _progenitor=child;
     reconstructTimeLikeJet(child);
     // calculate the momentum of the particle
     Lorentz5Momentum pnew=p->momentum()-child->momentum();
     pnew.rescaleMass();
     p->children()[0]->set5Momentum(pnew);
     child=dynamic_ptr_cast<ShowerParticlePtr>(p->children()[0]);
     reconstructDecayJet(child);
     return true;
   }
   return false;
 }
 
 bool KinematicsReconstructor::
 solveDecayKFactor(Energy mb, 
 		  const Lorentz5Momentum & n, 
 		  const Lorentz5Momentum & pjet, 
 		  const JetKinVect & jetKinematics, 
 		  ShowerParticlePtr partner, 
 		  Lorentz5Momentum ppartner[2],
 		  double & k1, double & k2,
 		  Lorentz5Momentum & qt) const {
   Energy2 pjn  = partner ? pjet.vect()*n.vect()        : ZERO;
   Energy2 pcn  = partner ? ppartner[0].vect()*n.vect() : 1.*MeV2;
   Energy2 nmag = n.vect().mag2();
   Lorentz5Momentum pn = partner ? (pjn/nmag)*n : Lorentz5Momentum();
   qt=pjet-pn; qt.setE(ZERO);
   Energy2 pt2=qt.vect().mag2();
   Energy  Ejet = pjet.e();
   // magnitudes of the momenta for fast access
   vector<Energy2> pmag;
   Energy total(Ejet);
   for(unsigned int ix=0;ix<jetKinematics.size();++ix) {
     pmag.push_back(jetKinematics[ix].p.vect().mag2());
     total+=jetKinematics[ix].q.mass();
   }
   // return if no possible solution
   if(total>mb) return false;
   Energy2 pcmag=ppartner[0].vect().mag2();
   // used newton-raphson to get the rescaling
   static const Energy eps=1e-8*GeV;
   long double d1(1.),d2(1.);
   Energy roots, ea, ec, ds;
   unsigned int ix=0;
   do {
     ++ix;
     d2    = d1 + pjn/pcn;
     roots = Ejet;
     ds    = ZERO;
     for(unsigned int iy=0;iy<jetKinematics.size();++iy) {
       if(jetKinematics[iy].parent==partner) continue;
       ea = sqrt(sqr(d2)*pmag[iy]+jetKinematics[iy].q.mass2());
       roots += ea;
       ds    += d2/ea*pmag[iy];
     }
     if(partner) {
       ec = sqrt(sqr(d1)*pcmag + pt2 + ppartner[1].mass2());
       roots += ec;
       ds    += d1/ec*pcmag;
     }
     d1    += (mb-roots)/ds;
     d2     = d1 + pjn/pcn;
   }
   while(abs(mb-roots)>eps && ix<100);
   k1=d1;
   k2=d2;
   // return true if N-R succeed, otherwise false
   return ix<100;
 }
 
 bool KinematicsReconstructor::
 deconstructDecayJets(HardTreePtr decay,ShowerInteraction) const {
   // extract the momenta of the particles
   vector<Lorentz5Momentum> pin;
   vector<Lorentz5Momentum> pout;
   // on-shell masses of the decay products
   vector<Energy> mon;
   Energy mbar(-GeV);
   // the hard branchings of the particles
   set<HardBranchingPtr>::iterator cit;
   set<HardBranchingPtr> branchings=decay->branchings();
   // properties of the incoming particle
   bool ISR = false;
   HardBranchingPtr initial;
   Lorentz5Momentum qisr;
   // find the incoming particle, both before and after
   // any ISR
   for(cit=branchings.begin();cit!=branchings.end();++cit){
     if((*cit)->status()==HardBranching::Incoming||
        (*cit)->status()==HardBranching::Decay) {
       // search back up isr if needed
       HardBranchingPtr branch = *cit;
       while(branch->parent()) branch=branch->parent();
       initial=branch;
       // momentum or original parent
       pin.push_back(branch->branchingParticle()->momentum());
       // ISR?
       ISR = !branch->branchingParticle()->children().empty();
       // ISR momentum
       qisr = pin.back()-(**cit).branchingParticle()->momentum();
       qisr.rescaleMass();
     }
   }
   assert(pin.size()==1);
   // compute boost to rest frame
   Boost boostv=-pin[0].boostVector();
   // partner for ISR
   ShowerParticlePtr partner;
   Lorentz5Momentum  ppartner;
   if(initial->branchingParticle()->partner()) {
     partner=initial->branchingParticle()->partner();
     ppartner=partner->momentum();
   }
   // momentum of the decay products
   for(cit=branchings.begin();cit!=branchings.end();++cit) {
     if((*cit)->status()!=HardBranching::Outgoing) continue;
     // find the mass of the particle
     // including special treatment for off-shell resonances
     // to preserve off-shell mass
     Energy mass;
     if(!(**cit).branchingParticle()->dataPtr()->stable()) {
       HardBranchingPtr branch=*cit;
       while(!branch->children().empty()) {
 	for(unsigned int ix=0;ix<branch->children().size();++ix) {
 	  if(branch->children()[ix]->branchingParticle()->id()==
 	     (**cit).branchingParticle()->id()) {
 	    branch = branch->children()[ix];
 	    continue;
 	  }
 	}
       };
       mass = branch->branchingParticle()->mass();
     }
     else {
       mass = (**cit).branchingParticle()->dataPtr()->mass();
     }
     // if not evolution partner of decaying particle
     if((*cit)->branchingParticle()!=partner) {
       pout.push_back((*cit)->branchingParticle()->momentum());
       mon.push_back(mass);
     }
     // evolution partner of decaying particle
     else {
       mbar = mass;
     }
   }
   // boost all the momenta to the rest frame of the decaying particle
   for(unsigned int ix=0;ix<pout.size();++ix) pout[ix].boost(boostv);
   if(initial->branchingParticle()->partner()) {
     ppartner.boost(boostv);
     qisr.boost(boostv);
   }
   // compute the rescaling factors
   double k1,k2;
   if(!ISR) {
     if(partner) {
       pout.push_back(ppartner);
       mon.push_back(mbar);
     }
     k1=k2=inverseRescalingFactor(pout,mon,pin[0].mass());
     if(partner) {
       pout.pop_back();
       mon.pop_back();
     }
   }
   else {
     if(!inverseDecayRescalingFactor(pout,mon,pin[0].mass(),
 				    ppartner,mbar,k1,k2)) return false;
   }
   // now calculate the p reference vectors 
   unsigned int ifinal=0;
   for(cit=branchings.begin();cit!=branchings.end();++cit) {
     if((**cit).status()!=HardBranching::Outgoing) continue;
     // for partners other than colour partner of decaying particle
     if((*cit)->branchingParticle()!=partner) {
       Lorentz5Momentum pvect = (*cit)->branchingParticle()->momentum();
       pvect.boost(boostv);
       pvect /= k1;
       pvect.setMass(mon[ifinal]);
       ++ifinal;
       pvect.rescaleEnergy();
       pvect.boost(-boostv);
       (*cit)->pVector(pvect);
       (*cit)->showerMomentum(pvect);
     }
     // for colour partner of decaying particle
     else {
       Lorentz5Momentum pvect = (*cit)->branchingParticle()->momentum();
       pvect.boost(boostv);
       Lorentz5Momentum qtotal;
       for(unsigned int ix=0;ix<pout.size();++ix) qtotal+=pout[ix];
       Lorentz5Momentum qperp = 
 	qisr-(qisr.vect()*qtotal.vect())/(qtotal.vect().mag2())*qtotal;
       pvect +=qperp;
       pvect /=k2;
       pvect.setMass(mbar);
       pvect.rescaleEnergy();
       pvect.boost(-boostv);
       (*cit)->pVector(pvect);
       (*cit)->showerMomentum(pvect);
     }
   }
   // For initial-state if needed
   if(initial) {
     tShowerParticlePtr newPartner=initial->branchingParticle()->partner();
     if(newPartner) {
       tHardBranchingPtr branch;
       for( set<HardBranchingPtr>::iterator clt = branchings.begin();
 	   clt != branchings.end(); ++clt ) {
 	if((**clt).branchingParticle()==newPartner) {
 	  initial->colourPartner(*clt);
 	  branch=*clt;
 	  break;
 	}
       }
       Lorentz5Momentum pvect = initial->branchingParticle()->momentum();
       initial->pVector(pvect);
       Lorentz5Momentum ptemp = branch->pVector();
       ptemp.boost(boostv);
       Lorentz5Momentum nvect = Lorentz5Momentum( ZERO,
 						 0.5*initial->branchingParticle()->mass()*
 						 ptemp.vect().unit());
       nvect.boost(-boostv);
       initial->nVector(nvect);
     }
   }
   // calculate the reference vectors, then for outgoing particles
   for(cit=branchings.begin();cit!=branchings.end();++cit){
     if((**cit).status()!=HardBranching::Outgoing) continue;
     // find the partner branchings
     tShowerParticlePtr newPartner=(*cit)->branchingParticle()->partner();
     if(!newPartner) continue;
     tHardBranchingPtr branch;
     for( set<HardBranchingPtr>::iterator clt = branchings.begin();
 	 clt != branchings.end(); ++clt ) {
       if(cit==clt) continue;
       if((**clt).branchingParticle()==newPartner) {
 	(**cit).colourPartner(*clt);
  	branch=*clt;
 	break;
       }
     }
     if((**decay->incoming().begin()).branchingParticle()==newPartner) {
       (**cit).colourPartner(*decay->incoming().begin());
       branch = *decay->incoming().begin();
     }
     // final-state colour partner
     if(branch->status()==HardBranching::Outgoing) {
       Boost boost=((*cit)->pVector()+branch->pVector()).findBoostToCM();
       Lorentz5Momentum pcm = branch->pVector();
       pcm.boost(boost);
       Lorentz5Momentum nvect = Lorentz5Momentum(ZERO,pcm.vect());
       nvect.boost( -boost);
       (*cit)->nVector(nvect);
     }
     // initial-state colour partner
     else {
       Boost boost=branch->pVector().findBoostToCM();
       Lorentz5Momentum pcm = (*cit)->pVector();
       pcm.boost(boost);
       Lorentz5Momentum nvect = Lorentz5Momentum( ZERO, -pcm.vect());
       nvect.boost( -boost);
       (*cit)->nVector(nvect);
     }
   }
   // now compute the new momenta 
   // and calculate the shower variables
   for(cit=branchings.begin();cit!=branchings.end();++cit) {
     if((**cit).status()!=HardBranching::Outgoing) continue;
     LorentzRotation B=LorentzRotation(-boostv);
     LorentzRotation A=LorentzRotation(boostv),R;
     if((*cit)->branchingParticle()==partner) {
       Lorentz5Momentum qnew;
       Energy2 dot=(*cit)->pVector()*(*cit)->nVector();
       double beta = 0.5*((*cit)->branchingParticle()->momentum().m2()
 			 -sqr((*cit)->pVector().mass()))/dot;
       qnew=(*cit)->pVector()+beta*(*cit)->nVector();
       qnew.rescaleMass();
       // compute the boost
       R=B*solveBoost(A*qnew,A*(*cit)->branchingParticle()->momentum())*A;
     }
     else {
       Lorentz5Momentum qnew;
       if((*cit)->branchingParticle()->partner()) {
 	Energy2 dot=(*cit)->pVector()*(*cit)->nVector();
 	double beta = 0.5*((*cit)->branchingParticle()->momentum().m2()
 			   -sqr((*cit)->pVector().mass()))/dot;
 	qnew=(*cit)->pVector()+beta*(*cit)->nVector();
 	qnew.rescaleMass();
       }
       else {
 	qnew = (*cit)->pVector();
       }
       // compute the boost
       R=B*solveBoost(A*qnew,A*(*cit)->branchingParticle()->momentum())*A;
     }
     // reconstruct the momenta
     (*cit)->setMomenta(R,1.0,Lorentz5Momentum());
   }
   if(initial) {
     initial->setMomenta(LorentzRotation(),1.0,Lorentz5Momentum());
   }
   return true;
 }
 
 double KinematicsReconstructor::
 inverseRescalingFactor(vector<Lorentz5Momentum> pout,
 		       vector<Energy> mon, Energy roots) const {
   double lambda=1.;
   if(pout.size()==2) { 
     double mu_q1(pout[0].m()/roots), mu_q2(pout[1].m()/roots);
     double mu_p1(mon[0]/roots)     , mu_p2(mon[1]/roots);
     lambda = 
       ((1.+mu_q1+mu_q2)*(1.-mu_q1-mu_q2)*(mu_q1-1.-mu_q2)*(mu_q2-1.-mu_q1))/
       ((1.+mu_p1+mu_p2)*(1.-mu_p1-mu_p2)*(mu_p1-1.-mu_p2)*(mu_p2-1.-mu_p1));
     if(lambda<0.)
       throw Exception() << "Rescaling factor is imaginary in  KinematicsReconstructor::"
 			<< "inverseRescalingFactor lambda^2= " << lambda
 			<< Exception::eventerror;
     lambda = sqrt(lambda);
   }
   else {
     unsigned int ntry=0;
     // compute magnitudes once for speed
     vector<Energy2> pmag;
     for(unsigned int ix=0;ix<pout.size();++ix) {
       pmag.push_back(pout[ix].vect().mag2());
     }
     // Newton-Raphson for the rescaling
     vector<Energy> root(pout.size());
     do {
       // compute new energies
       Energy sum(ZERO);
       for(unsigned int ix=0;ix<pout.size();++ix) {
 	root[ix] = sqrt(pmag[ix]/sqr(lambda)+sqr(mon[ix]));
 	sum+=root[ix];
       }
       // if accuracy reached exit
       if(abs(sum/roots-1.)<1e-10) break;
       // use Newton-Raphson to compute new guess for lambda
       Energy numer(ZERO),denom(ZERO);
       for(unsigned int ix=0;ix<pout.size();++ix) {
 	numer +=root[ix];
 	denom +=pmag[ix]/root[ix];
       }
       numer-=roots;
       double fact = 1.+sqr(lambda)*numer/denom;
       if(fact<0.) fact=0.5;
       lambda *=fact;
       ++ntry;
     }
     while(ntry<100);
   }
   if(std::isnan(lambda))
     throw Exception() << "Rescaling factor is nan in  KinematicsReconstructor::"
 		      << "inverseRescalingFactor " 
 		      << Exception::eventerror;
   return lambda;
 }
 
 bool KinematicsReconstructor::
 deconstructGeneralSystem(HardTreePtr tree,
 			 ShowerInteraction type) const {
   // extract incoming and outgoing particles
   ColourSingletShower in,out;
   for(set<HardBranchingPtr>::const_iterator it=tree->branchings().begin();
       it!=tree->branchings().end();++it) {
     if((**it).status()==HardBranching::Incoming) in .jets.push_back(*it);
     else                  out.jets.push_back(*it);
   }
   LorentzRotation toRest,fromRest;
   bool applyBoost(false);
   // do the initial-state reconstruction
   deconstructInitialInitialSystem(applyBoost,toRest,fromRest,
 				  tree,in.jets,type);
   // do the final-state reconstruction
   deconstructFinalStateSystem(toRest,fromRest,tree,
 			      out.jets,type);
   // only at this point that we can be sure all the reference vectors
   // are correct
   for(set<HardBranchingPtr>::const_iterator it=tree->branchings().begin();
       it!=tree->branchings().end();++it) {
     if((**it).status()==HardBranching::Incoming) continue;
     if((**it).branchingParticle()->coloured())
       (**it).setMomenta(LorentzRotation(),1.,Lorentz5Momentum(),false);
   }
   for(set<HardBranchingPtr>::const_iterator it=tree->incoming().begin();
       it!=tree->incoming().end();++it) {
     (**it).setMomenta(LorentzRotation(),1.,Lorentz5Momentum(),false);
   }
   return true;
 }
 
 bool KinematicsReconstructor::deconstructHardJets(HardTreePtr tree,
 					      ShowerInteraction type) const {
   // inverse of old recon method
   if(_reconopt == 0) {
     return deconstructGeneralSystem(tree,type);
   }
   else if(_reconopt == 1) {
     return deconstructColourSinglets(tree,type);
   }
   else if(_reconopt == 2) {
     throw Exception() << "Inverse reconstruction is not currently supported for ReconstructionOption Colour2 "
 		      << "in KinematicsReconstructor::deconstructHardJets(). Please use one of the other options\n"
 		      << Exception::runerror;
   }
   else if(_reconopt == 3 || _reconopt == 4 ) {
     return deconstructColourPartner(tree,type);
   }
   else
     assert(false);
 }
 
 bool KinematicsReconstructor::
 deconstructColourSinglets(HardTreePtr tree,
 			  ShowerInteraction type) const {
   // identify the colour singlet systems
   unsigned int nnun(0),nnii(0),nnif(0),nnf(0),nni(0);
   vector<ColourSingletShower> 
     systems(identifySystems(tree->branchings(),nnun,nnii,nnif,nnf,nni));
   // now decide what to do
   LorentzRotation toRest,fromRest;
   bool applyBoost(false);
   bool general(false);
   // initial-initial connection and final-state colour singlet systems
   // Drell-Yan type
   if(nnun==0&&nnii==1&&nnif==0&&nnf>0&&nni==0) {
     // reconstruct initial-initial system
     for(unsigned int ix=0;ix<systems.size();++ix) {
       if(systems[ix].type==II) 
 	deconstructInitialInitialSystem(applyBoost,toRest,fromRest,tree,
 					systems[ix].jets,type);
     }
     if(type!=ShowerInteraction::QCD) {
       combineFinalState(systems);
       general=false;
     }
   }
   // DIS and VBF type
   else if(nnun==0&&nnii==0&&((nnif==1&&nnf>0&&nni==1)||
 			     (nnif==2&&       nni==0))) {
     for(unsigned int ix=0;ix<systems.size();++ix) {
       if(systems[ix].type==IF)
 	deconstructInitialFinalSystem(tree,systems[ix].jets,type);
     }
   }
   // e+e- type
   else if(nnun==0&&nnii==0&&nnif==0&&nnf>0&&nni==2) {
     // only FS needed
     // but need to boost to rest frame if QED ISR
     Lorentz5Momentum ptotal;
     for(unsigned int ix=0;ix<systems.size();++ix) {
       if(systems[ix].type==I) 
 	ptotal += systems[ix].jets[0]->branchingParticle()->momentum();
     }
     toRest = LorentzRotation(ptotal.findBoostToCM());
     fromRest = toRest;
     fromRest.invert();
     if(type!=ShowerInteraction::QCD) {
       combineFinalState(systems);
       general=false;
     }
   }
   // general type
   else {
     general = true;
   }
   // final-state systems except for general recon
   if(!general) {
     for(unsigned int ix=0;ix<systems.size();++ix) {
       if(systems[ix].type==F)
 	deconstructFinalStateSystem(toRest,fromRest,tree,
 				    systems[ix].jets,type);
     }
     // only at this point that we can be sure all the reference vectors
     // are correct
     for(set<HardBranchingPtr>::const_iterator it=tree->branchings().begin();
 	it!=tree->branchings().end();++it) {
       if((**it).status()==HardBranching::Incoming) continue;
       if((**it).branchingParticle()->coloured())
 	(**it).setMomenta(LorentzRotation(),1.,Lorentz5Momentum(),false);
     }
     for(set<HardBranchingPtr>::const_iterator it=tree->incoming().begin();
 	it!=tree->incoming().end();++it) {
       (**it).setMomenta(LorentzRotation(),1.,Lorentz5Momentum(),false);
     }
     return true;
   }
   else {
     return deconstructGeneralSystem(tree,type);
   }
   return true;
 }
 
 bool KinematicsReconstructor::
 deconstructColourPartner(HardTreePtr tree,
 			 ShowerInteraction type) const {
   Lorentz5Momentum ptotal;
   HardBranchingPtr emitter;
   ColourSingletShower incomingShower,outgoingShower;
   for(set<HardBranchingPtr>::const_iterator it=tree->branchings().begin();
       it!=tree->branchings().end();++it) { 
     if((**it).status()==HardBranching::Incoming) {
       incomingShower.jets.push_back(*it);
       ptotal += (*it)->branchingParticle()->momentum();
       // check for emitting particle
       if((**it).parent() ) {
 	if(!emitter)
 	  emitter = *it;
 	else
 	  throw Exception() << "Only one emitting particle allowed in "
 			    << "KinematicsReconstructor::deconstructColourPartner()"
 			    << Exception::runerror;
       }
     }
     else if ((**it).status()==HardBranching::Outgoing) {
       outgoingShower.jets.push_back(*it);
       // check for emitting particle
       if(!(**it).children().empty() ) {
 	if(!emitter)
 	  emitter = *it;
 	else
 	  throw Exception() << "Only one emitting particle allowed in "
 			    << "KinematicsReconstructor::deconstructColourPartner()"
 			    << Exception::runerror;
       }
     }
   }
   assert(emitter);
   assert(emitter->colourPartner());
   ColourSingletShower system;
   system.jets.push_back(emitter);
   system.jets.push_back(emitter->colourPartner());
   LorentzRotation toRest,fromRest; 
   bool applyBoost(false);
   // identify the colour singlet system
   if(emitter->status()                  == HardBranching::Outgoing &&
      emitter->colourPartner()->status() == HardBranching::Outgoing ) {
     system.type=F;
     // need to boost to rest frame if QED ISR
     if(  !incomingShower.jets[0]->branchingParticle()->coloured() &&
 	 !incomingShower.jets[1]->branchingParticle()->coloured() ) {
       Boost boost = ptotal.findBoostToCM();
       toRest   = LorentzRotation( boost);
       fromRest = LorentzRotation(-boost);
     }
     else
       findInitialBoost(ptotal,ptotal,toRest,fromRest);
     deconstructFinalStateSystem(toRest,fromRest,tree,
 				system.jets,type);
   }
   else if (emitter->status()                  == HardBranching::Incoming &&
 	   emitter->colourPartner()->status() == HardBranching::Incoming) {
     system.type=II;
     deconstructInitialInitialSystem(applyBoost,toRest,fromRest,tree,system.jets,type);
     // make sure the recoil gets applied
     deconstructFinalStateSystem(toRest,fromRest,tree,
 				outgoingShower.jets,type);
   }
   else if ((emitter->status()                  == HardBranching::Outgoing &&
 	    emitter->colourPartner()->status() == HardBranching::Incoming ) || 
 	   (emitter->status()                  == HardBranching::Incoming &&
 	    emitter->colourPartner()->status() == HardBranching::Outgoing)) {
     system.type=IF;
     // enusre incoming first
     if(system.jets[0]->status() == HardBranching::Outgoing)
       swap(system.jets[0],system.jets[1]);
     deconstructInitialFinalSystem(tree,system.jets,type);
   }
   else {
     throw Exception() << "Unknown type of system in "
 		      << "KinematicsReconstructor::deconstructColourPartner()"
 		      << Exception::runerror;
   }
   // only at this point that we can be sure all the reference vectors
   // are correct
   for(set<HardBranchingPtr>::const_iterator it=tree->branchings().begin();
       it!=tree->branchings().end();++it) {
     if((**it).status()==HardBranching::Incoming) continue;
     if((**it).branchingParticle()->coloured())
       (**it).setMomenta(LorentzRotation(),1.,Lorentz5Momentum(),false);
   }
   for(set<HardBranchingPtr>::const_iterator it=tree->incoming().begin();
       it!=tree->incoming().end();++it) {
     (**it).setMomenta(LorentzRotation(),1.,Lorentz5Momentum(),false);
   }
   for(set<HardBranchingPtr>::const_iterator it=tree->branchings().begin();
       it!=tree->branchings().end();++it) {
     if((**it).status()!=HardBranching::Incoming) continue;
     if(*it==system.jets[0] || *it==system.jets[1]) continue;
     if((**it).branchingParticle()->momentum().z()>ZERO) {
       (**it).z((**it).branchingParticle()->momentum().plus()/(**it).beam()->momentum().plus());
     }
     else {
       (**it).z((**it).branchingParticle()->momentum().minus()/(**it).beam()->momentum().minus());
     }
   }
   return true;
 }
 
 void KinematicsReconstructor::
 reconstructInitialFinalSystem(vector<ShowerProgenitorPtr> jets) const {
   Lorentz5Momentum pin[2],pout[2],pbeam;
   for(unsigned int ix=0;ix<jets.size();++ix) {
     // final-state parton
     if(jets[ix]->progenitor()->isFinalState()) {
       pout[0] +=jets[ix]->progenitor()->momentum();
       _progenitor = jets[ix]->progenitor();
       if(jets[ix]->reconstructed()==ShowerProgenitor::notReconstructed) {
 	reconstructTimeLikeJet(jets[ix]->progenitor());
 	jets[ix]->reconstructed(ShowerProgenitor::done);
       }
     }
     // initial-state parton
     else {
       pin[0]  +=jets[ix]->progenitor()->momentum();
       if(jets[ix]->progenitor()->showerKinematics()) {
 	pbeam = jets[ix]->progenitor()->showerBasis()->getBasis()[0];
       }
       else {
 	if ( jets[ix]->original()->parents().empty() ) {
 	  pbeam = jets[ix]->progenitor()->momentum();
 	}
 	else {
 	  pbeam = jets[ix]->original()->parents()[0]->momentum();
 	}
       }
       if(jets[ix]->reconstructed()==ShowerProgenitor::notReconstructed) {
 	reconstructSpaceLikeJet(jets[ix]->progenitor());
 	jets[ix]->reconstructed(ShowerProgenitor::done);
       }
       assert(!jets[ix]->original()->parents().empty());
     }
   }
   // add intrinsic pt if needed
   addIntrinsicPt(jets);
   // momenta after showering
   for(unsigned int ix=0;ix<jets.size();++ix) {
     if(jets[ix]->progenitor()->isFinalState())
       pout[1] += jets[ix]->progenitor()->momentum();
     else
       pin[1]  += jets[ix]->progenitor()->momentum();
   }
   // work out the boost to the Breit frame
   Lorentz5Momentum pa = pout[0]-pin[0];
   Axis axis(pa.vect().unit());
   LorentzRotation rot;
   double sinth(sqrt(sqr(axis.x())+sqr(axis.y())));
   if ( sinth > 1.e-9 )
     rot.setRotate(-acos(axis.z()),Axis(-axis.y()/sinth,axis.x()/sinth,0.));
   rot.rotateX(Constants::pi);
   rot.boostZ( pa.e()/pa.vect().mag());
   Lorentz5Momentum ptemp=rot*pbeam;
   Boost trans = -1./ptemp.e()*ptemp.vect();
   trans.setZ(0.);
   if ( trans.mag2() - 1. >= 0. ) throw KinematicsReconstructionVeto();
   rot.boost(trans);
   pa *=rot;
   // project and calculate rescaling
   // reference vectors
   Lorentz5Momentum n1(ZERO,ZERO,-pa.z(),-pa.z());
   Lorentz5Momentum n2(ZERO,ZERO, pa.z(),-pa.z());
   Energy2 n1n2 = n1*n2;
   // decompose the momenta
   Lorentz5Momentum qbp=rot*pin[1],qcp=rot*pout[1];
   qbp.rescaleMass();
   qcp.rescaleMass();
   double a[2],b[2];
   a[0] = n2*qbp/n1n2;
   b[0] = n1*qbp/n1n2;
   Lorentz5Momentum qperp = qbp-a[0]*n1-b[0]*n2;
   b[1] = 0.5;
   a[1] = 0.5*(qcp.m2()-qperp.m2())/n1n2/b[1];
   double kb;
   if(a[0]!=0.) {
     double A(0.5*a[0]),B(b[0]*a[0]-a[1]*b[1]-0.25),C(-0.5*b[0]);
     if(sqr(B)-4.*A*C<0.) throw KinematicsReconstructionVeto();
     kb = 0.5*(-B+sqrt(sqr(B)-4.*A*C))/A;
   }
   else {
     kb = 0.5*b[0]/(b[0]*a[0]-a[1]*b[1]-0.25);
   }
   // changed to improve stability
   if(kb==0.) throw KinematicsReconstructionVeto();
   if ( a[1]>b[1] && abs(a[1]) < 1e-12 )
     throw KinematicsReconstructionVeto();
   if ( a[1]<=b[1] && abs(0.5+b[0]/kb) < 1e-12 )
     throw KinematicsReconstructionVeto();
   double kc = (a[1]>b[1]) ? (a[0]*kb-0.5)/a[1] : b[1]/(0.5+b[0]/kb);
   if(kc==0.) throw KinematicsReconstructionVeto();
   Lorentz5Momentum pnew[2] = { a[0]*kb*n1+b[0]/kb*n2+qperp,
 			       a[1]*kc*n1+b[1]/kc*n2+qperp};
   LorentzRotation rotinv=rot.inverse();
   for(unsigned int ix=0;ix<jets.size();++ix) {
     if(jets[ix]->progenitor()->isFinalState()) {
       deepTransform(jets[ix]->progenitor(),rot);
       deepTransform(jets[ix]->progenitor(),solveBoost(pnew[1],qcp));
       Energy delta = jets[ix]->progenitor()->momentum().m()-jets[ix]->progenitor()->momentum().mass();
       if ( abs(delta) > MeV ) throw KinematicsReconstructionVeto();
       deepTransform(jets[ix]->progenitor(),rotinv);
     }
     else {
       tPPtr parent;
       boostChain(jets[ix]->progenitor(),rot,parent);
       boostChain(jets[ix]->progenitor(),solveBoostZ(pnew[0],qbp),parent);
       // check the first boost worked, and if not apply small correction to
       // fix energy/momentum conservation
       // this is a kludge but it reduces momentum non-conservation dramatically
       Lorentz5Momentum pdiff = pnew[0]-jets[ix]->progenitor()->momentum();
       Energy2 delta = sqr(pdiff.x())+sqr(pdiff.y())+sqr(pdiff.z())+sqr(pdiff.t());
       unsigned int ntry=0;
       while(delta>1e-6*GeV2 && ntry<5 ) {
 	ntry +=1;
 	boostChain(jets[ix]->progenitor(),solveBoostZ(pnew[0],jets[ix]->progenitor()->momentum()),parent);
 	pdiff = pnew[0]-jets[ix]->progenitor()->momentum();
 	delta = sqr(pdiff.x())+sqr(pdiff.y())+sqr(pdiff.z())+sqr(pdiff.t());
       }
       // apply test in breit-frame
       Lorentz5Momentum ptest1 = parent->momentum();
       Lorentz5Momentum ptest2 = rot*pbeam;
       if(ptest1.z()/ptest2.z()<0. || ptest1.z()/ptest2.z()>1.)
       	throw KinematicsReconstructionVeto();
       boostChain(jets[ix]->progenitor(),rotinv,parent);
     }
   }
 }
 
 bool KinematicsReconstructor::addIntrinsicPt(vector<ShowerProgenitorPtr> jets) const {
   bool added=false;
   // add the intrinsic pt if needed
   for(unsigned int ix=0;ix<jets.size();++ix) {
     // only for initial-state particles which haven't radiated
     if(jets[ix]->progenitor()->isFinalState()||
        jets[ix]->hasEmitted()||
        jets[ix]->reconstructed()==ShowerProgenitor::dontReconstruct) continue;
     if(_intrinsic.find(jets[ix])==_intrinsic.end()) continue;
     pair<Energy,double> pt=_intrinsic[jets[ix]];
     Energy etemp = jets[ix]->original()->parents()[0]->momentum().z();
     Lorentz5Momentum 
       p_basis(ZERO, ZERO, etemp, abs(etemp)),
       n_basis(ZERO, ZERO,-etemp, abs(etemp));
     double alpha = jets[ix]->progenitor()->x();
     double beta  = 0.5*(sqr(jets[ix]->progenitor()->data().mass())+
 			sqr(pt.first))/alpha/(p_basis*n_basis);
     Lorentz5Momentum pnew=alpha*p_basis+beta*n_basis;
     pnew.setX(pt.first*cos(pt.second));
     pnew.setY(pt.first*sin(pt.second));
     pnew.rescaleMass();
     jets[ix]->progenitor()->set5Momentum(pnew);
     added = true;
   }
   return added;
 }
 
 namespace {
 
 double defaultSolveBoostGamma(const double & betam,const Energy2 & kps,
 			      const Energy2 & qs, const Energy2 & Q2,
 			      const Energy & kp,
 			      const Energy & q, const Energy & qE) {
   if(betam<0.5) {
     return 1./sqrt(1.-sqr(betam));
   }
   else {
     return ( kps+ qs + Q2)/
       sqrt(2.*kps*qs + kps*Q2 + qs*Q2 + sqr(Q2) + 2.*q*qE*kp*sqrt(kps + Q2));
   }
 }
 
 }
 
 LorentzRotation KinematicsReconstructor::
 solveBoost(const double k, const Lorentz5Momentum & newq, 
 	   const Lorentz5Momentum & oldp ) const {
   Energy q = newq.vect().mag(); 
   Energy2 qs = sqr(q); 
   Energy2 Q2 = newq.mass2();
   Energy kp = k*(oldp.vect().mag()); 
   Energy2 kps = sqr(kp);
   double betam = (q*newq.e() - kp*sqrt(kps + Q2))/(kps + qs + Q2); 
   if ( abs(betam) - 1. >= 0. ) throw KinematicsReconstructionVeto();
   Boost beta = -betam*(k/kp)*oldp.vect();
   double gamma = 0.;
   if(Q2/sqr(oldp.e())>1e-4) {
     gamma = defaultSolveBoostGamma(betam,kps,qs,Q2,kp,q,newq.e());
   }
   else {
     if(k>0) {
       gamma = 4.*kps*qs/sqr(kps +qs)  + 2.*sqr(kps-qs)*Q2/pow<3,1>(kps +qs) 
   	- 0.25*( sqr(kps) + 14.*kps*qs + sqr(qs))*sqr(kps-qs)/(pow<4,1>(kps +qs)*kps*qs)*sqr(Q2);
     }
     else { 
       gamma = 0.25*sqr(Q2)/(kps*qs)*(1. - 0.5*(kps+qs)/(kps*qs)*Q2);
     }
     if(gamma<=0.) throw KinematicsReconstructionVeto();
     gamma = 1./sqrt(gamma);
     if(gamma>2.) gamma = defaultSolveBoostGamma(betam,kps,qs,Q2,kp,q,newq.e());
   }
   // note that (k/kp)*oldp.vect() = oldp.vect()/oldp.vect().mag() but cheaper.
   ThreeVector<Energy2> ax = newq.vect().cross( oldp.vect() );
   double delta;
   if (newq.x()*oldp.x()+newq.y()*oldp.y()+newq.z()*oldp.z()< 1e-16*GeV2) {
     throw KinematicsReconstructionVeto();
   }else{
     delta = newq.vect().angle( oldp.vect() );
   }
   
   
   LorentzRotation R;
   using Constants::pi;
   Energy2 scale1 = sqr(newq.x())+ sqr(newq.y())+sqr(newq.z());
   Energy2 scale2 = sqr(oldp.x())+ sqr(oldp.y())+sqr(oldp.z());
   if ( ax.mag2()/scale1/scale2 > 1e-28 ) {
     R.rotate( delta, unitVector(ax) ).boost( beta , gamma );
   } 
   else if(abs(delta-pi)/pi < 0.001) {
     double phi=2.*pi*UseRandom::rnd();
     Axis axis(cos(phi),sin(phi),0.);
     axis.rotateUz(newq.vect().unit());
     R.rotate(delta,axis).boost( beta , gamma );
   }
   else {
     R.boost( beta , gamma );
   }
   return R;
 }
 
 LorentzRotation KinematicsReconstructor::solveBoost(const Lorentz5Momentum & q, 
 						const Lorentz5Momentum & p ) const {
   Energy modp = p.vect().mag();
   Energy modq = q.vect().mag();
   double betam = (p.e()*modp-q.e()*modq)/(sqr(modq)+sqr(modp)+p.mass2());
   if ( abs(betam)-1. >= 0. ) throw KinematicsReconstructionVeto();
   Boost beta = -betam*q.vect().unit();
   ThreeVector<Energy2> ax = p.vect().cross( q.vect() ); 
   double delta = p.vect().angle( q.vect() );
   LorentzRotation R;
   using Constants::pi;
   if ( beta.mag2() - 1. >= 0. ) throw KinematicsReconstructionVeto();
   if ( ax.mag2()/GeV2/MeV2 > 1e-16 ) {
     R.rotate( delta, unitVector(ax) ).boost( beta );
   } 
   else {
     R.boost( beta );
   } 
   return R;
 }
 
 LorentzRotation KinematicsReconstructor::solveBoostZ(const Lorentz5Momentum & q, 
 						 const Lorentz5Momentum & p ) const {
   static const double eps = 1e-6;
   LorentzRotation R;
   double beta;
   Energy2 mt2  = p.mass()<ZERO ? -sqr(p.mass())+sqr(p.x())+sqr(p.y()) : sqr(p.mass())+sqr(p.x())+sqr(p.y())  ;
   double ratio = mt2/(sqr(p.t())+sqr(q.t()));
   if(abs(ratio)>eps) {
     double erat  = (q.t()+q.z())/(p.t()+p.z());
     Energy2 den = mt2*(erat+1./erat);
     Energy2 num = (q.z()-p.z())*(q.t()+p.t()) + (p.z()+q.z())*(p.t()-q.t());
     beta = num/den;
     if ( abs(beta) - 1. >= 0. ) throw KinematicsReconstructionVeto();
     R.boostZ(beta);
   }
   else {
     double er = sqr(p.t()/q.t());
     double x = ratio+0.125*(er+10.+1./er)*sqr(ratio);
     beta = -(p.t()-q.t())*(p.t()+q.t())/(sqr(p.t())+sqr(q.t()))*(1.+x);
     double gamma = (4.*sqr(p.t()*q.t()) +sqr(p.t()-q.t())*sqr(p.t()+q.t())*
 		    (-2.*x+sqr(x)))/sqr(sqr(p.t())+sqr(q.t()));
     if ( abs(beta) - 1. >= 0. ) throw KinematicsReconstructionVeto();
     gamma  = 1./sqrt(gamma);
     R.boost(0.,0.,beta,gamma);
   }
   Lorentz5Momentum ptest = R*p;
   if(ptest.z()/q.z() < 0. || ptest.t()/q.t() < 0. ) {
     throw KinematicsReconstructionVeto();
   }
   return R;
 }
 
 void KinematicsReconstructor::
 reconstructFinalStateSystem(bool applyBoost, 
 			    const LorentzRotation &   toRest,
 			    const LorentzRotation & fromRest, 
 			    vector<ShowerProgenitorPtr> jets) const {
   LorentzRotation trans = applyBoost? toRest : LorentzRotation();
   // special for case of individual particle
   if(jets.size()==1) {
     deepTransform(jets[0]->progenitor(),trans);
     deepTransform(jets[0]->progenitor(),fromRest);
     return;
   }
   bool radiated(false);
   // find the hard process centre-of-mass energy
   Lorentz5Momentum pcm;
   // check if radiated and calculate total momentum
   for(unsigned int ix=0;ix<jets.size();++ix) {
     radiated |=jets[ix]->hasEmitted();
     pcm += jets[ix]->progenitor()->momentum();
   }
   if(applyBoost) pcm *= trans;
   // check if in CMF frame
   Boost beta_cm = pcm.findBoostToCM();
   bool gottaBoost(false);
   if(beta_cm.mag() > 1e-12) {
     gottaBoost = true;
     trans.boost(beta_cm);
   }
   // collection of pointers to initial hard particle and jet momenta
   // for final boosts
   JetKinVect jetKinematics;
   vector<ShowerProgenitorPtr>::const_iterator cit;
   for(cit = jets.begin(); cit != jets.end(); cit++) {
     JetKinStruct tempJetKin;      
     tempJetKin.parent = (*cit)->progenitor();
     if(applyBoost || gottaBoost) {
       deepTransform(tempJetKin.parent,trans);
     }
     tempJetKin.p = (*cit)->progenitor()->momentum();
     _progenitor=tempJetKin.parent;
     if((**cit).reconstructed()==ShowerProgenitor::notReconstructed) {
       radiated |= reconstructTimeLikeJet((*cit)->progenitor());
       (**cit).reconstructed(ShowerProgenitor::done);
     }
     else {
       radiated |= !(*cit)->progenitor()->children().empty();
     }
     tempJetKin.q = (*cit)->progenitor()->momentum();
     jetKinematics.push_back(tempJetKin);
   }
+  if(_finalFinalWeight && jetKinematics.size()==2) {
+    Energy m1 = jetKinematics[0].q.m();
+    Energy m2 = jetKinematics[1].q.m();
+    Energy m0 = pcm.m();
+    if(m0<m1+m2)  throw KinematicsReconstructionVeto();
+    Energy4 lambdaNew = (sqr(m0)-sqr(m1-m2))*(sqr(m0)-sqr(m1+m2));
+    m1 = jetKinematics[0].p.m();
+    m2 = jetKinematics[1].p.m();
+    Energy4 lambdaOld = (sqr(m0)-sqr(m1-m2))*(sqr(m0)-sqr(m1+m2));
+    if(UseRandom::rnd()>sqrt(lambdaNew/lambdaOld))
+      throw KinematicsReconstructionVeto();
+  }
   // default option rescale everything with the same factor
-  if( _finalStateReconOption == 0 || jetKinematics.size() <= 2 ) {
-    // find the rescaling factor
-    double k = 0.0;
-    if(radiated) {
-      k = solveKfactor(pcm.m(), jetKinematics);
-      // perform the rescaling and boosts
-      for(JetKinVect::iterator it = jetKinematics.begin();
-	  it != jetKinematics.end(); ++it) {
-	LorentzRotation Trafo = solveBoost(k, it->q, it->p);
-	deepTransform(it->parent,Trafo);
-      }
+  // find the rescaling factor
+  double k = 0.0;
+  if(radiated) {
+    k = solveKfactor(pcm.m(), jetKinematics);
+    // perform the rescaling and boosts
+    for(JetKinVect::iterator it = jetKinematics.begin();
+	it != jetKinematics.end(); ++it) {
+      LorentzRotation Trafo = solveBoost(k, it->q, it->p);
+      deepTransform(it->parent,Trafo);
     }
   }
-  // different treatment of most off-shell
-  else if ( _finalStateReconOption <= 4 ) {
-    // sort the jets by virtuality
-    std::sort(jetKinematics.begin(),jetKinematics.end(),JetOrdering());
-    // Bryan's procedures from FORTRAN
-    if( _finalStateReconOption <=2 ) {
-      // loop over the off-shell partons,  _finalStateReconOption==1 only first ==2 all
-      JetKinVect::const_iterator jend = _finalStateReconOption==1 ? jetKinematics.begin()+1 : jetKinematics.end();
-      for(JetKinVect::const_iterator jit=jetKinematics.begin(); jit!=jend;++jit) {
-	// calculate the 4-momentum of the recoiling system
-	Lorentz5Momentum psum;
-	bool done = true;
-	for(JetKinVect::const_iterator it=jetKinematics.begin();it!=jetKinematics.end();++it) {
-	  if(it==jit) {
-	    done = false;
-	    continue;
-	  }
-	  // first option put on-shell and sum 4-momenta
-	  if( _finalStateReconOption == 1 ) {
-	    LorentzRotation Trafo = solveBoost(1., it->q, it->p);
-	    deepTransform(it->parent,Trafo);
-	    psum += it->parent->momentum();
-	  }
-	  // second option, sum momenta
-	  else {
-	    // already rescaled
-	    if(done) psum += it->parent->momentum();
-	    // still needs to be rescaled
-	    else psum += it->p;
-	  }
-	}
-	// set the mass
-	psum.rescaleMass();
-	// calculate the 3-momentum rescaling factor
-	Energy2 s(pcm.m2());
-	Energy2 m1sq(jit->q.m2()),m2sq(psum.m2());
-	Energy4 num = sqr(s - m1sq - m2sq) - 4.*m1sq*m2sq;
-	if(num<ZERO) throw KinematicsReconstructionVeto();
-	double k = sqrt( num / (4.*s*jit->p.vect().mag2()) );
-	// boost the off-shell parton
-	LorentzRotation B1 = solveBoost(k, jit->q, jit->p);
-	deepTransform(jit->parent,B1);
-	// boost everything else to rescale
-	LorentzRotation B2 = solveBoost(k, psum, psum);
-	for(JetKinVect::iterator it=jetKinematics.begin();it!=jetKinematics.end();++it) {
-	  if(it==jit) continue;
-	  deepTransform(it->parent,B2);
-	  it->p *= B2;
-	  it->q *= B2;
-	}
-      }
-    }
-    // Peter's C++ procedures
-    else {
-      reconstructFinalFinalOffShell(jetKinematics,pcm.m2(), _finalStateReconOption == 4);
-    }
-  }
-  else
-    assert(false);
   // apply the final boosts
   if(gottaBoost || applyBoost) { 
     LorentzRotation finalBoosts;
     if(gottaBoost) finalBoosts.boost(-beta_cm);
     if(applyBoost) finalBoosts.transform(fromRest);
     for(JetKinVect::iterator it = jetKinematics.begin();
 	it != jetKinematics.end(); ++it) {
       deepTransform(it->parent,finalBoosts);
     }
   }
 }
 
 void KinematicsReconstructor::
 reconstructInitialInitialSystem(bool & applyBoost, 
 				LorentzRotation &   toRest, 
 				LorentzRotation & fromRest,  
 				vector<ShowerProgenitorPtr> jets) const {
   bool radiated = false;
   Lorentz5Momentum pcm;
   // check whether particles radiated and calculate total momentum
   for( unsigned int ix = 0; ix < jets.size(); ++ix ) {
     radiated |= jets[ix]->hasEmitted();
     pcm += jets[ix]->progenitor()->momentum();
     if(jets[ix]->original()->parents().empty()) return;
   }
   pcm.rescaleMass();
   // check if intrinsic pt to be added
   radiated |= !_intrinsic.empty();
   // if no radiation return
   if(!radiated) {
     for(unsigned int ix=0;ix<jets.size();++ix) {
       if(jets[ix]->reconstructed()==ShowerProgenitor::notReconstructed)
 	jets[ix]->reconstructed(ShowerProgenitor::done);
     }
     return;
   }
   // initial state shuffling
   applyBoost=false;
   vector<Lorentz5Momentum> p, pq, p_in;
   vector<Energy> pts;
   for(unsigned int ix=0;ix<jets.size();++ix) {
     // add momentum to vector
     p_in.push_back(jets[ix]->progenitor()->momentum());
     // reconstruct the jet
     if(jets[ix]->reconstructed()==ShowerProgenitor::notReconstructed) {
       radiated |= reconstructSpaceLikeJet(jets[ix]->progenitor());
       jets[ix]->reconstructed(ShowerProgenitor::done);
     }
     assert(!jets[ix]->original()->parents().empty());
     Energy etemp = jets[ix]->original()->parents()[0]->momentum().z();
     Lorentz5Momentum ptemp = Lorentz5Momentum(ZERO, ZERO, etemp, abs(etemp));
     pq.push_back(ptemp);
     pts.push_back(jets[ix]->highestpT());
   }
   // add the intrinsic pt if needed
   radiated |=addIntrinsicPt(jets);
   for(unsigned int ix=0;ix<jets.size();++ix) {
     p.push_back(jets[ix]->progenitor()->momentum());
   }
   double x1 = p_in[0].z()/pq[0].z();
   double x2 = p_in[1].z()/pq[1].z();
   vector<double> beta=initialStateRescaling(x1,x2,p_in[0]+p_in[1],p,pq,pts);
   // if not need don't apply boosts
   if(!(radiated && p.size() == 2 && pq.size() == 2)) return;
   applyBoost=true;
   // apply the boosts
   Lorentz5Momentum newcmf;
   for(unsigned int ix=0;ix<jets.size();++ix) {
     tPPtr toBoost = jets[ix]->progenitor();
     Boost betaboost(0, 0, beta[ix]);
     tPPtr parent;
     boostChain(toBoost, LorentzRotation(0.,0.,beta[ix]),parent);
     if(parent->momentum().e()/pq[ix].e()>1.||
        parent->momentum().z()/pq[ix].z()>1.) throw KinematicsReconstructionVeto();
     newcmf+=toBoost->momentum();
   }
   if(newcmf.m()<ZERO||newcmf.e()<ZERO) throw KinematicsReconstructionVeto();
   findInitialBoost(pcm,newcmf,toRest,fromRest);
 }
 
 void KinematicsReconstructor::
 deconstructInitialInitialSystem(bool & applyBoost,
 				LorentzRotation & toRest,
 				LorentzRotation & fromRest,
 				HardTreePtr tree,
 				vector<HardBranchingPtr> jets,
 				ShowerInteraction) const {
   assert(jets.size()==2);
   // put beam with +z first
   if(jets[0]->beam()->momentum().z()<ZERO) swap(jets[0],jets[1]);
   // get the momenta of the particles
   vector<Lorentz5Momentum> pin,pq;
   for(unsigned int ix=0;ix<jets.size();++ix) {
     pin.push_back(jets[ix]->branchingParticle()->momentum());
     Energy etemp = jets[ix]->beam()->momentum().z();
     pq.push_back(Lorentz5Momentum(ZERO, ZERO,etemp, abs(etemp)));
   }
   // calculate the rescaling
   double x[2];
   Lorentz5Momentum pcm=pin[0]+pin[1];
   assert(pcm.mass2()>ZERO);
   pcm.rescaleMass();
   vector<double> boost = inverseInitialStateRescaling(x[0],x[1],pcm,pin,pq);
   set<HardBranchingPtr>::const_iterator cjt=tree->incoming().begin();
   HardBranchingPtr incoming[2];
   incoming[0] = *cjt;
   ++cjt;
   incoming[1] = *cjt;
   if((*tree->incoming().begin())->beam()->momentum().z()/pq[0].z()<0.)
     swap(incoming[0],incoming[1]);
   // apply the boost the the particles
   unsigned int iswap[2]={1,0};
   for(unsigned int ix=0;ix<2;++ix) {
     LorentzRotation R(0.,0.,-boost[ix]);
     incoming[ix]->pVector(pq[ix]);
     incoming[ix]->nVector(pq[iswap[ix]]);
     incoming[ix]->setMomenta(R,1.,Lorentz5Momentum());
     jets[ix]->showerMomentum(x[ix]*jets[ix]->pVector());
   }
   // and calculate the boosts 
   applyBoost=true;
   // do one boost
   if(_initialBoost==0) {
     toRest   = LorentzRotation(-pcm.boostVector());
   }
   else if(_initialBoost==1) {
     // first the transverse boost
     Energy pT = sqrt(sqr(pcm.x())+sqr(pcm.y()));
     double beta = -pT/pcm.t();
     toRest=LorentzRotation(Boost(beta*pcm.x()/pT,beta*pcm.y()/pT,0.));
     // the longitudinal 
     beta = pcm.z()/sqrt(pcm.m2()+sqr(pcm.z()));
     toRest.boost(Boost(0.,0.,-beta));
   }
   else
     assert(false);
   fromRest = LorentzRotation((jets[0]->showerMomentum()+
   			      jets[1]->showerMomentum()).boostVector());
 }
 
 void KinematicsReconstructor::
 deconstructFinalStateSystem(const LorentzRotation &   toRest,
 			    const LorentzRotation & fromRest,
 			    HardTreePtr tree, vector<HardBranchingPtr> jets,
 			    ShowerInteraction type) const {
   LorentzRotation trans = toRest;
   if(jets.size()==1) {
     Lorentz5Momentum pnew = toRest*(jets[0]->branchingParticle()->momentum());
     pnew *= fromRest;
     jets[0]->      original(pnew);
     jets[0]->showerMomentum(pnew);
     // find the colour partners
     ShowerParticleVector particles;
     vector<Lorentz5Momentum> ptemp;
     set<HardBranchingPtr>::const_iterator cjt;
     for(cjt=tree->branchings().begin();cjt!=tree->branchings().end();++cjt) {
       ptemp.push_back((**cjt).branchingParticle()->momentum());
       (**cjt).branchingParticle()->set5Momentum((**cjt).showerMomentum());
       particles.push_back((**cjt).branchingParticle());
     }
     dynamic_ptr_cast<tcQTildeShowerHandlerPtr>(ShowerHandler::currentHandler())->partnerFinder()
       ->setInitialEvolutionScales(particles,false,type,false);
     // calculate the reference vectors
     unsigned int iloc(0);
     set<HardBranchingPtr>::iterator clt;
     for(cjt=tree->branchings().begin();cjt!=tree->branchings().end();++cjt) {
       // reset the momentum
       (**cjt).branchingParticle()->set5Momentum(ptemp[iloc]);
       ++iloc;
       // sort out the partners
       tShowerParticlePtr partner = 
 	(*cjt)->branchingParticle()->partner();
       if(!partner) continue;
       for(clt=tree->branchings().begin();clt!=tree->branchings().end();++clt) {
 	if((**clt).branchingParticle()==partner) {
 	  (**cjt).colourPartner(*clt);
 	  break;
 	}
       }
       tHardBranchingPtr branch;
       for(clt=tree->branchings().begin();clt!=tree->branchings().end();++clt) {
 	if(clt==cjt) continue;
 	if((*clt)->branchingParticle()==partner) {
 	  branch=*clt;
 	  break;
 	}
       }
     }
     return;
   }
   vector<HardBranchingPtr>::iterator cit;
   vector<Lorentz5Momentum> pout;
   vector<Energy> mon;
   Lorentz5Momentum pin;
   for(cit=jets.begin();cit!=jets.end();++cit) {
     pout.push_back((*cit)->branchingParticle()->momentum());
     mon.push_back(findMass(*cit));
     pin+=pout.back();
   }
   // boost all the momenta to the rest frame of the decaying particle
   pin.rescaleMass();
   pin *=trans;
   Boost beta_cm = pin.findBoostToCM();
   bool gottaBoost(false);
   if(beta_cm.mag() > 1e-12) {
     gottaBoost = true;
     trans.boost(beta_cm);
     pin.boost(beta_cm);
   }
   for(unsigned int ix=0;ix<pout.size();++ix) {
     pout[ix].transform(trans);
   }
   // rescaling factor
   double lambda=inverseRescalingFactor(pout,mon,pin.mass());
   if (lambda< 1.e-10) throw KinematicsReconstructionVeto();
   // now calculate the p reference vectors 
   for(unsigned int ix=0;ix<jets.size();++ix) {
     Lorentz5Momentum pvect = jets[ix]->branchingParticle()->momentum();
     pvect.transform(trans);
     pvect /= lambda;
     pvect.setMass(mon[ix]);
     pvect.rescaleEnergy();
     if(gottaBoost) pvect.boost(-beta_cm);
     pvect.transform(fromRest);
     jets[ix]->pVector(pvect);
     jets[ix]->showerMomentum(pvect);
   }
   // find the colour partners
   ShowerParticleVector particles;
   vector<Lorentz5Momentum> ptemp;
   set<HardBranchingPtr>::const_iterator cjt;
   for(cjt=tree->branchings().begin();cjt!=tree->branchings().end();++cjt) {
     ptemp.push_back((**cjt).branchingParticle()->momentum());
     (**cjt).branchingParticle()->set5Momentum((**cjt).showerMomentum());
     particles.push_back((**cjt).branchingParticle());
   }
   dynamic_ptr_cast<tcQTildeShowerHandlerPtr>(ShowerHandler::currentHandler())->partnerFinder()
     ->setInitialEvolutionScales(particles,false,type,false);
   // calculate the reference vectors
   unsigned int iloc(0);
   set<HardBranchingPtr>::iterator clt;
   for(cjt=tree->branchings().begin();cjt!=tree->branchings().end();++cjt) {
     // reset the momentum
     (**cjt).branchingParticle()->set5Momentum(ptemp[iloc]);
     ++iloc;
   }
   for(cjt=tree->branchings().begin();cjt!=tree->branchings().end();++cjt) {
     // sort out the partners
     tShowerParticlePtr partner = 
       (*cjt)->branchingParticle()->partner();
     if(!partner) continue;
     for(clt=tree->branchings().begin();clt!=tree->branchings().end();++clt) {
       if((**clt).branchingParticle()==partner) {
 	(**cjt).colourPartner(*clt);
 	break;
       }
     }
     tHardBranchingPtr branch;
     for(clt=tree->branchings().begin();clt!=tree->branchings().end();++clt) {
       if(clt==cjt) continue;
       if((*clt)->branchingParticle()==partner) {
  	branch=*clt;
  	break;
       }
     }
     // compute the reference vectors
     // both incoming, should all ready be done
     if((**cjt).status()==HardBranching::Incoming &&
        (**clt).status()==HardBranching::Incoming) {
       continue;
     }
     // both outgoing
     else if((**cjt).status()!=HardBranching::Incoming&&
 	    branch->status()==HardBranching::Outgoing) {
       Boost boost=((*cjt)->pVector()+branch->pVector()).findBoostToCM();
       Lorentz5Momentum pcm = branch->pVector();
       pcm.boost(boost);
       Lorentz5Momentum nvect = Lorentz5Momentum(ZERO,pcm.vect());
       nvect.boost( -boost);
       (**cjt).nVector(nvect);
     }
     else if((**cjt).status()==HardBranching::Incoming) {
       Lorentz5Momentum pa = -(**cjt).showerMomentum()+branch->showerMomentum();
       Lorentz5Momentum pb =  (**cjt).showerMomentum();
       Axis axis(pa.vect().unit());
       LorentzRotation rot;
       double sinth(sqrt(sqr(axis.x())+sqr(axis.y())));
       rot.setRotate(-acos(axis.z()),Axis(-axis.y()/sinth,axis.x()/sinth,0.));
       rot.rotateX(Constants::pi);
       rot.boostZ( pa.e()/pa.vect().mag());
       pb*=rot;
       Boost trans = -1./pb.e()*pb.vect();
       trans.setZ(0.);
       rot.boost(trans);
       Energy scale=(**cjt).beam()->momentum().e();
       Lorentz5Momentum pbasis(ZERO,(**cjt).beam()->momentum().vect().unit()*scale);
       Lorentz5Momentum pcm = rot*pbasis;
       rot.invert();
       (**cjt).nVector(rot*Lorentz5Momentum(ZERO,-pcm.vect()));
       tHardBranchingPtr branch2 = *cjt;;      
       while (branch2->parent()) {
 	branch2=branch2->parent();
 	branch2->nVector(rot*Lorentz5Momentum(ZERO,-pcm.vect()));
       }
     }
     else if(branch->status()==HardBranching::Incoming) {
       (**cjt).nVector(Lorentz5Momentum(ZERO,branch->showerMomentum().vect()));
     }
   }
   // now compute the new momenta 
   for(cjt=tree->branchings().begin();cjt!=tree->branchings().end();++cjt) {
     if(!(*cjt)->branchingParticle()->isFinalState()) continue;
     Lorentz5Momentum qnew;
     if((*cjt)->branchingParticle()->partner()) {
       Energy2 dot=(*cjt)->pVector()*(*cjt)->nVector();
       double beta = 0.5*((*cjt)->branchingParticle()->momentum().m2()
 			 -sqr((*cjt)->pVector().mass()))/dot;
       qnew=(*cjt)->pVector()+beta*(*cjt)->nVector();
       qnew.rescaleMass();
     }
     else {
       qnew = (*cjt)->pVector();
     }
     // qnew is the unshuffled momentum in the rest frame of the p basis vectors,
     // for the simple case Z->q qbar g this was checked against analytic formulae.
     // compute the boost
     LorentzRotation R=solveBoost(qnew,
 				 toRest*(*cjt)->branchingParticle()->momentum())*toRest;
     (*cjt)->setMomenta(R,1.0,Lorentz5Momentum());  
   }
 }
 
 Energy KinematicsReconstructor::momConsEq(double k, 
 				      const Energy & root_s, 
 				      const JetKinVect & jets) const {
   static const Energy2 eps=1e-8*GeV2;
   Energy dum = ZERO;
   for(JetKinVect::const_iterator it = jets.begin(); it != jets.end(); ++it) {
     Energy2 dum2 = (it->q).m2() + sqr(k)*(it->p).vect().mag2();
     if(dum2 < ZERO) {
       if(dum2 < -eps) throw KinematicsReconstructionVeto();
       dum2 = ZERO;
     }
     dum += sqrt(dum2);
   }
   return dum - root_s; 
 }
 
 void KinematicsReconstructor::boostChain(tPPtr p, const LorentzRotation &bv,
 				     tPPtr & parent) const {
   if(!p->parents().empty()) boostChain(p->parents()[0], bv,parent);
   else parent=p;
   p->transform(bv);
   if(p->children().size()==2) {
     if(dynamic_ptr_cast<ShowerParticlePtr>(p->children()[1]))
       deepTransform(p->children()[1],bv);
   }
 }
 
 namespace {
 
 bool sortJets(ShowerProgenitorPtr j1, ShowerProgenitorPtr j2) {
   return j1->highestpT()>j2->highestpT();
 }
 
 }
 
 void KinematicsReconstructor::
 reconstructGeneralSystem(vector<ShowerProgenitorPtr> & ShowerHardJets) const {
   // find initial- and final-state systems
   ColourSingletSystem in,out;
   for(unsigned int ix=0;ix<ShowerHardJets.size();++ix) {
     if(ShowerHardJets[ix]->progenitor()->isFinalState())
       out.jets.push_back(ShowerHardJets[ix]);
     else
       in.jets.push_back(ShowerHardJets[ix]);
   }
   // reconstruct initial-initial system
   LorentzRotation toRest,fromRest;
   bool applyBoost(false);
   // reconstruct initial-initial system
   reconstructInitialInitialSystem(applyBoost,toRest,fromRest,in.jets);
   // reconstruct the final-state systems
   reconstructFinalStateSystem(applyBoost,toRest,fromRest,out.jets);
 }
 
 
 void KinematicsReconstructor::
 reconstructFinalFirst(vector<ShowerProgenitorPtr> & ShowerHardJets) const {
   static const Energy2 minQ2 = 1e-4*GeV2;
   map<ShowerProgenitorPtr,bool> used;
   for(unsigned int ix=0;ix<ShowerHardJets.size();++ix) {
     used[ShowerHardJets[ix]] = false;
   }  // first to the final-state reconstruction of any systems which need it
   set<ShowerProgenitorPtr> outgoing;
   // first find any particles with final state partners
   for(unsigned int ix=0;ix<ShowerHardJets.size();++ix) {
     if(ShowerHardJets[ix]->progenitor()->isFinalState()&&
        ShowerHardJets[ix]->progenitor()->partner()&&
        ShowerHardJets[ix]->progenitor()->partner()->isFinalState()) outgoing.insert(ShowerHardJets[ix]);
   }
   // then find the colour partners
   if(!outgoing.empty()) {
     set<ShowerProgenitorPtr> partners;
     for(set<ShowerProgenitorPtr>::const_iterator it=outgoing.begin();it!=outgoing.end();++it) {
       for(unsigned int ix=0;ix<ShowerHardJets.size();++ix) {
 	if((**it).progenitor()->partner()==ShowerHardJets[ix]->progenitor()) {
 	  partners.insert(ShowerHardJets[ix]);
 	  break;
 	}
       }
     }
     outgoing.insert(partners.begin(),partners.end());
   }
   // do the final-state reconstruction if needed
   if(!outgoing.empty()) {
     assert(outgoing.size()!=1);
     LorentzRotation toRest,fromRest;
     vector<ShowerProgenitorPtr> outgoingJets(outgoing.begin(),outgoing.end());
     reconstructFinalStateSystem(false,toRest,fromRest,outgoingJets);
   }
   // Now do any initial-final systems which are needed
   vector<ColourSingletSystem> IFSystems;
   // find the systems N.B. can have duplicates
   // find initial-state with FS partners or FS with IS partners
   for(unsigned int ix=0;ix<ShowerHardJets.size();++ix) {
     if(!ShowerHardJets[ix]->progenitor()->isFinalState()&&
        ShowerHardJets[ix]->progenitor()->partner()&&
        ShowerHardJets[ix]->progenitor()->partner()->isFinalState()) {
       IFSystems.push_back(ColourSingletSystem(IF,ShowerHardJets[ix]));
     }
     else if(ShowerHardJets[ix]->progenitor()->isFinalState()&&
 	    ShowerHardJets[ix]->progenitor()->partner()&&
 	    !ShowerHardJets[ix]->progenitor()->partner()->isFinalState()) {
       IFSystems.push_back(ColourSingletSystem(IF,ShowerHardJets[ix]));
     }
   }
   // then add the partners
   for(unsigned int is=0;is<IFSystems.size();++is) {
     for(unsigned int ix=0;ix<ShowerHardJets.size();++ix) {
       if(IFSystems[is].jets[0]->progenitor()->partner()==ShowerHardJets[ix]->progenitor()) {
 	IFSystems[is].jets.push_back(ShowerHardJets[ix]);
       }
     }
     // ensure incoming first
     if(IFSystems[is].jets[0]->progenitor()->isFinalState())
       swap(IFSystems[is].jets[0],IFSystems[is].jets[1]);
   }
   if(!IFSystems.empty()) {
     unsigned int istart = UseRandom::irnd(IFSystems.size());
     unsigned int istop=IFSystems.size();
     for(unsigned int is=istart;is<=istop;++is) {
       if(is==IFSystems.size()) {
 	if(istart!=0) {
 	  istop = istart-1;
 	  is=0;
 	}
 	else break;
       }
       // skip duplicates
       if(used[IFSystems[is].jets[0]] &&
 	 used[IFSystems[is].jets[1]] ) continue;
       if(IFSystems[is].jets[0]->original()&&IFSystems[is].jets[0]->original()->parents().empty()) continue;
       Lorentz5Momentum psum;
       for(unsigned int ix=0;ix<IFSystems[is].jets.size();++ix) {
 	if(IFSystems[is].jets[ix]->progenitor()->isFinalState())
 	  psum += IFSystems[is].jets[ix]->progenitor()->momentum();
 	else
 	  psum -= IFSystems[is].jets[ix]->progenitor()->momentum();
       }
       if(-psum.m2()>minQ2) {
 	reconstructInitialFinalSystem(IFSystems[is].jets);
 	for(unsigned int ix=0;ix<IFSystems[is].jets.size();++ix) {
 	  used[IFSystems[is].jets[ix]] = true;
 	}
       }
     }
   }
   // now we finally need to handle the initial state system
   ColourSingletSystem in,out;
   for(unsigned int ix=0;ix<ShowerHardJets.size();++ix) {
     if(ShowerHardJets[ix]->progenitor()->isFinalState())
       out.jets.push_back(ShowerHardJets[ix]);
     else
       in.jets.push_back(ShowerHardJets[ix]);
   }
   // reconstruct initial-initial system
   bool doRecon = false;
   for(unsigned int ix=0;ix<in.jets.size();++ix) {
     if(!used[in.jets[ix]]) {
       doRecon = true;
       break;
     }
   }
   LorentzRotation toRest,fromRest;
   bool applyBoost(false);
   if(doRecon) {
     reconstructInitialInitialSystem(applyBoost,toRest,fromRest,in.jets);
   }
   // reconstruct the final-state systems
   if(!doRecon) {
     for(unsigned int ix=0;ix<out.jets.size();++ix) {
       if(!used[out.jets[ix]]) {
 	doRecon = true;
 	break;
       }
     }
   }
   if(doRecon) {
     reconstructFinalStateSystem(applyBoost,toRest,fromRest,out.jets);
   }
 }
 
 void KinematicsReconstructor::
 reconstructColourPartner(vector<ShowerProgenitorPtr> & ShowerHardJets) const {
   static const Energy2 minQ2 = 1e-4*GeV2;
   // sort the vector by hardness of emission
   std::sort(ShowerHardJets.begin(),ShowerHardJets.end(),sortJets);
   // map between particles and progenitors for easy lookup
   map<ShowerParticlePtr,ShowerProgenitorPtr> progenitorMap;
   for(unsigned int ix=0;ix<ShowerHardJets.size();++ix) {
     progenitorMap[ShowerHardJets[ix]->progenitor()] = ShowerHardJets[ix];
   }
   // check that the IF systems can be reconstructed
   bool canReconstruct = true;
   for(unsigned int ix=0;ix<ShowerHardJets.size();++ix) {
     tShowerParticlePtr progenitor = ShowerHardJets[ix]->progenitor();
     tShowerParticlePtr partner    = progenitor->partner();
     if(!partner) continue;
     else if((progenitor->isFinalState() &&
 	     !partner->isFinalState()) ||
 	    (!progenitor->isFinalState() &&
 	     partner->isFinalState()) ) {
       vector<ShowerProgenitorPtr> jets(2);
       jets[0] = ShowerHardJets[ix];
       jets[1] = progenitorMap[partner];
       Lorentz5Momentum psum;
       for(unsigned int iy=0;iy<jets.size();++iy) {
 	if(jets[iy]->progenitor()->isFinalState())
 	  psum += jets[iy]->progenitor()->momentum();
 	else
 	  psum -= jets[iy]->progenitor()->momentum();
       }
       if(-psum.m2()<minQ2) {
 	canReconstruct  = false;
 	break;
       }
     }
   }
   if(!canReconstruct) {
     reconstructGeneralSystem(ShowerHardJets);
     return;
   }
   map<ShowerProgenitorPtr,bool> used;
   for(unsigned int ix=0;ix<ShowerHardJets.size();++ix) {
     used[ShowerHardJets[ix]] = false;
   }
   for(unsigned int ix=0;ix<ShowerHardJets.size();++ix) {
     // skip jets which have already been handled
     if(ShowerHardJets[ix]->reconstructed()==ShowerProgenitor::done) continue;
     // already reconstructed
     if(used[ShowerHardJets[ix]]) continue; 
     // no partner continue
     tShowerParticlePtr progenitor = ShowerHardJets[ix]->progenitor();
     tShowerParticlePtr partner    = progenitor->partner();
     if(!partner) {
       // check if there's a daughter tree which also needs boosting
       Lorentz5Momentum porig = progenitor->momentum();
       map<tShowerTreePtr,pair<tShowerProgenitorPtr,tShowerParticlePtr> >::const_iterator tit;
       for(tit  = _currentTree->treelinks().begin();
 	  tit != _currentTree->treelinks().end();++tit) {
 	// if there is, boost it
 	if(tit->second.first && tit->second.second==progenitor) {
 	  Lorentz5Momentum pnew = tit->first->incomingLines().begin()
 	    ->first->progenitor()->momentum();
 	  pnew *=  tit->first->transform();
 	  Lorentz5Momentum pdiff = porig-pnew;
 	  Energy2 test = sqr(pdiff.x()) + sqr(pdiff.y()) + 
 	    sqr(pdiff.z()) + sqr(pdiff.t());
 	  LorentzRotation rot;
 	  if(test>1e-6*GeV2) rot = solveBoost(porig,pnew);
 	  tit->first->transform(rot,false);
 	  _treeBoosts[tit->first].push_back(rot);
 	}
       }
       ShowerHardJets[ix]->reconstructed(ShowerProgenitor::done);
       continue;
     }
     // do the reconstruction
     // final-final
     if(progenitor->isFinalState() &&
        partner->isFinalState() ) {
       LorentzRotation toRest,fromRest;
       vector<ShowerProgenitorPtr> jets(2);
       jets[0] = ShowerHardJets[ix];
       jets[1] = progenitorMap[partner];
       if(_reconopt==4 && jets[1]->reconstructed()==ShowerProgenitor::notReconstructed)
 	jets[1]->reconstructed(ShowerProgenitor::dontReconstruct);
       reconstructFinalStateSystem(false,toRest,fromRest,jets);
       if(_reconopt==4 && jets[1]->reconstructed()==ShowerProgenitor::dontReconstruct)
 	jets[1]->reconstructed(ShowerProgenitor::notReconstructed);
       used[jets[0]] = true;
       if(_reconopt==3) used[jets[1]] = true;
     }
     // initial-final
     else if((progenitor->isFinalState() &&
 	     !partner->isFinalState()) ||
 	    (!progenitor->isFinalState() &&
 	     partner->isFinalState()) ) {
       vector<ShowerProgenitorPtr> jets(2);
       jets[0] = ShowerHardJets[ix];
       jets[1] = progenitorMap[partner];
       if(jets[0]->progenitor()->isFinalState()) swap(jets[0],jets[1]);
       if(jets[0]->original()&&jets[0]->original()->parents().empty()) continue;
       Lorentz5Momentum psum;
       for(unsigned int iy=0;iy<jets.size();++iy) {
 	if(jets[iy]->progenitor()->isFinalState())
 	  psum += jets[iy]->progenitor()->momentum();
 	else
 	  psum -= jets[iy]->progenitor()->momentum();
       }
       if(_reconopt==4 && progenitorMap[partner]->reconstructed()==ShowerProgenitor::notReconstructed)
 	progenitorMap[partner]->reconstructed(ShowerProgenitor::dontReconstruct);
       reconstructInitialFinalSystem(jets);
       if(_reconopt==4 && progenitorMap[partner]->reconstructed()==ShowerProgenitor::dontReconstruct)
 	progenitorMap[partner]->reconstructed(ShowerProgenitor::notReconstructed);
       used[ShowerHardJets[ix]] = true;
       if(_reconopt==3) used[progenitorMap[partner]] = true;
     }
     // initial-initial
     else if(!progenitor->isFinalState() &&
 	    !partner->isFinalState() ) {
       ColourSingletSystem in,out;
       in.jets.push_back(ShowerHardJets[ix]);
       in.jets.push_back(progenitorMap[partner]);
       for(unsigned int iy=0;iy<ShowerHardJets.size();++iy) {
 	if(ShowerHardJets[iy]->progenitor()->isFinalState())
 	  out.jets.push_back(ShowerHardJets[iy]);
       }
       LorentzRotation toRest,fromRest;
       bool applyBoost(false);
       if(_reconopt==4 && in.jets[1]->reconstructed()==ShowerProgenitor::notReconstructed)
 	in.jets[1]->reconstructed(ShowerProgenitor::dontReconstruct);
       reconstructInitialInitialSystem(applyBoost,toRest,fromRest,in.jets);
       if(_reconopt==4 && in.jets[1]->reconstructed()==ShowerProgenitor::dontReconstruct)
 	in.jets[1]->reconstructed(ShowerProgenitor::notReconstructed);
       used[in.jets[0]] = true;
       if(_reconopt==3) used[in.jets[1]] = true;
       for(unsigned int iy=0;iy<out.jets.size();++iy) {
 	if(out.jets[iy]->reconstructed()==ShowerProgenitor::notReconstructed)
 	  out.jets[iy]->reconstructed(ShowerProgenitor::dontReconstruct);
       }
       // reconstruct the final-state systems
       LorentzRotation finalBoosts;
       finalBoosts.transform(  toRest);
       finalBoosts.transform(fromRest);
       for(unsigned int iy=0;iy<out.jets.size();++iy) {
 	deepTransform(out.jets[iy]->progenitor(),finalBoosts);
       }
       for(unsigned int iy=0;iy<out.jets.size();++iy) {
 	if(out.jets[iy]->reconstructed()==ShowerProgenitor::dontReconstruct)
 	  out.jets[iy]->reconstructed(ShowerProgenitor::notReconstructed);
       }
     }
   }
 }
 
 bool KinematicsReconstructor::
 inverseDecayRescalingFactor(vector<Lorentz5Momentum> pout,
 			    vector<Energy> mon,Energy roots,
 			    Lorentz5Momentum ppartner, Energy mbar,
 			    double & k1, double & k2) const {
   ThreeVector<Energy> qtotal;
   vector<Energy2> pmag; 
   for(unsigned int ix=0;ix<pout.size();++ix) {
     pmag.push_back(pout[ix].vect().mag2());
     qtotal+=pout[ix].vect();
   }
   Energy2 dot1 = qtotal*ppartner.vect();
   Energy2 qmag2=qtotal.mag2();
   double a = -dot1/qmag2;
   static const Energy eps=1e-10*GeV;
   unsigned int itry(0);
   Energy numer(ZERO),denom(ZERO);
   k1=1.;
   do {
     ++itry;
     numer=denom=0.*GeV;
     double k12=sqr(k1);
     for(unsigned int ix=0;ix<pout.size();++ix) {
       Energy en = sqrt(pmag[ix]/k12+sqr(mon[ix]));
       numer += en;
       denom += pmag[ix]/en;
     }
     Energy en = sqrt(qmag2/k12+sqr(mbar));
     numer += en-roots;
     denom += qmag2/en;
     k1 += numer/denom*k12*k1;
     if(abs(k1)>1e10) return false;
   }
   while (abs(numer)>eps&&itry<100);
   k1 = abs(k1);
   k2 = a*k1;
   return itry<100;
 }
 
 void KinematicsReconstructor::
 deconstructInitialFinalSystem(HardTreePtr tree,vector<HardBranchingPtr> jets,
 			      ShowerInteraction type) const {
   HardBranchingPtr incoming;
   Lorentz5Momentum pin[2],pout[2],pbeam;
   HardBranchingPtr initial;
   Energy mc(ZERO);
   for(unsigned int ix=0;ix<jets.size();++ix) {
     // final-state parton
     if(jets[ix]->status()==HardBranching::Outgoing) {
       pout[0] += jets[ix]->branchingParticle()->momentum();
       mc = jets[ix]->branchingParticle()->thePEGBase() ? 
 	jets[ix]->branchingParticle()->thePEGBase()->mass() :
 	jets[ix]->branchingParticle()->dataPtr()->mass();
     }
     // initial-state parton
     else {
       pin[0]  += jets[ix]->branchingParticle()->momentum();
       initial = jets[ix];
       pbeam = jets[ix]->beam()->momentum();
       Energy scale=pbeam.t();
       pbeam = Lorentz5Momentum(ZERO,pbeam.vect().unit()*scale);
       incoming = jets[ix];
       while(incoming->parent()) incoming = incoming->parent();
     }
   }
   if(jets.size()>2) {
     pout[0].rescaleMass();
     mc = pout[0].mass();
   }
   // work out the boost to the Breit frame
   Lorentz5Momentum pa = pout[0]-pin[0];
   Axis axis(pa.vect().unit());
   LorentzRotation rot;
   double sinth(sqrt(sqr(axis.x())+sqr(axis.y())));
   if(axis.perp2()>0.) {
     rot.setRotate(-acos(axis.z()),Axis(-axis.y()/sinth,axis.x()/sinth,0.));
     rot.rotateX(Constants::pi);
     rot.boostZ( pa.e()/pa.vect().mag());
   }
   // transverse part
   Lorentz5Momentum paxis=rot*pbeam;
   Boost trans = -1./paxis.e()*paxis.vect();
   trans.setZ(0.);
   rot.boost(trans);
   pa *= rot;
   // reference vectors
   Lorentz5Momentum n1(ZERO,ZERO,-pa.z(),-pa.z());
   Lorentz5Momentum n2(ZERO,ZERO, pa.z(),-pa.z());
   Energy2 n1n2 = n1*n2;
   // decompose the momenta
   Lorentz5Momentum qbp=rot*pin[0],qcp= rot*pout[0];
   double a[2],b[2];
   a[0] = n2*qbp/n1n2;
   b[0] = n1*qbp/n1n2;
   a[1] = n2*qcp/n1n2;
   b[1] = n1*qcp/n1n2;
   Lorentz5Momentum qperp = qbp-a[0]*n1-b[0]*n2;
   // before reshuffling
   Energy Q = abs(pa.z());
   double c = sqr(mc/Q);
   Lorentz5Momentum pb(ZERO,ZERO,0.5*Q*(1.+c),0.5*Q*(1.+c));
   Lorentz5Momentum pc(ZERO,ZERO,0.5*Q*(c-1.),0.5*Q*(1.+c));
   double anew[2],bnew[2];
   anew[0] = pb*n2/n1n2;
   bnew[0] = 0.5*(qbp.m2()-qperp.m2())/n1n2/anew[0];
   bnew[1] = pc*n1/n1n2;
   anew[1] = 0.5*qcp.m2()/bnew[1]/n1n2;
   Lorentz5Momentum qnewb = (anew[0]*n1+bnew[0]*n2+qperp);
   Lorentz5Momentum qnewc = (anew[1]*n1+bnew[1]*n2);
   // initial-state boost
   LorentzRotation rotinv=rot.inverse();
   LorentzRotation transb=rotinv*solveBoostZ(qnewb,qbp)*rot;
   // final-state boost
   LorentzRotation transc=rotinv*solveBoost(qnewc,qcp)*rot;
   // this will need changing for more than one outgoing particle
   // set the pvectors
   for(unsigned int ix=0;ix<jets.size();++ix) {
     if(jets[ix]->status()==HardBranching::Incoming) {
       jets[ix]->pVector(pbeam);
       jets[ix]->showerMomentum(rotinv*pb);
       incoming->pVector(jets[ix]->pVector());
     }
     else {
       jets[ix]->pVector(rotinv*pc);
       jets[ix]->showerMomentum(jets[ix]->pVector());
     }
   }
   // find the colour partners
   ShowerParticleVector particles;
   vector<Lorentz5Momentum> ptemp;
   set<HardBranchingPtr>::const_iterator cjt;
   for(cjt=tree->branchings().begin();cjt!=tree->branchings().end();++cjt) {
     ptemp.push_back((**cjt).branchingParticle()->momentum());
     (**cjt).branchingParticle()->set5Momentum((**cjt).showerMomentum());
     particles.push_back((**cjt).branchingParticle());
   }
   dynamic_ptr_cast<tcQTildeShowerHandlerPtr>(ShowerHandler::currentHandler())->partnerFinder()
     ->setInitialEvolutionScales(particles,false,type,false);
   unsigned int iloc(0);
   for(cjt=tree->branchings().begin();cjt!=tree->branchings().end();++cjt) {
     // reset the momentum
     (**cjt).branchingParticle()->set5Momentum(ptemp[iloc]);
     ++iloc;
   }
   for(vector<HardBranchingPtr>::const_iterator cjt=jets.begin();
       cjt!=jets.end();++cjt) {
     // sort out the partners
     tShowerParticlePtr partner = 
       (*cjt)->branchingParticle()->partner();
     if(!partner) continue;
     tHardBranchingPtr branch;
     for(set<HardBranchingPtr>::const_iterator 
 	  clt=tree->branchings().begin();clt!=tree->branchings().end();++clt) {
       if((**clt).branchingParticle()==partner) {
 	(**cjt).colourPartner(*clt);
   	branch=*clt;
 	break;
       }
     }
     // compute the reference vectors
     // both incoming, should all ready be done
     if((**cjt).status()==HardBranching::Incoming &&
        branch->status()==HardBranching::Incoming) {
       Energy etemp = (*cjt)->beam()->momentum().z();
       Lorentz5Momentum nvect(ZERO, ZERO,-etemp, abs(etemp));
       tHardBranchingPtr branch2 = *cjt;     
       (**cjt).nVector(nvect);
       while (branch2->parent()) {
 	branch2=branch2->parent();
 	branch2->nVector(nvect);
       }
     }
     // both outgoing
     else if((**cjt).status()==HardBranching::Outgoing&&
 	     branch->status()==HardBranching::Outgoing) {
       Boost boost=((*cjt)->pVector()+branch->pVector()).findBoostToCM();
       Lorentz5Momentum pcm = branch->pVector();
       pcm.boost(boost);
       Lorentz5Momentum nvect = Lorentz5Momentum(ZERO,pcm.vect());
       nvect.boost( -boost);
       (**cjt).nVector(nvect);
     }
     else if((**cjt).status()==HardBranching::Incoming) {
       Lorentz5Momentum pa = -(**cjt).showerMomentum()+branch->showerMomentum();
       Lorentz5Momentum pb =  (**cjt).showerMomentum();
       Axis axis(pa.vect().unit());
       LorentzRotation rot;
       double sinth(sqrt(sqr(axis.x())+sqr(axis.y())));
       if(axis.perp2()>1e-20) {
 	rot.setRotate(-acos(axis.z()),Axis(-axis.y()/sinth,axis.x()/sinth,0.));
 	rot.rotateX(Constants::pi);
       }
       if(abs(1.-pa.e()/pa.vect().mag())>1e-6) rot.boostZ( pa.e()/pa.vect().mag());
       pb*=rot;
       Boost trans = -1./pb.e()*pb.vect();
       trans.setZ(0.);
       rot.boost(trans);
       Energy scale=(**cjt).beam()->momentum().t();
       Lorentz5Momentum pbasis(ZERO,(**cjt).beam()->momentum().vect().unit()*scale);
       Lorentz5Momentum pcm = rot*pbasis;
       rot.invert();
       Lorentz5Momentum nvect = rot*Lorentz5Momentum(ZERO,-pcm.vect());
       (**cjt).nVector(nvect);
       tHardBranchingPtr branch2 = *cjt;     
       while (branch2->parent()) {
 	branch2=branch2->parent();
 	branch2->nVector(nvect);
       }
     }
     else if(branch->status()==HardBranching::Incoming) {
       Lorentz5Momentum nvect=Lorentz5Momentum(ZERO,branch->showerMomentum().vect());
       (**cjt).nVector(nvect);
     }
   }
   // now compute the new momenta
   for(vector<HardBranchingPtr>::const_iterator cjt=jets.begin();
       cjt!=jets.end();++cjt) {
     if((**cjt).status()==HardBranching::Outgoing) {
       (**cjt).setMomenta(transc,1.,Lorentz5Momentum());
     }
   }
   incoming->setMomenta(transb,1.,Lorentz5Momentum());
 }
 
 void KinematicsReconstructor::deepTransform(PPtr particle,
 					const LorentzRotation & r,
 					bool match,
 					PPtr original) const {
   if(_boosts.find(particle)!=_boosts.end()) {
     _boosts[particle].push_back(r);
   }
   Lorentz5Momentum porig = particle->momentum();
   if(!original) original = particle;
   for ( int i = 0, N = particle->children().size(); i < N; ++i ) {
     deepTransform(particle->children()[i],r,
 		  particle->children()[i]->id()==original->id()&&match,original);
   }
   particle->transform(r);
   // transform the p and n vectors
   ShowerParticlePtr sparticle = dynamic_ptr_cast<ShowerParticlePtr>(particle);
   if(sparticle && sparticle->showerBasis()) {
     sparticle->showerBasis()->transform(r);
   }
   if ( particle->next() ) deepTransform(particle->next(),r,match,original);
   if(!match) return;
   if(!particle->children().empty()) return;
   // force the mass shell
   if(particle->dataPtr()->stable()) {
     Lorentz5Momentum ptemp = particle->momentum();
     ptemp.rescaleEnergy();
     particle->set5Momentum(ptemp);
   }
   // check if there's a daughter tree which also needs boosting
   map<tShowerTreePtr,pair<tShowerProgenitorPtr,tShowerParticlePtr> >::const_iterator tit;
   for(tit  = _currentTree->treelinks().begin();
       tit != _currentTree->treelinks().end();++tit) {
     // if there is, boost it
     if(tit->second.first && tit->second.second==original) {
       Lorentz5Momentum pnew = tit->first->incomingLines().begin()
 	->first->progenitor()->momentum();
       pnew *=  tit->first->transform();
       Lorentz5Momentum pdiff = porig-pnew;
       Energy2 test = sqr(pdiff.x()) + sqr(pdiff.y()) + 
    	             sqr(pdiff.z()) + sqr(pdiff.t());
       LorentzRotation rot;
       if(test>1e-6*GeV2) rot = solveBoost(porig,pnew);
       tit->first->transform(r*rot,false);
       _treeBoosts[tit->first].push_back(r*rot);
     }
   }
 }
 
-void KinematicsReconstructor::reconstructFinalFinalOffShell(JetKinVect orderedJets,
-							Energy2 s,
-							bool recursive) const {
-  JetKinVect::iterator jit;
-  jit = orderedJets.begin(); ++jit;
-  // 4-momentum of recoiling system
-  Lorentz5Momentum psum;
-  for( ; jit!=orderedJets.end(); ++jit) psum += jit->p;
-  psum.rescaleMass();
-  // calculate the 3-momentum rescaling factor
-  Energy2 m1sq(orderedJets.begin()->q.m2()),m2sq(psum.m2());
-  Energy4 num = sqr(s - m1sq - m2sq) - 4.*m1sq*m2sq;
-  if(num<ZERO) throw KinematicsReconstructionVeto();
-  double k = sqrt( num / (4.*s*orderedJets.begin()->p.vect().mag2()) );
-  // boost the most off-shell
-  LorentzRotation B1 = solveBoost(k, orderedJets.begin()->q, orderedJets.begin()->p);
-  deepTransform(orderedJets.begin()->parent,B1);
-  // boost everything else 
-  // first to rescale
-  LorentzRotation B2 = solveBoost(k, psum, psum);
-  // and then to rest frame of new system
-  Lorentz5Momentum pnew = B2*psum;
-  pnew.rescaleMass();
-  B2.transform(pnew.findBoostToCM());
-  // apply transform (calling routine ensures at least 3 elements)
-  jit = orderedJets.begin(); ++jit;
-  for(;jit!=orderedJets.end();++jit) {
-    deepTransform(jit->parent,B2);
-    jit->p *= B2; 
-    jit->q *= B2;
-  }
-  JetKinVect newJets(orderedJets.begin()+1,orderedJets.end());
-  // final reconstruction 
-  if(newJets.size()==2 || !recursive ) {
-    // rescaling factor
-    double k = solveKfactor(psum.m(), newJets);
-    // rescale jets in the new CMF
-    for(JetKinVect::iterator it = newJets.begin(); it != newJets.end(); ++it) {
-      LorentzRotation Trafo = solveBoost(k, it->q, it->p);
-      deepTransform(it->parent,Trafo);
-    }
-  }
-  // recursive
-  else {
-    std::sort(newJets.begin(),newJets.end(),JetOrdering());
-    reconstructFinalFinalOffShell(newJets,psum.m2(),recursive);
-  }
-  // finally boost back from new CMF
-  LorentzRotation back(-pnew.findBoostToCM());
-  for(JetKinVect::iterator it = newJets.begin(); it != newJets.end(); ++it) {
-     deepTransform(it->parent,back);
-  }
-}
-
 Energy KinematicsReconstructor::findMass(HardBranchingPtr branch) const {
   // KH - 230909 - If the particle has no children then it will 
   // not have showered and so it should be "on-shell" so we can
   // get it's mass from it's momentum. This means that the
   // inverseRescalingFactor doesn't give any nans or do things 
   // it shouldn't if it gets e.g. two Z bosons generated with
   // off-shell masses. This is for sure not the best solution.
   // PR 1/1/10 modification to previous soln
   // PR 28/8/14 change to procedure and factorize into a function
   if(branch->children().empty()) {
     return branch->branchingParticle()->mass();
   }
   else if(!branch->children().empty() &&
 	  !branch->branchingParticle()->dataPtr()->stable() ) {
     for(unsigned int ix=0;ix<branch->children().size();++ix) {
       if(branch->branchingParticle()->id()==
 	 branch->children()[ix]->branchingParticle()->id())
 	return findMass(branch->children()[ix]);
     }
   }
   return branch->branchingParticle()->dataPtr()->mass();
 }
 
 vector<double>
 KinematicsReconstructor::inverseInitialStateRescaling(double & x1, double & x2,
 						  const Lorentz5Momentum & pold,
 						  const vector<Lorentz5Momentum> & p,
 						  const vector<Lorentz5Momentum> & pq) const {
   // hadronic CMS
   Energy2 s  = (pq[0] +pq[1] ).m2();
   // partonic CMS
   Energy MDY = pold.m();
   // find alpha, beta and pt
   Energy2 p12=pq[0]*pq[1];
   double a[2],b[2];
   Lorentz5Momentum pt[2];
   for(unsigned int ix=0;ix<2;++ix) {
     a[ix] = p[ix]*pq[1]/p12;
     b [ix] = p[ix]*pq[0]/p12;
     pt[ix]    = p[ix]-a[ix]*pq[0]-b[ix]*pq[1];
   }
   // compute kappa
   // we always want to preserve the mass of the system
   double k1(1.),k2(1.);
   if(_initialStateReconOption==0) {
     double rap=pold.rapidity();
     x2 = MDY/sqrt(s*exp(2.*rap));
     x1 = sqr(MDY)/s/x2;
     k1=a[0]/x1;
     k2=b[1]/x2;
   }
   // longitudinal momentum
   else if(_initialStateReconOption==1) {
     double A = 1.;
     double C = -sqr(MDY)/s;
     double B = 2.*pold.z()/sqrt(s);
     if(abs(B)>1e-10) {
       double discrim = 1.-4.*A*C/sqr(B);
       if(discrim < 0.) throw KinematicsReconstructionVeto();
       x1 = B>0. ? 0.5*B/A*(1.+sqrt(discrim)) : 0.5*B/A*(1.-sqrt(discrim));
     }
     else {
       x1 = -C/A;
       if( x1 <= 0.) throw KinematicsReconstructionVeto();
       x1 = sqrt(x1);
     }
     x2 = sqr(MDY)/s/x1;
     k1=a[0]/x1;
     k2=b[1]/x2;
   }
   // preserve mass and don't scale the softer system
   // to reproduce the dipole kinematics
   else if(_initialStateReconOption==2) {
     // in this case kp = k1 or k2 depending on who's the harder guy
     k1 = a[0]*b[1]*s/sqr(MDY);
     if ( pt[0].perp2() < pt[1].perp2() ) swap(k1,k2);
     x1 = a[0]/k1;
     x2 = b[1]/k2;
   }
   else
     assert(false);
   // decompose the momenta
   double anew[2] = {a[0]/k1,a[1]*k2};
   double bnew[2] = {b[0]*k1,b[1]/k2};
   vector<double> boost(2);
   for(unsigned int ix=0;ix<2;++ix) {
     boost[ix] = getBeta(a   [ix]+b   [ix], a[ix]   -b   [ix], 
 			anew[ix]+bnew[ix], anew[ix]-bnew[ix]);
   }
   return boost;
 }
 
 vector<double>
 KinematicsReconstructor::initialStateRescaling(double x1, double x2, 
 					   const Lorentz5Momentum & pold,
 					   const vector<Lorentz5Momentum> & p,
 					   const vector<Lorentz5Momentum> & pq,
 					   const vector<Energy>& highestpts) const {
   Energy2 S = (pq[0]+pq[1]).m2();
   // find alphas and betas in terms of desired basis
   Energy2 p12 = pq[0]*pq[1];
   double a[2] = {p[0]*pq[1]/p12,p[1]*pq[1]/p12};
   double b[2] = {p[0]*pq[0]/p12,p[1]*pq[0]/p12};
   Lorentz5Momentum p1p = p[0] - a[0]*pq[0] - b[0]*pq[1];
   Lorentz5Momentum p2p = p[1] - a[1]*pq[0] - b[1]*pq[1];
   // compute kappa
   // we always want to preserve the mass of the system
   Energy MDY = pold.m();
   Energy2 A = a[0]*b[1]*S;
   Energy2 B = Energy2(sqr(MDY)) - (a[0]*b[0]+a[1]*b[1])*S - (p1p+p2p).m2();
   Energy2 C = a[1]*b[0]*S;
   double rad = 1.-4.*A*C/sqr(B);
   if(rad < 0.) throw KinematicsReconstructionVeto();
   double kp = B/(2.*A)*(1.+sqrt(rad));
   // now compute k1
   // conserve rapidity
   double k1(0.);
   double k2(0.);
   if(_initialStateReconOption==0) {
     rad = kp*(b[0]+kp*b[1])/(kp*a[0]+a[1]);
     rad *= pq[0].z()<ZERO ? exp(-2.*pold.rapidity()) : exp(2.*pold.rapidity());
     if(rad <= 0.) throw KinematicsReconstructionVeto();
     k1 = sqrt(rad);
     k2 = kp/k1;
   }
   // conserve longitudinal momentum
   else if(_initialStateReconOption==1) {
     double a2 = (a[0]+a[1]/kp);
     double b2 = -x2+x1;
     double c2 = -(b[1]*kp+b[0]);
     if(abs(b2)>1e-10) {
       double discrim = 1.-4.*a2*c2/sqr(b2);
       if(discrim < 0.) throw KinematicsReconstructionVeto();
       k1 = b2>0. ? 0.5*b2/a2*(1.+sqrt(discrim)) : 0.5*b2/a2*(1.-sqrt(discrim));
     }
     else {
       k1 = -c2/a2;
       if( k1 <= 0.) throw KinematicsReconstructionVeto();
       k1 = sqrt(k1);
     }
     k2 = kp/k1;
   }
   // preserve mass and don't scale the softer system
   // to reproduce the dipole kinematics
   else if(_initialStateReconOption==2) {
     // in this case kp = k1 or k2 depending on who's the harder guy
     k1 = kp; k2 = 1.;
     if ( highestpts[0] < highestpts[1] )
       swap(k1,k2);
   }
   else
     assert(false);
   // calculate the boosts
   vector<double> beta(2);
   beta[0] = getBeta((a[0]+b[0]), (a[0]-b[0]), (k1*a[0]+b[0]/k1), (k1*a[0]-b[0]/k1));
   beta[1] = getBeta((a[1]+b[1]), (a[1]-b[1]), (a[1]/k2+k2*b[1]), (a[1]/k2-k2*b[1]));
   if (pq[0].z() > ZERO) {
     beta[0] = -beta[0];
     beta[1] = -beta[1];
   }
   return beta;
 }
 
 void KinematicsReconstructor::
 reconstructColourSinglets(vector<ShowerProgenitorPtr> & ShowerHardJets,
 			  ShowerInteraction type) const {
   // identify and catagorize the colour singlet systems
   unsigned int nnun(0),nnii(0),nnif(0),nnf(0),nni(0);
   vector<ColourSingletSystem> 
     systems(identifySystems(set<ShowerProgenitorPtr>(ShowerHardJets.begin(),ShowerHardJets.end()),
 			    nnun,nnii,nnif,nnf,nni));
   // now decide what to do
   // initial-initial connection and final-state colour singlet systems
   LorentzRotation toRest,fromRest;
   bool applyBoost(false),general(false);
   // Drell-Yan type
   if(nnun==0&&nnii==1&&nnif==0&&nnf>0&&nni==0) {
     // reconstruct initial-initial system
     for(unsigned int ix=0;ix<systems.size();++ix) {
       if(systems[ix].type==II) 
 	reconstructInitialInitialSystem(applyBoost,toRest,fromRest,
 					systems[ix].jets);
     }
     if(type!=ShowerInteraction::QCD) {
       combineFinalState(systems);
       general=false;
     }
   }
   // DIS and VBF type
   else if(nnun==0&&nnii==0&&((nnif==1&&nnf>0&&nni==1)||
 			     (nnif==2&&       nni==0))) {
     // check these systems can be reconstructed
     for(unsigned int ix=0;ix<systems.size();++ix) {
       // compute q^2
       if(systems[ix].type!=IF) continue;
       Lorentz5Momentum q;
       for(unsigned int iy=0;iy<systems[ix].jets.size();++iy) {
 	if(systems[ix].jets[iy]->progenitor()->isFinalState())
 	  q += systems[ix].jets[iy]->progenitor()->momentum();
 	else
 	  q -= systems[ix].jets[iy]->progenitor()->momentum();
       }
       q.rescaleMass();
       // check above cut
       if(abs(q.m())>=_minQ) continue;
       if(nnif==1&&nni==1) {
 	throw KinematicsReconstructionVeto();
       }
       else {
 	general = true;
 	break;
       }
     }
     if(!general) {
       for(unsigned int ix=0;ix<systems.size();++ix) {
 	if(systems[ix].type==IF)
 	  reconstructInitialFinalSystem(systems[ix].jets);
       }
     }
   }
   // e+e- type
   else if(nnun==0&&nnii==0&&nnif==0&&nnf>0&&nni==2) {
     general = type!=ShowerInteraction::QCD;
   }
   // general type
   else {
     general = true;
   }
   // final-state systems except for general recon
   if(!general) {
     for(unsigned int ix=0;ix<systems.size();++ix) {
       if(systems[ix].type==F)
 	reconstructFinalStateSystem(applyBoost,toRest,fromRest,
 				    systems[ix].jets);
     }
   }
   else {
     reconstructGeneralSystem(ShowerHardJets);
   }
 }
 
 void KinematicsReconstructor::findInitialBoost(const Lorentz5Momentum & pold,
 					   const Lorentz5Momentum & pnew,
 					   LorentzRotation & toRest,
 					   LorentzRotation & fromRest) const {
   // do one boost
   if(_initialBoost==0) {
     toRest   = LorentzRotation(pold.findBoostToCM());
     fromRest = LorentzRotation(pnew.boostVector());
   }
   else if(_initialBoost==1) {
     // boost to rest frame
     // first transverse
     toRest = Boost(-pold.x()/pold.t(),-pold.y()/pold.t(),0.);
     // then longitudinal
     double beta = pold.z()/sqrt(pold.m2()+sqr(pold.z()));
     toRest.boost((Boost(0.,0.,-beta)));
     // boost from rest frame
     // first apply longitudinal boost
     beta = pnew.z()/sqrt(pnew.m2()+sqr(pnew.z()));
     fromRest=LorentzRotation(Boost(0.,0.,beta));
     // then transverse one
     fromRest.boost(Boost(pnew.x()/pnew.t(),
 			 pnew.y()/pnew.t(),0.));
   }
   else
     assert(false);
 }
diff --git a/Shower/QTilde/Kinematics/KinematicsReconstructor.h b/Shower/QTilde/Kinematics/KinematicsReconstructor.h
--- a/Shower/QTilde/Kinematics/KinematicsReconstructor.h
+++ b/Shower/QTilde/Kinematics/KinematicsReconstructor.h
@@ -1,655 +1,661 @@
 // -*- C++ -*-
 //
 // KinematicsReconstructor.h is a part of Herwig - A multi-purpose Monte Carlo event generator
 // Copyright (C) 2002-2017 The Herwig Collaboration
 //
 // Herwig is licenced under version 3 of the GPL, see COPYING for details.
 // Please respect the MCnet academic guidelines, see GUIDELINES for details.
 //
 #ifndef HERWIG_KinematicsReconstructor_H
 #define HERWIG_KinematicsReconstructor_H
 //
 // This is the declaration of the KinematicsReconstructor class.
 //
 
 #include "ThePEG/Interface/Interfaced.h"
 #include "Herwig/Shower/QTilde/Base/ShowerParticle.h"
 #include "Herwig/Shower/QTilde/Base/ShowerProgenitor.h"
 #include "Herwig/Shower/QTilde/Base/ShowerTree.h"
 #include "Herwig/Shower/QTilde/Base/HardTree.h"
 #include "KinematicsReconstructor.fh"
 #include <cassert>
 
 namespace Herwig {
 
 using namespace ThePEG;
 
   /**\ingroup Shower
    * Exception class
    * used to communicate failure of kinematics
    * reconstruction.
    */
   struct KinematicsReconstructionVeto {};
 
 
 /** \ingroup Shower
  *  A simple struct to store the information we need on the 
  *  showering
  */
 struct JetKinStruct {
 
   /**
    *  Parent particle of the jet
    */
   tShowerParticlePtr parent;
 
   /**
    *  Momentum of the particle before reconstruction
    */
   Lorentz5Momentum p;
 
   /**
    *  Momentum of the particle after reconstruction
    */  
   Lorentz5Momentum q;
 };
 
 /**
  * typedef for a vector of JetKinStruct
  */  
 typedef vector<JetKinStruct> JetKinVect;
 
 /**
  *  Enum to identify types of colour singlet systems
  */
 enum SystemType { UNDEFINED=-1, II, IF, F ,I };
 
 /**
  *  Struct to store colour singlets
  */
 template<typename Value> struct ColourSinglet {
 
   typedef vector<ColourSinglet<Value> > VecType;
   
   ColourSinglet() : type(UNDEFINED) {}
   
   ColourSinglet(SystemType intype,Value inpart) 
     : type(intype),jets(1,inpart) {}
   
   /**
    * The type of system
    */
   SystemType type;
   
   /**
    *  The jets in the system
    */
   vector<Value> jets;
 
 };
 
 /**
  *  Struct to store a colour singlet system of particles
  */
 typedef ColourSinglet<ShowerProgenitorPtr> ColourSingletSystem;
 
 /**
  * Struct to store a colour singlet shower
  */
 typedef ColourSinglet<HardBranchingPtr> ColourSingletShower;
 
 /** \ingroup Shower
  *
  * This class is responsible for the kinematical reconstruction 
  * after each showering step, and also for the necessary Lorentz boosts 
  * in order to preserve energy-momentum conservation in the overall collision,
  * and also the invariant mass and the rapidity of the hard subprocess system.
  * In the case of multi-step showering, there will be not unnecessary
  * kinematical reconstructions. 
  *
  * There is also the option of taking a set of momenta for the particles
  * and inverting the reconstruction to give the evolution variables for the
  * shower.
  *
  * Notice:
  * - although we often use the term "jet" in either methods or variables names,
  *   or in comments, which could appear applicable only for QCD showering,
  *   there is indeed no "dynamics" represented in this class: only kinematics 
  *   is involved, as the name of this class remainds. Therefore it can be used
  *   for any kind of showers (QCD-,QED-,EWK-,... bremsstrahlung).
  * 
  * @see ShowerParticle
  * @see ShowerKinematics
  * @see \ref KinematicsReconstructorInterfaces "The interfaces"
  * defined for KinematicsReconstructor.
  */
 class KinematicsReconstructor: public Interfaced {
 
 public:
 
   /**
    *  Default constructor
    */
-  KinematicsReconstructor() : _reconopt(0), _initialBoost(0), 
-			  _finalStateReconOption(0), 
-			  _initialStateReconOption(0), _minQ(MeV) {};
+  KinematicsReconstructor() : _reconopt(0), _initialBoost(0),
+			      _finalStateReconOption(0),
+			      _initialStateReconOption(0),
+			      _finalFinalWeight(false), _minQ(MeV) {};
 
   /**
    *  Methods to reconstruct the kinematics of a scattering or decay process
    */
   //@{
   /**
    * Given in input a vector of the particles which initiated the showers
    * the method does the reconstruction of such jets,
    * including the appropriate boosts (kinematics reshufflings)  
    * needed to conserve the total energy-momentum of the collision
    * and preserving the invariant mass and the rapidity of the 
    * hard subprocess system.
    */
   virtual bool reconstructHardJets(ShowerTreePtr hard,
 				   const map<tShowerProgenitorPtr,
 				   pair<Energy,double> > & pt,
 				   ShowerInteraction type,
 				   bool switchRecon) const;
 
   /**
    * Given in input a vector of the particles which initiated the showers
    * the method does the reconstruction of such jets,
    * including the appropriate boosts (kinematics reshufflings)  
    * needed to conserve the total energy-momentum of the collision
    * and preserving the invariant mass and the rapidity of the 
    * hard subprocess system.
    */
   virtual bool reconstructDecayJets(ShowerTreePtr decay,
 				    ShowerInteraction type) const;
   //@}
 
   /**
    *  Methods to invert the reconstruction of the shower for
    *  a scattering or decay process and calculate
    *  the variables used to generate the
    *  shower given the particles produced.
    *  This is needed for the CKKW and POWHEG approaches
    */
   //@{
   /**
    *  Given the particles, with a history which we wish to interpret
    *  as a shower reconstruct the variables used to generate the 
    * shower
    */
   virtual bool deconstructDecayJets(HardTreePtr,ShowerInteraction) const;
 
   /**
    *  Given the particles, with a history which we wish to interpret
    *  as a shower reconstruct the variables used to generate the shower
    *  for a hard process
    */
   virtual bool deconstructHardJets(HardTreePtr,ShowerInteraction) const;
   //@}
 
 public:
 
   /** @name Functions used by the persistent I/O system. */
   //@{
   /**
    * Function used to write out object persistently.
    * @param os the persistent output stream written to.
    */
   void persistentOutput(PersistentOStream & os) const;
 
   /**
    * Function used to read in object persistently.
    * @param is the persistent input stream read from.
    * @param version the version number of the object when written.
    */
   void persistentInput(PersistentIStream & is, int version);
   //@}
 
   /**
    * The standard Init function used to initialize the interfaces.
    * Called exactly once for each class by the class description system
    * before the main function starts or
    * when this class is dynamically loaded.
    */
   static void Init();
 
 protected:
 
   /**
    *  Methods to reconstruct the kinematics of individual jets
    */
   //@{
   /**
    * Given the particle (ShowerParticle object) that 
    * originates a forward (time-like) jet, this method reconstructs the kinematics 
    * of the jet. That is, by starting from the final grand-children (which 
    * originates directly or indirectly from particleJetParent, 
    * and which don't have children), and moving "backwards" (in a physical
    * time picture), towards the particleJetParent, the 
    * ShowerKinematics objects associated with the various particles, 
    * which have been created during the showering, are now completed. 
    * In particular, at the end, we get the mass of the jet, which is the 
    * main information we want.
    * This methods returns false if there was no radiation or rescaling required
    */
   virtual bool reconstructTimeLikeJet(const tShowerParticlePtr particleJetParent) const;
 
   /**
    * Exactly similar to the previous one, but for a space-like jet.
    * Also in this case we start from the final grand-children (which
    * are childless) of the particle which originates the jet, but in
    * this case we proceed "forward" (in the physical time picture)
    * towards the particleJetParent.
    * This methods returns false if there was no radiation or rescaling required
    */
   bool reconstructSpaceLikeJet(const tShowerParticlePtr particleJetParent) const;
 
   /**
    * Exactly similar to the previous one, but for a decay jet
    * This methods returns false if there was no radiation or rescaling required
    */
   bool reconstructDecayJet(const tShowerParticlePtr particleJetParent) const;
   //@}
 
   /**
    *  Methods to perform the reconstruction of various types of colour
    *  singlet systems
    */
   //@{
   /**
    *  Perform the reconstruction of a system with one incoming and at least one
    *  outgoing particle
    */
   void reconstructInitialFinalSystem(vector<ShowerProgenitorPtr>) const;
 
   /**
    *  Perform the reconstruction of a system with only final-state
    *  particles
    */
   void reconstructFinalStateSystem(bool applyBoost, 
 				   const LorentzRotation & toRest,
 				   const LorentzRotation & fromRest, 
 				   vector<ShowerProgenitorPtr>) const;
 
   /**
    *  Reconstruction of a general coloured system
    */
   void reconstructGeneralSystem(vector<ShowerProgenitorPtr> & ShowerHardJets) const;
 
   /**
    * Reconstruction of a general coloured system doing 
    * final-final, then initial-final and then initial-initial
    */
   void reconstructFinalFirst(vector<ShowerProgenitorPtr> & ShowerHardJets) const;
 
   /**
    *  Reconstruction of a general coloured system doing
    *  colour parners
    */
   void reconstructColourPartner(vector<ShowerProgenitorPtr> & ShowerHardJets) const;
 
   /**
    *  Reconstruction based on colour singlet systems
    */
   void reconstructColourSinglets(vector<ShowerProgenitorPtr> & ShowerHardJets,
 				 ShowerInteraction type) const;
 
   /**
    *  Perform the reconstruction of a system with only final-state
    *  particles
    */
   void reconstructInitialInitialSystem(bool & applyBoost,
 				       LorentzRotation &   toRest,
 				       LorentzRotation & fromRest,
 				       vector<ShowerProgenitorPtr>) const;
   //@}
 
   /**
    *  Methods to perform the inverse reconstruction of various types of
    *  colour singlet systems
    */
   //@{
   /**
    *  Perform the inverse reconstruction of a system with only final-state
    *  particles
    */
   void deconstructFinalStateSystem(const LorentzRotation &   toRest,
 				   const LorentzRotation & fromRest,
 				   HardTreePtr,
 				   vector<HardBranchingPtr>,
 				   ShowerInteraction) const;
   
   /**
    *  Perform the inverse reconstruction of a system with only initial-state
    *  particles
    */
   void deconstructInitialInitialSystem(bool & applyBoost,
 				       LorentzRotation &   toRest,
 				       LorentzRotation & fromRest,
 				       HardTreePtr,
 				       vector<HardBranchingPtr>,
 				       ShowerInteraction ) const;
 
   /**
    *  Perform the inverse reconstruction of a system with only initial-state
    *  particles
    */
   void deconstructInitialFinalSystem(HardTreePtr,
 				     vector<HardBranchingPtr>,
 				     ShowerInteraction ) const;
 
   bool deconstructGeneralSystem(HardTreePtr,
 				ShowerInteraction) const;
 
   bool deconstructColourSinglets(HardTreePtr,
 				 ShowerInteraction) const;
 
   bool deconstructColourPartner(HardTreePtr,
 				ShowerInteraction) const;
   //@}
 
   /**
    *   Recursively treat the most off-shell paricle seperately
    * for final-final reconstruction
    */
   void reconstructFinalFinalOffShell(JetKinVect orderedJets, Energy2 s,
 				     bool recursive) const;
 
   /**
    *  Various methods for the Lorentz transforms needed to do the 
    *  rescalings
    */
   //@{
   /**
    * Compute the boost to get from the the old momentum to the new 
    */
   LorentzRotation solveBoost(const double k, 
 			     const Lorentz5Momentum & newq, 
 			     const Lorentz5Momentum & oldp) const;
   
   /**
    * Compute the boost to get from the the old momentum to the new 
    */
   LorentzRotation solveBoost(const Lorentz5Momentum & newq, 
 			     const Lorentz5Momentum & oldq) const;
   
   /**
    * Compute the boost to get from the the old momentum to the new 
    */
   LorentzRotation solveBoostZ(const Lorentz5Momentum & newq, 
 			      const Lorentz5Momentum & oldq) const;
   
   /**
    *  Recursively boost the initial-state shower
    * @param p The particle
    * @param bv The boost
    * @param parent The parent of the chain
    */
   void boostChain(tPPtr p, const LorentzRotation & bv, tPPtr & parent) const;
 
   /**
    * Given a 5-momentum and a scale factor, the method returns the
    * Lorentz boost that transforms the 3-vector vec{momentum} --->
    * k*vec{momentum}. The method returns the null boost in the case no
    * solution exists. This will only work in the case where the
    * outgoing jet-momenta are parallel to the momenta of the particles
    * leaving the hard subprocess. 
    */
   Boost solveBoostBeta( const double k, const Lorentz5Momentum & newq, 
 			  const Lorentz5Momentum & oldp);
 
   /**
    * Compute boost parameter along z axis to get (Ep, any perp, qp)
    * from (E, same perp, q).
    */
   double getBeta(const double E, const double q, 
 		 const double Ep, const double qp) const
   {return (q*E-qp*Ep)/(sqr(qp)+sqr(E));}
   //@}
 
   /**
    *  Methods to calculate the various scaling factors
    */
   //@{
   /**
    * Given a vector of 5-momenta of jets, where the 3-momenta are the initial
    * ones before showering and the masses are reconstructed after the showering,
    * this method returns the overall scaling factor for the 3-momenta of the
    * vector of particles, vec{P}_i -> k * vec{P}_i, such to preserve energy-
    * momentum conservation, i.e. after the rescaling the center of mass 5-momentum 
    * is equal to the one specified in input, cmMomentum. 
    * The method returns 0 if such factor cannot be found.
    * @param root_s Centre-of-mass energy
    * @param jets The jets
    */
   double solveKfactor( const Energy & root_s, const JetKinVect & jets ) const;
 
   /**
    *  Calculate the rescaling factors for the jets in a particle decay where
    *  there was initial-state radiation
    * @param mb The mass of the decaying particle
    * @param n  The reference vector for the initial state radiation
    * @param pjet The momentum of the initial-state jet
    * @param jetKinematics The JetKinStruct objects for the jets
    * @param partner The colour partner
    * @param ppartner The momentum of the colour partner of the decaying particle
    * before and after radiation
    * @param k1 The rescaling parameter for the partner
    * @param k2 The rescaling parameter for the outgoing singlet
    * @param qt The transverse momentum vector
    */
   bool solveDecayKFactor(Energy mb, 
 			 const Lorentz5Momentum & n, 
 			 const Lorentz5Momentum & pjet, 
 			 const JetKinVect & jetKinematics, 
 			 ShowerParticlePtr partner,
 			 Lorentz5Momentum ppartner[2],
 			 double & k1, 
 			 double & k2,
 			 Lorentz5Momentum & qt) const;
 
   /**
    * Compute the momentum rescaling factor needed to invert the shower
    * @param pout The momenta of the outgoing particles
    * @param mon  The on-shell masses
    * @param roots The mass of the decaying particle
    */
   double inverseRescalingFactor(vector<Lorentz5Momentum> pout,
 				vector<Energy> mon,Energy roots) const;
 
   /**
    * Compute the momentum rescaling factor needed to invert the shower
    * @param pout The momenta of the outgoing particles
    * @param mon  The on-shell masses
    * @param roots The mass of the decaying particle
    * @param ppartner The momentum of the colour partner
    * @param mbar The mass of the decaying particle
    * @param k1 The first scaling factor
    * @param k2 The second scaling factor
    */
   bool inverseDecayRescalingFactor(vector<Lorentz5Momentum> pout,
 				   vector<Energy> mon,Energy roots,
 				   Lorentz5Momentum ppartner, Energy mbar,
 				   double & k1, double & k2) const;
 
   /**
    * Check the rescaling conserves momentum
    * @param k The rescaling
    * @param root_s The centre-of-mass energy
    * @param jets The jets
    */
   Energy momConsEq(double k, const Energy & root_s,
 		   const JetKinVect & jets) const;
 
 
   void findInitialBoost(const Lorentz5Momentum & pold, const Lorentz5Momentum & pnew,
 			LorentzRotation & toRest, LorentzRotation & fromRest) const;
   //@}
 
   /**
    *  Find the colour partners of a particle to identify the colour singlet
    *  systems for the reconstruction.
    */
   template<typename Value> void findPartners(Value branch,set<Value> & done,
 					     const set<Value> & branchings,
 					     vector<Value> & jets) const;
 
   /**
    *  Add the intrinsic \f$p_T\f$ to the system if needed
    */
   bool addIntrinsicPt(vector<ShowerProgenitorPtr>) const;
 
   /**
    *  Apply a transform to the particle and any child, including child ShowerTree
    *  objects
    * @param particle The particle
    * @param r The Lorentz transformation
    * @param match Whether or not to look at children etc
    * @param original The original particle
    */
   void deepTransform(PPtr particle,const LorentzRotation & r,
 		     bool match=true,PPtr original=PPtr()) const;
 
   /**
    *  Find the mass of a particle in the hard branching
    */
   Energy findMass(HardBranchingPtr) const;
 
   /**
    *  Calculate the initial-state rescaling factors
    */
   vector<double> initialStateRescaling(double x1, double x2, 
 				       const Lorentz5Momentum & pold,
 				       const vector<Lorentz5Momentum> & p,
 				       const vector<Lorentz5Momentum> & pq,
 				       const vector<Energy>& highespts) const;
 
   /**
    *  Calculate the inverse of the initial-state rescaling factor
    */
   vector<double> inverseInitialStateRescaling(double & x1, double & x2,
 					      const Lorentz5Momentum & pold,
 					      const vector<Lorentz5Momentum> & p,
 					      const vector<Lorentz5Momentum> & pq) const;
 
   /**
    *  Find the colour singlet systems
    */
   template<typename Value >
   typename ColourSinglet<Value>::VecType identifySystems(set<Value> jets,
 							 unsigned int & nnun,unsigned int & nnii,
 							 unsigned int & nnif,unsigned int & nnf,
 							 unsigned int & nni) const;
 
   /**
    *  Combine final-state colour systems
    */
   template<typename Value>
   void combineFinalState(vector<ColourSinglet<Value> > & systems) const;
 
 protected:
 
   /** @name Clone Methods. */
   //@{
   /**
    * Make a simple clone of this object.
    * @return a pointer to the new object.
    */
   virtual IBPtr clone() const {return new_ptr(*this);}
 
   /** Make a clone of this object, possibly modifying the cloned object
    * to make it sane.
    * @return a pointer to the new object.
    */
   virtual IBPtr fullclone() const {return new_ptr(*this);}
   //@}
 
 protected:
 
   /** @name Standard Interfaced functions. */
   //@{
   /**
    * Initialize this object after the setup phase before saving an
    * EventGenerator to disk.
    * @throws InitException if object could not be initialized properly.
    */
   virtual void doinit();
   //@}
 
 private:
 
   /**
    * The assignment operator is private and must never be called.
    * In fact, it should not even be implemented.
    */
   KinematicsReconstructor & operator=(const KinematicsReconstructor &) = delete;
 
 private:
 
   /**
    *  Option for handling the reconstruction
    */
   unsigned int _reconopt;
 
   /**
    *  Option for the boost for initial-initial reconstruction
    */
   unsigned int _initialBoost;
 
   /**
    * Option for the reconstruction of final state systems
    */
   unsigned int _finalStateReconOption;
 
   /**
    * Option for the initial state reconstruction
    */
   unsigned int _initialStateReconOption;
 
   /**
+   *  Option for FF kinematic factor
+   */
+  bool _finalFinalWeight;
+
+  /**
    * Minimum invariant mass for initial-final dipoles to allow the
    * reconstruction
    */
   Energy _minQ;
 
   /**
    *  The progenitor of the jet currently being reconstructed
    */
   mutable tShowerParticlePtr _progenitor;
 
   /**
    * Storage of the intrinsic \f$p_T\f$
    */
   mutable map<tShowerProgenitorPtr,pair<Energy,double> > _intrinsic;
 
   /**
    *  Current ShowerTree
    */
   mutable tShowerTreePtr _currentTree;
 
   /**
    * Particles which shouldn't have their masses rescaled as
    * vector for the interface
    */
   PDVector _noRescaleVector;
 
   /**
    * Particles which shouldn't have their masses rescaled as
    * set for quick access
    */
   set<cPDPtr> _noRescale;
 
   /**
    * Storage of the boosts applied to enable resetting after failure
    */
   mutable map<tPPtr,vector<LorentzRotation> > _boosts;
 
   /**
    * Storage of the boosts applied to enable resetting after failure
    */
   mutable map<tShowerTreePtr,vector<LorentzRotation> > _treeBoosts;
 };
 
 }
 
 #endif /* HERWIG_KinematicsReconstructor_H */
diff --git a/Shower/QTilde/Kinematics/ShowerKinematics.cc b/Shower/QTilde/Kinematics/ShowerKinematics.cc
--- a/Shower/QTilde/Kinematics/ShowerKinematics.cc
+++ b/Shower/QTilde/Kinematics/ShowerKinematics.cc
@@ -1,69 +1,70 @@
 // -*- C++ -*-
 //
 // ShowerKinematics.cc is a part of Herwig - A multi-purpose Monte Carlo event generator
 // Copyright (C) 2002-2017 The Herwig Collaboration
 //
 // Herwig is licenced under version 3 of the GPL, see COPYING for details.
 // Please respect the MCnet academic guidelines, see GUIDELINES for details.
 //
 //
 // This is the implementation of the non-inlined, non-templated member
 // functions of the ShowerKinematics class.
 //
 #include "ShowerKinematics.h"
 #include "ThePEG/Utilities/DescribeClass.h"
 
 using namespace Herwig;
 
 DescribeAbstractNoPIOClass<ShowerKinematics,Base>
 describeShowerKinematics("Herwig::ShowerKinematics","Herwig.so");
 
 void ShowerKinematics::updateChildren(const tShowerParticlePtr, 
 				      const ShowerParticleVector &,
 				      ShowerPartnerType) const {
   throw Exception() << "Base class ShowerKinematics::updateChildren called,"
 		    << " should have been overriden in an inheriting class" 
 		    << Exception::runerror;
 }
 void ShowerKinematics::resetChildren(const tShowerParticlePtr, 
 				      const ShowerParticleVector &) const {
   throw Exception() << "Base class ShowerKinematics::resetChildren called,"
 		    << " should have been overriden in an inheriting class" 
 		    << Exception::runerror;
 }
 
 void ShowerKinematics::updateParent(const tShowerParticlePtr, 
 				    const ShowerParticleVector &,
+				    unsigned int ,
 				    ShowerPartnerType) const {
   throw Exception() << "Base class ShowerKinematics::updateParent called,"
 		    << " should have been overriden in an inheriting class" 
 		    << Exception::runerror;
 }
 
 void ShowerKinematics::reconstructChildren(const tShowerParticlePtr, 
 					   const ShowerParticleVector &) const {
   throw Exception() << "Base class ShowerKinematics::reconstructChildren called,"
 		    << " should have been overriden in an inheriting class" 
 		    << Exception::runerror;
 }
 
 void ShowerKinematics::reconstructParent(const tShowerParticlePtr, 
 					 const ParticleVector &) const {
   throw Exception() << "Base class ShowerKinematics::reconstructParent called,"
 		    << " should have been overriden in an inheriting class" 
 		    << Exception::runerror;
 }
 
 void ShowerKinematics::reconstructLast(const tShowerParticlePtr,
 				       Energy) const {
   throw Exception() << "Base class ShowerKinematics::reconstructLast called,"
 		    << " should have been overriden in an inheriting class"
 		    << Exception::runerror;
 }
 
 void ShowerKinematics::updateLast(const tShowerParticlePtr,
 				  Energy,Energy) const {
   throw Exception() << "Base class ShowerKinematics::updatetLast called,"
 		    << " should have been overriden in an inheriting class"
 		    << Exception::runerror;
 }
diff --git a/Shower/QTilde/Kinematics/ShowerKinematics.h b/Shower/QTilde/Kinematics/ShowerKinematics.h
--- a/Shower/QTilde/Kinematics/ShowerKinematics.h
+++ b/Shower/QTilde/Kinematics/ShowerKinematics.h
@@ -1,261 +1,262 @@
 // -*- C++ -*-
 //
 // ShowerKinematics.h is a part of Herwig - A multi-purpose Monte Carlo event generator
 // Copyright (C) 2002-2017 The Herwig Collaboration
 //
 // Herwig is licenced under version 3 of the GPL, see COPYING for details.
 // Please respect the MCnet academic guidelines, see GUIDELINES for details.
 //
 #ifndef HERWIG_ShowerKinematics_H
 #define HERWIG_ShowerKinematics_H
 //
 // This is the declaration of the ShowerKinematics class.
 //
 
 #include "Herwig/Shower/QTilde/ShowerConfig.h"
 #include "ThePEG/Config/ThePEG.h"
 #include "Herwig/Shower/QTilde/SplittingFunctions/SudakovFormFactor.h"
 #include "Herwig/Shower/QTilde/Kinematics/ShowerKinematics.fh"
 
 namespace Herwig {
 
 using namespace ThePEG;
 
 /**\ingroup Shower
  *
  * This is the abstract base class from which all other shower
  * kinematics classes derive. The main purpose of the
  * shower kinematics classes is to allow the reconstruction
  * of jet masses, at the end of the showering (indeed, for
  * multi-scale showering, at the end of each scale-range evolution).
  * This is necessary for the kinematics reshuffling
  * in order to compensate the recoil of the emissions.
  * The KinematicsReconstructor class is in 
  * charge of this job, and which is the main "user" of
  * ShowerKinematics and its derived classes.
  * How this is done depends on the choice of kinematics variables 
  * and whether the jet is time-like (forward evolved) or 
  * space-like (backward evolved), whereas the class ShowerKinematics
  * describes only the common features which are independent by them.   
  *
  *  In general there are a number of methods specific to a shower approach
  *
  * @see KinematicsReconstructor
  */
 class ShowerKinematics: public Base {
 
 public:
 
   /**
    * The default constructor.
    */
   ShowerKinematics() : Base(),
 		       _scale(), _z( 0.0 ), _phi( 0.0 ), _pt(),
 		       _sudakov() {}
 
   /**
    * The default constructor.
    */
   ShowerKinematics(Energy scale, double z, double phi, Energy pt, tSudakovPtr sud) 
     : Base(),
       _scale(scale), _z(z), _phi(phi), _pt(pt),
       _sudakov(sud) {}
 
   /**
    *  The updateChildren and updateParent
    *  members to update the values of the \f$\alpha\f$ and 
    *  \f$p_\perp\f$ variables during the shower evolution.
    */
   //@{
   /**
    * Along with the showering evolution --- going forward for
    * time-like (forward) evolution, and going backward for space-like
    * (backward) evolution --- the kinematical variables of the
    * branching products are calculated and updated from the knowledge
    * of the parent kinematics. 
    * @param parent   The parent
    * @param children The children
    * @param partnerType The type of evolution partner
    */
   virtual void updateChildren(const tShowerParticlePtr parent, 
 			      const ShowerParticleVector & children,
 			      ShowerPartnerType partnerType) const;
 
   virtual void resetChildren( const tShowerParticlePtr parent, 
 			      const ShowerParticleVector & children) const;
 
   /**
    * Update the parent Kinematics from the knowledge of the kinematics
    * of the children. This method will be used by the KinematicsReconstructor.
    * @param parent   The parent
    * @param children The children
    * @param partnerType The type of evolution partner
    */
   virtual void updateParent(const tShowerParticlePtr parent,
 			    const ShowerParticleVector & children,
+			    unsigned int pTscheme,
 			    ShowerPartnerType partnerType) const;
 
   /**
    * Update the kinematical data of a particle when a reconstruction
    * fixpoint was found. This will highly depend on the kind of
    * kinematics chosen and will be defined in the inherited concrete
    * classes. This method will be used by the KinematicsReconstructor.
    * @param last The particle.
    * @param px The \f$x\f$ component of the \f$p_T\f$.
    * @param py The \f$y\f$ component of the \f$p_T\f$.
    */
   virtual void updateLast(const tShowerParticlePtr last,
 			  Energy px, Energy py) const;
   //@}
 
   /**
    *  The reconstructLast, reconstructChildren and reconstructParent members
    *  are used during the reconstruction 
    */
   //@{
   /**
    * Along with the showering evolution --- going forward for
    * time-like (forward) evolution, and going backward for space-like
    * (backward) evolution --- the kinematical variables of the
    * branching products are calculated and updated from the knowledge
    * of the parent kinematics. 
    * @param parent   The parent
    * @param children The children
    */
   virtual void reconstructChildren(const tShowerParticlePtr parent, 
 			      const ShowerParticleVector & children) const;
 
   /**
    * Reconstruct the parent Kinematics from the knowledge of the kinematics
    * of the children. This method will be used by the KinematicsReconstructor.
    * @param parent   The parent
    * @param children The children
    */
   virtual void reconstructParent(const tShowerParticlePtr parent, 
 				 const ParticleVector & children) const;
 
   /**
    * Update the kinematical data of a particle when a reconstruction
    * fixpoint was found. This will highly depend on the kind of
    * kinematics chosen and will be defined in the inherited concrete
    * classes. This method will be used by the KinematicsReconstructor.
    * @param last The particle.
    * @param mass The mass to be used, if less than zero on-shell
    */
   virtual void reconstructLast(const tShowerParticlePtr last, Energy mass=-1.*GeV) const;
   //@}
 
 public:
 
   /**
    *  Set/Get methods for the kinematic variables
    */
   //@{
   /**
    * Access the scale of the splitting.
    */
   Energy scale() const { return _scale; }
 
   /**
    * Set the scale of the splitting.
    */
   void scale(const Energy in) { _scale=in; }
 
   /**
    *  Access the energy fraction, \f$z\f$.
    */
   double z() const { return _z; }
 
   /**
    *  Set the energy fraction, \f$z\f$.
    */
   void z(const double in) { _z=in; }
 
   /**
    *  Access the azimuthal angle, \f$\phi\f$.
    */
   double phi() const { return _phi; }
 
   /**
    *  Set the azimuthal angle, \f$\phi\f$.
    */
   void phi(const double in) { _phi=in; }
 
   /**
    *  Access the relative \f$p_T\f$ for the branching
    */
   Energy pT() const { return _pt; }
 
   /**
    *  Set the relative \f$p_T\f$ for the branching
    */
   void pT(const Energy in) const { _pt=in; }
   //@}
 
   /**
    *  Set and get methods for the SplittingFunction object
    */
   //@{
   /**
    * Access the SplittingFunction object responsible of the 
    * eventual branching of this particle.
    */
   tSplittingFnPtr splittingFn() const { return _sudakov-> splittingFn(); }
   //@}
 
   /**
    *  Set and get methods for the SudakovFormFactor object
    */
   /**
    * Access the SudakovFormFactor object responsible of the 
    * eventual branching of this particle.
    */
   tSudakovPtr SudakovFormFactor() const { return _sudakov; }
 
   /**
    * Set the SudakovFormFactor object responsible of the 
    * eventual branching of this particle.
    */
   void SudakovFormFactor(const tSudakovPtr sud) { _sudakov=sud; }
   //@}
 
 private:
 
   /**
    * The assignment operator is private and must never be called.
    * In fact, it should not even be implemented.
    */
   ShowerKinematics & operator=(const ShowerKinematics &) = delete;
 
 private:
 
   /**
    *  The \f$\tilde{q}\f$ evolution variable.
    */
   Energy _scale;
 
   /**
    *  The energy fraction, \f$z\f$
    */
   double _z;
 
   /**
    *  The azimuthal angle, \f$\phi\f$.
    */
   double _phi;
 
   /**
    *  The relative \f$p_T\f$
    */
   mutable Energy _pt;
 
   /**
    *  The splitting function for the branching of the particle
    */
   tSudakovPtr _sudakov;
 
 };
 
 }
 
 #endif /* HERWIG_ShowerKinematics_H */
diff --git a/Shower/QTilde/QTildeShowerHandler.cc b/Shower/QTilde/QTildeShowerHandler.cc
--- a/Shower/QTilde/QTildeShowerHandler.cc
+++ b/Shower/QTilde/QTildeShowerHandler.cc
@@ -1,3229 +1,3237 @@
 // -*- C++ -*-
 //
 // QTildeShowerHandler.cc is a part of Herwig - A multi-purpose Monte Carlo event generator
 // Copyright (C) 2002-2017 The Herwig Collaboration
 //
 // Herwig is licenced under version 3 of the GPL, see COPYING for details.
 // Please respect the MCnet academic guidelines, see GUIDELINES for details.
 //
 // This is the implementation of the non-inlined, non-templated member
 // functions of the QTildeShowerHandler class.
 //
 
 #include "QTildeShowerHandler.h"
+#include "ThePEG/Interface/Deleted.h"
 #include "ThePEG/Interface/ClassDocumentation.h"
 #include "ThePEG/Interface/Switch.h"
 #include "ThePEG/Interface/Reference.h"
 #include "ThePEG/Interface/RefVector.h"
 #include "ThePEG/Interface/Parameter.h"
 #include "ThePEG/EventRecord/Particle.h"
 #include "ThePEG/Repository/UseRandom.h"
 #include "ThePEG/Repository/EventGenerator.h"
 #include "ThePEG/Utilities/DescribeClass.h"
 #include "ThePEG/Persistency/PersistentOStream.h"
 #include "ThePEG/Persistency/PersistentIStream.h"
 #include "ThePEG/Utilities/EnumIO.h"
 #include "Herwig/Shower/QTilde/Base/ShowerParticle.h"
 #include "Herwig/PDF/MPIPDF.h"
 #include "Herwig/PDF/MinBiasPDF.h"
 #include "Herwig/Shower/QTilde/Base/ShowerTree.h"
 #include "Herwig/Shower/QTilde/Base/HardTree.h"
 #include "Herwig/Shower/QTilde/Kinematics/KinematicsReconstructor.h"
 #include "Herwig/Shower/QTilde/Base/PartnerFinder.h"
 #include "Herwig/PDF/HwRemDecayer.h"
 #include "Herwig/Shower/QTilde/Base/ShowerVertex.h"
 #include "ThePEG/Repository/CurrentGenerator.h"
 #include "Herwig/MatrixElement/Matchbox/Base/SubtractedME.h"
 #include "Herwig/MatrixElement/Matchbox/MatchboxFactory.h"
 #include "ThePEG/PDF/PartonExtractor.h"
 #include "Herwig/Shower/RealEmissionProcess.h"
 #include "Herwig/Shower/QTilde/Kinematics/FS_QTildeShowerKinematics1to2.h"
 #include "Herwig/Shower/QTilde/Kinematics/IS_QTildeShowerKinematics1to2.h"
 #include "Herwig/Shower/QTilde/Kinematics/Decay_QTildeShowerKinematics1to2.h"
 
 
 using namespace Herwig;
 
 bool QTildeShowerHandler::_hardEmissionWarn = true;
 bool QTildeShowerHandler::_missingTruncWarn = true;
 
 QTildeShowerHandler::QTildeShowerHandler() :
-  _maxtry(100), _meCorrMode(1), _reconOpt(0),
+  _maxtry(100), _meCorrMode(1), _evolutionScheme(1),
   _hardVetoReadOption(false),
   _iptrms(ZERO), _beta(0.), _gamma(ZERO), _iptmax(),
   _limitEmissions(0), _initialenhance(1.), _finalenhance(1.),
   _nReWeight(100), _reWeight(false),
   interaction_(ShowerInteraction::QEDQCD),
   _trunc_Mode(true), _hardEmission(1),
   _softOpt(2), _hardPOWHEG(false), muPt(ZERO)
 {}
 
 QTildeShowerHandler::~QTildeShowerHandler() {}
 
 IBPtr QTildeShowerHandler::clone() const {
   return new_ptr(*this);
 }
 
 IBPtr QTildeShowerHandler::fullclone() const {
   return new_ptr(*this);
 }
 
 void QTildeShowerHandler::persistentOutput(PersistentOStream & os) const {
   os << _splittingGenerator << _maxtry 
      << _meCorrMode << _hardVetoReadOption
      << _limitEmissions << _softOpt << _hardPOWHEG
      << ounit(_iptrms,GeV) << _beta << ounit(_gamma,GeV) << ounit(_iptmax,GeV) 
      << _vetoes << _fullShowerVetoes << _nReWeight << _reWeight
-     << _trunc_Mode << _hardEmission << _reconOpt 
+     << _trunc_Mode << _hardEmission << _evolutionScheme 
      << ounit(muPt,GeV) << oenum(interaction_) 
      << _reconstructor << _partnerfinder;
 }
 
 void QTildeShowerHandler::persistentInput(PersistentIStream & is, int) {
   is >> _splittingGenerator >> _maxtry 
      >> _meCorrMode >> _hardVetoReadOption
      >> _limitEmissions >> _softOpt >> _hardPOWHEG
      >> iunit(_iptrms,GeV) >> _beta >> iunit(_gamma,GeV) >> iunit(_iptmax,GeV)
      >> _vetoes >> _fullShowerVetoes >> _nReWeight >> _reWeight
-     >> _trunc_Mode >> _hardEmission >> _reconOpt
+     >> _trunc_Mode >> _hardEmission >> _evolutionScheme
      >> iunit(muPt,GeV) >> ienum(interaction_)
      >> _reconstructor >> _partnerfinder;
 }
 
 
 // The following static variable is needed for the type
 // description system in ThePEG. 
 DescribeClass<QTildeShowerHandler,ShowerHandler>
 describeHerwigQTildeShowerHandler("Herwig::QTildeShowerHandler", "HwShower.so");
 
 void QTildeShowerHandler::Init() {
 
   static ClassDocumentation<QTildeShowerHandler> documentation
     ("TheQTildeShowerHandler class is the main class"
      " for the angular-ordered parton shower",
      "The Shower evolution was performed using an algorithm described in "
      "\\cite{Marchesini:1983bm,Marchesini:1987cf,Gieseke:2003rz,Bahr:2008pv}.",
      "%\\cite{Marchesini:1983bm}\n"
      "\\bibitem{Marchesini:1983bm}\n"
      "  G.~Marchesini and B.~R.~Webber,\n"
      "  ``Simulation Of QCD Jets Including Soft Gluon Interference,''\n"
      "  Nucl.\\ Phys.\\  B {\\bf 238}, 1 (1984).\n"
      "  %%CITATION = NUPHA,B238,1;%%\n"
      "%\\cite{Marchesini:1987cf}\n"
      "\\bibitem{Marchesini:1987cf}\n"
      "  G.~Marchesini and B.~R.~Webber,\n"
      "   ``Monte Carlo Simulation of General Hard Processes with Coherent QCD\n"
      "  Radiation,''\n"
      "  Nucl.\\ Phys.\\  B {\\bf 310}, 461 (1988).\n"
      "  %%CITATION = NUPHA,B310,461;%%\n"
      "%\\cite{Gieseke:2003rz}\n"
      "\\bibitem{Gieseke:2003rz}\n"
      "  S.~Gieseke, P.~Stephens and B.~Webber,\n"
      "  ``New formalism for QCD parton showers,''\n"
      "  JHEP {\\bf 0312}, 045 (2003)\n"
      "  [arXiv:hep-ph/0310083].\n"
      "  %%CITATION = JHEPA,0312,045;%%\n"
      );
 
   static Reference<QTildeShowerHandler,SplittingGenerator> 
     interfaceSplitGen("SplittingGenerator", 
 		      "A reference to the SplittingGenerator object", 
 		      &Herwig::QTildeShowerHandler::_splittingGenerator,
 		      false, false, true, false);
 
   static Parameter<QTildeShowerHandler,unsigned int> interfaceMaxTry
     ("MaxTry",
      "The maximum number of attempts to generate the shower from a"
      " particular ShowerTree",
      &QTildeShowerHandler::_maxtry, 100, 1, 100000,
      false, false, Interface::limited);
 
   static Parameter<QTildeShowerHandler,unsigned int> interfaceNReWeight
     ("NReWeight",
      "The number of attempts for the shower when reweighting",
      &QTildeShowerHandler::_nReWeight, 100, 10, 10000,
      false, false, Interface::limited);
 
   static Switch<QTildeShowerHandler, unsigned int> ifaceMECorrMode
     ("MECorrMode",
      "Choice of the ME Correction Mode",
      &QTildeShowerHandler::_meCorrMode, 1, false, false);
   static SwitchOption on
     (ifaceMECorrMode,"HardPlusSoft","hard+soft on", 1);
   static SwitchOption hard
     (ifaceMECorrMode,"Hard","only hard on", 2);
   static SwitchOption soft
     (ifaceMECorrMode,"Soft","only soft on", 3);
 
   static Switch<QTildeShowerHandler, bool> ifaceHardVetoReadOption
     ("HardVetoReadOption",
      "Apply read-in scale veto to all collisions or just the primary one?",
      &QTildeShowerHandler::_hardVetoReadOption, false, false, false);
   static SwitchOption AllCollisions
     (ifaceHardVetoReadOption,
      "AllCollisions",
      "Read-in pT veto applied to primary and secondary collisions.",
      false);
   static SwitchOption PrimaryCollision
     (ifaceHardVetoReadOption,
      "PrimaryCollision",
      "Read-in pT veto applied to primary but not secondary collisions.",
      true);
 
   static Parameter<QTildeShowerHandler, Energy> ifaceiptrms
     ("IntrinsicPtGaussian",
      "RMS of intrinsic pT of Gaussian distribution:\n"
      "2*(1-Beta)*exp(-sqr(intrinsicpT/RMS))/sqr(RMS)",
      &QTildeShowerHandler::_iptrms, GeV, ZERO, ZERO, 1000000.0*GeV,
      false, false, Interface::limited);
 
   static Parameter<QTildeShowerHandler, double> ifacebeta
     ("IntrinsicPtBeta",
      "Proportion of inverse quadratic distribution in generating intrinsic pT.\n"
      "(1-Beta) is the proportion of Gaussian distribution",
      &QTildeShowerHandler::_beta, 0, 0, 1,
      false, false, Interface::limited);
 
   static Parameter<QTildeShowerHandler, Energy> ifacegamma
     ("IntrinsicPtGamma",
      "Parameter for inverse quadratic:\n"
      "2*Beta*Gamma/(sqr(Gamma)+sqr(intrinsicpT))",
      &QTildeShowerHandler::_gamma,GeV, ZERO, ZERO, 100000.0*GeV,
      false, false, Interface::limited);
 
   static Parameter<QTildeShowerHandler, Energy> ifaceiptmax
     ("IntrinsicPtIptmax",
      "Upper bound on intrinsic pT for inverse quadratic",
      &QTildeShowerHandler::_iptmax,GeV, ZERO, ZERO, 100000.0*GeV,
      false, false, Interface::limited);
 
   static RefVector<QTildeShowerHandler,ShowerVeto> ifaceVetoes
     ("Vetoes",
      "The vetoes to be checked during showering",
      &QTildeShowerHandler::_vetoes, -1,
      false,false,true,true,false);
  
   static RefVector<QTildeShowerHandler,FullShowerVeto> interfaceFullShowerVetoes
     ("FullShowerVetoes",
      "The vetos to be appliede on the full final state of the shower",
      &QTildeShowerHandler::_fullShowerVetoes, -1, false, false, true, false, false);
 
   static Switch<QTildeShowerHandler,unsigned int> interfaceLimitEmissions
     ("LimitEmissions",
      "Limit the number and type of emissions for testing",
      &QTildeShowerHandler::_limitEmissions, 0, false, false);
   static SwitchOption interfaceLimitEmissionsNoLimit
     (interfaceLimitEmissions,
      "NoLimit",
      "Allow an arbitrary number of emissions",
      0);
   static SwitchOption interfaceLimitEmissionsOneInitialStateEmission
     (interfaceLimitEmissions,
      "OneInitialStateEmission",
      "Allow one emission in the initial state and none in the final state",
      1);
   static SwitchOption interfaceLimitEmissionsOneFinalStateEmission
     (interfaceLimitEmissions,
      "OneFinalStateEmission",
      "Allow one emission in the final state and none in the initial state",
      2);
   static SwitchOption interfaceLimitEmissionsHardOnly
     (interfaceLimitEmissions,
      "HardOnly",
      "Only allow radiation from the hard ME correction",
      3);
   static SwitchOption interfaceLimitEmissionsOneEmission
     (interfaceLimitEmissions,
      "OneEmission",
      "Allow one emission in either the final state or initial state, but not both",
      4);
 
   static Switch<QTildeShowerHandler,bool> interfaceTruncMode
     ("TruncatedShower", "Include the truncated shower?", 
      &QTildeShowerHandler::_trunc_Mode, 1, false, false);
   static SwitchOption interfaceTruncMode0
     (interfaceTruncMode,"No","Truncated Shower is OFF", 0);
   static SwitchOption interfaceTruncMode1
     (interfaceTruncMode,"Yes","Truncated Shower is ON", 1);
 
   static Switch<QTildeShowerHandler,int> interfaceHardEmission
     ("HardEmission",
      "Whether to use ME corrections or POWHEG for the hardest emission",
      &QTildeShowerHandler::_hardEmission, 0, false, false);
   static SwitchOption interfaceHardEmissionNone
     (interfaceHardEmission,
      "None",
      "No Corrections",
      0);
   static SwitchOption interfaceHardEmissionMECorrection
     (interfaceHardEmission,
      "MECorrection",
      "Old fashioned ME correction",
      1);
   static SwitchOption interfaceHardEmissionPOWHEG
     (interfaceHardEmission,
      "POWHEG",
      "Powheg style hard emission",
      2);
 
   static Switch<QTildeShowerHandler,ShowerInteraction> interfaceInteractions
     ("Interactions",
      "The interactions to be used in the shower",
      &QTildeShowerHandler::interaction_, ShowerInteraction::QEDQCD, false, false);
   static SwitchOption interfaceInteractionsQCD
     (interfaceInteractions,
      "QCD",
      "Only QCD radiation",
      ShowerInteraction::QCD);
   static SwitchOption interfaceInteractionsQED
     (interfaceInteractions,
      "QED",
      "Only QEd radiation",
      ShowerInteraction::QED);
   static SwitchOption interfaceInteractionEWOnly
     (interfaceInteractions,
      "EWOnly",
      "Only EW",
      ShowerInteraction::EW);
   static SwitchOption interfaceInteractionQEDQCD
     (interfaceInteractions,
      "QEDQCD",
      "QED and QCD",
      ShowerInteraction::QEDQCD);
   static SwitchOption interfaceInteractionALL
     (interfaceInteractions,
      "ALL",
      "QED, QCD and EW",
      ShowerInteraction::ALL);
+  
+  static Deleted<QTildeShowerHandler> delReconstructionOption
+    ("ReconstructionOption", "The old reconstruction option switch has been replaced with"
+     " the new EvolutionScheme switch, see  arXiv:1904.11866 for details");
 
-  static Switch<QTildeShowerHandler,unsigned int> interfaceReconstructionOption
-    ("ReconstructionOption",
-     "Treatment of the reconstruction of the transverse momentum of "
-     "a branching from the evolution scale.",
-     &QTildeShowerHandler::_reconOpt, 0, false, false);
-  static SwitchOption interfaceReconstructionOptionCutOff
-    (interfaceReconstructionOption,
-     "CutOff",
-     "Use the cut-off masses in the calculation",
+  static Switch<QTildeShowerHandler,unsigned int> interfaceEvolutionScheme
+    ("EvolutionScheme",
+     "The scheme to interpret the evolution variable in the case of multple emission.",
+     &QTildeShowerHandler::_evolutionScheme, 1, false, false);
+  static SwitchOption interfaceEvolutionSchemepT
+    (interfaceEvolutionScheme,
+     "pT",
+     "pT scheme",
      0);
-  static SwitchOption interfaceReconstructionOptionOffShell5
-    (interfaceReconstructionOption,
-     "OffShell5",
-     "Try and preserve q2 but if pt negative just zero it",
-     5);
+  static SwitchOption interfaceEvolutionSchemeDotProduct
+    (interfaceEvolutionScheme,
+     "DotProduct",
+     "Dot-product scheme",
+     1);
+  static SwitchOption interfaceEvolutionSchemeQ2
+    (interfaceEvolutionScheme,
+     "Q2",
+     "Q2 scheme",
+     2);
 
   static Switch<QTildeShowerHandler,unsigned int> interfaceSoftCorrelations
     ("SoftCorrelations",
      "Option for the treatment of soft correlations in the parton shower",
      &QTildeShowerHandler::_softOpt, 2, false, false);
   static SwitchOption interfaceSoftCorrelationsNone
     (interfaceSoftCorrelations,
      "No",
      "No soft correlations",
      0);
   static SwitchOption interfaceSoftCorrelationsFull
     (interfaceSoftCorrelations,
      "Full",
      "Use the full eikonal",
      1);
   static SwitchOption interfaceSoftCorrelationsSingular
     (interfaceSoftCorrelations,
      "Singular",
      "Use original Webber-Marchisini form",
      2);
 
   static Switch<QTildeShowerHandler,bool> interfaceHardPOWHEG
     ("HardPOWHEG",
      "Treatment of powheg emissions which are too hard to have a shower interpretation",
      &QTildeShowerHandler::_hardPOWHEG, false, false, false);
   static SwitchOption interfaceHardPOWHEGAsShower
     (interfaceHardPOWHEG,
      "AsShower",
      "Still interpret as shower emissions",
      false);
   static SwitchOption interfaceHardPOWHEGRealEmission
     (interfaceHardPOWHEG,
      "RealEmission",
      "Generate shower from the real emmission configuration",
      true);
 
   static Reference<QTildeShowerHandler,KinematicsReconstructor> interfaceKinematicsReconstructor
     ("KinematicsReconstructor",
      "Reference to the KinematicsReconstructor object",
      &QTildeShowerHandler::_reconstructor, false, false, true, false, false);
 
   static Reference<QTildeShowerHandler,PartnerFinder> interfacePartnerFinder
     ("PartnerFinder",
      "Reference to the PartnerFinder object",
      &QTildeShowerHandler::_partnerfinder, false, false, true, false, false);
 
 }
 
 tPPair QTildeShowerHandler::cascade(tSubProPtr sub,
 				    XCPtr xcomb) {
   // use me for reference in tex file etc
   useMe();
   prepareCascade(sub);
   // set things up in the base class
   resetWeights();
   hard_=ShowerTreePtr();
   decay_.clear();
   done_.clear();
   // start of the try block for the whole showering process
   unsigned int countFailures=0;
   while (countFailures<maxtry()) {
     try {
       decay_.clear();
       done_.clear();
       PerturbativeProcessPtr hard;
       DecayProcessMap decay;
       splitHardProcess(firstInteraction() ? tagged() :
       		       tPVector(currentSubProcess()->outgoing().begin(),
       				currentSubProcess()->outgoing().end()),
       		       hard,decay);
       ShowerTree::constructTrees(hard_,decay_,hard,decay);
       // if no hard process
       if(!hard_)  throw Exception() << "Shower starting with a decay"
 				    << "is not implemented" 
 				    << Exception::runerror;
       // perform the shower for the hard process
       showerHardProcess(hard_,xcomb);
       done_.push_back(hard_);
       hard_->updateAfterShower(decay_);
       // if no decaying particles to shower break out of the loop
       if(decay_.empty()) break;
       // shower the decay products
       while(!decay_.empty()) {
 	// find particle whose production process has been showered
 	ShowerDecayMap::iterator dit = decay_.begin();
 	while(!dit->second->parent()->hasShowered() && dit!=decay_.end()) ++dit;
 	assert(dit!=decay_.end());
 	// get the particle
 	ShowerTreePtr decayingTree = dit->second;
 	// remove it from the multimap
 	decay_.erase(dit);
 	// make sure the particle has been decayed
 	QTildeShowerHandler::decay(decayingTree,decay_);
 	// now shower the decay
 	showerDecay(decayingTree);
 	done_.push_back(decayingTree);
 	decayingTree->updateAfterShower(decay_);
       }
       // suceeded break out of the loop
       break;
     }
     catch (KinematicsReconstructionVeto) {
       resetWeights();
       ++countFailures;
     }
     catch ( ... ) {
       hard_=ShowerTreePtr();
       decay_.clear();
       done_.clear();
       throw;
     }
   }
   // if loop exited because of too many tries, throw event away
   if (countFailures >= maxtry()) {
     resetWeights();
     hard_=ShowerTreePtr();
     decay_.clear();
     done_.clear();
     throw Exception() << "Too many tries for main while loop "
 		      << "in QTildeShowerHandler::cascade()." 
 		      << Exception::eventerror; 	
   }
   //enter the particles in the event record
   fillEventRecord();
   // clear storage
   hard_=ShowerTreePtr();
   decay_.clear();
   done_.clear();
   // non hadronic case return
   if (!isResolvedHadron(incomingBeams().first ) && 
       !isResolvedHadron(incomingBeams().second) )
     return incomingBeams();
   // remake the remnants (needs to be after the colours are sorted
   //                       out in the insertion into the event record)
   if ( firstInteraction() ) return remakeRemnant(sub->incoming());
   //Return the new pair of incoming partons. remakeRemnant is not
   //necessary here, because the secondary interactions are not yet
   //connected to the remnants.
   return make_pair(findFirstParton(sub->incoming().first ),
 		   findFirstParton(sub->incoming().second));
 }
 
 void QTildeShowerHandler::fillEventRecord() {
   // create a new step 
   StepPtr pstep = newStep();
   assert(!done_.empty());
   assert(done_[0]->isHard());
   // insert the steps
   for(unsigned int ix=0;ix<done_.size();++ix) {
     done_[ix]->fillEventRecord(pstep,doISR(),doFSR());
   }
 }
 
 HardTreePtr QTildeShowerHandler::generateCKKW(ShowerTreePtr ) const {
   return HardTreePtr();
 }
 
 void QTildeShowerHandler::doinit() {
   ShowerHandler::doinit();
   // check on the reweighting
   for(unsigned int ix=0;ix<_fullShowerVetoes.size();++ix) {
     if(_fullShowerVetoes[ix]->behaviour()==1) {
       _reWeight = true;
       break;
     }
   }
   if(_reWeight && maximumTries()<_nReWeight) {
     throw Exception() << "Reweight being performed in the shower but the number of attempts for the"
 		      << "shower is less than that for the reweighting.\n"
 		      << "Maximum number of attempt for the shower "
 		      << fullName() << ":MaxTry is " << maximumTries() << "\nand for reweighting is "
 		      << fullName() << ":NReWeight is " << _nReWeight << "\n"
 		      << "we recommend the number of attempts is 10 times the number for reweighting\n"
 		      << Exception::runerror;
   }
   ShowerTree::_vmin2 = vMin();
   ShowerTree::_spaceTime = includeSpaceTime();
 }
 
 void QTildeShowerHandler::doinitrun() {
   ShowerHandler::doinitrun();
   ShowerTree::_vmin2 = vMin();
   ShowerTree::_spaceTime = includeSpaceTime();
 }
   
 void QTildeShowerHandler::generateIntrinsicpT(vector<ShowerProgenitorPtr> particlesToShower) {
   _intrinsic.clear();
   if ( !ipTon() || !doISR() ) return;
   // don't do anything for the moment for secondary scatters
   if( !firstInteraction() ) return;
   // generate intrinsic pT
   for(unsigned int ix=0;ix<particlesToShower.size();++ix) {
     // only consider initial-state particles
     if(particlesToShower[ix]->progenitor()->isFinalState()) continue;
     if(!particlesToShower[ix]->progenitor()->dataPtr()->coloured()) continue;
     Energy ipt;
     if(UseRandom::rnd() > _beta) {
       ipt=_iptrms*sqrt(-log(UseRandom::rnd()));
     }
     else {
       ipt=_gamma*sqrt(pow(1.+sqr(_iptmax/_gamma), UseRandom::rnd())-1.);
     }
     pair<Energy,double> pt = make_pair(ipt,UseRandom::rnd(Constants::twopi));
     _intrinsic[particlesToShower[ix]] = pt;
   }
 }
 
 void QTildeShowerHandler::setupMaximumScales(const vector<ShowerProgenitorPtr> & p,
 				 XCPtr xcomb) {
   // let POWHEG events radiate freely
   if(_hardEmission==2&&hardTree()) {
     vector<ShowerProgenitorPtr>::const_iterator ckt = p.begin();
     for (; ckt != p.end(); ckt++) (*ckt)->maxHardPt(Constants::MaxEnergy);
     return;
   }
   // return if no vetos
   if (!restrictPhasespace()) return; 
   // find out if hard partonic subprocess.
   bool isPartonic(false); 
   map<ShowerProgenitorPtr,ShowerParticlePtr>::const_iterator 
     cit = _currenttree->incomingLines().begin();
   Lorentz5Momentum pcm;
   for(; cit!=currentTree()->incomingLines().end(); ++cit) {
     pcm += cit->first->progenitor()->momentum();
     isPartonic |= cit->first->progenitor()->coloured();
   }
   // find minimum pt from hard process, the maximum pt from all outgoing
   // coloured lines (this is simpler and more general than
   // 2stu/(s^2+t^2+u^2)).  Maximum scale for scattering processes will
   // be transverse mass.
   Energy ptmax = generator()->maximumCMEnergy();
   // general case calculate the scale  
   if ( !hardScaleIsMuF() || (hardVetoReadOption()&&!firstInteraction()) ) {
     // scattering process
     if(currentTree()->isHard()) {
       assert(xcomb);
       // coloured incoming particles
       if (isPartonic) {
 	map<ShowerProgenitorPtr,tShowerParticlePtr>::const_iterator 
 	  cjt = currentTree()->outgoingLines().begin();
 	for(; cjt!=currentTree()->outgoingLines().end(); ++cjt) {
 	  if (cjt->first->progenitor()->coloured())
 	    ptmax = min(ptmax,cjt->first->progenitor()->momentum().mt());
 	}
       }
       if (ptmax == generator()->maximumCMEnergy() ) ptmax = pcm.m();
       if(hardScaleIsMuF()&&hardVetoReadOption()&&
 	 !firstInteraction()) {
 	ptmax=min(ptmax,sqrt(xcomb->lastShowerScale()));
       }
     } 
     // decay, incoming() is the decaying particle.
     else { 
       ptmax = currentTree()->incomingLines().begin()->first
 	->progenitor()->momentum().mass(); 
     }
   }
   // hepeup.SCALUP is written into the lastXComb by the
   // LesHouchesReader itself - use this by user's choice. 
   // Can be more general than this. 
   else {
     if(currentTree()->isHard()) {
       assert(xcomb);
       ptmax = sqrt( xcomb->lastShowerScale() );
     }
     else {
       ptmax = currentTree()->incomingLines().begin()->first
 	->progenitor()->momentum().mass(); 
     }
   }
   ptmax *= hardScaleFactor();
   // set maxHardPt for all progenitors.  For partonic processes this
   // is now the max pt in the FS, for non-partonic processes or
   // processes with no coloured FS the invariant mass of the IS
   vector<ShowerProgenitorPtr>::const_iterator ckt = p.begin();
   for (; ckt != p.end(); ckt++) (*ckt)->maxHardPt(ptmax);
 }
 
 void QTildeShowerHandler::setupHardScales(const vector<ShowerProgenitorPtr> & p,
 					  XCPtr xcomb) {
   if ( hardScaleIsMuF() &&
        (!hardVetoReadOption() || firstInteraction()) ) {
     Energy hardScale = ZERO;
     if(currentTree()->isHard()) {
       assert(xcomb);
       hardScale = sqrt( xcomb->lastShowerScale() );
     }
     else {
       hardScale = currentTree()->incomingLines().begin()->first
 	->progenitor()->momentum().mass(); 
     }
     hardScale *= hardScaleFactor();
     vector<ShowerProgenitorPtr>::const_iterator ckt = p.begin();
     for (; ckt != p.end(); ckt++) (*ckt)->hardScale(hardScale);
     muPt = hardScale;
   }
 }
 
 void QTildeShowerHandler::showerHardProcess(ShowerTreePtr hard, XCPtr xcomb) {
   _hardme = HwMEBasePtr();
   // extract the matrix element
   tStdXCombPtr lastXC = dynamic_ptr_cast<tStdXCombPtr>(xcomb);
   if(lastXC) {
     _hardme = dynamic_ptr_cast<HwMEBasePtr>(lastXC->matrixElement());
   }
   _decayme = HwDecayerBasePtr();
   // set the current tree
   currentTree(hard);
   hardTree(HardTreePtr());
   // work out the type of event
   currentTree()->xcombPtr(dynamic_ptr_cast<StdXCombPtr>(xcomb));
   currentTree()->identifyEventType();
   checkFlags();
   // generate the showering
   doShowering(true,xcomb);
 }
 
 RealEmissionProcessPtr QTildeShowerHandler::hardMatrixElementCorrection(bool hard) {
   // set the initial enhancement factors for the soft correction
   _initialenhance = 1.;
   _finalenhance   = 1.;
   // see if we can get the correction from the matrix element
   // or decayer
   RealEmissionProcessPtr real;
   if(hard) {
     if(_hardme&&_hardme->hasMECorrection()) {
       _hardme->initializeMECorrection(_currenttree->perturbativeProcess(),
      				      _initialenhance,_finalenhance);
       if(hardMEC())
      	real = 
 	  _hardme->applyHardMatrixElementCorrection(_currenttree->perturbativeProcess());
     }
   }
   else {
     if(_decayme&&_decayme->hasMECorrection()) {
       _decayme->initializeMECorrection(_currenttree->perturbativeProcess(),
    				       _initialenhance,_finalenhance);
       if(hardMEC())
    	real = _decayme->applyHardMatrixElementCorrection(_currenttree->perturbativeProcess());
     }
   }
   return real;
 }
 
 ShowerParticleVector QTildeShowerHandler::createTimeLikeChildren(tShowerParticlePtr, IdList ids) {
   // Create the ShowerParticle objects for the two children of
   // the emitting particle; set the parent/child relationship
   // if same as definition create particles, otherwise create cc
   ShowerParticleVector children;
   for(unsigned int ix=0;ix<2;++ix) {
     children.push_back(new_ptr(ShowerParticle(ids[ix+1],true)));
     if(children[ix]->id()==_progenitor->id()&&!ids[ix+1]->stable()&&abs(ids[ix+1]->id())!=ParticleID::tauminus)
       children[ix]->set5Momentum(Lorentz5Momentum(_progenitor->progenitor()->mass()));
     else
       children[ix]->set5Momentum(Lorentz5Momentum(ids[ix+1]->mass()));
   }
   return children;
 }
 
 bool QTildeShowerHandler::timeLikeShower(tShowerParticlePtr particle, 
 					 ShowerInteraction type,
 					 Branching fb, bool first) {
   // don't do anything if not needed
   if(_limitEmissions == 1 || hardOnly() || 
      ( _limitEmissions == 2 && _nfs != 0) ||
      ( _limitEmissions == 4 && _nfs + _nis != 0) ) {
     if(particle->spinInfo()) particle->spinInfo()->develop();
     return false;
   }
   // generate the emission
   ShowerParticleVector children;
   // generate the emission
   if(!fb.kinematics) 
     fb = selectTimeLikeBranching(particle,type,HardBranchingPtr());
   // no emission, return
   if(!fb.kinematics) {
     if(particle->spinInfo()) particle->spinInfo()->develop();
     return false;
   }
   Branching fc[2] = {Branching(),Branching()};
 
   assert(fb.kinematics);
   // has emitted
   // Assign the shower kinematics to the emitting particle.
   particle->showerKinematics(fb.kinematics);
   // check highest pT
   if(fb.kinematics->pT()>progenitor()->highestpT())
     progenitor()->highestpT(fb.kinematics->pT());
   // create the children
   children = createTimeLikeChildren(particle,fb.ids);
   // update the children
   particle->showerKinematics()->
     updateChildren(particle, children,fb.type);
   // update number of emissions
   ++_nfs;
   if(_limitEmissions!=0) {
     if(children[0]->spinInfo()) children[0]->spinInfo()->develop();
     if(children[1]->spinInfo()) children[1]->spinInfo()->develop();
     if(particle->spinInfo()) particle->spinInfo()->develop();
     return true;
   }
   // select branchings for children
   fc[0] = selectTimeLikeBranching(children[0],type,HardBranchingPtr());
   fc[1] = selectTimeLikeBranching(children[1],type,HardBranchingPtr());
   // shower the first  particle
   if(fc[0].kinematics) timeLikeShower(children[0],type,fc[0],false);
   if(children[0]->spinInfo()) children[0]->spinInfo()->develop();
   // shower the second particle
   if(fc[1].kinematics) timeLikeShower(children[1],type,fc[1],false);
   if(children[1]->spinInfo()) children[1]->spinInfo()->develop();
-  if(_reconOpt>=1)
-    particle->showerKinematics()->updateParent(particle, children,fb.type);
+  particle->showerKinematics()->updateParent(particle, children,_evolutionScheme,fb.type);
   // branching has happened
   if(first&&!children.empty())
     particle->showerKinematics()->resetChildren(particle,children);
   if(particle->spinInfo()) particle->spinInfo()->develop();
   return true;
 }
 
 bool 
 QTildeShowerHandler::spaceLikeShower(tShowerParticlePtr particle, PPtr beam,
 				     ShowerInteraction type) {
   //using the pdf's associated with the ShowerHandler assures, that
   //modified pdf's are used for the secondary interactions via 
   //CascadeHandler::resetPDFs(...)
   tcPDFPtr pdf;
   if(firstPDF().particle() == _beam)
     pdf = firstPDF().pdf();
   if(secondPDF().particle() == _beam)
     pdf = secondPDF().pdf();
   Energy freeze = pdfFreezingScale();
   // don't do anything if not needed
   if(_limitEmissions == 2  || hardOnly() ||
      ( _limitEmissions == 1 && _nis != 0 ) ||
      ( _limitEmissions == 4 && _nis + _nfs != 0 ) ) {
     if(particle->spinInfo()) particle->spinInfo()->develop();
     return false;
   }
   Branching bb;
   // generate branching
   while (true) {
     bb=_splittingGenerator->chooseBackwardBranching(*particle,beam,
 						    _initialenhance,
 						    _beam,type,
 						    pdf,freeze);
     // return if no emission
     if(!bb.kinematics) {
       if(particle->spinInfo()) particle->spinInfo()->develop();
       return false;
     }
     // if not vetoed break
     if(!spaceLikeVetoed(bb,particle)) break;
     // otherwise reset scale and continue
     particle->vetoEmission(bb.type,bb.kinematics->scale());
     if(particle->spinInfo()) particle->spinInfo()->decayVertex(VertexPtr());
   }
   // assign the splitting function and shower kinematics
   particle->showerKinematics(bb.kinematics);
   if(bb.kinematics->pT()>progenitor()->highestpT())
     progenitor()->highestpT(bb.kinematics->pT());
   // For the time being we are considering only 1->2 branching
   // particles as in Sudakov form factor
   tcPDPtr part[2]={bb.ids[0],bb.ids[2]};
   // Now create the actual particles, make the otherChild a final state
   // particle, while the newParent is not
   ShowerParticlePtr newParent  = new_ptr(ShowerParticle(part[0],false));
   ShowerParticlePtr otherChild = new_ptr(ShowerParticle(part[1],true,true));
   ShowerParticleVector theChildren;
   theChildren.push_back(particle); 
   theChildren.push_back(otherChild);
   //this updates the evolution scale
   particle->showerKinematics()->
-    updateParent(newParent, theChildren,bb.type);
+    updateParent(newParent, theChildren,_evolutionScheme,bb.type);
   // update the history if needed
   _currenttree->updateInitialStateShowerProduct(_progenitor,newParent);
   _currenttree->addInitialStateBranching(particle,newParent,otherChild);
   // for the reconstruction of kinematics, parent/child
   // relationships are according to the branching process:
   // now continue the shower
   ++_nis;
   bool emitted = _limitEmissions==0 ? 
     spaceLikeShower(newParent,beam,type) : false;
   if(newParent->spinInfo()) newParent->spinInfo()->develop();
   // now reconstruct the momentum
   if(!emitted) {
     if(_intrinsic.find(_progenitor)==_intrinsic.end()) {
       bb.kinematics->updateLast(newParent,ZERO,ZERO);
     }
     else {
       pair<Energy,double> kt=_intrinsic[_progenitor];
       bb.kinematics->updateLast(newParent,
 				kt.first*cos(kt.second),
 				kt.first*sin(kt.second));
     }
   }
   particle->showerKinematics()->
     updateChildren(newParent, theChildren,bb.type);
   if(_limitEmissions!=0) {
     if(particle->spinInfo()) particle->spinInfo()->develop();
     return true;
   }
   // perform the shower of the final-state particle
   timeLikeShower(otherChild,type,Branching(),true);
   updateHistory(otherChild);
   if(theChildren[1]->spinInfo()) theChildren[1]->spinInfo()->develop();
   // return the emitted
   if(particle->spinInfo()) particle->spinInfo()->develop();
   return true;
 }
 
 void QTildeShowerHandler::showerDecay(ShowerTreePtr decay) {
   // work out the type of event
   currentTree()->xcombPtr(StdXCombPtr());
   currentTree()->identifyEventType();
   _decayme = HwDecayerBasePtr();
   _hardme  = HwMEBasePtr();
   // find the decayer
   // try the normal way if possible
   tDMPtr dm = decay->incomingLines().begin()->first->original()   ->decayMode();
   if(!dm) dm = decay->incomingLines().begin()->first->copy()      ->decayMode();
   if(!dm) dm = decay->incomingLines().begin()->first->progenitor()->decayMode();
   // otherwise make a string and look it up
   if(!dm) {
     string tag = decay->incomingLines().begin()->first->original()->dataPtr()->name() 
       + "->";
     OrderedParticles outgoing;
     for(map<ShowerProgenitorPtr,tShowerParticlePtr>::const_iterator 
 	  it=decay->outgoingLines().begin();it!=decay->outgoingLines().end();++it) {
       if(abs(decay->incomingLines().begin()->first->original()->id()) == ParticleID::t &&
 	 abs(it->first->original()->id())==ParticleID::Wplus &&
 	 decay->treelinks().size() == 1) {
 	ShowerTreePtr Wtree = decay->treelinks().begin()->first;
 	for(map<ShowerProgenitorPtr,tShowerParticlePtr>::const_iterator
 	      it2=Wtree->outgoingLines().begin();it2!=Wtree->outgoingLines().end();++it2) {
 	  outgoing.insert(it2->first->original()->dataPtr());
 	}
       }
       else {
 	outgoing.insert(it->first->original()->dataPtr());
       }
     }
     for(OrderedParticles::const_iterator it=outgoing.begin(); it!=outgoing.end();++it) {
       if(it!=outgoing.begin()) tag += ",";
       tag +=(**it).name();
     }
     tag += ";";
     dm = findDecayMode(tag);
   }
   if(dm) _decayme = dynamic_ptr_cast<HwDecayerBasePtr>(dm->decayer());
   // set the ShowerTree to be showered
   currentTree(decay);
   decay->applyTransforms();
   hardTree(HardTreePtr());
   // generate the showering
   doShowering(false,XCPtr());
   // if no vetos 
   // force calculation of spin correlations
   SpinPtr spInfo = decay->incomingLines().begin()->first->progenitor()->spinInfo();
   if(spInfo) {
     if(!spInfo->developed()) spInfo->needsUpdate();
     spInfo->develop();
   }
 }
 
 bool QTildeShowerHandler::spaceLikeDecayShower(tShowerParticlePtr particle,
 				   const ShowerParticle::EvolutionScales & maxScales,
 				   Energy minmass,ShowerInteraction type,
 				   Branching fb) {
   // don't do anything if not needed
   if(_limitEmissions == 1 || hardOnly() || 
      ( _limitEmissions == 3 && _nis != 0) ||
      ( _limitEmissions == 4 && _nfs + _nis != 0) ) {
     return false;
   }
   // generate the emission
   ShowerParticleVector children;
   // generate the emission
   if(!fb.kinematics) 
     fb = selectSpaceLikeDecayBranching(particle,maxScales,minmass,type,
 				       HardBranchingPtr());
   // no emission, return
   if(!fb.kinematics) return false;
   Branching fc[2];
   if(particle->virtualMass()==ZERO) 
     particle->virtualMass(_progenitor->progenitor()->mass());
   fc[0] = Branching();
   fc[1] = Branching();
   assert(fb.kinematics);
   // has emitted
   // Assign the shower kinematics to the emitting particle.
   particle->showerKinematics(fb.kinematics);
   if(fb.kinematics->pT()>progenitor()->highestpT())
     progenitor()->highestpT(fb.kinematics->pT());
   // create the ShowerParticle objects for the two children
   children = createTimeLikeChildren(particle,fb.ids);
   // updateChildren the children
   particle->showerKinematics()->
     updateChildren(particle, children, fb.type);
   // select branchings for children
   fc[0] = selectSpaceLikeDecayBranching(children[0],maxScales,minmass,
 					type,HardBranchingPtr());
   fc[1] = selectTimeLikeBranching      (children[1],type,HardBranchingPtr());
   // old default
   ++_nis;
   // shower the first  particle
   _currenttree->updateInitialStateShowerProduct(_progenitor,children[0]);
   _currenttree->addInitialStateBranching(particle,children[0],children[1]);
   if(fc[0].kinematics) spaceLikeDecayShower(children[0],maxScales,minmass,type,Branching());
   // shower the second particle
   if(fc[1].kinematics) timeLikeShower(children[1],type,fc[1],true);
   updateHistory(children[1]);
   // TODO NEED AN UPDATE HERE FOR RECONOPT!=0
   // branching has happened
   return true;
 }
 
 vector<ShowerProgenitorPtr> QTildeShowerHandler::setupShower(bool hard) {
   RealEmissionProcessPtr real;
   // generate hard me if needed
   if(_hardEmission==1) {
     real = hardMatrixElementCorrection(hard);
     if(real&&!real->outgoing().empty()) setupMECorrection(real);
   }
   // generate POWHEG hard emission if needed
   else if(_hardEmission==2) 
     hardestEmission(hard);
   // set the initial colour partners
   setEvolutionPartners(hard,interaction_,false);
   // get the particles to be showered
   vector<ShowerProgenitorPtr> particlesToShower = 
     currentTree()->extractProgenitors();
   // return the answer
   return particlesToShower;
 }
 
 void QTildeShowerHandler::setEvolutionPartners(bool hard,ShowerInteraction type,
 					       bool clear) {
   // match the particles in the ShowerTree and hardTree
   if(hardTree() && !hardTree()->connect(currentTree()))
     throw Exception() << "Can't match trees in "
 		      << "QTildeShowerHandler::setEvolutionPartners()"
 		      << Exception::eventerror;
   // extract the progenitors
   vector<ShowerParticlePtr> particles = 
     currentTree()->extractProgenitorParticles();
   // clear the partners if needed
   if(clear) {
     for(unsigned int ix=0;ix<particles.size();++ix) {
       particles[ix]->partner(ShowerParticlePtr());
       particles[ix]->clearPartners();
     }
   }
   // sort out the colour partners
   if(hardTree()) {
     // find the partner
     for(unsigned int ix=0;ix<particles.size();++ix) {
       tShowerParticlePtr partner = hardTree()->particles()[particles[ix]]->branchingParticle()->partner();
       if(!partner) continue;
       for(map<ShowerParticlePtr,tHardBranchingPtr>::const_iterator
 	    it=hardTree()->particles().begin();
 	  it!=hardTree()->particles().end();++it) {
 	if(it->second->branchingParticle()==partner) {
 	  particles[ix]->partner(it->first);
 	  break;
 	}
       }
       if(!particles[ix]->partner()) 
 	throw Exception() << "Can't match partners in "
 			  << "QTildeShowerHandler::setEvolutionPartners()"
 			  << Exception::eventerror;
     }
   }
 
   // Set the initial evolution scales
   partnerFinder()->
     setInitialEvolutionScales(particles,!hard,interaction_,!_hardtree);
   if(hardTree() && _hardPOWHEG) {
     bool tooHard=false;
     map<ShowerParticlePtr,tHardBranchingPtr>::const_iterator 
       eit=hardTree()->particles().end();
     for(unsigned int ix=0;ix<particles.size();++ix) {
       map<ShowerParticlePtr,tHardBranchingPtr>::const_iterator 
 	mit = hardTree()->particles().find(particles[ix]);
       Energy hardScale(ZERO);
       ShowerPartnerType type(ShowerPartnerType::Undefined);
       // final-state
       if(particles[ix]->isFinalState()) {
 	if(mit!= eit && !mit->second->children().empty()) {
 	  hardScale = mit->second->scale();
 	  type = mit->second->type();
 	}
       }
       // initial-state
       else {
 	if(mit!= eit && mit->second->parent()) {
 	  hardScale = mit->second->parent()->scale();
 	  type = mit->second->parent()->type();
 	}
       }
       if(type!=ShowerPartnerType::Undefined) {
 	if(type==ShowerPartnerType::QED) {
 	  tooHard |= particles[ix]->scales().QED_noAO<hardScale;
 	}
 	else if(type==ShowerPartnerType::QCDColourLine) {
 	  tooHard |= particles[ix]->scales().QCD_c_noAO<hardScale;
 	}
 	else if(type==ShowerPartnerType::QCDAntiColourLine) {
 	  tooHard |= particles[ix]->scales().QCD_ac_noAO<hardScale;
 	}
 	else if(type==ShowerPartnerType::EW && 
 	       (particles[1]->id()==ParticleID::Z0 
 		   || particles[2]->id()==ParticleID::Z0)) {
 	  tooHard |= particles[ix]->scales().EW_Z<hardScale;
 	}
 	else if(type==ShowerPartnerType::EW && 
 	       (abs(particles[1]->id())==ParticleID::Wplus 
 	       || abs(particles[2]->id())==ParticleID::Wplus)) {
 	  tooHard |= particles[ix]->scales().EW_W<hardScale;
 	}
       }
     }
     if(tooHard) convertHardTree(hard,type);
   }
 }
 
 void QTildeShowerHandler::updateHistory(tShowerParticlePtr particle) {
   if(!particle->children().empty()) {
     ShowerParticleVector theChildren;
     for(unsigned int ix=0;ix<particle->children().size();++ix) {
       ShowerParticlePtr part = dynamic_ptr_cast<ShowerParticlePtr>
 	(particle->children()[ix]);
       theChildren.push_back(part);
     }
     // update the history if needed
     if(particle==_currenttree->getFinalStateShowerProduct(_progenitor))
       _currenttree->updateFinalStateShowerProduct(_progenitor,
 						  particle,theChildren);
     _currenttree->addFinalStateBranching(particle,theChildren);
     for(unsigned int ix=0;ix<theChildren.size();++ix)
       updateHistory(theChildren[ix]);
   }
 }
 
 bool QTildeShowerHandler::startTimeLikeShower(ShowerInteraction type) {
   // initialize basis vectors etc
   if(!progenitor()->progenitor()->partner()) return false;
   progenitor()->progenitor()->initializeFinalState();
   if(hardTree()) {
     map<ShowerParticlePtr,tHardBranchingPtr>::const_iterator 
       eit=hardTree()->particles().end(),
       mit = hardTree()->particles().find(progenitor()->progenitor());
     if( mit != eit && !mit->second->children().empty() ) {
       bool output=truncatedTimeLikeShower(progenitor()->progenitor(),
 					  mit->second ,type,Branching(),true);
       if(output) updateHistory(progenitor()->progenitor());
       return output;
     }
   }
   // do the shower
   bool output = hardOnly() ? false :
     timeLikeShower(progenitor()->progenitor() ,type,Branching(),true) ;
   if(output) updateHistory(progenitor()->progenitor());
   return output;
 }
 
 bool QTildeShowerHandler::startSpaceLikeShower(PPtr parent, ShowerInteraction type) {
   // initialise the basis vectors
   if(!progenitor()->progenitor()->partner()) return false;
   progenitor()->progenitor()->initializeInitialState(parent);
   if(hardTree()) {
     map<ShowerParticlePtr,tHardBranchingPtr>::const_iterator 
       eit =hardTree()->particles().end(),
       mit = hardTree()->particles().find(progenitor()->progenitor());
     if( mit != eit && mit->second->parent() ) {
       return truncatedSpaceLikeShower( progenitor()->progenitor(),
 				       parent, mit->second->parent(), type );
     } 
   }
   // perform the shower
   return  hardOnly() ? false :
     spaceLikeShower(progenitor()->progenitor(),parent,type);
 }
 
 bool QTildeShowerHandler::
 startSpaceLikeDecayShower(const ShowerParticle::EvolutionScales & maxScales,
 			  Energy minimumMass,ShowerInteraction type) {
   // set up the particle basis vectors
   if(!progenitor()->progenitor()->partner()) return false;
   progenitor()->progenitor()->initializeDecay();
   if(hardTree()) {
     map<ShowerParticlePtr,tHardBranchingPtr>::const_iterator 
       eit =hardTree()->particles().end(),
       mit = hardTree()->particles().find(progenitor()->progenitor());
     if( mit != eit && mit->second->parent() ) {
       HardBranchingPtr branch=mit->second;
       while(branch->parent()) branch=branch->parent();
       return truncatedSpaceLikeDecayShower(progenitor()->progenitor(),maxScales,
 					   minimumMass, branch ,type, Branching());
     }
   }
   // perform the shower
   return  hardOnly() ? false :
     spaceLikeDecayShower(progenitor()->progenitor(),maxScales,minimumMass,type,Branching());
 }
 
 bool QTildeShowerHandler::timeLikeVetoed(const Branching & fb,
 			     ShowerParticlePtr particle) {
   // work out type of interaction
   ShowerInteraction type = convertInteraction(fb.type);
   // check whether emission was harder than largest pt of hard subprocess
   if ( restrictPhasespace() && fb.kinematics->pT() > _progenitor->maxHardPt() ) 
     return true;
   // soft matrix element correction veto
   if( softMEC()) {
     if(_hardme && _hardme->hasMECorrection()) {
       if(_hardme->softMatrixElementVeto(particle,
 					_progenitor->progenitor(),
 					particle->isFinalState(),
 					_progenitor->highestpT(),
 					fb.ids, fb.kinematics->z(),
 					fb.kinematics->scale(),
 					fb.kinematics->pT()))
 	return true;
     }
     else if(_decayme && _decayme->hasMECorrection()) {
       if(_decayme->softMatrixElementVeto(particle,
 					 _progenitor->progenitor(),
 					 particle->isFinalState(),
 					 _progenitor->highestpT(),
 					 fb.ids, fb.kinematics->z(),
 					 fb.kinematics->scale(),
 					 fb.kinematics->pT()))
 	return true;
     }
   }
   // veto on maximum pt
   if(fb.kinematics->pT()>_progenitor->maximumpT(type)) return true;
   // general vetos
   if (fb.kinematics && !_vetoes.empty()) {
     bool vetoed=false;
     for (vector<ShowerVetoPtr>::iterator v = _vetoes.begin();
 	 v != _vetoes.end(); ++v) {
       bool test = (**v).vetoTimeLike(_progenitor,particle,fb,currentTree());
       switch((**v).vetoType()) {
       case ShowerVeto::Emission:
 	vetoed |= test;
 	break;
       case ShowerVeto::Shower:
 	if(test) throw VetoShower();
 	break;
       case ShowerVeto::Event:
 	if(test) throw Veto();
 	break;
       }
     }
     if(vetoed) return true;
   }
   if ( firstInteraction() &&
        profileScales() ) {
     double weight = 
       profileScales()->
       hardScaleProfile(_progenitor->hardScale(),fb.kinematics->pT());
     if ( UseRandom::rnd() > weight )
       return true;
   }
   return false;
 }
 
 bool QTildeShowerHandler::spaceLikeVetoed(const Branching & bb,
 			      ShowerParticlePtr particle) {
   // work out type of interaction
   ShowerInteraction type = convertInteraction(bb.type);
   // check whether emission was harder than largest pt of hard subprocess
   if (restrictPhasespace() && bb.kinematics->pT() > _progenitor->maxHardPt())
     return true;
   // apply the soft correction
   if( softMEC() && _hardme && _hardme->hasMECorrection() ) {
     if(_hardme->softMatrixElementVeto(particle,
 				      _progenitor->progenitor(),
 				      particle->isFinalState(),
 				      _progenitor->highestpT(),
 				      bb.ids, bb.kinematics->z(),
 				      bb.kinematics->scale(),
 				      bb.kinematics->pT()))
       return true;
   }
   // the more general vetos
 
   // check vs max pt for the shower
   if(bb.kinematics->pT()>_progenitor->maximumpT(type)) return true;
 
   if (!_vetoes.empty()) {
     bool vetoed=false;
     for (vector<ShowerVetoPtr>::iterator v = _vetoes.begin();
 	 v != _vetoes.end(); ++v) {
       bool test = (**v).vetoSpaceLike(_progenitor,particle,bb,currentTree());
       switch ((**v).vetoType()) {
       case ShowerVeto::Emission:
 	vetoed |= test;
 	break;
       case ShowerVeto::Shower:
 	if(test) throw VetoShower();
 	break;
       case ShowerVeto::Event:
 	if(test) throw Veto();
 	break;
       }
     }
     if (vetoed) return true;
   }
   if ( firstInteraction() &&
        profileScales() ) {
     double weight = 
       profileScales()->
       hardScaleProfile(_progenitor->hardScale(),bb.kinematics->pT());
     if ( UseRandom::rnd() > weight )
       return true;
   }
   return false;
 }
 
 bool QTildeShowerHandler::spaceLikeDecayVetoed( const Branching & fb,
 				    ShowerParticlePtr particle) {
   // work out type of interaction
   ShowerInteraction type = convertInteraction(fb.type);
   // apply the soft correction
   if( softMEC() && _decayme && _decayme->hasMECorrection() ) {
     if(_decayme->softMatrixElementVeto(particle,
 				       _progenitor->progenitor(),
 				       particle->isFinalState(),
 				       _progenitor->highestpT(),
 				       fb.ids, fb.kinematics->z(),
 				       fb.kinematics->scale(),
 				       fb.kinematics->pT()))
       return true;
   }
   // veto on hardest pt in the shower
   if(fb.kinematics->pT()> _progenitor->maximumpT(type)) return true;
   // general vetos
   if (!_vetoes.empty()) {
     bool vetoed=false;
     for (vector<ShowerVetoPtr>::iterator v = _vetoes.begin();
 	 v != _vetoes.end(); ++v) {
       bool test = (**v).vetoSpaceLike(_progenitor,particle,fb,currentTree());
       switch((**v).vetoType()) {
       case ShowerVeto::Emission:
 	vetoed |= test;
 	break;
       case ShowerVeto::Shower:
 	if(test) throw VetoShower();
 	break;
       case ShowerVeto::Event:
 	if(test) throw Veto();
 	break;
       }
       if (vetoed) return true;
     }
   }
   return false;
 }
 
 void QTildeShowerHandler::hardestEmission(bool hard) {
   HardTreePtr ISRTree;
   // internal POWHEG in production or decay
   if( (( _hardme  &&  _hardme->hasPOWHEGCorrection()!=0 ) ||
        ( _decayme && _decayme->hasPOWHEGCorrection()!=0 ) ) ) {
     RealEmissionProcessPtr real;
     unsigned int type(0);
     // production
     if(_hardme) {
       assert(hard);
       real = _hardme->generateHardest( currentTree()->perturbativeProcess(),
 				       interaction_);
       type = _hardme->hasPOWHEGCorrection();
     }
     // decay
     else {
       assert(!hard);
       real = _decayme->generateHardest( currentTree()->perturbativeProcess() );
       type = _decayme->hasPOWHEGCorrection();
     }
     if(real) {
       // set up ther hard tree
       if(!real->outgoing().empty()) _hardtree = new_ptr(HardTree(real));
       // set up the vetos
       currentTree()->setVetoes(real->pT(),type);
     }
     // store initial state POWHEG radiation
     if(_hardtree && _hardme && _hardme->hasPOWHEGCorrection()==1) 
       ISRTree = _hardtree;
   }
   else if (hard) {
     // Get minimum pT cutoff used in shower approximation
     Energy maxpt = 1.*GeV;
 
     if ( currentTree()->showerApproximation() ) {
       int colouredIn  = 0;
       int colouredOut = 0;
       for( map< ShowerProgenitorPtr, tShowerParticlePtr >::iterator it
 	     = currentTree()->outgoingLines().begin();
 	   it != currentTree()->outgoingLines().end(); ++it ) {
 	if( it->second->coloured() ) ++colouredOut;
       }
       for( map< ShowerProgenitorPtr, ShowerParticlePtr >::iterator it
 	     = currentTree()->incomingLines().begin();
 	   it != currentTree()->incomingLines().end(); ++it ) {
 	if( it->second->coloured() ) ++colouredIn;
       }
       if ( currentTree()->showerApproximation()->ffPtCut() == currentTree()->showerApproximation()->fiPtCut() &&
 	   currentTree()->showerApproximation()->ffPtCut() == currentTree()->showerApproximation()->iiPtCut() )
 	maxpt = currentTree()->showerApproximation()->ffPtCut();
       else if ( colouredIn == 2 && colouredOut == 0 )
 	maxpt = currentTree()->showerApproximation()->iiPtCut();
       else if ( colouredIn == 0 && colouredOut > 1 )
 	maxpt = currentTree()->showerApproximation()->ffPtCut();
       else if ( colouredIn == 2 && colouredOut == 1 )
 	maxpt = min(currentTree()->showerApproximation()->iiPtCut(), currentTree()->showerApproximation()->fiPtCut());
       else if ( colouredIn == 1 && colouredOut > 1 )
 	maxpt = min(currentTree()->showerApproximation()->ffPtCut(), currentTree()->showerApproximation()->fiPtCut());
       else
 	maxpt = min(min(currentTree()->showerApproximation()->iiPtCut(), currentTree()->showerApproximation()->fiPtCut()), 
 		    currentTree()->showerApproximation()->ffPtCut());
     }
 
     // Generate hardtree from born and real emission subprocesses
     _hardtree = generateCKKW(currentTree());
 
     // Find transverse momentum of hardest emission
     if (_hardtree){
       for(set<HardBranchingPtr>::iterator it=_hardtree->branchings().begin();
      	  it!=_hardtree->branchings().end();++it) {
       	if ((*it)->parent() && (*it)->status()==HardBranching::Incoming)
       	  maxpt=(*it)->branchingParticle()->momentum().perp();
       	if ((*it)->children().size()==2 && (*it)->status()==HardBranching::Outgoing){
 	  if ((*it)->branchingParticle()->id()!=21 &&
 	      abs((*it)->branchingParticle()->id())>5 ){
 	    if ((*it)->children()[0]->branchingParticle()->id()==21 ||
 		abs((*it)->children()[0]->branchingParticle()->id())<6)
 	      maxpt=(*it)->children()[0]->branchingParticle()->momentum().perp();
 	    else if ((*it)->children()[1]->branchingParticle()->id()==21 ||
 		     abs((*it)->children()[1]->branchingParticle()->id())<6)
 	      maxpt=(*it)->children()[1]->branchingParticle()->momentum().perp();
 	  }
 	  else {
 	    if ( abs((*it)->branchingParticle()->id())<6){
 	      if (abs((*it)->children()[0]->branchingParticle()->id())<6)
 		maxpt = (*it)->children()[1]->branchingParticle()->momentum().perp();
 	      else 
 		maxpt = (*it)->children()[0]->branchingParticle()->momentum().perp();
 	    }
 	    else maxpt = (*it)->children()[1]->branchingParticle()->momentum().perp();
 	  }
       	}
       } 
     }
      
     
     // Hardest (pt) emission should be the first powheg emission.
     maxpt=min(sqrt(lastXCombPtr()->lastShowerScale()),maxpt);
 
     // set maximum pT for subsequent emissions from S events
     if ( currentTree()->isPowhegSEvent() ) {
       for( map< ShowerProgenitorPtr, tShowerParticlePtr >::iterator it
 	     = currentTree()->outgoingLines().begin(); 
 	   it != currentTree()->outgoingLines().end(); ++it ) {
 	if( ! it->second->coloured() ) continue;
 	it->first->maximumpT(maxpt, ShowerInteraction::QCD  );
       }  
       for( map< ShowerProgenitorPtr, ShowerParticlePtr >::iterator it
 	     = currentTree()->incomingLines().begin(); 
 	   it != currentTree()->incomingLines().end(); ++it ) {
 	if( ! it->second->coloured() ) continue;
 	it->first->maximumpT(maxpt, ShowerInteraction::QCD );
       }
     }
   }
   else 
     _hardtree = generateCKKW(currentTree());
 
   // if hard me doesn't have a FSR powheg 
   // correction use decay powheg correction
   if (_hardme && _hardme->hasPOWHEGCorrection()<2) {
     addFSRUsingDecayPOWHEG(ISRTree);
   }
   // connect the trees
   if(_hardtree) {
     connectTrees(currentTree(),_hardtree,hard); 
   }
 }
 
 void QTildeShowerHandler::addFSRUsingDecayPOWHEG(HardTreePtr ISRTree) {
   // check for intermediate colour singlet resonance
   const ParticleVector inter =  _hardme->subProcess()->intermediates();
   if (inter.size()!=1 || inter[0]->momentum().m2()/GeV2 < 0 || 
       inter[0]->dataPtr()->iColour()!=PDT::Colour0) {
     return;
   }
    
   // ignore cases where outgoing particles are not coloured
   map<ShowerProgenitorPtr, tShowerParticlePtr > out = currentTree()->outgoingLines();
   if (out.size() != 2 ||
       out. begin()->second->dataPtr()->iColour()==PDT::Colour0 ||
       out.rbegin()->second->dataPtr()->iColour()==PDT::Colour0) {
     return;
   }
 
   // look up decay mode
   tDMPtr dm;
   string tag;
   string inParticle = inter[0]->dataPtr()->name() + "->";
   vector<string> outParticles;
   outParticles.push_back(out.begin ()->first->progenitor()->dataPtr()->name());
   outParticles.push_back(out.rbegin()->first->progenitor()->dataPtr()->name());
   for (int it=0; it<2; ++it){
     tag = inParticle + outParticles[it] + "," + outParticles[(it+1)%2] + ";";
     dm = generator()->findDecayMode(tag);
     if(dm) break;
   }
 
   // get the decayer
   HwDecayerBasePtr decayer;   
   if(dm) decayer = dynamic_ptr_cast<HwDecayerBasePtr>(dm->decayer());
   // check if decayer has a FSR POWHEG correction 
   if (!decayer || decayer->hasPOWHEGCorrection()<2) {
     return;
   }
   // generate the hardest emission
   // create RealEmissionProcess
   PPtr in = new_ptr(*inter[0]);
   RealEmissionProcessPtr newProcess(new_ptr(RealEmissionProcess()));
   newProcess->bornIncoming().push_back(in);
   newProcess->bornOutgoing().push_back(out.begin ()->first->progenitor());
   newProcess->bornOutgoing().push_back(out.rbegin()->first->progenitor());
   // generate the FSR
   newProcess = decayer->generateHardest(newProcess);
   HardTreePtr FSRTree;
   if(newProcess) {
     // set up ther hard tree
     if(!newProcess->outgoing().empty()) FSRTree = new_ptr(HardTree(newProcess));
     // set up the vetos
     currentTree()->setVetoes(newProcess->pT(),2);
   }
   if(!FSRTree) return;
   
   // if there is no ISRTree make _hardtree from FSRTree
   if (!ISRTree){
     vector<HardBranchingPtr> inBranch,hardBranch;
     for(map<ShowerProgenitorPtr,ShowerParticlePtr>::const_iterator
 	  cit =currentTree()->incomingLines().begin();
 	cit!=currentTree()->incomingLines().end();++cit ) {
       inBranch.push_back(new_ptr(HardBranching(cit->second,SudakovPtr(),
 					       HardBranchingPtr(),
 					       HardBranching::Incoming)));
       inBranch.back()->beam(cit->first->original()->parents()[0]);
       hardBranch.push_back(inBranch.back());
     }
     if(inBranch[0]->branchingParticle()->dataPtr()->coloured()) {
       inBranch[0]->colourPartner(inBranch[1]);
       inBranch[1]->colourPartner(inBranch[0]);
     }
     for(set<HardBranchingPtr>::iterator it=FSRTree->branchings().begin();
 	it!=FSRTree->branchings().end();++it) {
       if((**it).branchingParticle()->id()!=in->id()) 
 	hardBranch.push_back(*it);
     } 
     hardBranch[2]->colourPartner(hardBranch[3]);
     hardBranch[3]->colourPartner(hardBranch[2]);
     HardTreePtr newTree = new_ptr(HardTree(hardBranch,inBranch,
 					   ShowerInteraction::QCD));            
     _hardtree = newTree;    
   }
   
   // Otherwise modify the ISRTree to include the emission in FSRTree
   else {
     vector<tShowerParticlePtr> FSROut, ISROut;   
     set<HardBranchingPtr>::iterator itFSR, itISR;
     // get outgoing particles 
     for(itFSR =FSRTree->branchings().begin();
 	itFSR!=FSRTree->branchings().end();++itFSR){
       if ((**itFSR).status()==HardBranching::Outgoing) 
 	FSROut.push_back((*itFSR)->branchingParticle());
     }     
     for(itISR =ISRTree->branchings().begin();
 	itISR!=ISRTree->branchings().end();++itISR){
       if ((**itISR).status()==HardBranching::Outgoing) 
 	ISROut.push_back((*itISR)->branchingParticle());
     }
     
     // find COM frame formed by outgoing particles
     LorentzRotation eventFrameFSR, eventFrameISR;
     eventFrameFSR = ((FSROut[0]->momentum()+FSROut[1]->momentum()).findBoostToCM());  
     eventFrameISR = ((ISROut[0]->momentum()+ISROut[1]->momentum()).findBoostToCM());
 
     // find rotation between ISR and FSR frames
     int j=0;
     if (ISROut[0]->id()!=FSROut[0]->id()) j=1;
     eventFrameISR.rotateZ( (eventFrameFSR*FSROut[0]->momentum()).phi()-
 			   (eventFrameISR*ISROut[j]->momentum()).phi() );
     eventFrameISR.rotateY( (eventFrameFSR*FSROut[0]->momentum()).theta()-
 			   (eventFrameISR*ISROut[j]->momentum()).theta() );
     eventFrameISR.invert();
     
     for (itFSR=FSRTree->branchings().begin();
 	 itFSR!=FSRTree->branchings().end();++itFSR){
       if ((**itFSR).branchingParticle()->id()==in->id()) continue;
       for (itISR =ISRTree->branchings().begin();
 	   itISR!=ISRTree->branchings().end();++itISR){
 	if ((**itISR).status()==HardBranching::Incoming) continue;
 	if ((**itFSR).branchingParticle()->id()==
 	    (**itISR).branchingParticle()->id()){
 	  // rotate FSRTree particle to ISRTree event frame
 	  (**itISR).branchingParticle()->setMomentum(eventFrameISR*
 						     eventFrameFSR*
 						     (**itFSR).branchingParticle()->momentum());
 	  (**itISR).branchingParticle()->rescaleMass();
 	  // add the children of the FSRTree particles to the ISRTree
 	  if(!(**itFSR).children().empty()){
 	    (**itISR).addChild((**itFSR).children()[0]);
 	    (**itISR).addChild((**itFSR).children()[1]);
 	    // rotate momenta to ISRTree event frame
 	    (**itISR).children()[0]->branchingParticle()->setMomentum(eventFrameISR*
 								      eventFrameFSR*
 								      (**itFSR).children()[0]->branchingParticle()->momentum());
 	    (**itISR).children()[1]->branchingParticle()->setMomentum(eventFrameISR*
 								      eventFrameFSR*
 								      (**itFSR).children()[1]->branchingParticle()->momentum());
 	  }
 	}
       }	
     }
     _hardtree = ISRTree;
   }
 }
 
 bool QTildeShowerHandler::truncatedTimeLikeShower(tShowerParticlePtr particle,
 				      HardBranchingPtr branch,
 				      ShowerInteraction type,
 				      Branching fb, bool first) {
   // select a branching if we don't have one
   if(!fb.kinematics)
     fb = selectTimeLikeBranching(particle,type,branch);
   // must be an emission, the forced one it not a truncated one
   assert(fb.kinematics);
   ShowerParticleVector children;
   Branching fc[2] = {Branching(),Branching()};
   // Assign the shower kinematics to the emitting particle.
   particle->showerKinematics(fb.kinematics);
   if(fb.kinematics->pT()>progenitor()->highestpT())
     progenitor()->highestpT(fb.kinematics->pT());
   // create the children
   children = createTimeLikeChildren(particle,fb.ids);
   // update the children
   particle->showerKinematics()->
     updateChildren(particle, children,fb.type);
   // select branchings for children
   if(!fc[0].kinematics) {
     // select branching for first particle
     if(!fb.hard && fb.iout ==1 )
       fc[0] = selectTimeLikeBranching(children[0],type,branch);
     else if(fb.hard && !branch->children()[0]->children().empty() )
       fc[0] = selectTimeLikeBranching(children[0],type,branch->children()[0]);
     else
       fc[0] = selectTimeLikeBranching(children[0],type,HardBranchingPtr());
   }
   // select branching for the second particle
   if(!fc[1].kinematics) {
     // select branching for first particle
     if(!fb.hard && fb.iout ==2 )
       fc[1] = selectTimeLikeBranching(children[1],type,branch);
     else if(fb.hard && !branch->children()[1]->children().empty() )
       fc[1] = selectTimeLikeBranching(children[1],type,branch->children()[1]);
     else
       fc[1] = selectTimeLikeBranching(children[1],type,HardBranchingPtr());
   }
   // shower the first  particle
   if(fc[0].kinematics) {
     // the parent has truncated emission and following line
     if(!fb.hard && fb.iout == 1)
       truncatedTimeLikeShower(children[0],branch,type,fc[0],false);
     // hard emission and subsquent hard emissions
     else if(fb.hard && !branch->children()[0]->children().empty() )
       truncatedTimeLikeShower(children[0],branch->children()[0],type,fc[0],false);
     // normal shower
     else
       timeLikeShower(children[0],type,fc[0],false);
   }
   if(children[0]->spinInfo()) children[0]->spinInfo()->develop();
   // shower the second particle
   if(fc[1].kinematics) {
     // the parent has truncated emission and following line
     if(!fb.hard && fb.iout == 2)
       truncatedTimeLikeShower(children[1],branch,type,fc[1],false);
     // hard emission and subsquent hard emissions
     else if(fb.hard && !branch->children()[1]->children().empty() )
       truncatedTimeLikeShower(children[1],branch->children()[1],type,fc[1],false);
     else
       timeLikeShower(children[1],type,fc[1],false);
   }
   if(children[1]->spinInfo()) children[1]->spinInfo()->develop();
   // branching has happened
-  particle->showerKinematics()->updateParent(particle, children,fb.type); 
+  particle->showerKinematics()->updateParent(particle, children,_evolutionScheme,fb.type); 
   if(first&&!children.empty())
     particle->showerKinematics()->resetChildren(particle,children);
   if(particle->spinInfo()) particle->spinInfo()->develop();
   // TODO NEED AN UPDATE HERE FOR RECONOPT!=0 ?
   return true;
 }
 
 bool QTildeShowerHandler::truncatedSpaceLikeShower(tShowerParticlePtr particle, PPtr beam,
 				       HardBranchingPtr branch,
 				       ShowerInteraction type) {
   tcPDFPtr pdf;
   if(firstPDF().particle()  == beamParticle())
     pdf = firstPDF().pdf();
   if(secondPDF().particle() == beamParticle())
     pdf = secondPDF().pdf();
   Energy freeze = pdfFreezingScale();
   Branching bb;
   // parameters of the force branching
   double z(0.);
   HardBranchingPtr timelike;
   for( unsigned int ix = 0; ix < branch->children().size(); ++ix ) {
     if( branch->children()[ix]->status() ==HardBranching::Outgoing) {
       timelike = branch->children()[ix];
     }
     if( branch->children()[ix]->status() ==HardBranching::Incoming )
       z = branch->children()[ix]->z();
   }
   // generate truncated branching
   tcPDPtr part[2];
   if(z>=0.&&z<=1.) {
     while (true) {
       if( !isTruncatedShowerON() || hardOnly() ) break;
       bb = splittingGenerator()->chooseBackwardBranching( *particle, 
 							  beam, 1., beamParticle(), 
 							  type , pdf,freeze);
       if( !bb.kinematics || bb.kinematics->scale() < branch->scale() ) {
 	bb = Branching();
 	break;
       }
       // particles as in Sudakov form factor
       part[0] = bb.ids[0];
       part[1] = bb.ids[2];
       double zsplit = bb.kinematics->z();
       // apply the vetos for the truncated shower
       // if doesn't carry most of momentum
       ShowerInteraction type2 = convertInteraction(bb.type);
       if(type2==branch->sudakov()->interactionType() &&
 	 zsplit < 0.5) {
 	particle->vetoEmission(bb.type,bb.kinematics->scale());
 	continue;
       }
       // others
       if( part[0]->id() != particle->id() || // if particle changes type
 	  bb.kinematics->pT() > progenitor()->maximumpT(type2) ||   // pt veto
 	  bb.kinematics->scale() < branch->scale()) { // angular ordering veto
 	particle->vetoEmission(bb.type,bb.kinematics->scale());
 	continue;
       }
       // and those from the base class
       if(spaceLikeVetoed(bb,particle)) {
 	particle->vetoEmission(bb.type,bb.kinematics->scale());
 	continue;
       }
       break;
     }
   }
   if( !bb.kinematics ) {
     //do the hard emission
     ShoKinPtr kinematics = new_ptr(IS_QTildeShowerKinematics1to2(
     	branch->scale(), z, branch->phi(),
     	branch->children()[0]->pT(), branch->sudakov() 
     	));
     // assign the splitting function and shower kinematics
     particle->showerKinematics( kinematics );
     if(kinematics->pT()>progenitor()->highestpT())
       progenitor()->highestpT(kinematics->pT());
     // For the time being we are considering only 1->2 branching
     // Now create the actual particles, make the otherChild a final state
     // particle, while the newParent is not
     ShowerParticlePtr newParent = 
       new_ptr( ShowerParticle( branch->branchingParticle()->dataPtr(), false ) );
     ShowerParticlePtr otherChild = 
       new_ptr( ShowerParticle( timelike->branchingParticle()->dataPtr(),
     			       true, true ) );
     ShowerParticleVector theChildren;
     theChildren.push_back( particle ); 
     theChildren.push_back( otherChild );
     particle->showerKinematics()->
-      updateParent( newParent, theChildren, branch->type());
+      updateParent( newParent, theChildren,_evolutionScheme, branch->type());
     // update the history if needed
     currentTree()->updateInitialStateShowerProduct( progenitor(), newParent );
     currentTree()->addInitialStateBranching( particle, newParent, otherChild );
     // for the reconstruction of kinematics, parent/child
     // relationships are according to the branching process:
     // now continue the shower
     bool emitted=false;
     if(!hardOnly()) {
       if( branch->parent() ) {
     	emitted = truncatedSpaceLikeShower( newParent, beam, branch->parent() , type);
       }
       else {
     	emitted = spaceLikeShower( newParent, beam , type);
       }
     }
     if( !emitted ) {
       if( intrinsicpT().find( progenitor() ) == intrinsicpT().end() ) {
     	kinematics->updateLast( newParent, ZERO, ZERO );
       }
       else {
     	pair<Energy,double> kt = intrinsicpT()[progenitor()];
     	kinematics->updateLast( newParent,
     				kt.first*cos( kt.second ),
     				kt.first*sin( kt.second ) );
       }
     }
     particle->showerKinematics()->
       updateChildren( newParent, theChildren,bb.type);
     if(hardOnly()) return true;
     // perform the shower of the final-state particle
     if( timelike->children().empty() ) {
       timeLikeShower( otherChild , type,Branching(),true);
     }
     else {
       truncatedTimeLikeShower( otherChild, timelike , type,Branching(), true);
     }
     updateHistory(otherChild);
     // return the emitted
     return true;
   }
   // assign the splitting function and shower kinematics
   particle->showerKinematics( bb.kinematics );
   if(bb.kinematics->pT()>progenitor()->highestpT())
     progenitor()->highestpT(bb.kinematics->pT());
   // For the time being we are considering only 1->2 branching
   // Now create the actual particles, make the otherChild a final state
   // particle, while the newParent is not
   ShowerParticlePtr newParent = new_ptr( ShowerParticle( part[0], false ) );
   ShowerParticlePtr otherChild = new_ptr( ShowerParticle( part[1], true, true ) );
   ShowerParticleVector theChildren; 
   theChildren.push_back( particle ); 
   theChildren.push_back( otherChild );
   particle->showerKinematics()->
-    updateParent( newParent, theChildren, bb.type);
+    updateParent( newParent, theChildren,_evolutionScheme, bb.type);
   // update the history if needed
   currentTree()->updateInitialStateShowerProduct( progenitor(), newParent );
   currentTree()->addInitialStateBranching( particle, newParent, otherChild );
   // for the reconstruction of kinematics, parent/child
   // relationships are according to the branching process:
   // now continue the shower
   bool emitted = truncatedSpaceLikeShower( newParent, beam, branch,type);
   // now reconstruct the momentum
   if( !emitted ) {
     if( intrinsicpT().find( progenitor() ) == intrinsicpT().end() ) {
       bb.kinematics->updateLast( newParent, ZERO, ZERO );
     }
     else {
       pair<Energy,double> kt = intrinsicpT()[ progenitor() ];
       bb.kinematics->updateLast( newParent,
 				 kt.first*cos( kt.second ),
 				 kt.first*sin( kt.second ) );
     }
   }
   particle->showerKinematics()->
     updateChildren( newParent, theChildren, bb.type);
   // perform the shower of the final-state particle
   timeLikeShower( otherChild , type,Branching(),true);
   updateHistory(otherChild);
   // return the emitted
   return true;
 }
 
 bool QTildeShowerHandler::
 truncatedSpaceLikeDecayShower(tShowerParticlePtr particle, 
 			      const ShowerParticle::EvolutionScales & maxScales,
 			      Energy minmass, HardBranchingPtr branch,
 			      ShowerInteraction type, Branching fb) {
   // select a branching if we don't have one
   if(!fb.kinematics)
     fb = selectSpaceLikeDecayBranching(particle,maxScales,minmass,type,branch);
   // must be an emission, the forced one it not a truncated one
   assert(fb.kinematics);
   ShowerParticleVector children;
   Branching fc[2]={Branching(),Branching()};
   // Assign the shower kinematics to the emitting particle.
   particle->showerKinematics(fb.kinematics);
   if(fb.kinematics->pT()>progenitor()->highestpT())
     progenitor()->highestpT(fb.kinematics->pT());
   // create the ShowerParticle objects for the two children
   children = createTimeLikeChildren(particle,fb.ids);
   // updateChildren the children
   particle->showerKinematics()->
     updateChildren(particle, children, fb.type);
   // select branchings for children
   if(!fc[0].kinematics) {
     if(children[0]->id()==particle->id()) {
       // select branching for first particle
       if(!fb.hard)
 	fc[0] = selectSpaceLikeDecayBranching(children[0],maxScales,minmass,type,branch);
       else if(fb.hard && ! branch->children()[0]->children().empty() )
 	fc[0] = selectSpaceLikeDecayBranching(children[0],maxScales,minmass,type,
 					      branch->children()[0]);
       else
 	fc[0] = selectSpaceLikeDecayBranching(children[0],maxScales,minmass,type,
 					      HardBranchingPtr());
     }
     else {
       // select branching for first particle
       if(fb.hard && !branch->children()[0]->children().empty() )
 	fc[0] = selectTimeLikeBranching(children[0],type,branch->children()[0]);
       else
 	fc[0] = selectTimeLikeBranching(children[0],type,HardBranchingPtr());
     }
   }
   // select branching for the second particle
   if(!fc[1].kinematics) {
     if(children[1]->id()==particle->id()) {
       // select branching for first particle
       if(!fb.hard)
 	   fc[1] = selectSpaceLikeDecayBranching(children[1],maxScales,minmass,type,branch);
       else if(fb.hard && ! branch->children()[1]->children().empty() )
 	fc[1] = selectSpaceLikeDecayBranching(children[1],maxScales,minmass,type,
 					      branch->children()[1]);
       else
 	fc[1] = selectSpaceLikeDecayBranching(children[1],maxScales,minmass,type,
 					      HardBranchingPtr());
     }
     else {
       if(fb.hard && !branch->children()[1]->children().empty() )
 	fc[1] = selectTimeLikeBranching(children[1],type,branch->children()[1]);
       else
 	fc[1] = selectTimeLikeBranching(children[1],type,HardBranchingPtr());
     }
   }
   // old default
   // update the history if needed
   currentTree()->updateInitialStateShowerProduct(progenitor(),children[0]);
   currentTree()->addInitialStateBranching(particle,children[0],children[1]);
   // shower the first  particle
   if(fc[0].kinematics) {
     if(children[0]->id()==particle->id()) {
       if(!fb.hard)
 	truncatedSpaceLikeDecayShower( children[0],maxScales,minmass,
 				       branch,type,fc[0]);
       else if(fb.hard && ! branch->children()[0]->children().empty() )
 	truncatedSpaceLikeDecayShower( children[0],maxScales,minmass,
 				       branch->children()[0],type,fc[0]);
       else
 	spaceLikeDecayShower( children[0],maxScales,minmass,type,fc[0]);
     }
     else {
       if(fb.hard && !branch->children()[0]->children().empty() )
 	truncatedTimeLikeShower(children[0],branch->children()[0],type,fc[0],false);
       // normal shower
       else
 	timeLikeShower(children[0],type,fc[0],false);
     }
   }
   // shower the second  particle
   if(fc[1].kinematics) {
     if(children[0]->id()==particle->id()) {
       if(!fb.hard)
 	truncatedSpaceLikeDecayShower( children[0],maxScales,minmass,
 				       branch,type,fc[1]);
       else if(fb.hard && ! branch->children()[0]->children().empty() )
 	truncatedSpaceLikeDecayShower( children[0],maxScales,minmass,
 				       branch->children()[0],type,fc[1]);
       else
 	spaceLikeDecayShower( children[0],maxScales,minmass,type,fc[1]);
     }
     else {
       if(fb.hard && !branch->children()[0]->children().empty() )
 	truncatedTimeLikeShower(children[0],branch->children()[0],type,fc[1],false);
       // normal shower
       else
 	timeLikeShower(children[0],type,fc[1],false);
     }
   }
   updateHistory(children[1]);
   // TODO DO WE NEED A CHECK IF RECONPT !=0
   return true;
 }
 
 void QTildeShowerHandler::connectTrees(ShowerTreePtr showerTree, 
 				       HardTreePtr hardTree, bool hard ) {
   ShowerParticleVector particles;
   // find the Sudakovs
   for(set<HardBranchingPtr>::iterator cit=hardTree->branchings().begin();
       cit!=hardTree->branchings().end();++cit) {
     // Sudakovs for ISR
     if((**cit).parent()&&(**cit).status()==HardBranching::Incoming) {
       ++_nis;
       array<long,3> br;
       br[0] = (**cit).parent()->branchingParticle()->id();
       br[1] = (**cit).          branchingParticle()->id();
       br[2] = (**cit).parent()->children()[0]==*cit ?
 	(**cit).parent()->children()[1]->branchingParticle()->id() :
 	(**cit).parent()->children()[0]->branchingParticle()->id();
       BranchingList branchings = splittingGenerator()->initialStateBranchings();
       if(br[1]<0&&br[0]==br[1]) {
 	br[0] = abs(br[0]);
 	br[1] = abs(br[1]);
       }
       else if(br[1]<0) {
 	br[1] = -br[1];
 	br[2] = -br[2];
       }
       long index = abs(br[1]);
       SudakovPtr sudakov;
       for(BranchingList::const_iterator cjt = branchings.lower_bound(index); 
 	  cjt != branchings.upper_bound(index); ++cjt ) {
 	IdList ids = cjt->second.particles;
 	if(ids[0]->id()==br[0]&&ids[1]->id()==br[1]&&ids[2]->id()==br[2]) {
 	  sudakov=cjt->second.sudakov;
 	  break;
 	}
       }
       if(!sudakov) throw Exception() << "Can't find Sudakov for the hard emission in "
 				     << "QTildeShowerHandler::connectTrees() for ISR" 
 				     << Exception::runerror;
       (**cit).parent()->sudakov(sudakov);
     }
     // Sudakovs for FSR
     else if(!(**cit).children().empty()) {
       ++_nfs;
       array<long,3> br;
       br[0] = (**cit)               .branchingParticle()->id();
       br[1] = (**cit).children()[0]->branchingParticle()->id();
       br[2] = (**cit).children()[1]->branchingParticle()->id();
       BranchingList branchings = splittingGenerator()->finalStateBranchings();
       if(br[0]<0) {
 	br[0] = abs(br[0]);
 	br[1] = abs(br[1]);
 	br[2] = abs(br[2]);
       }
       long index = br[0];
       SudakovPtr sudakov;
       for(BranchingList::const_iterator cjt = branchings.lower_bound(index); 
 	  cjt != branchings.upper_bound(index); ++cjt ) {
 	IdList ids = cjt->second.particles;
 	if(ids[0]->id()==br[0]&&ids[1]->id()==br[1]&&ids[2]->id()==br[2]) {
 	  sudakov=cjt->second.sudakov;
 	  break;
 	}
       }
       if(!sudakov) {
 	throw Exception() << "Can't find Sudakov for the hard emission in "
 			  << "QTildeShowerHandler::connectTrees()" 
 			  << Exception::runerror;
       }
       (**cit).sudakov(sudakov);
     }
   }
   // calculate the evolution scale
   for(set<HardBranchingPtr>::iterator cit=hardTree->branchings().begin();
       cit!=hardTree->branchings().end();++cit) {
     particles.push_back((*cit)->branchingParticle());
   }
   partnerFinder()->
     setInitialEvolutionScales(particles,!hard,interaction_,true);
   hardTree->partnersSet(true);
   // inverse reconstruction
   if(hard) {
     kinematicsReconstructor()->
       deconstructHardJets(hardTree,interaction_);
   }
   else
     kinematicsReconstructor()->
       deconstructDecayJets(hardTree,interaction_);
   // now reset the momenta of the showering particles
   vector<ShowerProgenitorPtr> particlesToShower=showerTree->extractProgenitors();
   // match them
   map<ShowerProgenitorPtr,HardBranchingPtr> partners;
   for(set<HardBranchingPtr>::const_iterator bit=hardTree->branchings().begin();
       bit!=hardTree->branchings().end();++bit) {
     Energy2 dmin( 1e30*GeV2 );
     ShowerProgenitorPtr partner;
     for(vector<ShowerProgenitorPtr>::const_iterator pit=particlesToShower.begin();
 	pit!=particlesToShower.end();++pit) {
       if(partners.find(*pit)!=partners.end()) continue;
       if( (**bit).branchingParticle()->id() !=  (**pit).progenitor()->id() ) continue;
       if( (**bit).branchingParticle()->isFinalState() !=
 	  (**pit).progenitor()->isFinalState() ) continue;
       if( (**pit).progenitor()->isFinalState() ) {
 	Energy2 dtest =
 	  sqr( (**pit).progenitor()->momentum().x() - (**bit).showerMomentum().x() ) +
 	  sqr( (**pit).progenitor()->momentum().y() - (**bit).showerMomentum().y() ) +
 	  sqr( (**pit).progenitor()->momentum().z() - (**bit).showerMomentum().z() ) +
 	  sqr( (**pit).progenitor()->momentum().t() - (**bit).showerMomentum().t() );
 	// add mass difference for identical particles (e.g. Z0 Z0 production)
 	dtest += 1e10*sqr((**pit).progenitor()->momentum().m()-(**bit).showerMomentum().m());
 	if( dtest < dmin ) {
 	  partner = *pit;
 	  dmin = dtest;
 	}
       }
       else {
 	// ensure directions are right
 	if((**pit).progenitor()->momentum().z()/(**bit).showerMomentum().z()>ZERO) {
 	  partner = *pit;
 	  break;
 	}
       }
     }
     if(!partner) throw Exception() << "Failed to match shower and hard trees in QTildeShowerHandler::hardestEmission"
 				   << Exception::eventerror;
     partners[partner] = *bit;
   }
   for(vector<ShowerProgenitorPtr>::const_iterator pit=particlesToShower.begin();
       pit!=particlesToShower.end();++pit) {
     HardBranchingPtr partner = partners[*pit];
     if((**pit).progenitor()->dataPtr()->stable()) {
       (**pit).progenitor()->set5Momentum(partner->showerMomentum());
       (**pit).copy()->set5Momentum(partner->showerMomentum());
     }
     else {
       Lorentz5Momentum oldMomentum = (**pit).progenitor()->momentum();
       Lorentz5Momentum newMomentum = partner->showerMomentum();
       LorentzRotation boost( oldMomentum.findBoostToCM(),oldMomentum.e()/oldMomentum.mass());
       (**pit).progenitor()->transform(boost);
       (**pit).copy()      ->transform(boost);
       boost = LorentzRotation(-newMomentum.findBoostToCM(),newMomentum.e()/newMomentum.mass());
       (**pit).progenitor()->transform(boost);
       (**pit).copy()      ->transform(boost);
     }
   }
   // correction boosts for daughter trees
   for(map<tShowerTreePtr,pair<tShowerProgenitorPtr,tShowerParticlePtr> >::const_iterator 
 	tit  = showerTree->treelinks().begin();
       tit != showerTree->treelinks().end();++tit) {
     ShowerTreePtr decayTree = tit->first;
     map<ShowerProgenitorPtr,ShowerParticlePtr>::const_iterator 
       cit = decayTree->incomingLines().begin();
     // reset the momentum of the decay particle
     Lorentz5Momentum oldMomentum = cit->first->progenitor()->momentum();
     Lorentz5Momentum newMomentum = tit->second.second->momentum();
     LorentzRotation boost( oldMomentum.findBoostToCM(),oldMomentum.e()/oldMomentum.mass());
     decayTree->transform(boost,true);
     boost = LorentzRotation(-newMomentum.findBoostToCM(),newMomentum.e()/newMomentum.mass());
     decayTree->transform(boost,true);
   }
 }
 
 void QTildeShowerHandler::doShowering(bool hard,XCPtr xcomb) {
   // zero number of emissions
   _nis = _nfs = 0;
   // if MC@NLO H event and limited emissions
   // indicate both final and initial state emission
   if ( currentTree()->isMCatNLOHEvent() && _limitEmissions != 0 ) {
     _nis = _nfs = 1;
   }
   // extract particles to shower
   vector<ShowerProgenitorPtr> particlesToShower(setupShower(hard));
   // check if we should shower
   bool colCharge = false;
   for(unsigned int ix=0;ix<particlesToShower.size();++ix) {
     if(particlesToShower[ix]->progenitor()->dataPtr()->coloured() ||
        particlesToShower[ix]->progenitor()->dataPtr()->charged()) {
       colCharge = true;
       break;
     }
   }
   if(!colCharge) {
     _currenttree->hasShowered(true);
     return;
   }
   // setup the maximum scales for the shower
   if (restrictPhasespace()) setupMaximumScales(particlesToShower,xcomb);
   // set the hard scales for the profiles
   setupHardScales(particlesToShower,xcomb);
   // specific stuff for hard processes and decays
   Energy minmass(ZERO), mIn(ZERO);
   // hard process generate the intrinsic p_T once and for all
   if(hard) {
     generateIntrinsicpT(particlesToShower);
   }
   // decay compute the minimum mass of the final-state
   else {
     for(unsigned int ix=0;ix<particlesToShower.size();++ix) {
       if(particlesToShower[ix]->progenitor()->isFinalState()) {
         if(particlesToShower[ix]->progenitor()->dataPtr()->stable()) {
           auto dm=  ShowerHandler::currentHandler()->retConstituentMasses()?
 	    particlesToShower[ix]->progenitor()->dataPtr()->constituentMass():
 	    particlesToShower[ix]->progenitor()->dataPtr()->mass();
           minmass += dm;
 	}
         else
 	  minmass += particlesToShower[ix]->progenitor()->mass();
       }
       else {
 	mIn = particlesToShower[ix]->progenitor()->mass();
       }
     }
     // throw exception if decay can't happen
     if ( minmass > mIn ) {
       throw Exception() << "QTildeShowerHandler.cc: Mass of decaying particle is "
 			<< "below constituent masses of decay products."
 			<< Exception::eventerror;
     }
   }
   // setup for reweighted
   bool reWeighting = _reWeight && hard && ShowerHandler::currentHandler()->firstInteraction();
   double eventWeight=0.;
   unsigned int nTryReWeight(0);
   // create random particle vector (only need to do once)
   vector<ShowerProgenitorPtr> tmp;
   unsigned int nColouredIncoming = 0;
   while(particlesToShower.size()>0){
     unsigned int xx=UseRandom::irnd(particlesToShower.size());
     tmp.push_back(particlesToShower[xx]);
     particlesToShower.erase(particlesToShower.begin()+xx);
   }
   particlesToShower=tmp;
   for(unsigned int ix=0;ix<particlesToShower.size();++ix) {
     if(!particlesToShower[ix]->progenitor()->isFinalState() &&
        particlesToShower[ix]->progenitor()->coloured()) ++nColouredIncoming;
   }
   bool switchRecon = hard && nColouredIncoming !=1;
   // main shower loop
   unsigned int ntry(0);
   bool reconstructed = false;
   do {
     // clear results of last attempt if needed
     if(ntry!=0) {
       currentTree()->clear();
       setEvolutionPartners(hard,interaction_,true);
       _nis = _nfs = 0;
       // if MC@NLO H event and limited emissions
       // indicate both final and initial state emission
       if ( currentTree()->isMCatNLOHEvent() && _limitEmissions != 0 ) {
 	_nis = _nfs = 1;
       }
       for(unsigned int ix=0; ix<particlesToShower.size();++ix) {
 	SpinPtr spin = particlesToShower[ix]->progenitor()->spinInfo();
 	if(spin && spin->decayVertex() &&
 	   dynamic_ptr_cast<tcSVertexPtr>(spin->decayVertex())) {
 	  spin->decayVertex(VertexPtr());
 	}
       }
       for(unsigned int ix=0;ix<particlesToShower.size();++ix) {
 	if(particlesToShower[ix]->progenitor()->isFinalState() ||
 	   (hard && !particlesToShower[ix]->progenitor()->isFinalState())) {
 	  if(particlesToShower[ix]->progenitor()->spinInfo())
 	    particlesToShower[ix]->progenitor()->spinInfo()->reset();
 	}
       }
     }
     // loop over particles
     for(unsigned int ix=0;ix<particlesToShower.size();++ix) {
       // extract the progenitor
       progenitor(particlesToShower[ix]);
       // final-state radiation
       if(progenitor()->progenitor()->isFinalState()) {
 	if(!doFSR()) continue;
 	// perform shower
 	progenitor()->hasEmitted(startTimeLikeShower(interaction_));
       }
       // initial-state radiation
       else {
 	if(!doISR()) continue;
 	// hard process
 	if(hard) {
 	  // get the PDF
 	  setBeamParticle(_progenitor->beam());
 	  if(!beamParticle()) {
 	    throw Exception() << "Incorrect type of beam particle in "
 			      << "QTildeShowerHandler::doShowering(). "
 			      << "This should not happen for conventional choices but may happen if you have used a"
 			      << " non-default choice and have not changed the create ParticleData line in the input files"
 			      << " for this particle to create BeamParticleData."
 			      << Exception::runerror;
 	  }
 	  // perform the shower
 	  // set the beam particle
 	  tPPtr beamparticle=progenitor()->original();
 	  if(!beamparticle->parents().empty()) 
 	    beamparticle=beamparticle->parents()[0];
 	  // generate the shower
 	  progenitor()->hasEmitted(startSpaceLikeShower(beamparticle,
 							interaction_));
 	}
 	// decay
 	else {
 	  // skip colour and electrically neutral particles
 	  if(!progenitor()->progenitor()->dataPtr()->coloured() &&
 	     !progenitor()->progenitor()->dataPtr()->charged()) {
 	    progenitor()->hasEmitted(false);
 	    continue;
 	  }
 	  // perform shower
 	  // set the scales correctly. The current scale is the maximum scale for
 	  // emission not the starting scale
 	  ShowerParticle::EvolutionScales maxScales(progenitor()->progenitor()->scales());
 	  progenitor()->progenitor()->scales() = ShowerParticle::EvolutionScales();
 	  if(progenitor()->progenitor()->dataPtr()->charged()) {
 	    progenitor()->progenitor()->scales().QED      = progenitor()->progenitor()->mass();
 	    progenitor()->progenitor()->scales().QED_noAO = progenitor()->progenitor()->mass();
 	  }
 	  if(progenitor()->progenitor()->hasColour()) {
 	    progenitor()->progenitor()->scales().QCD_c       = progenitor()->progenitor()->mass();
 	    progenitor()->progenitor()->scales().QCD_c_noAO  = progenitor()->progenitor()->mass();
 	  }
 	  if(progenitor()->progenitor()->hasAntiColour()) {
 	    progenitor()->progenitor()->scales().QCD_ac      = progenitor()->progenitor()->mass();
 	    progenitor()->progenitor()->scales().QCD_ac_noAO = progenitor()->progenitor()->mass();
 	  }
 	  // perform the shower
 	  progenitor()->hasEmitted(startSpaceLikeDecayShower(maxScales,minmass,
 							     interaction_));
 	}
       }
     }
     // do the kinematic reconstruction, checking if it worked
     reconstructed = hard ?
       kinematicsReconstructor()->
       reconstructHardJets (currentTree(),intrinsicpT(),interaction_,
 			   switchRecon && ntry>maximumTries()/2) :
       kinematicsReconstructor()->
       reconstructDecayJets(currentTree(),interaction_);
     if(!reconstructed) continue;
     // apply vetos on the full shower
     for(vector<FullShowerVetoPtr>::const_iterator it=_fullShowerVetoes.begin();
 	it!=_fullShowerVetoes.end();++it) {
       int veto = (**it).applyVeto(currentTree());
       if(veto<0) continue;
       // veto the shower
       if(veto==0) {
 	reconstructed = false;
 	break;
       }
       // veto the shower and reweight
       else if(veto==1) {
 	reconstructed = false;
 	break;
       }
       // veto the event
       else if(veto==2) {
 	throw Veto();
       }
     }
     if(reWeighting) {
       if(reconstructed) eventWeight += 1.;
       reconstructed=false;
       ++nTryReWeight;
       if(nTryReWeight==_nReWeight) {
 	reWeighting = false;
 	if(eventWeight==0.) throw Veto();
       }
     }
   }
   while(!reconstructed&&maximumTries()>++ntry);
   // check if failed to generate the shower
   if(ntry==maximumTries()) {
     if(hard)
       throw ShowerHandler::ShowerTriesVeto(ntry);
     else
       throw Exception() << "Failed to generate the shower after "
 			<< ntry << " attempts in QTildeShowerHandler::showerDecay()"
 			<< Exception::eventerror;
   }
   // handle the weights and apply any reweighting required
   if(nTryReWeight>0) {
     tStdEHPtr seh = dynamic_ptr_cast<tStdEHPtr>(generator()->currentEventHandler());
     static bool first = true;
     if(seh) {
       seh->reweight(eventWeight/double(nTryReWeight));
     }
     else if(first) {
       generator()->log() << "Reweighting the shower only works with internal Herwig7 processes"
     			 << "Presumably you are showering Les Houches Events. These will not be"
     			 << "reweighted\n";
       first = false;
     }
   }
   // tree has now showered
   _currenttree->hasShowered(true);
   hardTree(HardTreePtr());
 }
 
 void QTildeShowerHandler:: convertHardTree(bool hard,ShowerInteraction type) {
   map<ColinePtr,ColinePtr> cmap;
   // incoming particles
   for(map<ShowerProgenitorPtr,ShowerParticlePtr>::const_iterator 
 	cit=currentTree()->incomingLines().begin();cit!=currentTree()->incomingLines().end();++cit) {
     map<ShowerParticlePtr,tHardBranchingPtr>::const_iterator 
       mit = hardTree()->particles().find(cit->first->progenitor());
     // put the colour lines in the map
     ShowerParticlePtr oldParticle = cit->first->progenitor();
     ShowerParticlePtr newParticle = mit->second->branchingParticle();
     ColinePtr cLine = oldParticle->    colourLine();
     ColinePtr aLine = oldParticle->antiColourLine();
     if(newParticle->colourLine() &&
        cmap.find(newParticle->    colourLine())==cmap.end())
       cmap[newParticle->    colourLine()] = cLine;
     if(newParticle->antiColourLine() &&
        cmap.find(newParticle->antiColourLine())==cmap.end())
       cmap[newParticle->antiColourLine()] = aLine;
     // check whether or not particle emits
     bool emission = mit->second->parent();
     if(emission) {
       if(newParticle->colourLine()) {
 	ColinePtr ctemp = newParticle->    colourLine();
 	ctemp->removeColoured(newParticle);
       }
       if(newParticle->antiColourLine()) {
 	ColinePtr ctemp = newParticle->antiColourLine();
 	ctemp->removeAntiColoured(newParticle);
       }
       newParticle = mit->second->parent()->branchingParticle();
     }
     // get the new colour lines
     ColinePtr newCLine,newALine;
     // sort out colour lines
     if(newParticle->colourLine()) {
       ColinePtr ctemp = newParticle->    colourLine();
       ctemp->removeColoured(newParticle);
       if(cmap.find(ctemp)!=cmap.end()) {
 	newCLine = cmap[ctemp];
       }
       else {
 	newCLine = new_ptr(ColourLine());
 	cmap[ctemp] = newCLine;
       }
     }
     // and anticolour lines
     if(newParticle->antiColourLine()) {
       ColinePtr ctemp = newParticle->antiColourLine();
       ctemp->removeAntiColoured(newParticle);
       if(cmap.find(ctemp)!=cmap.end()) {
 	newALine = cmap[ctemp];
       }
       else {
 	newALine = new_ptr(ColourLine());
 	cmap[ctemp] = newALine;
       }
     }
     // remove colour lines from old particle
     if(aLine) {
       aLine->removeAntiColoured(cit->first->copy());
       aLine->removeAntiColoured(cit->first->progenitor());
     }
     if(cLine) {
       cLine->removeColoured(cit->first->copy());
       cLine->removeColoured(cit->first->progenitor());
     }
     // add particle to colour lines
     if(newCLine) newCLine->addColoured    (newParticle);
     if(newALine) newALine->addAntiColoured(newParticle);
     // insert new particles
     cit->first->copy(newParticle);
     ShowerParticlePtr sp(new_ptr(ShowerParticle(*newParticle,1,false)));
     cit->first->progenitor(sp);
     currentTree()->incomingLines()[cit->first]=sp;
     cit->first->perturbative(!emission);
     // and the emitted particle if needed
     if(emission) {
       ShowerParticlePtr newOut = mit->second->parent()->children()[1]->branchingParticle();
       if(newOut->colourLine()) {
 	ColinePtr ctemp = newOut->    colourLine();
 	ctemp->removeColoured(newOut);
 	assert(cmap.find(ctemp)!=cmap.end());
 	cmap[ctemp]->addColoured    (newOut);
       }
       if(newOut->antiColourLine()) {
 	ColinePtr ctemp = newOut->antiColourLine();
 	ctemp->removeAntiColoured(newOut);
 	assert(cmap.find(ctemp)!=cmap.end());
 	cmap[ctemp]->addAntiColoured(newOut);
       }
       ShowerParticlePtr sout=new_ptr(ShowerParticle(*newOut,1,true));
       ShowerProgenitorPtr out=new_ptr(ShowerProgenitor(cit->first->original(),newOut,sout));
       out->perturbative(false);
       currentTree()->outgoingLines().insert(make_pair(out,sout));
     }
     if(hard) {
       // sort out the value of x
       if(mit->second->beam()->momentum().z()>ZERO) {
 	sp->x(newParticle->momentum(). plus()/mit->second->beam()->momentum(). plus());
       }
       else {
 	sp->x(newParticle->momentum().minus()/mit->second->beam()->momentum().minus());
       }
     }
   }
   // outgoing particles
   for(map<ShowerProgenitorPtr,tShowerParticlePtr>::const_iterator 
 	cit=currentTree()->outgoingLines().begin();cit!=currentTree()->outgoingLines().end();++cit) {
     map<tShowerTreePtr,pair<tShowerProgenitorPtr,
 			    tShowerParticlePtr> >::const_iterator tit;
     for(tit  = currentTree()->treelinks().begin();
 	tit != currentTree()->treelinks().end();++tit) {
       if(tit->second.first && tit->second.second==cit->first->progenitor())
 	break;
     }
     map<ShowerParticlePtr,tHardBranchingPtr>::const_iterator 
       mit = hardTree()->particles().find(cit->first->progenitor());
     if(mit==hardTree()->particles().end()) continue;
     // put the colour lines in the map
     ShowerParticlePtr oldParticle = cit->first->progenitor();
     ShowerParticlePtr newParticle = mit->second->branchingParticle();
     ShowerParticlePtr newOut;
     ColinePtr cLine = oldParticle->    colourLine();
     ColinePtr aLine = oldParticle->antiColourLine();
     if(newParticle->colourLine() &&
        cmap.find(newParticle->    colourLine())==cmap.end())
       cmap[newParticle->    colourLine()] = cLine;
     if(newParticle->antiColourLine() &&
        cmap.find(newParticle->antiColourLine())==cmap.end())
       cmap[newParticle->antiColourLine()] = aLine;
     // check whether or not particle emits
     bool emission = !mit->second->children().empty();
     if(emission) {
       if(newParticle->colourLine()) {
 	ColinePtr ctemp = newParticle->    colourLine();
 	ctemp->removeColoured(newParticle);
       }
       if(newParticle->antiColourLine()) {
 	ColinePtr ctemp = newParticle->antiColourLine();
 	ctemp->removeAntiColoured(newParticle);
       }
       newParticle = mit->second->children()[0]->branchingParticle();
       newOut      = mit->second->children()[1]->branchingParticle();
       if(newParticle->id()!=oldParticle->id()&&newParticle->id()==newOut->id())
 	swap(newParticle,newOut);
     }
     // get the new colour lines
     ColinePtr newCLine,newALine;
     // sort out colour lines
     if(newParticle->colourLine()) {
       ColinePtr ctemp = newParticle->    colourLine();
       ctemp->removeColoured(newParticle);
       if(cmap.find(ctemp)!=cmap.end()) {
 	newCLine = cmap[ctemp];
       }
       else {
 	newCLine = new_ptr(ColourLine());
 	cmap[ctemp] = newCLine;
       }
     }
     // and anticolour lines
     if(newParticle->antiColourLine()) {
       ColinePtr ctemp = newParticle->antiColourLine();
       ctemp->removeAntiColoured(newParticle);
       if(cmap.find(ctemp)!=cmap.end()) {
 	newALine = cmap[ctemp];
       }
       else {
 	newALine = new_ptr(ColourLine());
 	cmap[ctemp] = newALine;
       }
     }
     // remove colour lines from old particle
     if(aLine) {
       aLine->removeAntiColoured(cit->first->copy());
       aLine->removeAntiColoured(cit->first->progenitor());
     }
     if(cLine) {
       cLine->removeColoured(cit->first->copy());
       cLine->removeColoured(cit->first->progenitor());
     }
     // special for unstable particles
     if(newParticle->id()==oldParticle->id() &&
        (tit!=currentTree()->treelinks().end()||!oldParticle->dataPtr()->stable())) {
       Lorentz5Momentum oldMomentum = oldParticle->momentum();
       Lorentz5Momentum newMomentum = newParticle->momentum();
       LorentzRotation boost( oldMomentum.findBoostToCM(),oldMomentum.e()/oldMomentum.mass());
       if(tit!=currentTree()->treelinks().end()) tit->first->transform(boost,false);
       oldParticle->transform(boost);
       boost = LorentzRotation(-newMomentum.findBoostToCM(),newMomentum.e()/newMomentum.mass());
       oldParticle->transform(boost);
       if(tit!=currentTree()->treelinks().end()) tit->first->transform(boost,false);
       newParticle=oldParticle;
     }
     // add particle to colour lines
     if(newCLine) newCLine->addColoured    (newParticle);
     if(newALine) newALine->addAntiColoured(newParticle);
     // insert new particles
     cit->first->copy(newParticle);
     ShowerParticlePtr sp(new_ptr(ShowerParticle(*newParticle,1,true)));
     cit->first->progenitor(sp);
     currentTree()->outgoingLines()[cit->first]=sp;
     cit->first->perturbative(!emission);
     // and the emitted particle if needed
     if(emission) {
       if(newOut->colourLine()) {
 	ColinePtr ctemp = newOut->    colourLine();
 	ctemp->removeColoured(newOut);
 	assert(cmap.find(ctemp)!=cmap.end());
 	cmap[ctemp]->addColoured    (newOut);
       }
       if(newOut->antiColourLine()) {
 	ColinePtr ctemp = newOut->antiColourLine();
 	ctemp->removeAntiColoured(newOut);
 	assert(cmap.find(ctemp)!=cmap.end());
 	cmap[ctemp]->addAntiColoured(newOut);
       }
       ShowerParticlePtr sout=new_ptr(ShowerParticle(*newOut,1,true));
       ShowerProgenitorPtr out=new_ptr(ShowerProgenitor(cit->first->original(),newOut,sout));
       out->perturbative(false);
       currentTree()->outgoingLines().insert(make_pair(out,sout));
     }
     // update any decay products
     if(tit!=currentTree()->treelinks().end())
       currentTree()->updateLink(tit->first,make_pair(cit->first,sp));
   }
   // reset the tree
   currentTree()->resetShowerProducts();
   // reextract the particles and set the colour partners
   vector<ShowerParticlePtr> particles = 
     currentTree()->extractProgenitorParticles();
   // clear the partners
   for(unsigned int ix=0;ix<particles.size();++ix) {
     particles[ix]->partner(ShowerParticlePtr());
     particles[ix]->clearPartners();
   }
   // clear the tree
   hardTree(HardTreePtr());
   // Set the initial evolution scales
   partnerFinder()->
     setInitialEvolutionScales(particles,!hard,type,!_hardtree);
 }
 
 Branching QTildeShowerHandler::selectTimeLikeBranching(tShowerParticlePtr particle,
 						       ShowerInteraction type,
 						       HardBranchingPtr branch) {
   Branching fb;
   unsigned int iout=0;
   while (true) {
     // break if doing truncated shower and no truncated shower needed
     if(branch && (!isTruncatedShowerON()||hardOnly())) break;
     fb=_splittingGenerator->chooseForwardBranching(*particle,_finalenhance,type);
     // no emission break
     if(!fb.kinematics) break;
     // special for truncated shower
     if(branch) {
       // check haven't evolved too far
       if(fb.kinematics->scale() < branch->scale()) {
 	fb=Branching();
 	break;
       }
       // find the truncated line
       iout=0;
       if(fb.ids[1]->id()!=fb.ids[2]->id()) {
 	if(fb.ids[1]->id()==particle->id())       iout=1;
 	else if (fb.ids[2]->id()==particle->id()) iout=2;
       }
       else if(fb.ids[1]->id()==particle->id()) {
 	if(fb.kinematics->z()>0.5) iout=1;
 	else                       iout=2;
       }
       // apply the vetos for the truncated shower
       // no flavour changing branchings
       if(iout==0) {
 	particle->vetoEmission(fb.type,fb.kinematics->scale());
 	continue;
       }
       double zsplit = iout==1 ? fb.kinematics->z() : 1-fb.kinematics->z();
       // only if same interaction for forced branching
       ShowerInteraction type2 = convertInteraction(fb.type);
       // and evolution
       if(type2==branch->sudakov()->interactionType()) {
 	if(zsplit < 0.5 || // hardest line veto
 	   fb.kinematics->scale()*zsplit < branch->scale() ) { // angular ordering veto
 	  particle->vetoEmission(fb.type,fb.kinematics->scale());
 	  continue;
 	}
       }
       // pt veto
       if(fb.kinematics->pT() > progenitor()->maximumpT(type2)) {
 	particle->vetoEmission(fb.type,fb.kinematics->scale());
 	continue;
       }
     }
     // standard vetos for all emissions
     if(timeLikeVetoed(fb,particle)) {
       particle->vetoEmission(fb.type,fb.kinematics->scale());
       if(particle->spinInfo()) particle->spinInfo()->decayVertex(VertexPtr());
       continue;
     }
     // special for already decayed particles
     // don't allow flavour changing branchings
     bool vetoDecay = false;
     for(map<tShowerTreePtr,pair<tShowerProgenitorPtr,
 	  tShowerParticlePtr> >::const_iterator tit  = currentTree()->treelinks().begin();
 	tit != currentTree()->treelinks().end();++tit) {
       if(tit->second.first == progenitor()) {
 	map<ShowerProgenitorPtr,tShowerParticlePtr>::const_iterator 
 	  it = currentTree()->outgoingLines().find(progenitor());
 	if(it!=currentTree()->outgoingLines().end() && particle == it->second &&
 	   fb.ids[0]!=fb.ids[1] && fb.ids[1]!=fb.ids[2]) {
 	  vetoDecay = true;
 	  break;
 	}
       }
     }
     if(vetoDecay) {
       particle->vetoEmission(fb.type,fb.kinematics->scale());
       if(particle->spinInfo()) particle->spinInfo()->decayVertex(VertexPtr());
       continue;
     }
     break;
   }
   // normal case
   if(!branch) {
     if(fb.kinematics) fb.hard = false;
     return fb;
   }
   // truncated emission
   if(fb.kinematics) {
     fb.hard = false;
     fb.iout = iout;
     return fb;
   }
   // otherwise need to return the hard emission
   // construct the kinematics for the hard emission
   ShoKinPtr showerKin = new_ptr(FS_QTildeShowerKinematics1to2(
     branch->scale(),
     branch->children()[0]->z(),
     branch->phi(),
     branch->children()[0]->pT(),
     branch->sudakov()
     ));						 
 
   IdList idlist(3);
   idlist[0] = particle->dataPtr();
   idlist[1] = branch->children()[0]->branchingParticle()->dataPtr();
   idlist[2] = branch->children()[1]->branchingParticle()->dataPtr();
   fb = Branching( showerKin, idlist, branch->sudakov(),branch->type() );
   fb.hard = true;
   fb.iout=0;
   // return it
   return fb;
 }
 
 Branching QTildeShowerHandler::selectSpaceLikeDecayBranching(tShowerParticlePtr particle,
 						 const ShowerParticle::EvolutionScales & maxScales,
 						 Energy minmass,ShowerInteraction type,
 						 HardBranchingPtr branch) {
   Branching fb;
   unsigned int iout=0;
   while (true) {
     // break if doing truncated shower and no truncated shower needed
     if(branch && (!isTruncatedShowerON()||hardOnly())) break;
     // select branching
     fb=_splittingGenerator->chooseDecayBranching(*particle,maxScales,minmass,
 						 _initialenhance,type);
     // return if no radiation
     if(!fb.kinematics) break;
     // special for truncated shower
     if(branch) {
       // check haven't evolved too far
       if(fb.kinematics->scale() < branch->scale()) {
 	fb=Branching();
 	break;
       }
       // find the truncated line
       iout=0;
       if(fb.ids[1]->id()!=fb.ids[2]->id()) {
 	if(fb.ids[1]->id()==particle->id())       iout=1;
 	else if (fb.ids[2]->id()==particle->id()) iout=2;
       }
       else if(fb.ids[1]->id()==particle->id()) {
 	if(fb.kinematics->z()>0.5) iout=1;
 	else                       iout=2;
       }
       // apply the vetos for the truncated shower
       // no flavour changing branchings
       if(iout==0) {
 	particle->vetoEmission(fb.type,fb.kinematics->scale());
 	continue;
       }
       ShowerInteraction type2 = convertInteraction(fb.type);
       double zsplit = iout==1 ? fb.kinematics->z() : 1-fb.kinematics->z();
       if(type2==branch->sudakov()->interactionType()) {
 	if(zsplit < 0.5 || // hardest line veto
 	   fb.kinematics->scale()*zsplit < branch->scale() ) { // angular ordering veto
 	  particle->vetoEmission(fb.type,fb.kinematics->scale());
 	  continue;
 	}
       }
       // pt veto
       if(fb.kinematics->pT() > progenitor()->maximumpT(type2)) {
 	particle->vetoEmission(fb.type,fb.kinematics->scale());
 	continue;
       }
     }
     // if not vetoed break
     if(spaceLikeDecayVetoed(fb,particle)) {
       // otherwise reset scale and continue
       particle->vetoEmission(fb.type,fb.kinematics->scale());
       continue;
     }
     break;
   }
   // normal case
   if(!branch) {
     if(fb.kinematics) fb.hard = false;
     return fb;
   }
   // truncated emission
   if(fb.kinematics) {
     fb.hard = false;
     fb.iout = iout;
     return fb;
   }
   // otherwise need to return the hard emission
   // construct the kinematics for the hard emission
   ShoKinPtr showerKin = new_ptr(Decay_QTildeShowerKinematics1to2(
                                 branch->scale(),
 				branch->children()[0]->z(),
 				branch->phi(),
 				branch->children()[0]->pT(),
 				branch->sudakov()));
    IdList idlist(3);
    idlist[0] = particle->dataPtr();
    idlist[1] = branch->children()[0]->branchingParticle()->dataPtr();
    idlist[2] = branch->children()[1]->branchingParticle()->dataPtr();
    // create the branching
    fb = Branching( showerKin, idlist, branch->sudakov(),ShowerPartnerType::QCDColourLine  );
    fb.hard=true;
    fb.iout=0;
    // return it
   return fb;
 }
 
 void QTildeShowerHandler::checkFlags() {
   string error = "Inconsistent hard emission set-up in QTildeShowerHandler::showerHardProcess(). "; 
   if ( ( currentTree()->isMCatNLOSEvent() || currentTree()->isMCatNLOHEvent() ) ) {
     if (_hardEmission ==2 )
       throw Exception() << error
 			<< "Cannot generate POWHEG matching with MC@NLO shower "
 			<< "approximation.  Add 'set QTildeShowerHandler:HardEmission 0' to input file."
 			<< Exception::runerror;
     if ( canHandleMatchboxTrunc() )
       throw Exception() << error
 			<< "Cannot use truncated qtilde shower with MC@NLO shower "
 			<< "approximation.  Set LHCGenerator:EventHandler"
 			<< ":CascadeHandler to '/Herwig/Shower/ShowerHandler' or "
 			<< "'/Herwig/Shower/Dipole/DipoleShowerHandler'."
 			<< Exception::runerror;
   }
   else if ( ((currentTree()->isPowhegSEvent() || currentTree()->isPowhegHEvent()) ) &&
 	    _hardEmission != 2){
     if ( canHandleMatchboxTrunc())
       throw Exception() << error
 			<< "Unmatched events requested for POWHEG shower "
 			<< "approximation.  Set QTildeShowerHandler:HardEmission to "
 			<< "'POWHEG'."
 			<< Exception::runerror;
     else if (_hardEmissionWarn) {
       _hardEmissionWarn = false;
       _hardEmission=2;
       throw Exception() << error
 			<< "Unmatched events requested for POWHEG shower "
 			<< "approximation. Changing QTildeShowerHandler:HardEmission from "
 			<< _hardEmission << " to 2"
 			<< Exception::warning;
     }
   }
 
   if ( currentTree()->isPowhegSEvent() || currentTree()->isPowhegHEvent()) {
     if (currentTree()->showerApproximation()->needsTruncatedShower() &&
 	!canHandleMatchboxTrunc() )
       throw Exception() << error
 			<< "Current shower handler cannot generate truncated shower.  "
 			<< "Set Generator:EventHandler:CascadeHandler to "
 			<< "'/Herwig/Shower/PowhegShowerHandler'."
 			<< Exception::runerror;
   }
   else if ( currentTree()->truncatedShower() && _missingTruncWarn) {
     _missingTruncWarn=false;
     throw Exception() << "Warning: POWHEG shower approximation used without "
 		      << "truncated shower.  Set Generator:EventHandler:"
 		      << "CascadeHandler to '/Herwig/Shower/PowhegShowerHandler' and "
 		      << "'MEMatching:TruncatedShower Yes'."
 		      << Exception::warning;   
   }
   // else if ( !dipme && _hardEmissionMode > 1 && 
   // 	    firstInteraction())
   //   throw Exception() << error
   // 		      << "POWHEG matching requested for LO events.  Include "
   // 		      << "'set Factory:ShowerApproximation MEMatching' in input file."
   // 		      << Exception::runerror;
 }
 
 
 tPPair QTildeShowerHandler::remakeRemnant(tPPair oldp){
   // get the parton extractor
   PartonExtractor & pex = *lastExtractor();
   // get the new partons
   tPPair newp = make_pair(findFirstParton(oldp.first ), 
 			  findFirstParton(oldp.second));
   // if the same do nothing
   if(newp == oldp) return oldp;
   // Creates the new remnants and returns the new PartonBinInstances
   // ATTENTION Broken here for very strange configuration
   PBIPair newbins = pex.newRemnants(oldp, newp, newStep());
   newStep()->addIntermediate(newp.first);
   newStep()->addIntermediate(newp.second);
   // return the new partons
   return newp;
 }
 
 PPtr QTildeShowerHandler::findFirstParton(tPPtr seed) const{
   if(seed->parents().empty()) return seed;
   tPPtr parent = seed->parents()[0];
   //if no parent there this is a loose end which will 
   //be connected to the remnant soon.
   if(!parent || parent == incomingBeams().first || 
      parent == incomingBeams().second ) return seed;
   else return findFirstParton(parent);
 }
 
 void QTildeShowerHandler::decay(ShowerTreePtr tree, ShowerDecayMap & decay) {
   // must be one incoming particle
   assert(tree->incomingLines().size()==1);
   // apply any transforms
   tree->applyTransforms();
   // if already decayed return
   if(!tree->outgoingLines().empty()) return;
   // now we need to replace the particle with a new copy after the shower
   // find particle after the shower
   map<tShowerTreePtr,pair<tShowerProgenitorPtr,tShowerParticlePtr> >::const_iterator
     tit = tree->parent()->treelinks().find(tree);
   assert(tit!=tree->parent()->treelinks().end());
   ShowerParticlePtr newparent=tit->second.second;
   PerturbativeProcessPtr newProcess =  new_ptr(PerturbativeProcess());
   newProcess->incoming().push_back(make_pair(newparent,PerturbativeProcessPtr()));
   DecayProcessMap decayMap;
   ShowerHandler::decay(newProcess,decayMap);
   ShowerTree::constructTrees(tree,decay,newProcess,decayMap);
 }
 
 namespace {
 
   ShowerProgenitorPtr
   findFinalStateLine(ShowerTreePtr tree, long id, Lorentz5Momentum momentum) { 
     map<ShowerProgenitorPtr,tShowerParticlePtr>::iterator partner;
     Energy2 dmin(1e30*GeV2);
     for(map<ShowerProgenitorPtr,tShowerParticlePtr>::iterator 
 	  cit =tree->outgoingLines().begin(); cit!=tree->outgoingLines().end(); ++cit) {
       if(cit->second->id()!=id) continue;
       Energy2 test = 
 	sqr(cit->second->momentum().x()-momentum.x())+
 	sqr(cit->second->momentum().y()-momentum.y())+
 	sqr(cit->second->momentum().z()-momentum.z())+
 	sqr(cit->second->momentum().t()-momentum.t());
       if(test<dmin) {
 	dmin    = test;
 	partner = cit;
       }
     }
     return partner->first;
   }
 
   ShowerProgenitorPtr 
   findInitialStateLine(ShowerTreePtr tree, long id, Lorentz5Momentum momentum) { 
     map<ShowerProgenitorPtr,ShowerParticlePtr>::iterator partner;
     Energy2 dmin(1e30*GeV2);
     for(map<ShowerProgenitorPtr,ShowerParticlePtr>::iterator 
 	  cit =tree->incomingLines().begin(); cit!=tree->incomingLines().end(); ++cit) {
       if(cit->second->id()!=id) continue;
       Energy2 test = 
 	sqr(cit->second->momentum().x()-momentum.x())+
 	sqr(cit->second->momentum().y()-momentum.y())+
 	sqr(cit->second->momentum().z()-momentum.z())+
 	sqr(cit->second->momentum().t()-momentum.t());
       if(test<dmin) {
 	dmin    = test;
 	partner = cit;
       }
     }
     return partner->first;
   }
 
   void fixSpectatorColours(PPtr newSpect,ShowerProgenitorPtr oldSpect,
 			   ColinePair & cline,ColinePair & aline, bool reconnect) {
     cline.first  = oldSpect->progenitor()->colourLine();
     cline.second = newSpect->colourLine();
     aline.first  = oldSpect->progenitor()->antiColourLine();
     aline.second = newSpect->antiColourLine();
     if(!reconnect) return;
     if(cline.first) {
       cline.first ->removeColoured(oldSpect->copy());
       cline.first ->removeColoured(oldSpect->progenitor());
       cline.second->removeColoured(newSpect);
       cline.first ->addColoured(newSpect);
     }
     if(aline.first) {
       aline.first ->removeAntiColoured(oldSpect->copy());
       aline.first ->removeAntiColoured(oldSpect->progenitor());
       aline.second->removeAntiColoured(newSpect);
       aline.first ->addAntiColoured(newSpect);
     }
   }
 
   void fixInitialStateEmitter(ShowerTreePtr tree, PPtr newEmit,PPtr emitted, ShowerProgenitorPtr emitter,
 			      ColinePair cline,ColinePair aline,double x) {
     // sort out the colours
     if(emitted->dataPtr()->iColour()==PDT::Colour8) {
       // emitter
       if(cline.first && cline.first == emitter->progenitor()->antiColourLine() &&
 	 cline.second !=newEmit->antiColourLine()) {
 	// sort out not radiating line
 	ColinePtr col = emitter->progenitor()->colourLine();
 	if(col) {
 	  col->removeColoured(emitter->copy());
 	  col->removeColoured(emitter->progenitor());
 	  newEmit->colourLine()->removeColoured(newEmit);
 	  col->addColoured(newEmit);
 	}
       }
       else if(aline.first && aline.first == emitter->progenitor()->colourLine() &&
 	      aline.second !=newEmit->colourLine()) {
 	// sort out not radiating line
 	ColinePtr anti = emitter->progenitor()->antiColourLine();
 	if(anti) {
 	  anti->removeAntiColoured(emitter->copy());
 	  anti->removeAntiColoured(emitter->progenitor());
 	  newEmit->colourLine()->removeAntiColoured(newEmit);
 	  anti->addAntiColoured(newEmit);
 	}
       }
       else
 	assert(false);
       // emitted
       if(cline.first && cline.second==emitted->colourLine()) {
 	cline.second->removeColoured(emitted);
 	cline.first->addColoured(emitted);
       }
       else if(aline.first && aline.second==emitted->antiColourLine()) {
 	aline.second->removeAntiColoured(emitted);
 	aline.first->addAntiColoured(emitted);
       }
       else
 	assert(false);
     }
     else {
       if(emitter->progenitor()->antiColourLine() ) {
 	ColinePtr col = emitter->progenitor()->antiColourLine();
 	col->removeAntiColoured(emitter->copy());
 	col->removeAntiColoured(emitter->progenitor());
  	if(newEmit->antiColourLine()) {
 	  newEmit->antiColourLine()->removeAntiColoured(newEmit);
 	  col->addAntiColoured(newEmit);
 	}
 	else if (emitted->colourLine()) {
 	  emitted->colourLine()->removeColoured(emitted);
 	  col->addColoured(emitted);
 	}
 	else
 	  assert(false);
       }
       if(emitter->progenitor()->colourLine() ) {
 	ColinePtr col = emitter->progenitor()->colourLine();
 	col->removeColoured(emitter->copy());
 	col->removeColoured(emitter->progenitor());
  	if(newEmit->colourLine()) {
 	  newEmit->colourLine()->removeColoured(newEmit);
 	  col->addColoured(newEmit);
 	}
 	else if (emitted->antiColourLine()) {
 	  emitted->antiColourLine()->removeAntiColoured(emitted);
 	  col->addAntiColoured(emitted);
 	}
 	else
 	  assert(false);
       }
     }
     // update the emitter
     emitter->copy(newEmit);
     ShowerParticlePtr sp = new_ptr(ShowerParticle(*newEmit,1,false));
     sp->x(x);
     emitter->progenitor(sp);
     tree->incomingLines()[emitter]=sp;
     emitter->perturbative(false);
     // add emitted
     sp=new_ptr(ShowerParticle(*emitted,1,true));
     ShowerProgenitorPtr gluon=new_ptr(ShowerProgenitor(emitter->original(),emitted,sp));
     gluon->perturbative(false);
     tree->outgoingLines().insert(make_pair(gluon,sp));
   }
 
   void fixFinalStateEmitter(ShowerTreePtr tree, PPtr newEmit,PPtr emitted, ShowerProgenitorPtr emitter,
 			    ColinePair cline,ColinePair aline) {
     map<tShowerTreePtr,pair<tShowerProgenitorPtr,tShowerParticlePtr> >::const_iterator tit;
     // special case if decayed
     for(tit  = tree->treelinks().begin(); tit != tree->treelinks().end();++tit) {
       if(tit->second.first && tit->second.second==emitter->progenitor())
 	break;
     }
     // sort out the colour lines
     if(cline.first && cline.first == emitter->progenitor()->antiColourLine() &&
        cline.second !=newEmit->antiColourLine()) {
       // sort out not radiating line
       ColinePtr col = emitter->progenitor()->colourLine();
       if(col) {
 	col->removeColoured(emitter->copy());
 	col->removeColoured(emitter->progenitor());
 	newEmit->colourLine()->removeColoured(newEmit);
 	col->addColoured(newEmit);
       }
     }
     else if(aline.first && aline.first == emitter->progenitor()->colourLine() &&
 	    aline.second !=newEmit->colourLine()) {
       // sort out not radiating line
       ColinePtr anti = emitter->progenitor()->antiColourLine();
       if(anti) {
 	anti->removeAntiColoured(emitter->copy());
 	anti->removeAntiColoured(emitter->progenitor());
 	newEmit->colourLine()->removeAntiColoured(newEmit);
 	anti->addAntiColoured(newEmit);
       }
     }
     else
       assert(false);
     // update the emitter
     emitter->copy(newEmit);
     ShowerParticlePtr sp = new_ptr(ShowerParticle(*newEmit,1,true));
     emitter->progenitor(sp);
     tree->outgoingLines()[emitter]=sp;
     emitter->perturbative(false);
     // update for decaying particles
     if(tit!=tree->treelinks().end())
       tree->updateLink(tit->first,make_pair(emitter,sp));
     // add the emitted particle
     // sort out the colour
     if(cline.first && cline.second==emitted->antiColourLine()) {
       cline.second->removeAntiColoured(emitted);
       cline.first->addAntiColoured(emitted);
     }
     else if(aline.first && aline.second==emitted->colourLine()) {
       aline.second->removeColoured(emitted);
       aline.first->addColoured(emitted);
     }
     else
       assert(false);
     sp=new_ptr(ShowerParticle(*emitted,1,true));
     ShowerProgenitorPtr gluon=new_ptr(ShowerProgenitor(emitter->original(),
 						       emitted,sp));
     gluon->perturbative(false);
     tree->outgoingLines().insert(make_pair(gluon,sp));
   }
   
 }
 
 void QTildeShowerHandler::setupMECorrection(RealEmissionProcessPtr real) {
   assert(real);
   // II emission
   if(real->emitter()   < real->incoming().size() &&
      real->spectator() < real->incoming().size()) {
     // recoiling system
     for( map<ShowerProgenitorPtr,tShowerParticlePtr>::const_iterator 
 	   cjt= currentTree()->outgoingLines().begin();
 	 cjt != currentTree()->outgoingLines().end();++cjt ) {
       cjt->first->progenitor()->transform(real->transformation());
       cjt->first->copy()->transform(real->transformation());
     }
     // the the radiating system
     ShowerProgenitorPtr emitter,spectator;
     unsigned int iemit  = real->emitter();
     unsigned int ispect = real->spectator();
     int ig = int(real->emitted())-int(real->incoming().size());
     emitter = findInitialStateLine(currentTree(),
 				   real->bornIncoming()[iemit]->id(),
 				   real->bornIncoming()[iemit]->momentum());
     spectator = findInitialStateLine(currentTree(),
 				     real->bornIncoming()[ispect]->id(),
 				     real->bornIncoming()[ispect]->momentum());
     // sort out the colours
     ColinePair cline,aline;
     fixSpectatorColours(real->incoming()[ispect],spectator,cline,aline,true);
     // update the spectator
     spectator->copy(real->incoming()[ispect]);
     ShowerParticlePtr sp(new_ptr(ShowerParticle(*real->incoming()[ispect],1,false)));
     sp->x(ispect ==0 ? real->x().first :real->x().second);
     spectator->progenitor(sp);
     currentTree()->incomingLines()[spectator]=sp;
     spectator->perturbative(true);
     // now for the emitter
     fixInitialStateEmitter(currentTree(),real->incoming()[iemit],real->outgoing()[ig],
 			   emitter,cline,aline,iemit ==0 ? real->x().first :real->x().second);
   }
   // FF emission
   else if(real->emitter()   >= real->incoming().size() &&
 	  real->spectator() >= real->incoming().size()) {
     assert(real->outgoing()[real->emitted()-real->incoming().size()]->id()==ParticleID::g);
     // find the emitter and spectator in the shower tree
     ShowerProgenitorPtr emitter,spectator;
     int iemit = int(real->emitter())-int(real->incoming().size());
     emitter = findFinalStateLine(currentTree(),
 				 real->bornOutgoing()[iemit]->id(),
 				 real->bornOutgoing()[iemit]->momentum());
     int ispect = int(real->spectator())-int(real->incoming().size());
     spectator = findFinalStateLine(currentTree(),
 				   real->bornOutgoing()[ispect]->id(),
 				   real->bornOutgoing()[ispect]->momentum());
     map<tShowerTreePtr,pair<tShowerProgenitorPtr,tShowerParticlePtr> >::const_iterator tit;
     // first the spectator
     // special case if decayed
     for(tit  = currentTree()->treelinks().begin(); tit != currentTree()->treelinks().end();++tit) {
       if(tit->second.first && tit->second.second==spectator->progenitor())
     	break;
     }
     // sort out the colours
     ColinePair cline,aline;
     fixSpectatorColours(real->outgoing()[ispect],spectator,cline,aline,true);
     // update the spectator
     spectator->copy(real->outgoing()[ispect]);
     ShowerParticlePtr sp(new_ptr(ShowerParticle(*real->outgoing()[ispect],1,true)));
     spectator->progenitor(sp);
     currentTree()->outgoingLines()[spectator]=sp;
     spectator->perturbative(true);
     // update for decaying particles
     if(tit!=currentTree()->treelinks().end())
       currentTree()->updateLink(tit->first,make_pair(spectator,sp));
     // now the emitting particle
     int ig = int(real->emitted())-int(real->incoming().size());
     fixFinalStateEmitter(currentTree(),real->outgoing()[iemit],
 			 real->outgoing()[ig],
 			 emitter,cline,aline);
   }
   // IF emission
   else {
     // scattering process
     if(real->incoming().size()==2) {
       ShowerProgenitorPtr emitter,spectator;
       unsigned int iemit  = real->emitter();
       unsigned int ispect = real->spectator();
       int ig = int(real->emitted())-int(real->incoming().size());
       ColinePair cline,aline;
       // incoming spectator
       if(ispect<2) {
 	spectator = findInitialStateLine(currentTree(),
 					 real->bornIncoming()[ispect]->id(),
 					 real->bornIncoming()[ispect]->momentum());
 	fixSpectatorColours(real->incoming()[ispect],spectator,cline,aline,true);
 	// update the spectator
 	spectator->copy(real->incoming()[ispect]);
 	ShowerParticlePtr sp(new_ptr(ShowerParticle(*real->incoming()[ispect],1,false)));
 	sp->x(ispect ==0 ? real->x().first :real->x().second);
 	spectator->progenitor(sp);
 	currentTree()->incomingLines()[spectator]=sp;
 	spectator->perturbative(true);
       }
       // outgoing spectator
       else {
 	spectator = findFinalStateLine(currentTree(),
 				       real->bornOutgoing()[ispect-real->incoming().size()]->id(),
 				       real->bornOutgoing()[ispect-real->incoming().size()]->momentum());
 	// special case if decayed
 	map<tShowerTreePtr,pair<tShowerProgenitorPtr,tShowerParticlePtr> >::const_iterator tit;
 	for(tit  = currentTree()->treelinks().begin(); tit != currentTree()->treelinks().end();++tit) {
 	  if(tit->second.first && tit->second.second==spectator->progenitor())
 	    break;
 	}
 	fixSpectatorColours(real->outgoing()[ispect-real->incoming().size()],spectator,cline,aline,true);
 	// update the spectator
 	spectator->copy(real->outgoing()[ispect-real->incoming().size()]);
 	ShowerParticlePtr sp(new_ptr(ShowerParticle(*real->outgoing()[ispect-real->incoming().size()],1,true)));
 	spectator->progenitor(sp);
 	currentTree()->outgoingLines()[spectator]=sp;
 	spectator->perturbative(true);
 	// update for decaying particles
 	if(tit!=currentTree()->treelinks().end())
 	  currentTree()->updateLink(tit->first,make_pair(spectator,sp));
       }
       // incoming emitter
       if(iemit<2) {
 	emitter = findInitialStateLine(currentTree(),
 				       real->bornIncoming()[iemit]->id(),
 				       real->bornIncoming()[iemit]->momentum());
 	fixInitialStateEmitter(currentTree(),real->incoming()[iemit],real->outgoing()[ig],
 			       emitter,aline,cline,iemit ==0 ? real->x().first :real->x().second);
       }
       // outgoing emitter
       else {
 	emitter = findFinalStateLine(currentTree(),
 				     real->bornOutgoing()[iemit-real->incoming().size()]->id(),
 				     real->bornOutgoing()[iemit-real->incoming().size()]->momentum());
 	fixFinalStateEmitter(currentTree(),real->outgoing()[iemit-real->incoming().size()],
 			     real->outgoing()[ig],emitter,aline,cline);
       }
     }
     // decay process
     else {
       assert(real->spectator()==0);
       unsigned int iemit  = real->emitter()-real->incoming().size();
       int ig = int(real->emitted())-int(real->incoming().size());
       ColinePair cline,aline;
       // incoming spectator
       ShowerProgenitorPtr spectator = findInitialStateLine(currentTree(),
 							   real->bornIncoming()[0]->id(),
 							   real->bornIncoming()[0]->momentum());
       fixSpectatorColours(real->incoming()[0],spectator,cline,aline,false);
       // find the emitter
       ShowerProgenitorPtr emitter = 
 	findFinalStateLine(currentTree(),
 			   real->bornOutgoing()[iemit]->id(),
 			   real->bornOutgoing()[iemit]->momentum());
       // recoiling system
       for( map<ShowerProgenitorPtr,tShowerParticlePtr>::const_iterator 
 	     cjt= currentTree()->outgoingLines().begin();
 	   cjt != currentTree()->outgoingLines().end();++cjt ) {
 	if(cjt->first==emitter) continue;
 	cjt->first->progenitor()->transform(real->transformation());
 	cjt->first->copy()->transform(real->transformation());
       }
       // sort out the emitter
       fixFinalStateEmitter(currentTree(),real->outgoing()[iemit],
 			   real->outgoing()[ig],emitter,aline,cline);
     }
   }
   // clean up the shower tree
   _currenttree->resetShowerProducts();
 }
diff --git a/Shower/QTilde/QTildeShowerHandler.h b/Shower/QTilde/QTildeShowerHandler.h
--- a/Shower/QTilde/QTildeShowerHandler.h
+++ b/Shower/QTilde/QTildeShowerHandler.h
@@ -1,846 +1,846 @@
 // -*- C++ -*-
 #ifndef Herwig_QTildeShowerHandler_H
 #define Herwig_QTildeShowerHandler_H
 //
 // This is the declaration of the QTildeShowerHandler class.
 //
 
 #include "QTildeShowerHandler.fh"
 #include "Herwig/Shower/ShowerHandler.h"
 #include "Herwig/Shower/QTilde/SplittingFunctions/SplittingGenerator.h"
 #include "Herwig/Shower/QTilde/Base/ShowerTree.h"
 #include "Herwig/Shower/QTilde/Base/ShowerProgenitor.fh"
 #include "Herwig/Shower/QTilde/Base/HardTree.h"
 #include "Herwig/Shower/QTilde/Base/Branching.h"
 #include "Herwig/Shower/QTilde/Base/ShowerVeto.h"
 #include "Herwig/Shower/QTilde/Base/FullShowerVeto.h"
 #include "Herwig/Shower/QTilde/Kinematics/KinematicsReconstructor.fh"
 #include "Herwig/Shower/QTilde/Base/PartnerFinder.fh"
 #include "Herwig/Shower/QTilde/SplittingFunctions/SudakovFormFactor.fh"
 #include "Herwig/MatrixElement/HwMEBase.h"
 #include "Herwig/Decay/HwDecayerBase.h"
 #include "Herwig/MatrixElement/Matchbox/Matching/ShowerApproximation.h"
 #include "Herwig/Shower/RealEmissionProcess.h"
 #include "Herwig/Utilities/Statistic.h"
 
 namespace Herwig {
 
 using namespace ThePEG;
 
 /**
  * The QTildeShowerHandler class.
  *
  * @see \ref QTildeShowerHandlerInterfaces "The interfaces"
  * defined for QTildeShowerHandler.
  */
 class QTildeShowerHandler: public ShowerHandler {
 
 public:
   
   /**
    *  Pointer to an XComb object
    */
   typedef Ptr<XComb>::pointer XCPtr;
 
 public:
 
   /** @name Standard constructors and destructors. */
   //@{
   /**
    * The default constructor.
    */
   QTildeShowerHandler();
 
   /**
    * The destructor.
    */
   virtual ~QTildeShowerHandler();
   //@}
 
 public:
 
   /**
    * At the end of the Showering, transform ShowerParticle objects
    * into ThePEG particles and fill the event record with them.
    * Notice that the parent/child relationships and the 
    * transformation from ShowerColourLine objects into ThePEG
    * ColourLine ones must be properly handled.
    */
   void fillEventRecord();
   
   /**
    * Return the relevant hard scale to be used in the profile scales
    */
   virtual Energy hardScale() const {
     return muPt;
   }
 
   /**
    * Hook to allow vetoing of event after showering hard sub-process
    * as in e.g. MLM merging.
    */
   virtual bool showerHardProcessVeto() const { return false; }
   
   /**
    *  Generate hard emissions for CKKW etc
    */
   virtual HardTreePtr generateCKKW(ShowerTreePtr tree) const;
 
   /**
    *  Members to perform the shower
    */
   //@{
   /**
    * Perform the shower of the hard process
    */
   virtual void showerHardProcess(ShowerTreePtr,XCPtr);
 
   /**
    * Perform the shower of a decay
    */
   virtual void showerDecay(ShowerTreePtr);
   //@}
 
   /**
    *  Access to the flags and shower variables
    */
   //@{
 
   /**
    *  Get the SplittingGenerator
    */
   tSplittingGeneratorPtr splittingGenerator() const { return _splittingGenerator; }
 
   /**
    * Mode for hard emissions
    */
   int hardEmission() const {return _hardEmission;}
   //@}
 
   /**
    *  Connect the Hard and Shower trees
    */
   virtual void connectTrees(ShowerTreePtr showerTree, HardTreePtr hardTree, bool hard );
 
   /**
    *   Access to switches for spin correlations
    */
   //@{
   /**
    *  Soft correlations
    */
   unsigned int softCorrelations() const {
     return _softOpt;
   }
 
   /**
    *  Any correlations
    */
   virtual bool correlations() const {
     return spinCorrelations()!=0||_softOpt!=0;
   }
   //@}
 
 public:
   /**
    *  Access methods to access the objects
    */
   //@{
   /**
    *  Access to the KinematicsReconstructor object
    */
   tKinematicsReconstructorPtr kinematicsReconstructor() const { return _reconstructor; }
 
   /**
    *  Access to the PartnerFinder object
    */
   tPartnerFinderPtr partnerFinder() const { return _partnerfinder; }
 
   //@}
 
 protected:
 
   /**
    *   Perform the shower
    */
   void doShowering(bool hard,XCPtr);
 
   /**
    *  Generate the hard matrix element correction
    */
   virtual RealEmissionProcessPtr hardMatrixElementCorrection(bool);
 
   /**
    *  Generate the hardest emission
    */
   virtual void hardestEmission(bool hard);
 
   /**
    *  Set up for applying a matrix element correction
    */
   void setupMECorrection(RealEmissionProcessPtr real);
 
   /**
    * Extract the particles to be showered, set the evolution scales
    * and apply the hard matrix element correction
    * @param hard Whether this is a hard process or decay
    * @return The particles to be showered
    */
   virtual vector<ShowerProgenitorPtr> setupShower(bool hard);
 
   /**
    *  set the colour partners
    */
   virtual void setEvolutionPartners(bool hard,ShowerInteraction,
 				    bool clear);
 
   /**
    *  Methods to perform the evolution of an individual particle, including
    *  recursive calling on the products
    */
   //@{
   /**
    * It does the forward evolution of the time-like input particle
    * (and recursively for all its radiation products).
    * accepting only emissions which conforms to the showerVariables
    * and soft matrix element correction.
    * If at least one emission has occurred then the method returns true.
    * @param particle The particle to be showered
    */
   virtual bool timeLikeShower(tShowerParticlePtr particle, ShowerInteraction,
 			      Branching fb, bool first);
 
   /**
    * It does the backward evolution of the space-like input particle 
    * (and recursively for all its time-like radiation products).
    * accepting only emissions which conforms to the showerVariables.
    * If at least one emission has occurred then the method returns true
    * @param particle The particle to be showered
    * @param beam The beam particle
    */
   virtual bool spaceLikeShower(tShowerParticlePtr particle,PPtr beam,
 			       ShowerInteraction); 
 
   /**
    * If does the forward evolution of the input on-shell particle
    * involved in a decay 
    * (and recursively for all its time-like radiation products).
    * accepting only emissions which conforms to the showerVariables.
    * @param particle    The particle to be showered
    * @param maxscale    The maximum scale for the shower.
    * @param minimumMass The minimum mass of the final-state system
    */
   virtual bool 
   spaceLikeDecayShower(tShowerParticlePtr particle,
 		       const ShowerParticle::EvolutionScales & maxScales,
 		       Energy minimumMass,ShowerInteraction,
 		       Branching fb);
 
   /**
    * Truncated shower from a time-like particle
    */
   virtual bool truncatedTimeLikeShower(tShowerParticlePtr particle,
 				       HardBranchingPtr branch,
 				       ShowerInteraction type,
 				       Branching fb, bool first);
  
   /**
    * Truncated shower from a space-like particle
    */
   virtual bool truncatedSpaceLikeShower(tShowerParticlePtr particle,PPtr beam,
 					HardBranchingPtr branch,
 					ShowerInteraction type);
 
   /**
    * Truncated shower from a time-like particle
    */
   virtual bool truncatedSpaceLikeDecayShower(tShowerParticlePtr particle,
 					     const ShowerParticle::EvolutionScales & maxScales,
 					     Energy minimumMass, HardBranchingPtr branch,
 					     ShowerInteraction type, Branching fb);
   //@}
 
   /**
    *  Switches for matrix element corrections
    */
   //@{
   /**
    * Any ME correction?   
    */
   bool MECOn() const { 
     return _hardEmission == 1;
   }
 
   /**
    * Any hard ME correction? 
    */
   bool hardMEC() const {
     return _hardEmission == 1 && (_meCorrMode == 1 || _meCorrMode == 2);
   }
 
   /**
    * Any soft ME correction? 
    */
   bool softMEC() const {
     return _hardEmission == 1 && (_meCorrMode == 1 || _meCorrMode > 2);
   }
   //@}
 
   /**
    * Is the truncated shower on?
    */
   bool isTruncatedShowerON() const {return _trunc_Mode;}
 
   /**
    *  Switch for intrinsic pT
    */
   //@{
   /**
    * Any intrinsic pT?
    */
   bool ipTon() const {
     return _iptrms != ZERO || ( _beta == 1.0 && _gamma != ZERO && _iptmax !=ZERO );
   }
    //@}  
 
   /**@name Additional shower vetoes */
   //@{
   /**
    * Insert a veto.
    */
   void addVeto (ShowerVetoPtr v) { _vetoes.push_back(v); }
 
   /**
    * Remove a veto.
    */
   void removeVeto (ShowerVetoPtr v) { 
     vector<ShowerVetoPtr>::iterator vit = find(_vetoes.begin(),_vetoes.end(),v);
     if (vit != _vetoes.end())
       _vetoes.erase(vit);
   }
 
   //@}
 
   /**
    *  Switches for vetoing hard emissions
    */
   //@{
   /**
    * Returns true if the hard veto read-in is to be applied to only
    * the primary collision and false otherwise.
    */
   bool hardVetoReadOption() const {return _hardVetoReadOption;}
   //@}
 
   /**
    *  Enhancement factors for radiation needed to generate the soft matrix
    *  element correction.
    */
   //@{
   /**
    *  Access the enhancement factor for initial-state radiation
    */
   double initialStateRadiationEnhancementFactor() const { return _initialenhance; }
 
   /**
    *  Access the enhancement factor for final-state radiation
    */
   double finalStateRadiationEnhancementFactor() const { return _finalenhance; }
 
   /**
    *  Set the enhancement factor for initial-state radiation
    */
   void initialStateRadiationEnhancementFactor(double in) { _initialenhance=in; }
 
   /**
    *  Set the enhancement factor for final-state radiation
    */
   void finalStateRadiationEnhancementFactor(double in) { _finalenhance=in; }
   //@}
 
   /**
    *  Access to set/get the HardTree currently beinging showered
    */
   //@{
   /**
    *  The HardTree currently being showered
    */
   tHardTreePtr hardTree() {return _hardtree;}
 
   /**
    *  The HardTree currently being showered
    */
   void hardTree(tHardTreePtr in) {_hardtree = in;}
   //@}
 
   /**
    * Access/set the beam particle for the current initial-state shower
    */
   //@{
   /**
    *  Get the beam particle data
    */
   Ptr<BeamParticleData>::const_pointer beamParticle() const { return _beam; }
 
   /**
    *  Set the beam particle data
    */
   void setBeamParticle(Ptr<BeamParticleData>::const_pointer in) { _beam=in; }
   //@}
 
   /**
    * Set/Get the current tree being evolver for inheriting classes
    */
   //@{
   /**
    * Get the tree
    */
   tShowerTreePtr currentTree() { return _currenttree; }
 
   /**
    * Set the tree
    */
   void currentTree(tShowerTreePtr tree) { _currenttree=tree; }
 
   //@}
 
   /**
    *  Access the maximum number of attempts to generate the shower
    */
   unsigned int maximumTries() const { return _maxtry; }
 
   /**
    * Set/Get the ShowerProgenitor for the current shower
    */
   //@{
   /**
    *  Access the progenitor
    */
   ShowerProgenitorPtr progenitor() { return _progenitor; }
 
   /**
    *  Set the progenitor
    */
   void progenitor(ShowerProgenitorPtr in) { _progenitor=in; }
   //@}
 
   /**
    *  Calculate the intrinsic \f$p_T\f$.
    */
   virtual void generateIntrinsicpT(vector<ShowerProgenitorPtr>);
 
   /**
    *  Access to the intrinsic \f$p_T\f$ for inheriting classes
    */
   map<tShowerProgenitorPtr,pair<Energy,double> > & intrinsicpT() { return _intrinsic; }
 
   /**
    *  find the maximally allowed pt acc to the hard process. 
    */
   void setupMaximumScales(const vector<ShowerProgenitorPtr> &,XCPtr);
 
   /**
    *  find the relevant hard scales for profile scales. 
    */
   void setupHardScales(const vector<ShowerProgenitorPtr> &,XCPtr);
 
   /**
    *  Convert the HardTree into an extra shower emission 
    */
   void convertHardTree(bool hard,ShowerInteraction type);
 
 protected:
 
   /**
    * Find the parton extracted from the incoming particle after ISR
    */
   PPtr findFirstParton(tPPtr seed) const;
 
   /**
    * Fix Remnant connections after ISR
    */
   tPPair remakeRemnant(tPPair oldp); 
 
 protected:
 
   /**
    *  Start the shower of a timelike particle
    */
   virtual bool startTimeLikeShower(ShowerInteraction);
 
   /**
    *  Update of the time-like stuff
    */
   void updateHistory(tShowerParticlePtr particle);
 
   /**
    *  Start the shower of a spacelike particle
    */
   virtual bool startSpaceLikeShower(PPtr,ShowerInteraction);
 
   /**
    *  Start the shower of a spacelike particle
    */
   virtual bool 
   startSpaceLikeDecayShower(const ShowerParticle::EvolutionScales & maxScales,
 			    Energy minimumMass,ShowerInteraction);
 
   /**
    * Select the branching for the next time-like emission
    */
   Branching selectTimeLikeBranching(tShowerParticlePtr particle,
 				    ShowerInteraction type,
 				    HardBranchingPtr branch);
 
   /**
    * Select the branching for the next space-like emission in a decay
    */
   Branching selectSpaceLikeDecayBranching(tShowerParticlePtr particle,
 					  const ShowerParticle::EvolutionScales & maxScales,
 					  Energy minmass,ShowerInteraction type,
 					  HardBranchingPtr branch);
   /**
    *  Create the timelike child of a branching
    */
   ShowerParticleVector createTimeLikeChildren(tShowerParticlePtr particle,
 					      IdList ids);
 
   /**
    *  Vetos for the timelike shower
    */
   virtual bool timeLikeVetoed(const Branching &,ShowerParticlePtr);
 
   /**
    *  Vetos for the spacelike shower
    */
   virtual bool spaceLikeVetoed(const Branching &,ShowerParticlePtr);
 
   /**
    *  Vetos for the spacelike shower
    */
   virtual bool spaceLikeDecayVetoed(const Branching &,ShowerParticlePtr);
 
   /**
    *  Only generate the hard emission, for testing only.
    */
   bool hardOnly() const {return _limitEmissions==3;}
 
   /**
    *  Check the flags
    */
   void checkFlags();
 
   /**
    *
    */
   void addFSRUsingDecayPOWHEG(HardTreePtr ISRTree);
 
 public:
 
   /** @name Functions used by the persistent I/O system. */
   //@{
   /**
    * Function used to write out object persistently.
    * @param os the persistent output stream written to.
    */
   void persistentOutput(PersistentOStream & os) const;
 
   /**
    * Function used to read in object persistently.
    * @param is the persistent input stream read from.
    * @param version the version number of the object when written.
    */
   void persistentInput(PersistentIStream & is, int version);
   //@}
 
   /**
    * The standard Init function used to initialize the interfaces.
    * Called exactly once for each class by the class description system
    * before the main function starts or
    * when this class is dynamically loaded.
    */
   static void Init();
 
 protected:
 
   /**
    * The main method which manages the showering of a subprocess.
    */
   virtual tPPair cascade(tSubProPtr sub, XCPtr xcomb);
 
   /**
    *  Decay a ShowerTree
    */
   void decay(ShowerTreePtr tree, ShowerDecayMap & decay);
 
 protected:
 
   /** @name Clone Methods. */
   //@{
   /**
    * Make a simple clone of this object.
    * @return a pointer to the new object.
    */
   virtual IBPtr clone() const;
 
   /** Make a clone of this object, possibly modifying the cloned object
    * to make it sane.
    * @return a pointer to the new object.
    */
   virtual IBPtr fullclone() const;
   //@}
 
 protected:
 
   /**
    * Initialize this object after the setup phase before saving an
    * EventGenerator to disk.
    * @throws InitException if object could not be initialized properly.
    */
   virtual void doinit();
 
   /**
    * Initialize this object. Called in the run phase just before
    * a run begins.
    */
   virtual void doinitrun();
   //@}
 
 private:
 
   /**
    * The assignment operator is private and must never be called.
    * In fact, it should not even be implemented.
    */
   QTildeShowerHandler & operator=(const QTildeShowerHandler &) = delete;
 
 private:
 
 
   /**
    *  Stuff from the ShowerHandler
    */
   //@{
 
   /**
    *  The ShowerTree for the hard process
    */
   ShowerTreePtr hard_;
 
   /**
    *  The ShowerTree for the decays
    */
   ShowerDecayMap decay_;
 
   /**
    *  The ShowerTrees for which the initial shower 
    */
   vector<ShowerTreePtr> done_;
   //@}
 
 private :
 
   /**
    * Pointer to the splitting generator
    */
   SplittingGeneratorPtr _splittingGenerator;
 
   /**
    *  Maximum number of tries to generate the shower of a particular tree
    */
   unsigned int _maxtry;
 
   /**
    * Matrix element correction switch
    */
   unsigned int _meCorrMode;
 
   /**
    *  Control of the reconstruction option
    */
-  unsigned int _reconOpt;
+  unsigned int _evolutionScheme;
 
   /**
    * If hard veto pT scale is being read-in this determines
    * whether the read-in value is applied to primary and 
    * secondary (MPI) scatters or just the primary one, with
    * the usual computation of the veto being performed for
    * the secondary (MPI) scatters.
    */
   bool _hardVetoReadOption; 
 
   /**
    * rms intrinsic pT of Gaussian distribution
    */
   Energy _iptrms;
 
    /**
    * Proportion of inverse quadratic intrinsic pT distribution
    */
   double _beta;
 
   /**
    * Parameter for inverse quadratic: 2*Beta*Gamma/(sqr(Gamma)+sqr(intrinsicpT))
    */
   Energy _gamma;
 
   /**
    * Upper bound on intrinsic pT for inverse quadratic
    */
   Energy _iptmax;
 
   /**
    *  Limit the number of emissions for testing
    */
   unsigned int _limitEmissions;
   
   /**
    *  The progenitor of the current shower
    */
   ShowerProgenitorPtr _progenitor;
 
   /**
    *  Matrix element
    */
   HwMEBasePtr _hardme;
 
   /**
    *  Decayer
    */
   HwDecayerBasePtr _decayme;
 
   /**
    * The ShowerTree currently being showered
    */
   ShowerTreePtr _currenttree;
 
   /**
    *  The HardTree currently being showered
    */
   HardTreePtr _hardtree;
 
   /**
    *  Radiation enhancement factors for use with the veto algorithm
    *  if needed by the soft matrix element correction 
    */
   //@{
   /**
    *  Enhancement factor for initial-state radiation
    */
   double _initialenhance;
 
   /**
    *  Enhancement factor for final-state radiation
    */
   double _finalenhance;
   //@}
 
   /**
    *  The beam particle data for the current initial-state shower
    */
   Ptr<BeamParticleData>::const_pointer _beam;
 
   /**
    *  Storage of the intrinsic \f$p_t\f$ of the particles
    */
   map<tShowerProgenitorPtr,pair<Energy,double> > _intrinsic;
 
   /**
    * Vetoes
    */
   vector<ShowerVetoPtr> _vetoes;
 
   /**
    *  Full Shower Vetoes
    */
   vector<FullShowerVetoPtr> _fullShowerVetoes;
 
   /**
    *  Number of iterations for reweighting
    */
   unsigned int _nReWeight;
 
   /**
    *  Whether or not we are reweighting
    */
   bool _reWeight;
 
   /**
    *  number of IS emissions
    */
   unsigned int _nis;
 
   /**
    *  Number of FS emissions
    */
   unsigned int _nfs;
 
   /**
    *  The option for wqhich interactions to use
    */
   ShowerInteraction interaction_;
 
   /**
    *  Truncated shower switch
    */
   bool _trunc_Mode;
   
   /**
    *  Count of the number of truncated emissions
    */
   unsigned int _truncEmissions;
 
   /**
    *  Mode for the hard emissions
    */
   int _hardEmission;
 
   /**
    *  Option for the kernal for soft correlations
    */
   unsigned int _softOpt;
 
   /**
    *  Option for hard radiation in POWHEG events
    */
   bool _hardPOWHEG;
 
   /**
    * True if no warnings about incorrect hard emission
    * mode setting have been issued yet
    */
   static bool _hardEmissionWarn;
 
   /**
    * True if no warnings about missing truncated shower 
    * have been issued yet
    */
   static bool _missingTruncWarn;
 
   /**
    * The relevant hard scale to be used in the profile scales
    */
   Energy muPt;
 
 private:
   /**
    *  Pointer to the various objects
    */
   //@{
   /**
    *  Pointer to the KinematicsReconstructor object
    */
   KinematicsReconstructorPtr _reconstructor;
 
   /**
    *  Pointer to the PartnerFinder object
    */
   PartnerFinderPtr _partnerfinder;
 
   //@}
 
 };
 
 }
 
 #endif /* HERWIG_QTildeShowerHandler_H */
diff --git a/Shower/QTilde/SplittingFunctions/SplittingFunction.cc b/Shower/QTilde/SplittingFunctions/SplittingFunction.cc
--- a/Shower/QTilde/SplittingFunctions/SplittingFunction.cc
+++ b/Shower/QTilde/SplittingFunctions/SplittingFunction.cc
@@ -1,1047 +1,1071 @@
 // -*- C++ -*-
 //
 // SplittingFunction.cc is a part of Herwig - A multi-purpose Monte Carlo event generator
 // Copyright (C) 2002-2017 The Herwig Collaboration
 //
 // Herwig is licenced under version 3 of the GPL, see COPYING for details.
 // Please respect the MCnet academic guidelines, see GUIDELINES for details.
 //
 //
 // This is the implementation of the non-inlined, non-templated member
 // functions of the SplittingFunction class.
 //
 
 #include "SplittingFunction.h"
 #include "ThePEG/Utilities/DescribeClass.h"
 #include "ThePEG/Persistency/PersistentOStream.h"
 #include "ThePEG/Persistency/PersistentIStream.h"
 #include "ThePEG/Interface/Switch.h"
 #include "ThePEG/Repository/UseRandom.h"
 #include "ThePEG/Utilities/EnumIO.h"
 #include "Herwig/Shower/QTilde/Base/ShowerParticle.h"
 #include "ThePEG/Utilities/DescribeClass.h"
 
 using namespace Herwig;
 
 DescribeAbstractClass<SplittingFunction,Interfaced>
 describeSplittingFunction ("Herwig::SplittingFunction","");
 
 void SplittingFunction::Init() {
 
   static ClassDocumentation<SplittingFunction> documentation
     ("The SplittingFunction class is the based class for 1->2 splitting functions"
      " in Herwig");
 
   static Switch<SplittingFunction,ColourStructure> interfaceColourStructure
     ("ColourStructure",
      "The colour structure for the splitting function",
      &SplittingFunction::_colourStructure, Undefined, false, false);
   static SwitchOption interfaceColourStructureTripletTripletOctet
     (interfaceColourStructure,
      "TripletTripletOctet",
      "3 -> 3 8",
      TripletTripletOctet);
   static SwitchOption interfaceColourStructureOctetOctetOctet
     (interfaceColourStructure,
      "OctetOctetOctet",
      "8 -> 8 8",
      OctetOctetOctet);
   static SwitchOption interfaceColourStructureOctetTripletTriplet
     (interfaceColourStructure,
      "OctetTripletTriplet",
      "8 -> 3 3bar",
      OctetTripletTriplet);
   static SwitchOption interfaceColourStructureTripletOctetTriplet
     (interfaceColourStructure,
      "TripletOctetTriplet",
      "3 -> 8 3",
      TripletOctetTriplet); 
   static SwitchOption interfaceColourStructureSextetSextetOctet
     (interfaceColourStructure,
      "SextetSextetOctet",
      "6 -> 6 8",
      SextetSextetOctet);
   
   static SwitchOption interfaceColourStructureChargedChargedNeutral
     (interfaceColourStructure,
      "ChargedChargedNeutral",
      "q -> q 0",
      ChargedChargedNeutral);
   static SwitchOption interfaceColourStructureNeutralChargedCharged
     (interfaceColourStructure,
      "NeutralChargedCharged",
      "0 -> q qbar",
      NeutralChargedCharged);
   static SwitchOption interfaceColourStructureChargedNeutralCharged
     (interfaceColourStructure,
      "ChargedNeutralCharged",
      "q -> 0 q",
      ChargedNeutralCharged);
   static SwitchOption interfaceColourStructureEW
     (interfaceColourStructure,
      "EW",
      "q -> q W/Z",
      EW);
 
   static Switch<SplittingFunction,ShowerInteraction> 
     interfaceInteractionType
     ("InteractionType",
      "Type of the interaction",
      &SplittingFunction::_interactionType, 
      ShowerInteraction::UNDEFINED, false, false);
   static SwitchOption interfaceInteractionTypeQCD
     (interfaceInteractionType,
      "QCD","QCD",ShowerInteraction::QCD);
   static SwitchOption interfaceInteractionTypeQED
     (interfaceInteractionType,
      "QED","QED",ShowerInteraction::QED);
   static SwitchOption interfaceInteractionTypeEW
     (interfaceInteractionType,
      "EW","EW",ShowerInteraction::EW);
 
   static Switch<SplittingFunction,bool> interfaceAngularOrdered
     ("AngularOrdered",
      "Whether or not this interaction is angular ordered, "
      "normally only g->q qbar and gamma-> f fbar are the only ones which aren't.",
      &SplittingFunction::angularOrdered_, true, false, false);
   static SwitchOption interfaceAngularOrderedYes
     (interfaceAngularOrdered,
      "Yes",
      "Interaction is angular ordered",
      true);
   static SwitchOption interfaceAngularOrderedNo
     (interfaceAngularOrdered,
      "No",
      "Interaction isn't angular ordered",
      false);
 
   static Switch<SplittingFunction,unsigned int> interfaceScaleChoice
     ("ScaleChoice",
      "The scale choice to be used",
      &SplittingFunction::scaleChoice_, 2, false, false);
   static SwitchOption interfaceScaleChoicepT
     (interfaceScaleChoice,
      "pT",
      "pT of the branching",
      0);
   static SwitchOption interfaceScaleChoiceQ2
     (interfaceScaleChoice,
      "Q2",
      "Q2 of the branching",
      1);
   static SwitchOption interfaceScaleChoiceFromAngularOrdering
     (interfaceScaleChoice,
      "FromAngularOrdering",
      "If angular order use pT, otherwise Q2",
      2);
 
+  static Switch<SplittingFunction,bool> interfaceStrictAO
+    ("StrictAO",
+     "Whether or not to apply strict angular-ordering,"
+     " i.e. for QED even in QCD emission, and vice versa",
+     &SplittingFunction::strictAO_, true, false, false);
+  static SwitchOption interfaceStrictAOYes
+    (interfaceStrictAO,
+     "Yes",
+     "Apply strict ordering",
+     true);
+  static SwitchOption interfaceStrictAONo
+    (interfaceStrictAO,
+     "No",
+     "Don't apply strict ordering",
+     false);
 }
 
 void SplittingFunction::persistentOutput(PersistentOStream & os) const {
    os << oenum(_interactionType)
       << oenum(_colourStructure) << _colourFactor
-      << angularOrdered_ << scaleChoice_;
+      << angularOrdered_ << scaleChoice_ << strictAO_;
 }
 
 void SplittingFunction::persistentInput(PersistentIStream & is, int) {
   is >> ienum(_interactionType)
      >>	ienum(_colourStructure) >> _colourFactor
-     >> angularOrdered_ >> scaleChoice_;
+     >> angularOrdered_ >> scaleChoice_ >> strictAO_;
 }
 
 void SplittingFunction::colourConnection(tShowerParticlePtr parent,
                                          tShowerParticlePtr first,
                                          tShowerParticlePtr second,
 					 ShowerPartnerType partnerType, 
                                          const bool back) const {
   if(_colourStructure==TripletTripletOctet) {
     if(!back) {
       ColinePair cparent = ColinePair(parent->colourLine(), 
                                       parent->antiColourLine());
       // ensure input consistency
       assert((  cparent.first && !cparent.second && 
 		partnerType==ShowerPartnerType::QCDColourLine) || 
              ( !cparent.first &&  cparent.second && 
 		partnerType==ShowerPartnerType::QCDAntiColourLine));
       // q -> q g
       if(cparent.first) {
         ColinePtr newline=new_ptr(ColourLine());
         cparent.first->addColoured(second);
         newline->addColoured     ( first);
         newline->addAntiColoured (second);
       }
       // qbar -> qbar g
       else {
         ColinePtr newline=new_ptr(ColourLine());
         cparent.second->addAntiColoured(second);
         newline->addColoured(second);
         newline->addAntiColoured(first);
       }
       // Set progenitor
       first->progenitor(parent->progenitor());
       second->progenitor(parent->progenitor());
     }
     else {
       ColinePair cfirst = ColinePair(first->colourLine(), 
                                      first->antiColourLine());
       // ensure input consistency
       assert((  cfirst.first && !cfirst.second && 
 		partnerType==ShowerPartnerType::QCDColourLine) || 
              ( !cfirst.first &&  cfirst.second && 
 		partnerType==ShowerPartnerType::QCDAntiColourLine));
       // q -> q g
       if(cfirst.first) {
         ColinePtr newline=new_ptr(ColourLine());
         cfirst.first->addAntiColoured(second);
         newline->addColoured(second);
         newline->addColoured(parent);
       }
       // qbar -> qbar g
       else {
         ColinePtr newline=new_ptr(ColourLine());
         cfirst.second->addColoured(second);
         newline->addAntiColoured(second);
         newline->addAntiColoured(parent);
       }
       // Set progenitor
       parent->progenitor(first->progenitor());
       second->progenitor(first->progenitor());
     }
   }
   else if(_colourStructure==OctetOctetOctet) {
     if(!back) {
       ColinePair cparent = ColinePair(parent->colourLine(), 
                                       parent->antiColourLine());
       // ensure input consistency
       assert(cparent.first&&cparent.second);
       // ensure first gluon is hardest
       if( first->id()==second->id() && parent->showerKinematics()->z()<0.5 ) 
 	swap(first,second);
       // colour line radiates
       if(partnerType==ShowerPartnerType::QCDColourLine) {
 	// The colour line is radiating
 	ColinePtr newline=new_ptr(ColourLine());
 	cparent.first->addColoured(second);
 	cparent.second->addAntiColoured(first);
 	newline->addColoured(first);
 	newline->addAntiColoured(second);
       }
       // anti colour line radiates
       else if(partnerType==ShowerPartnerType::QCDAntiColourLine) {
 	ColinePtr newline=new_ptr(ColourLine());
 	cparent.first->addColoured(first);
 	cparent.second->addAntiColoured(second);
 	newline->addColoured(second);
 	newline->addAntiColoured(first);
       }
       else
 	assert(false);
     }
     else {
       ColinePair cfirst = ColinePair(first->colourLine(), 
                                      first->antiColourLine());
       // ensure input consistency
       assert(cfirst.first&&cfirst.second);
       // The colour line is radiating
       if(partnerType==ShowerPartnerType::QCDColourLine) {
 	ColinePtr newline=new_ptr(ColourLine());
 	cfirst.first->addAntiColoured(second);
 	cfirst.second->addAntiColoured(parent);
 	newline->addColoured(parent);
 	newline->addColoured(second);
       }
       // anti colour line radiates
       else if(partnerType==ShowerPartnerType::QCDAntiColourLine) {
 	ColinePtr newline=new_ptr(ColourLine());
 	cfirst.first->addColoured(parent);
 	cfirst.second->addColoured(second);
 	newline->addAntiColoured(second);
 	newline->addAntiColoured(parent);
       }
       else
 	assert(false);
     }    
   }
   else if(_colourStructure == OctetTripletTriplet) {
     if(!back) {
       ColinePair cparent = ColinePair(parent->colourLine(), 
                                       parent->antiColourLine());
       // ensure input consistency
       assert(cparent.first&&cparent.second);
       cparent.first ->addColoured    ( first);
       cparent.second->addAntiColoured(second);
       // Set progenitor
       first->progenitor(parent->progenitor());
       second->progenitor(parent->progenitor());
     }
     else {
       ColinePair cfirst = ColinePair(first->colourLine(), 
                                      first->antiColourLine());
       // ensure input consistency
       assert(( cfirst.first && !cfirst.second) ||
              (!cfirst.first &&  cfirst.second));
       // g -> q qbar
       if(cfirst.first) {
 	ColinePtr newline=new_ptr(ColourLine());
 	cfirst.first->addColoured(parent);
 	newline->addAntiColoured(second);
 	newline->addAntiColoured(parent);	
       }
       // g -> qbar q
       else {
         ColinePtr newline=new_ptr(ColourLine());
         cfirst.second->addAntiColoured(parent);
         newline->addColoured(second);
         newline->addColoured(parent);
       }
       // Set progenitor
       parent->progenitor(first->progenitor());
       second->progenitor(first->progenitor());
     }
   }
   else if(_colourStructure == TripletOctetTriplet) {
     if(!back) {
       ColinePair cparent = ColinePair(parent->colourLine(), 
                                       parent->antiColourLine());
       // ensure input consistency
       assert(( cparent.first && !cparent.second) || 
              (!cparent.first &&  cparent.second));
       // q -> g q
       if(cparent.first) {
         ColinePtr newline=new_ptr(ColourLine());
         cparent.first->addColoured(first);
         newline->addColoured    (second);
         newline->addAntiColoured( first);
       }
       // qbar -> g qbar
       else {
 	ColinePtr newline=new_ptr(ColourLine());
 	cparent.second->addAntiColoured(first);
 	newline->addColoured    ( first);
 	newline->addAntiColoured(second);	
       }
       // Set progenitor
       first->progenitor(parent->progenitor());
       second->progenitor(parent->progenitor());
     }
     else {
       ColinePair cfirst = ColinePair(first->colourLine(), 
                                      first->antiColourLine());
       // ensure input consistency
       assert(cfirst.first&&cfirst.second);
       // q -> g q
       if(parent->id()>0) {
         cfirst.first ->addColoured(parent);
         cfirst.second->addColoured(second);
       }
       else {
         cfirst.first ->addAntiColoured(second);
         cfirst.second->addAntiColoured(parent);
       }
       // Set progenitor
       parent->progenitor(first->progenitor());
       second->progenitor(first->progenitor());
     }
   }
   else if(_colourStructure==SextetSextetOctet) {
     //make sure we're not doing backward evolution
     assert(!back);
 
     //make sure something sensible
     assert(parent->colourLine() || parent->antiColourLine());
    
     //get the colour lines or anti-colour lines
     bool isAntiColour=true;
     ColinePair cparent;
     if(parent->colourLine()) {
       cparent = ColinePair(const_ptr_cast<tColinePtr>(parent->colourInfo()->colourLines()[0]), 
 			   const_ptr_cast<tColinePtr>(parent->colourInfo()->colourLines()[1]));
       isAntiColour=false;
     }
     else {
       cparent = ColinePair(const_ptr_cast<tColinePtr>(parent->colourInfo()->antiColourLines()[0]), 
 			   const_ptr_cast<tColinePtr>(parent->colourInfo()->antiColourLines()[1]));
     }
     
     //check for sensible input
     //    assert(cparent.first && cparent.second);
 
     // sextet has 2 colour lines
     if(!isAntiColour) {
       //pick at random which of the colour topolgies to take
       double topology = UseRandom::rnd();
       if(topology < 0.25) {
         ColinePtr newline=new_ptr(ColourLine());
         cparent.first->addColoured(second);
         cparent.second->addColoured(first);
         newline->addColoured(first);
         newline->addAntiColoured(second);
       }
       else if(topology >=0.25 && topology < 0.5) {
         ColinePtr newline=new_ptr(ColourLine());
         cparent.first->addColoured(first);
         cparent.second->addColoured(second);
         newline->addColoured(first);
         newline->addAntiColoured(second); 
       }
       else if(topology >= 0.5 && topology < 0.75) {
         ColinePtr newline=new_ptr(ColourLine());
         cparent.first->addColoured(second);
         cparent.second->addColoured(first); 
         newline->addColoured(first); 
         newline->addAntiColoured(second); 
       }
       else {
         ColinePtr newline=new_ptr(ColourLine());
         cparent.first->addColoured(first);
         cparent.second->addColoured(second);
         newline->addColoured(first);
         newline->addAntiColoured(second);
       }
     }
     // sextet has 2 anti-colour lines
     else {
       double topology = UseRandom::rnd();
       if(topology < 0.25){
         ColinePtr newline=new_ptr(ColourLine());
         cparent.first->addAntiColoured(second);
         cparent.second->addAntiColoured(first);
         newline->addAntiColoured(first);
         newline->addColoured(second);
       }
       else if(topology >=0.25 && topology < 0.5) {
         ColinePtr newline=new_ptr(ColourLine());
         cparent.first->addAntiColoured(first);
         cparent.second->addAntiColoured(second);
         newline->addAntiColoured(first);
         newline->addColoured(second); 
       }
       else if(topology >= 0.5 && topology < 0.75) {
         ColinePtr newline=new_ptr(ColourLine());
         cparent.first->addAntiColoured(second);
         cparent.second->addAntiColoured(first);
         newline->addAntiColoured(first);
         newline->addColoured(second); 
       }
       else {
         ColinePtr newline=new_ptr(ColourLine());
         cparent.first->addAntiColoured(first);
         cparent.second->addAntiColoured(second);
         newline->addAntiColoured(first);
         newline->addColoured(second);
       }
     }   
   }
   else if(_colourStructure == ChargedChargedNeutral) {
     if(!parent->data().coloured()) return;
     if(!back) {
       ColinePair cparent = ColinePair(parent->colourLine(), 
 				      parent->antiColourLine());
       // q -> q g
       if(cparent.first) {
 	cparent.first->addColoured(first);
       }
       // qbar -> qbar g
       if(cparent.second) {
 	cparent.second->addAntiColoured(first);
       }
     }
     else {
       ColinePair cfirst = ColinePair(first->colourLine(), 
 				     first->antiColourLine());
       // q -> q g
       if(cfirst.first) {
 	cfirst.first->addColoured(parent);
       }
       // qbar -> qbar g
       if(cfirst.second) {
 	cfirst.second->addAntiColoured(parent);
       }
     }
   }
   else if(_colourStructure == ChargedNeutralCharged) {
     if(!parent->data().coloured()) return;
     if(!back) {
       ColinePair cparent = ColinePair(parent->colourLine(), 
 				      parent->antiColourLine());
       // q -> q g
       if(cparent.first) {
 	cparent.first->addColoured(second);
       }
       // qbar -> qbar g
       if(cparent.second) {
 	cparent.second->addAntiColoured(second);
       }
     }
     else {
       if (second->dataPtr()->iColour()==PDT::Colour3 ) {
 	ColinePtr newline=new_ptr(ColourLine());
 	newline->addColoured(second);
 	newline->addColoured(parent);
       }
       else if (second->dataPtr()->iColour()==PDT::Colour3bar ) {
 	ColinePtr newline=new_ptr(ColourLine());
 	newline->addAntiColoured(second);
 	newline->addAntiColoured(parent);
       }
     }
   }
   else if(_colourStructure == NeutralChargedCharged ) {
     if(!back) {
       if(first->dataPtr()->coloured()) {
 	ColinePtr newline=new_ptr(ColourLine());
 	if(first->dataPtr()->iColour()==PDT::Colour3) {
 	  newline->addColoured    (first );
 	  newline->addAntiColoured(second);
 	}
 	else if (first->dataPtr()->iColour()==PDT::Colour3bar) {
 	  newline->addColoured    (second);
 	  newline->addAntiColoured(first );
 	}
 	else
 	  assert(false);
       }
     }
     else {   
       ColinePair cfirst = ColinePair(first->colourLine(), 
 				     first->antiColourLine());
       // gamma -> q qbar
       if(cfirst.first) {
 	cfirst.first->addAntiColoured(second);
       }
       // gamma -> qbar q
       else if(cfirst.second) {
 	cfirst.second->addColoured(second);
       }
       else 
 	assert(false);
     }
   }
   else if(_colourStructure == EW) {
     if(!parent->data().coloured()) return;
     if(!back) {
       ColinePair cparent = ColinePair(parent->colourLine(), 
 				      parent->antiColourLine());
       // q -> q g
       if(cparent.first) {
 	cparent.first->addColoured(first);
       }
       // qbar -> qbar g
       if(cparent.second) {
 	cparent.second->addAntiColoured(first);
       }
     }
     else {
       ColinePair cfirst = ColinePair(first->colourLine(), 
 				     first->antiColourLine());
       // q -> q g
       if(cfirst.first) {
 	cfirst.first->addColoured(parent);
       }
       // qbar -> qbar g
       if(cfirst.second) {
 	cfirst.second->addAntiColoured(parent);
       }
     }
   }
   else {
     assert(false);
   }
 }
 
 void SplittingFunction::doinit() {
   Interfaced::doinit();
   assert(_interactionType!=ShowerInteraction::UNDEFINED);
   assert((_colourStructure>0&&_interactionType==ShowerInteraction::QCD) ||
 	 (_colourStructure<0&&(_interactionType==ShowerInteraction::QED ||
 			       _interactionType==ShowerInteraction::EW)) );
   if(_colourFactor>0.) return;
   // compute the colour factors if need
   if(_colourStructure==TripletTripletOctet) {
     _colourFactor = 4./3.;
   }
   else if(_colourStructure==OctetOctetOctet) {
     _colourFactor = 3.;
   }
   else if(_colourStructure==OctetTripletTriplet) {
     _colourFactor = 0.5;
   }
   else if(_colourStructure==TripletOctetTriplet) {
     _colourFactor = 4./3.;
   }
   else if(_colourStructure==SextetSextetOctet) {
     _colourFactor = 10./3.;
   }
   else if(_colourStructure<0) {
     _colourFactor = 1.;
   }
   else {
     assert(false);
   }
 }
 
 bool SplittingFunction::checkColours(const IdList & ids) const {
   if(_colourStructure==TripletTripletOctet) {
     if(ids[0]!=ids[1]) return false;
     if((ids[0]->iColour()==PDT::Colour3||ids[0]->iColour()==PDT::Colour3bar) &&
        ids[2]->iColour()==PDT::Colour8) return true;
     return false;
   }
   else if(_colourStructure==OctetOctetOctet) {
     for(unsigned int ix=0;ix<3;++ix) {
       if(ids[ix]->iColour()!=PDT::Colour8) return false;
     }
     return true;
   }
   else if(_colourStructure==OctetTripletTriplet) {
     if(ids[0]->iColour()!=PDT::Colour8) return false;
     if(ids[1]->iColour()==PDT::Colour3&&ids[2]->iColour()==PDT::Colour3bar)
       return true;
     if(ids[1]->iColour()==PDT::Colour3bar&&ids[2]->iColour()==PDT::Colour3)
       return true;
     return false;
   }
   else if(_colourStructure==TripletOctetTriplet) {
     if(ids[0]!=ids[2]) return false;
     if((ids[0]->iColour()==PDT::Colour3||ids[0]->iColour()==PDT::Colour3bar) &&
        ids[1]->iColour()==PDT::Colour8) return true;
     return false;
   }
   else if(_colourStructure==SextetSextetOctet) {
     if(ids[0]!=ids[1]) return false;
     if((ids[0]->iColour()==PDT::Colour6 || ids[0]->iColour()==PDT::Colour6bar) &&
        ids[2]->iColour()==PDT::Colour8) return true;
     return false;
   }
   else if(_colourStructure==ChargedChargedNeutral) {
     if(ids[0]!=ids[1]) return false;
     if(ids[2]->iCharge()!=0) return false;
     if(ids[0]->iCharge()==ids[1]->iCharge()) return true;
     return false;
   }
   else if(_colourStructure==ChargedNeutralCharged) {
     if(ids[0]!=ids[2]) return false;
     if(ids[1]->iCharge()!=0) return false;
     if(ids[0]->iCharge()==ids[2]->iCharge()) return true;
     return false;
   }
   else if(_colourStructure==NeutralChargedCharged) {
     if(ids[1]->id()!=-ids[2]->id()) return false;
     if(ids[0]->iCharge()!=0) return false;
     if(ids[1]->iCharge()==-ids[2]->iCharge()) return true;
     return false;
   }
   else {
     assert(false);
   }
   return false;
 }
 
 namespace {
 
   bool hasColour(tPPtr p) {
     PDT::Colour colour = p->dataPtr()->iColour();
     return colour==PDT::Colour3 || colour==PDT::Colour8 || colour == PDT::Colour6;
   }
 
   bool hasAntiColour(tPPtr p) {
     PDT::Colour colour = p->dataPtr()->iColour();
     return colour==PDT::Colour3bar || colour==PDT::Colour8 || colour == PDT::Colour6bar;
   }
   
 }
 
 void SplittingFunction::evaluateFinalStateScales(ShowerPartnerType partnerType,
 						 Energy scale, double z,
 						 tShowerParticlePtr parent,
 						 tShowerParticlePtr emitter,
 						 tShowerParticlePtr emitted) {
   // identify emitter and emitted
   double zEmitter = z, zEmitted = 1.-z;
   bool bosonSplitting(false);
   // special for g -> gg, particle highest z is emitter
   if(emitter->id() == emitted->id() && emitter->id() == parent->id() &&
      zEmitted > zEmitter) {
     swap(zEmitted,zEmitter);
     swap( emitted, emitter);
   }
   // otherwise if particle ID same
   else if(emitted->id()==parent->id()) {
     swap(zEmitted,zEmitter);
     swap( emitted, emitter);
   }
   // no real emitter/emitted
   else if(emitter->id()!=parent->id()) {
     bosonSplitting = true;
   }
   // may need to add angularOrder flag here
   // now the various scales
   // QED
   if(partnerType==ShowerPartnerType::QED) {
     assert(colourStructure()==ChargedChargedNeutral ||
 	   colourStructure()==ChargedNeutralCharged ||
 	   colourStructure()==NeutralChargedCharged );
     // normal case
     if(!bosonSplitting) {
       assert(colourStructure()==ChargedChargedNeutral ||
 	     colourStructure()==ChargedNeutralCharged );
       // set the scales
       // emitter
       emitter->scales().QED         = zEmitter*scale;
       emitter->scales().QED_noAO    =          scale;
-      emitter->scales().QCD_c       = min(scale,parent->scales().QCD_c      );
+      if(strictAO_)
+	emitter->scales().QCD_c       = min(zEmitter*scale,parent->scales().QCD_c      );
+      else
+	emitter->scales().QCD_c       = min(         scale,parent->scales().QCD_c      );
       emitter->scales().QCD_c_noAO  = min(scale,parent->scales().QCD_c_noAO );
-      emitter->scales().QCD_ac      = min(scale,parent->scales().QCD_ac     );
+      if(strictAO_)
+	emitter->scales().QCD_ac      = min(zEmitter*scale,parent->scales().QCD_ac     );
+      else
+	emitter->scales().QCD_ac      = min(         scale,parent->scales().QCD_ac     );
       emitter->scales().QCD_ac_noAO = min(scale,parent->scales().QCD_ac_noAO);
       emitter->scales().EW_Z        = min(scale,parent->scales().EW_Z       );
       emitter->scales().EW_W        = min(scale,parent->scales().EW_W       );
       // emitted 
       emitted->scales().QED         = zEmitted*scale;
       emitted->scales().QED_noAO    =          scale;
       emitted->scales().QCD_c       = ZERO;
       emitted->scales().QCD_c_noAO  = ZERO;
       emitted->scales().QCD_ac      = ZERO;
       emitted->scales().QCD_ac_noAO = ZERO;
       emitted->scales().EW_Z        = min(scale,parent->scales().EW_Z       );
       emitted->scales().EW_W        = min(scale,parent->scales().EW_W       );
     }
     // gamma -> f fbar
     else {
       assert(colourStructure()==NeutralChargedCharged );
       // emitter
       emitter->scales().QED           = zEmitter*scale;
       emitter->scales().QED_noAO      =          scale;
       if(hasColour(emitter)) {
 	emitter->scales().QCD_c       = zEmitter*scale;
 	emitter->scales().QCD_c_noAO  =          scale;
       }
       if(hasAntiColour(emitter)) {
 	emitter->scales().QCD_ac      = zEmitter*scale;
 	emitter->scales().QCD_ac_noAO =          scale;
       }
       emitter->scales().EW_Z          = zEmitter*scale;
       emitter->scales().EW_W          = zEmitter*scale;
       // emitted 
       emitted->scales().QED           = zEmitted*scale;
       emitted->scales().QED_noAO      =          scale;
       if(hasColour(emitted)) {
 	emitted->scales().QCD_c       = zEmitted*scale;
 	emitted->scales().QCD_c_noAO  =          scale;
       }
       if(hasAntiColour(emitted)) {
 	emitted->scales().QCD_ac      = zEmitted*scale;
 	emitted->scales().QCD_ac_noAO =          scale;
       }
       emitted->scales().EW_Z          = zEmitted*scale;
       emitted->scales().EW_W          = zEmitted*scale;
     }
   }
   // QCD
   else if (partnerType==ShowerPartnerType::QCDColourLine ||
 	   partnerType==ShowerPartnerType::QCDAntiColourLine) {
    // normal case eg q -> q g and g -> g g
     if(!bosonSplitting) {
-      emitter->scales().QED         = min(scale,parent->scales().QED     );
+      if(strictAO_)
+	emitter->scales().QED         = min(zEmitter*scale,parent->scales().QED     );
+      else
+	emitter->scales().QED         = min(         scale,parent->scales().QED     );
       emitter->scales().QED_noAO    = min(scale,parent->scales().QED_noAO);
       emitter->scales().EW_Z        = min(scale,parent->scales().EW_Z   );
       emitter->scales().EW_W        = min(scale,parent->scales().EW_W   );
       if(partnerType==ShowerPartnerType::QCDColourLine) {
 	emitter->scales().QCD_c       = zEmitter*scale;
 	emitter->scales().QCD_c_noAO  =          scale;
 	emitter->scales().QCD_ac      = min(zEmitter*scale,parent->scales().QCD_ac     );
 	emitter->scales().QCD_ac_noAO = min(         scale,parent->scales().QCD_ac_noAO);
       }
       else {
 	emitter->scales().QCD_c       = min(zEmitter*scale,parent->scales().QCD_c      );
 	emitter->scales().QCD_c_noAO  = min(         scale,parent->scales().QCD_c_noAO );
 	emitter->scales().QCD_ac      = zEmitter*scale;
 	emitter->scales().QCD_ac_noAO =          scale;
       }
       // emitted 
       emitted->scales().QED         = ZERO;
       emitted->scales().QED_noAO    = ZERO;
       emitted->scales().QCD_c       = zEmitted*scale;
       emitted->scales().QCD_c_noAO  =          scale;
       emitted->scales().QCD_ac      = zEmitted*scale;
       emitted->scales().QCD_ac_noAO =          scale;
       emitted->scales().EW_Z        = min(scale,parent->scales().EW_Z   );
       emitted->scales().EW_W        = min(scale,parent->scales().EW_W   );
     }
     // g -> q qbar
     else {
       // emitter
       if(emitter->dataPtr()->charged()) {
 	emitter->scales().QED         = zEmitter*scale;
 	emitter->scales().QED_noAO    =          scale;
       }
       emitter->scales().EW_Z          = zEmitter*scale;
       emitter->scales().EW_W          = zEmitter*scale;
       emitter->scales().QCD_c         = zEmitter*scale;
       emitter->scales().QCD_c_noAO    =          scale;
       emitter->scales().QCD_ac        = zEmitter*scale;
       emitter->scales().QCD_ac_noAO   =          scale;
       // emitted 
       if(emitted->dataPtr()->charged()) {
 	emitted->scales().QED         = zEmitted*scale;
 	emitted->scales().QED_noAO    =          scale;
       }
       emitted->scales().EW_Z          = zEmitted*scale;
       emitted->scales().EW_W          = zEmitted*scale;
       emitted->scales().QCD_c         = zEmitted*scale;
       emitted->scales().QCD_c_noAO    =          scale;
       emitted->scales().QCD_ac        = zEmitted*scale;
       emitted->scales().QCD_ac_noAO   =          scale;
     }
   }
   else if(partnerType==ShowerPartnerType::EW) {
     // EW
     emitter->scales().EW_Z        = zEmitter*scale;
     emitter->scales().EW_W        = zEmitter*scale;
     emitted->scales().EW_Z        = zEmitted*scale;
     emitted->scales().EW_W        = zEmitted*scale;
     // QED
     // W radiation AO
     if(emitted->dataPtr()->charged()) {
       emitter->scales().QED       = zEmitter*scale;
       emitter->scales().QED_noAO  =          scale;
       emitted->scales().QED       = zEmitted*scale;
       emitted->scales().QED_noAO  =          scale;
     }
     // Z don't
     else {
       emitter->scales().QED         = min(scale,parent->scales().QED     );
       emitter->scales().QED_noAO    = min(scale,parent->scales().QED_noAO);
       emitted->scales().QED         = ZERO;
       emitted->scales().QED_noAO    = ZERO;
     }
     // QCD
     emitter->scales().QCD_c       = min(scale,parent->scales().QCD_c      );
     emitter->scales().QCD_c_noAO  = min(scale,parent->scales().QCD_c_noAO );
     emitter->scales().QCD_ac      = min(scale,parent->scales().QCD_ac     );
     emitter->scales().QCD_ac_noAO = min(scale,parent->scales().QCD_ac_noAO);
     emitted->scales().QCD_c       = ZERO;
     emitted->scales().QCD_c_noAO  = ZERO;
     emitted->scales().QCD_ac      = ZERO;
     emitted->scales().QCD_ac_noAO = ZERO;
   }
   else
     assert(false);
 }
 
 void SplittingFunction::evaluateInitialStateScales(ShowerPartnerType partnerType,
 						   Energy scale, double z,
 						   tShowerParticlePtr parent,
 						   tShowerParticlePtr spacelike,
 						   tShowerParticlePtr timelike) {
   // scale for time-like child
   Energy AOScale = (1.-z)*scale;
   // QED
   if(partnerType==ShowerPartnerType::QED) {
     if(parent->id()==spacelike->id()) {
       // parent
       parent   ->scales().QED         =   scale;
       parent   ->scales().QED_noAO    =   scale;
       parent   ->scales().QCD_c       = min(scale,spacelike->scales().QCD_c      );
       parent   ->scales().QCD_c_noAO  = min(scale,spacelike->scales().QCD_c_noAO );
       parent   ->scales().QCD_ac      = min(scale,spacelike->scales().QCD_ac     );
       parent   ->scales().QCD_ac_noAO = min(scale,spacelike->scales().QCD_ac_noAO);
       // timelike
       timelike->scales().QED         = AOScale;
       timelike->scales().QED_noAO    =   scale;
       timelike->scales().QCD_c       =    ZERO;
       timelike->scales().QCD_c_noAO  =    ZERO;
       timelike->scales().QCD_ac      =    ZERO;
       timelike->scales().QCD_ac_noAO =    ZERO;
     }
     else if(parent->id()==timelike->id()) {
       parent   ->scales().QED         =   scale;
       parent   ->scales().QED_noAO    =   scale;
       if(hasColour(parent)) {
 	parent   ->scales().QCD_c       = scale;
 	parent   ->scales().QCD_c_noAO  = scale;
       }
       if(hasAntiColour(parent)) {
 	parent   ->scales().QCD_ac      = scale;
 	parent   ->scales().QCD_ac_noAO = scale;
       }
       // timelike 
       timelike->scales().QED         = AOScale;
       timelike->scales().QED_noAO    =   scale;
       if(hasColour(timelike)) {
 	timelike->scales().QCD_c       = AOScale;
 	timelike->scales().QCD_c_noAO  =   scale;
       }
       if(hasAntiColour(timelike)) {
 	timelike->scales().QCD_ac      = AOScale;
 	timelike->scales().QCD_ac_noAO =   scale;
       }
     }
     else {
       parent   ->scales().QED         = scale;
       parent   ->scales().QED_noAO    = scale;
       parent   ->scales().QCD_c       = ZERO ;
       parent   ->scales().QCD_c_noAO  = ZERO ;
       parent   ->scales().QCD_ac      = ZERO ;
       parent   ->scales().QCD_ac_noAO = ZERO ;
       // timelike 
       timelike->scales().QED         = AOScale;
       timelike->scales().QED_noAO    =   scale;
       if(hasColour(timelike)) {
 	timelike->scales().QCD_c       = min(AOScale,spacelike->scales().QCD_ac     );
 	timelike->scales().QCD_c_noAO  = min(  scale,spacelike->scales().QCD_ac_noAO);
       }
       if(hasAntiColour(timelike)) {
 	timelike->scales().QCD_ac      = min(AOScale,spacelike->scales().QCD_c      );
 	timelike->scales().QCD_ac_noAO = min(  scale,spacelike->scales().QCD_c_noAO );
       }
     }
   }
   // QCD
   else if (partnerType==ShowerPartnerType::QCDColourLine ||
 	   partnerType==ShowerPartnerType::QCDAntiColourLine) {
     // timelike 
     if(timelike->dataPtr()->charged()) {
       timelike->scales().QED         = AOScale;
       timelike->scales().QED_noAO    =   scale;
     }
     if(hasColour(timelike)) {
       timelike->scales().QCD_c       = AOScale;
       timelike->scales().QCD_c_noAO  =   scale;
     }
     if(hasAntiColour(timelike)) {
       timelike->scales().QCD_ac      = AOScale;
       timelike->scales().QCD_ac_noAO =   scale;
     }
     if(parent->id()==spacelike->id()) {
       parent   ->scales().QED         = min(scale,spacelike->scales().QED        );
       parent   ->scales().QED_noAO    = min(scale,spacelike->scales().QED_noAO   );
       parent   ->scales().QCD_c       = min(scale,spacelike->scales().QCD_c      );
       parent   ->scales().QCD_c_noAO  = min(scale,spacelike->scales().QCD_c_noAO );
       parent   ->scales().QCD_ac      = min(scale,spacelike->scales().QCD_ac     );
       parent   ->scales().QCD_ac_noAO = min(scale,spacelike->scales().QCD_ac_noAO);
     }
     else {
       if(parent->dataPtr()->charged()) {
 	parent   ->scales().QED         = scale;
 	parent   ->scales().QED_noAO    = scale;
       }
       if(hasColour(parent)) {
 	parent   ->scales().QCD_c      = scale;
 	parent   ->scales().QCD_c_noAO  = scale;
       }
       if(hasAntiColour(parent)) {
 	parent   ->scales().QCD_ac      = scale;
 	parent   ->scales().QCD_ac_noAO = scale;
       }
     }
   }
   else if(partnerType==ShowerPartnerType::EW) {
     if(abs(spacelike->id())!=ParticleID::Wplus && 
        spacelike->id() !=ParticleID::Z0 ) {
       // QCD scales
       parent   ->scales().QCD_c       = min(scale,spacelike->scales().QCD_c      );
       parent   ->scales().QCD_c_noAO  = min(scale,spacelike->scales().QCD_c_noAO );
       parent   ->scales().QCD_ac      = min(scale,spacelike->scales().QCD_ac     );
       parent   ->scales().QCD_ac_noAO = min(scale,spacelike->scales().QCD_ac_noAO);
       timelike->scales().QCD_c       =    ZERO;
       timelike->scales().QCD_c_noAO  =    ZERO;
       timelike->scales().QCD_ac      =    ZERO;
       timelike->scales().QCD_ac_noAO =    ZERO;
       // QED scales
       if(timelike->id()==ParticleID::Z0) {
 	parent   ->scales().QED       = min(scale,spacelike->scales().QED      );
 	parent   ->scales().QED_noAO  = min(scale,spacelike->scales().QED_noAO );
 	timelike->scales().QED       =    ZERO;
 	timelike->scales().QED_noAO  =    ZERO;
       }
       else {
 	parent   ->scales().QED         =   scale;
 	parent   ->scales().QED_noAO    =   scale;
 	timelike->scales().QED          = AOScale;
 	timelike->scales().QED_noAO     =   scale;
       }
       // EW scales
       if(timelike->id()==ParticleID::Z0) {
 	parent   ->scales().EW_Z       =   scale;
 	timelike->scales().EW_Z        = AOScale;
       }
       if(timelike->id()==ParticleID::Wplus){
 	parent   ->scales().EW_W       =   scale;
 	timelike->scales().EW_W        = AOScale;
       }
     }
     else assert(false);
   }
   else
     assert(false);
 }
 
 void SplittingFunction::evaluateDecayScales(ShowerPartnerType partnerType,
 					    Energy scale, double z,
 					    tShowerParticlePtr parent,
 					    tShowerParticlePtr spacelike,
 					    tShowerParticlePtr timelike) {
   assert(parent->id()==spacelike->id());
   // angular-ordered scale for 2nd child
   Energy AOScale = (1.-z)*scale;
   // QED
   if(partnerType==ShowerPartnerType::QED) {
     // timelike
     timelike->scales().QED         = AOScale;
     timelike->scales().QED_noAO    =   scale;
     timelike->scales().QCD_c       =    ZERO;
     timelike->scales().QCD_c_noAO  =    ZERO;
     timelike->scales().QCD_ac      =    ZERO;
     timelike->scales().QCD_ac_noAO =    ZERO;
     timelike->scales().EW_Z        = ZERO;
     timelike->scales().EW_W        = ZERO;
     // spacelike
     spacelike->scales().QED         =   scale;
     spacelike->scales().QED_noAO    =   scale;
     spacelike->scales().EW_Z        = max(scale,parent->scales().EW_Z       );
     spacelike->scales().EW_W        = max(scale,parent->scales().EW_W       );
   }
   // QCD
   else if(partnerType==ShowerPartnerType::QCDColourLine ||
 	  partnerType==ShowerPartnerType::QCDAntiColourLine) {
     // timelike 
     timelike->scales().QED         = ZERO;
     timelike->scales().QED_noAO    = ZERO;
     timelike->scales().QCD_c       = AOScale;
     timelike->scales().QCD_c_noAO  =   scale;
     timelike->scales().QCD_ac      = AOScale;
     timelike->scales().QCD_ac_noAO =   scale;
     timelike->scales().EW_Z        = ZERO;
     timelike->scales().EW_W        = ZERO;
     // spacelike
     spacelike->scales().QED         = max(scale,parent->scales().QED        );
     spacelike->scales().QED_noAO    = max(scale,parent->scales().QED_noAO   );
     spacelike->scales().EW_Z        = max(scale,parent->scales().EW_Z       );
     spacelike->scales().EW_W        = max(scale,parent->scales().EW_W       );
   }
   else if(partnerType==ShowerPartnerType::EW) {
     // EW
     timelike->scales().EW_Z         = AOScale;
     timelike->scales().EW_W         = AOScale;
     spacelike->scales().EW_Z        = max(scale,parent->scales().EW_Z       );
     spacelike->scales().EW_W        = max(scale,parent->scales().EW_W       );
     // QCD
     timelike->scales().QCD_c       =    ZERO;
     timelike->scales().QCD_c_noAO  =    ZERO;
     timelike->scales().QCD_ac      =    ZERO;
     timelike->scales().QCD_ac_noAO =    ZERO;
     timelike->scales().EW_Z        = ZERO;
     timelike->scales().EW_W        = ZERO;
     // QED
     timelike->scales().QED         = ZERO;
     timelike->scales().QED_noAO    = ZERO;
     spacelike->scales().QED         = max(scale,parent->scales().QED        );
     spacelike->scales().QED_noAO    = max(scale,parent->scales().QED_noAO   );
   }
   else 
     assert(false);
   spacelike->scales().QCD_c       = max(scale,parent->scales().QCD_c      );
   spacelike->scales().QCD_c_noAO  = max(scale,parent->scales().QCD_c_noAO );
   spacelike->scales().QCD_ac      = max(scale,parent->scales().QCD_ac     );
   spacelike->scales().QCD_ac_noAO = max(scale,parent->scales().QCD_ac_noAO);
 }
diff --git a/Shower/QTilde/SplittingFunctions/SplittingFunction.h b/Shower/QTilde/SplittingFunctions/SplittingFunction.h
--- a/Shower/QTilde/SplittingFunctions/SplittingFunction.h
+++ b/Shower/QTilde/SplittingFunctions/SplittingFunction.h
@@ -1,382 +1,387 @@
 // -*- C++ -*-
 //
 // SplittingFunction.h is a part of Herwig - A multi-purpose Monte Carlo event generator
 // Copyright (C) 2002-2017 The Herwig Collaboration
 //
 // Herwig is licenced under version 3 of the GPL, see COPYING for details.
 // Please respect the MCnet academic guidelines, see GUIDELINES for details.
 //
 #ifndef HERWIG_SplittingFunction_H
 #define HERWIG_SplittingFunction_H
 //
 // This is the declaration of the SplittingFunction class.
 //
 
 #include "ThePEG/Interface/Interfaced.h"
 #include "Herwig/Shower/QTilde/ShowerConfig.h"
 #include "ThePEG/EventRecord/RhoDMatrix.h"
 #include "Herwig/Decay/DecayMatrixElement.h"
 #include "Herwig/Shower/QTilde/Kinematics/ShowerKinematics.fh"
 #include "ThePEG/EventRecord/ColourLine.h"
 #include "ThePEG/PDT/ParticleData.h"
 #include "SplittingFunction.fh"
 
 namespace Herwig {
 
 using namespace ThePEG;
 
   /** \ingroup Shower
    * Enum to define the possible types of colour structure which can occur in
    * the branching.
    */
   enum ColourStructure {Undefined=0,
 			TripletTripletOctet  = 1,OctetOctetOctet    =2,
 			OctetTripletTriplet  = 3,TripletOctetTriplet=4,
 			SextetSextetOctet    = 5,
 			ChargedChargedNeutral=-1,ChargedNeutralCharged=-2,
 			NeutralChargedCharged=-3,EW=-4};
 
 /** \ingroup Shower
  *
  *  This is an abstract class which defines the common interface
  *  for all \f$1\to2\f$ splitting functions, for both initial-state
  *  and final-state radiation. 
  *
  *  The SplittingFunction class contains a number of purely virtual members
  *  which must be implemented in the inheriting classes. The class also stores
  *  the interaction type of the spltting function.
  *
  *  The inheriting classes need to specific the splitting function 
  *  \f$P(z,2p_j\cdot p_k)\f$, in terms of the energy fraction \f$z\f$ and
  *  the evolution scale. In order to allow the splitting functions to be used
  *  with different choices of evolution functions the scale is given by
  * \f[2p_j\cdot p_k=(p_j+p_k)^2-m_{jk}^2=Q^2-(p_j+p_k)^2=z(1-z)\tilde{q}^2=
  *   \frac{p_T^2}{z(1-z)}-m_{jk}^2+\frac{m_j^2}{z}+\frac{m_k^2}{1-z},\f]
  *  where \f$Q^2\f$ is the virtuality of the branching particle,
  *  $p_T$ is the relative transverse momentum of the branching products and
  *  \f$\tilde{q}^2\f$ is the angular variable described in hep-ph/0310083.
  *
  *  In addition an overestimate of the 
  *  splitting function, \f$P_{\rm over}(z)\f$ which only depends upon \f$z\f$, 
  *  the integral, inverse of the integral for this overestimate and
  *  ratio of the true splitting function to the overestimate must be provided
  *  as they are necessary for the veto alogrithm used to implement the evolution.
  *
  * @see \ref SplittingFunctionInterfaces "The interfaces"
  * defined for SplittingFunction.
  */
 class SplittingFunction: public Interfaced {
 
 public:
 
   /**
    * The default constructor.   
    * @param b All splitting functions must have an interaction order
    */
   SplittingFunction()
     : Interfaced(), _interactionType(ShowerInteraction::UNDEFINED),
       _colourStructure(Undefined), _colourFactor(-1.),
-      angularOrdered_(true), scaleChoice_(2) {}
+      angularOrdered_(true), scaleChoice_(2), strictAO_(true) {}
 
 public:
 
   /**
    *  Methods to return the interaction type and order for the splitting function
    */
   //@{
   /**
    *  Return the type of the interaction
    */
   ShowerInteraction interactionType() const {return _interactionType;}
 
   /**
    *  Return the colour structure
    */
   ColourStructure colourStructure() const {return _colourStructure;}
 
   /**
    *  Return the colour factor
    */
   double colourFactor(const IdList &ids) const {
     if(_colourStructure>0)
       return _colourFactor;
     else if(_colourStructure<0) {
       if(_colourStructure==ChargedChargedNeutral ||
 	 _colourStructure==ChargedNeutralCharged) {
 	return sqr(double(ids[0]->iCharge())/3.);
       }
       else if(_colourStructure==NeutralChargedCharged) {
 	double fact = sqr(double(ids[1]->iCharge())/3.);
 	if(ids[1]->coloured())
 	  fact *= abs(double(ids[1]->iColour()));
 	return fact;
       }
       else if(_colourStructure==EW) {
 	return 1.;
       }
       else
 	assert(false);
     }
     else
       assert(false);
   }
   //@}
 
   /**
    *  Purely virtual method which should determine whether this splitting
    *  function can be used for a given set of particles.
    *  @param ids The PDG codes for the particles in the splitting.
    */
   virtual bool accept(const IdList & ids) const = 0;
 
   /**
    *  Method to check the colours are correct
    */
   virtual bool checkColours(const IdList & ids) const;
 
   /**
    *   Methods to return the splitting function.
    */
   //@{
   /**
    * Purely virtual method which should return the exact value of the splitting function,
    * \f$P\f$ evaluated in terms of the energy fraction, \f$z\f$, and the evolution scale 
    \f$\tilde{q}^2\f$.
    * @param z   The energy fraction.
    * @param t   The scale \f$t=2p_j\cdot p_k\f$.
    * @param ids The PDG codes for the particles in the splitting.
    * @param mass Whether or not to include the mass dependent terms
    * @param rho The spin density matrix
    */
   virtual double P(const double z, const Energy2 t, const IdList & ids,
 		   const bool mass, const RhoDMatrix & rho) const = 0;
 
   /**
    * Purely virtual method which should return
    * an overestimate of the splitting function,
    * \f$P_{\rm over}\f$ such that the result \f$P_{\rm over}\geq P\f$. This function
    * should be simple enough that it does not depend on the evolution scale.
    * @param z   The energy fraction.
    * @param ids The PDG codes for the particles in the splitting.
    */
   virtual double overestimateP(const double z, const IdList & ids) const = 0; 
 
   /**
    * Purely virtual method which should return
    * the ratio of the splitting function to the overestimate, i.e.
    * \f$P(z,\tilde{q}^2)/P_{\rm over}(z)\f$.
    * @param z   The energy fraction.
    * @param t   The scale \f$t=2p_j\cdot p_k\f$.
    * @param ids The PDG codes for the particles in the splitting.
    * @param mass Whether or not to include the mass dependent terms
    * @param rho The spin density matrix
    */
   virtual double ratioP(const double z, const Energy2 t, const IdList & ids,
 			const bool mass, const RhoDMatrix & rho) const = 0;
 
   /**
    * Purely virtual method which should return the indefinite integral of the 
    * overestimated splitting function, \f$P_{\rm over}\f$.
    * @param z         The energy fraction.
    * @param ids The PDG codes for the particles in the splitting.
    * @param PDFfactor Which additional factor to include for the PDF
    *                  0 is no additional factor,
    *                  1 is \f$1/z\f$, 2 is \f$1/(1-z)\f$ and 3 is \f$1/z/(1-z)\f$
    *                  
    */
   virtual double integOverP(const double z, const IdList & ids, 
 			    unsigned int PDFfactor=0) const = 0; 
 
   /**
    * Purely virtual method which should return the inverse of the 
    * indefinite integral of the 
    * overestimated splitting function, \f$P_{\rm over}\f$ which is used to
    * generate the value of \f$z\f$.
    * @param r Value of the splitting function to be inverted
    * @param ids The PDG codes for the particles in the splitting.
    * @param PDFfactor Which additional factor to include for the PDF
    *                  0 is no additional factor,
    *                  1 is \f$1/z\f$, 2 is \f$1/(1-z)\f$ and 3 is \f$1/z/(1-z)\f$
    */
   virtual double invIntegOverP(const double r, const IdList & ids, 
 			       unsigned int PDFfactor=0) const = 0;
   //@}
 
   /**
    * Purely virtual method which should make the proper colour connection 
    * between the emitting parent and the branching products.
    * @param parent The parent for the branching
    * @param first  The first  branching product
    * @param second The second branching product
    * @param partnerType The type of evolution partner
    * @param back Whether this is foward or backward evolution.
    */
   virtual void colourConnection(tShowerParticlePtr parent,
 				tShowerParticlePtr first,
 				tShowerParticlePtr second,
 				ShowerPartnerType partnerType, 
 				const bool back) const;
 
   /**
    * Method to calculate the azimuthal angle for forward evolution
    * @param z The energy fraction
    * @param t The scale \f$t=2p_j\cdot p_k\f$.
    * @param ids The PDG codes for the particles in the splitting.
    * @param The azimuthal angle, \f$\phi\f$.
    * @return The weight
    */
   virtual vector<pair<int,Complex> > 
   generatePhiForward(const double z, const Energy2 t, const IdList & ids,
 		     const RhoDMatrix &) = 0;
 
   /**
    * Method to calculate the azimuthal angle for backward evolution
    * @param z The energy fraction
    * @param t The scale \f$t=2p_j\cdot p_k\f$.
    * @param ids The PDG codes for the particles in the splitting.
    * @return The weight
    */
   virtual vector<pair<int,Complex> > 
   generatePhiBackward(const double z, const Energy2 t, const IdList & ids,
 		      const RhoDMatrix &) = 0;
 
   /**
    * Calculate the matrix element for the splitting
    * @param z The energy fraction
    * @param t The scale \f$t=2p_j\cdot p_k\f$.
    * @param ids The PDG codes for the particles in the splitting.
    * @param phi The azimuthal angle, \f$\phi\f$.
    * @param timeLike Whether timelike or spacelike, affects inclusive of mass terms
    */
   virtual DecayMEPtr matrixElement(const double z, const Energy2 t, 
 				   const IdList & ids, const double phi,
                                    bool timeLike) = 0;
 
   /**
    *  Whether or not the interaction is angular ordered
    */
   bool angularOrdered() const {return angularOrdered_;}
 
   /**
    *  Scale choice
    */
   bool pTScale() const {
     return scaleChoice_ == 2 ? angularOrdered_ : scaleChoice_ == 0;
   }
 
   /**
    *  Functions to state scales after branching happens
    */
   //@{
   /**
    *  Sort out scales for final-state emission
    */
   void evaluateFinalStateScales(ShowerPartnerType type,
 				Energy scale, double z,
 				tShowerParticlePtr parent,
 				tShowerParticlePtr first,
 				tShowerParticlePtr second);
   /**
    *  Sort out scales for initial-state emission
    */
   void evaluateInitialStateScales(ShowerPartnerType type,
 				  Energy scale, double z,
 				  tShowerParticlePtr parent,
 				  tShowerParticlePtr first,
 				  tShowerParticlePtr second);
 
   /**
    *  Sort out scales for decay emission
    */
   void evaluateDecayScales(ShowerPartnerType type,
 			   Energy scale, double z,
 			   tShowerParticlePtr parent,
 			   tShowerParticlePtr first,
 			   tShowerParticlePtr second);
   //@}
 
 public:
 
   /** @name Functions used by the persistent I/O system. */
   //@{
   /**
    * Function used to write out object persistently.
    * @param os the persistent output stream written to.
    */
   void persistentOutput(PersistentOStream & os) const;
 
   /**
    * Function used to read in object persistently.
    * @param is the persistent input stream read from.
    * @param version the version number of the object when written.
    */
   void persistentInput(PersistentIStream & is, int version);
   //@}
 
   /**
    * The standard Init function used to initialize the interfaces.
    * Called exactly once for each class by the class description system
    * before the main function starts or
    * when this class is dynamically loaded.
    */
   static void Init();
 
 protected:
 
   /** @name Standard Interfaced functions. */
   //@{
   /**
    * Initialize this object after the setup phase before saving an
    * EventGenerator to disk.
    * @throws InitException if object could not be initialized properly.
    */
   virtual void doinit();
   //@}
 
 protected:
 
   /**
    *  Set the colour factor
    */
   void colourFactor(double in) {_colourFactor=in;}
 
 private:
 
   /**
    * The assignment operator is private and must never be called.
    * In fact, it should not even be implemented.
    */
   SplittingFunction & operator=(const SplittingFunction &) = delete;
 
 private:
 
   /**
    *  The interaction type for the splitting function.
    */
   ShowerInteraction _interactionType;
 
   /**
    *  The colour structure
    */
   ColourStructure _colourStructure;
 
   /**
    *  The colour factor
    */
   double _colourFactor;
 
   /**
    *  Whether or not this interaction is angular-ordered
    */
   bool angularOrdered_;
 
   /**
    *  The choice of scale
    */
   unsigned int scaleChoice_;
 
+  /**
+   *   Enforce strict AO 
+   */
+  bool strictAO_;
+
 };
 
 }
 
 #endif /* HERWIG_SplittingFunction_H */
diff --git a/Shower/QTilde/SplittingFunctions/SudakovFormFactor.cc b/Shower/QTilde/SplittingFunctions/SudakovFormFactor.cc
--- a/Shower/QTilde/SplittingFunctions/SudakovFormFactor.cc
+++ b/Shower/QTilde/SplittingFunctions/SudakovFormFactor.cc
@@ -1,1223 +1,1224 @@
 // -*- C++ -*-
 //
 // SudakovFormFactor.cc is a part of Herwig - A multi-purpose Monte Carlo event generator
 // Copyright (C) 2002-2017 The Herwig Collaboration
 //
 // Herwig is licenced under version 3 of the GPL, see COPYING for details.
 // Please respect the MCnet academic guidelines, see GUIDELINES for details.
 //
 //
 // This is the implementation of the non-inlined, non-templated member
 // functions of the SudakovFormFactor class.
 //
 
 #include "SudakovFormFactor.h"
 #include "ThePEG/Interface/ClassDocumentation.h"
 #include "ThePEG/Persistency/PersistentOStream.h"
 #include "ThePEG/Persistency/PersistentIStream.h"
 #include "ThePEG/Interface/Reference.h"
 #include "ThePEG/Interface/Switch.h"
 #include "ThePEG/Interface/Parameter.h"
 #include "Herwig/Shower/QTilde/Kinematics/ShowerKinematics.h"
 #include "Herwig/Shower/QTilde/Base/ShowerParticle.h"
 #include "ThePEG/Utilities/DescribeClass.h"
 #include "Herwig/Shower/QTilde/QTildeShowerHandler.h"
 #include "Herwig/Shower/QTilde/Kinematics/FS_QTildeShowerKinematics1to2.h"
 #include "Herwig/Shower/QTilde/Kinematics/IS_QTildeShowerKinematics1to2.h"
 #include "Herwig/Shower/QTilde/Kinematics/Decay_QTildeShowerKinematics1to2.h"
 #include "Herwig/Shower/QTilde/Kinematics/KinematicHelpers.h"
 #include "SudakovCutOff.h"
 
 #include <array>
 using std::array;
 
 using namespace Herwig;
 
 DescribeClass<SudakovFormFactor,Interfaced>
 describeSudakovFormFactor ("Herwig::SudakovFormFactor","");
 
 void SudakovFormFactor::persistentOutput(PersistentOStream & os) const {
   os << splittingFn_ << alpha_ << pdfmax_ << particles_ << pdffactor_ << cutoff_;
 }
 
 void SudakovFormFactor::persistentInput(PersistentIStream & is, int) {
   is >> splittingFn_ >> alpha_ >> pdfmax_ >> particles_ >> pdffactor_ >> cutoff_;
 }
 
 void SudakovFormFactor::Init() {
 
   static ClassDocumentation<SudakovFormFactor> documentation
     ("The SudakovFormFactor class is the base class for the implementation of Sudakov"
      " form factors in Herwig");
 
   static Reference<SudakovFormFactor,SplittingFunction>
     interfaceSplittingFunction("SplittingFunction",
 			       "A reference to the SplittingFunction object",
 			       &Herwig::SudakovFormFactor::splittingFn_,
 			       false, false, true, false);
 
   static Reference<SudakovFormFactor,ShowerAlpha>
     interfaceAlpha("Alpha",
 		   "A reference to the Alpha object",
 		   &Herwig::SudakovFormFactor::alpha_,
 		   false, false, true, false);
 
   static Reference<SudakovFormFactor,SudakovCutOff>
     interfaceCutoff("Cutoff",
 		   "A reference to the SudakovCutOff object",
 		   &Herwig::SudakovFormFactor::cutoff_,
 		   false, false, true, false);
 
   static Parameter<SudakovFormFactor,double> interfacePDFmax
     ("PDFmax",
      "Maximum value of PDF weight. ",
      &SudakovFormFactor::pdfmax_, 35.0, 1.0, 1000000.0,
      false, false, Interface::limited);
 
   static Switch<SudakovFormFactor,unsigned int> interfacePDFFactor
     ("PDFFactor",
      "Include additional factors in the overestimate for the PDFs",
      &SudakovFormFactor::pdffactor_, 0, false, false);
   static SwitchOption interfacePDFFactorNo
     (interfacePDFFactor,
      "No",
      "Don't include any factors",
      0);
   static SwitchOption interfacePDFFactorOverZ
     (interfacePDFFactor,
      "OverZ",
      "Include an additional factor of 1/z",
      1);
   static SwitchOption interfacePDFFactorOverOneMinusZ
     (interfacePDFFactor,
      "OverOneMinusZ",
      "Include an additional factor of 1/(1-z)",
      2);
   static SwitchOption interfacePDFFactorOverZOneMinusZ
     (interfacePDFFactor,
      "OverZOneMinusZ",
      "Include an additional factor of 1/z/(1-z)",
      3);
   static SwitchOption interfacePDFFactorOverRootZ
     (interfacePDFFactor,
      "OverRootZ",
      "Include an additional factor of 1/sqrt(z)",
      4);
   static SwitchOption interfacePDFFactorRootZ
     (interfacePDFFactor,
      "RootZ",
      "Include an additional factor of sqrt(z)",
      5);
 
 
 }
 
 bool SudakovFormFactor::alphaSVeto(Energy2 pt2) const {
   double ratio=alphaSVetoRatio(pt2,1.);
   return UseRandom::rnd() > ratio;
 }
 
 double SudakovFormFactor::alphaSVetoRatio(Energy2 pt2, double factor) const {
   factor *= ShowerHandler::currentHandler()->renormalizationScaleFactor();
   return alpha_->ratio(pt2, factor);
 }
 
 
 bool SudakovFormFactor::PDFVeto(const Energy2 t, const double x,
 	const tcPDPtr parton0, const tcPDPtr parton1,
 	Ptr<BeamParticleData>::transient_const_pointer beam) const {
   double ratio=PDFVetoRatio(t,x,parton0,parton1,beam,1.);
   return UseRandom::rnd() > ratio;
 }
 
 double SudakovFormFactor::PDFVetoRatio(const Energy2 t, const double x,
         const tcPDPtr parton0, const tcPDPtr parton1,
         Ptr<BeamParticleData>::transient_const_pointer beam,double factor) const {
   assert(pdf_);
   Energy2 theScale = t * sqr(ShowerHandler::currentHandler()->factorizationScaleFactor()*factor);
   if (theScale < sqr(freeze_)) theScale = sqr(freeze_);
 
   const double newpdf=pdf_->xfx(beam,parton0,theScale,x/z());
   if(newpdf<=0.) return 0.;
 
   const double oldpdf=pdf_->xfx(beam,parton1,theScale,x);
   if(oldpdf<=0.) return 1.;
   
   const double ratio = newpdf/oldpdf;
   double maxpdf = pdfmax_;
 
   switch (pdffactor_) {
   case 0: break;
   case 1: maxpdf /= z(); break;
   case 2: maxpdf /= 1.-z(); break;
   case 3: maxpdf /= (z()*(1.-z())); break;
   case 4: maxpdf /= sqrt(z()); break;
   case 5: maxpdf *= sqrt(z()); break;
   default :
     throw Exception() << "SudakovFormFactor::PDFVetoRatio invalid PDFfactor = "
 		      << pdffactor_ << Exception::runerror;
     
   }
 
   if (ratio > maxpdf) {
     generator()->log() << "PDFVeto warning: Ratio > " << name()
                        << ":PDFmax (by a factor of "
                        << ratio/maxpdf <<") for "
                        << parton0->PDGName() << " to "
                        << parton1->PDGName() << "\n";
   }
   return ratio/maxpdf ;
 }
 
 void SudakovFormFactor::addSplitting(const IdList & in) {
   bool add=true;
   for(unsigned int ix=0;ix<particles_.size();++ix) {
     if(particles_[ix].size()==in.size()) {
       bool match=true;
       for(unsigned int iy=0;iy<in.size();++iy) {
 	if(particles_[ix][iy]!=in[iy]) {
 	  match=false;
 	  break;
 	}
       }
       if(match) {
 	add=false;
 	break;
       }
     }
   }
   if(add) particles_.push_back(in);
 }
 
 void SudakovFormFactor::removeSplitting(const IdList & in) {
   for(vector<IdList>::iterator it=particles_.begin();
       it!=particles_.end();++it) {
     if(it->size()==in.size()) {
       bool match=true;
       for(unsigned int iy=0;iy<in.size();++iy) {
 	if((*it)[iy]!=in[iy]) {
 	  match=false;
 	  break;
 	}
       }
       if(match) {
 	vector<IdList>::iterator itemp=it;
 	--itemp;
 	particles_.erase(it);
 	it = itemp;
       }
     }
   }
 }
 
 void SudakovFormFactor::guesstz(Energy2 t1,unsigned int iopt,
 				  const IdList &ids,
 				  double enhance,bool ident,
 				  double detune, 
 				  Energy2 &t_main, double &z_main){
   unsigned int pdfopt = iopt!=1 ? 0 : pdffactor_;
   double lower = splittingFn_->integOverP(zlimits_.first ,ids,pdfopt);
   double upper = splittingFn_->integOverP(zlimits_.second,ids,pdfopt);
   double c = 1./((upper - lower)
            * alpha_->overestimateValue()/Constants::twopi*enhance*detune);
   double r = UseRandom::rnd();
   assert(iopt<=2);
   if(iopt==1) {
     c/=pdfmax_;
     //symmetry of FS gluon splitting
     if(ident) c*=0.5;
   }
   else if(iopt==2) c*=-1.;
 // guessing t
   if(iopt!=2 || c*log(r)<log(Constants::MaxEnergy2/t1)) {
     t_main = t1*pow(r,c);
   }
   else
     t_main = Constants::MaxEnergy2;
 // guessing z
   z_main = splittingFn_->invIntegOverP(lower + UseRandom::rnd()
          *(upper - lower),ids,pdfopt);
 }
 
 bool SudakovFormFactor::guessTimeLike(Energy2 &t,Energy2 tmin,double enhance,
 				  double detune) {
   Energy2 told = t;
   // calculate limits on z and if lower>upper return
   if(!computeTimeLikeLimits(t)) return false;
   // guess values of t and z
   guesstz(told,0,ids_,enhance,ids_[1]==ids_[2],detune,t,z_);
   // actual values for z-limits
   if(!computeTimeLikeLimits(t)) return false;
   if(t<tmin) {
     t=-1.0*GeV2;
     return false;
   }
   else
     return true; 
 } 
 
 bool SudakovFormFactor::guessSpaceLike(Energy2 &t, Energy2 tmin, const double x,
 				   double enhance,
 				   double detune) {
   Energy2 told = t;
   // calculate limits on z if lower>upper return
   if(!computeSpaceLikeLimits(t,x)) return false;
   // guess values of t and z
   guesstz(told,1,ids_,enhance,ids_[1]==ids_[2],detune,t,z_);
   // actual values for z-limits
   if(!computeSpaceLikeLimits(t,x)) return false;
   if(t<tmin) {
     t=-1.0*GeV2;
     return false;
   }
   else
     return true; 
 } 
 
 bool SudakovFormFactor::PSVeto(const Energy2 t) {
   // still inside PS, return true if outside
   // check vs overestimated limits
   if (z() < zlimits_.first || z() > zlimits_.second) return true;
 
   Energy2 m02 = (ids_[0]->id()!=ParticleID::g && ids_[0]->id()!=ParticleID::gamma) ?
   	masssquared_[0] : Energy2();
   
-  Energy2 pt2 = QTildeKinematics::pT2_FSR(t,z(),m02,masssquared_[1],masssquared_[2]);
+  Energy2 pt2 = QTildeKinematics::pT2_FSR(t,z(),m02,masssquared_[1],masssquared_[2],
+					  masssquared_[1],masssquared_[2]);
 
   // if pt2<0 veto
   if (pt2<cutoff_->pT2min()) return true;
   // otherwise calculate pt and return
   pT_ = sqrt(pt2);
   return false;
 }
 
 
  
 ShoKinPtr SudakovFormFactor::generateNextTimeBranching(const Energy startingScale,
 						   const IdList &ids,
 						   const RhoDMatrix & rho,
 						   double enhance,
 						   double detuning) {
   // First reset the internal kinematics variables that can
   // have been eventually set in the previous call to the method.
   q_ = ZERO;
   z_ = 0.;
   phi_ = 0.; 
   // perform initialization
   Energy2 tmax(sqr(startingScale)),tmin;
   initialize(ids,tmin);
   // check max > min
   if(tmax<=tmin) return ShoKinPtr();
   // calculate next value of t using veto algorithm
   Energy2 t(tmax);
   // no shower variations to calculate
   if(ShowerHandler::currentHandler()->showerVariations().empty()){
     // Without variations do the usual Veto algorithm
     // No need for more if-statements in this loop.
     do {
       if(!guessTimeLike(t,tmin,enhance,detuning)) break;
     }
     while(PSVeto(t) ||
         SplittingFnVeto(z()*(1.-z())*t,ids,true,rho,detuning) || 
         alphaSVeto(splittingFn()->pTScale() ? sqr(z()*(1.-z()))*t : z()*(1.-z())*t));
   }
   else {
     bool alphaRew(true),PSRew(true),SplitRew(true);
     do {
       if(!guessTimeLike(t,tmin,enhance,detuning)) break;
       PSRew=PSVeto(t);
       if (PSRew) continue;
       SplitRew=SplittingFnVeto(z()*(1.-z())*t,ids,true,rho,detuning);
       alphaRew=alphaSVeto(splittingFn()->pTScale() ? sqr(z()*(1.-z()))*t : z()*(1.-z())*t);
       double factor=alphaSVetoRatio(splittingFn()->pTScale() ? sqr(z()*(1.-z()))*t : z()*(1.-z())*t,1.)*
                     SplittingFnVetoRatio(z()*(1.-z())*t,ids,true,rho,detuning);
 
       tShowerHandlerPtr ch = ShowerHandler::currentHandler();
 
       if( !(SplitRew || alphaRew) ) {
         //Emission
         q_ = t > ZERO ? Energy(sqrt(t)) : -1.*MeV;
         if (q_ <= ZERO) break;
       }
 
         for ( map<string,ShowerVariation>::const_iterator var =
 	          ch->showerVariations().begin();
 	          var != ch->showerVariations().end(); ++var ) {
           if ( ( ch->firstInteraction() && var->second.firstInteraction ) ||
 	           ( !ch->firstInteraction() && var->second.secondaryInteractions ) ) {
 
                 double newfactor = alphaSVetoRatio(splittingFn()->pTScale() ?
                                         sqr(z()*(1.-z()))*t :
                                         z()*(1.-z())*t,var->second.renormalizationScaleFactor)
 		  * SplittingFnVetoRatio(z()*(1.-z())*t,ids,true,rho,detuning);
 
                 double varied;
                 if ( SplitRew || alphaRew ) {
                   // No Emission
                   varied = (1. - newfactor) / (1. - factor);
                 } else {
                   // Emission
                   varied = newfactor / factor;
                 }
 
                 map<string,double>::iterator wi = ch->currentWeights().find(var->first);
 	        if ( wi != ch->currentWeights().end() )
 	          wi->second *= varied;
 	        else {
                   assert(false);
                   //ch->currentWeights()[var->first] = varied;
                 }
 	  }
         }
       
     }
     while(PSRew || SplitRew || alphaRew);
   }
   q_ = t > ZERO ? Energy(sqrt(t)) : -1.*MeV;
   if(q_ < ZERO) return ShoKinPtr();
   
   // return the ShowerKinematics object
   return new_ptr(FS_QTildeShowerKinematics1to2(q_,z(),phi(),pT(),this)); 
 }
 
 ShoKinPtr SudakovFormFactor::
 generateNextSpaceBranching(const Energy startingQ,
 			   const IdList &ids,
 			   double x,
 			   const RhoDMatrix & rho,
 			   double enhance,
 			   Ptr<BeamParticleData>::transient_const_pointer beam,
 			   double detuning) {
   // First reset the internal kinematics variables that can
   // have been eventually set in the previous call to the method.
   q_ = ZERO;
   z_ = 0.;
   phi_ = 0.;
   // perform the initialization
   Energy2 tmax(sqr(startingQ)),tmin;
   initialize(ids,tmin);
   // check max > min
   if(tmax<=tmin) return ShoKinPtr();
   // calculate next value of t using veto algorithm
   Energy2 t(tmax),pt2(ZERO);
   // no shower variations
   if(ShowerHandler::currentHandler()->showerVariations().empty()){
     // Without variations do the usual Veto algorithm
     // No need for more if-statements in this loop.
     do {
       if(!guessSpaceLike(t,tmin,x,enhance,detuning)) break;
       pt2 = QTildeKinematics::pT2_ISR(t,z(),masssquared_[2]);
     }
     while(pt2 < cutoff_->pT2min()||
         z() > zlimits_.second||
 	  SplittingFnVeto((1.-z())*t/z(),ids,false,rho,detuning)||
         alphaSVeto(splittingFn()->pTScale() ? sqr(1.-z())*t : (1.-z())*t)||
         PDFVeto(t,x,ids[0],ids[1],beam));
   }
   // shower variations
   else
     {
     bool alphaRew(true),PDFRew(true),ptRew(true),zRew(true),SplitRew(true);
     do {
       if(!guessSpaceLike(t,tmin,x,enhance,detuning)) break;
       pt2 = QTildeKinematics::pT2_ISR(t,z(),masssquared_[2]);
       ptRew=pt2 < cutoff_->pT2min();
       zRew=z() > zlimits_.second;
       if (ptRew||zRew) continue;
       SplitRew=SplittingFnVeto((1.-z())*t/z(),ids,false,rho,detuning);
       alphaRew=alphaSVeto(splittingFn()->pTScale() ? sqr(1.-z())*t : (1.-z())*t);
       PDFRew=PDFVeto(t,x,ids[0],ids[1],beam);
       double factor=PDFVetoRatio(t,x,ids[0],ids[1],beam,1.)*
                     alphaSVetoRatio(splittingFn()->pTScale() ? sqr(1.-z())*t : (1.-z())*t,1.)*
 	SplittingFnVetoRatio((1.-z())*t/z(),ids,false,rho,detuning);
 
       tShowerHandlerPtr ch = ShowerHandler::currentHandler();
 
       if( !(PDFRew || SplitRew || alphaRew) ) {
         //Emission
         q_ = t > ZERO ? Energy(sqrt(t)) : -1.*MeV;
         if (q_ <= ZERO) break;
       }
 
         for ( map<string,ShowerVariation>::const_iterator var =
 	          ch->showerVariations().begin();
 	          var != ch->showerVariations().end(); ++var ) {
           if ( ( ch->firstInteraction() && var->second.firstInteraction ) ||
 	           ( !ch->firstInteraction() && var->second.secondaryInteractions ) ) {
 
 
 
             double newfactor = PDFVetoRatio(t,x,ids[0],ids[1],beam,var->second.factorizationScaleFactor)*
                            alphaSVetoRatio(splittingFn()->pTScale() ?
                            sqr(1.-z())*t : (1.-z())*t,var->second.renormalizationScaleFactor)
 	      *SplittingFnVetoRatio((1.-z())*t/z(),ids,false,rho,detuning);
 
             double varied;
             if( PDFRew || SplitRew || alphaRew) {
                 // No Emission
                 varied = (1. - newfactor) / (1. - factor);
             } else {
                 // Emission
                 varied = newfactor / factor;
             }
 
 
             map<string,double>::iterator wi = ch->currentWeights().find(var->first);
             if ( wi != ch->currentWeights().end() )
 	      wi->second *= varied;
 	    else {
 	      assert(false);
 	      //ch->currentWeights()[var->first] = varied;
             }
 	  }
         }
       
     }
     while( PDFRew || SplitRew || alphaRew);
   }
   if(t > ZERO && zlimits_.first < zlimits_.second)  q_ = sqrt(t);
   else return ShoKinPtr();
   
   pT_ = sqrt(pt2);
   // create the ShowerKinematics and return it
   return new_ptr(IS_QTildeShowerKinematics1to2(q_,z(),phi(),pT(),this)); 
 }
 
 void SudakovFormFactor::initialize(const IdList & ids, Energy2 & tmin) {
   ids_=ids;
   tmin = 4.*cutoff_->pT2min();
   masses_ = cutoff_->virtualMasses(ids);
   masssquared_.clear();
   for(unsigned int ix=0;ix<masses_.size();++ix) {
     masssquared_.push_back(sqr(masses_[ix]));
     if(ix>0) tmin=max(masssquared_[ix],tmin);
   }
 }
 
 ShoKinPtr SudakovFormFactor::generateNextDecayBranching(const Energy startingScale,
 						    const Energy stoppingScale,
 						    const Energy minmass,
 						    const IdList &ids,
 						    const RhoDMatrix & rho, 
 						    double enhance,
 						    double detuning) {
   // First reset the internal kinematics variables that can
   // have been eventually set in the previous call to this method.
   q_ = Constants::MaxEnergy;
   z_ = 0.;
   phi_ = 0.;
   // perform initialisation
   Energy2 tmax(sqr(stoppingScale)),tmin;
   initialize(ids,tmin);
   tmin=sqr(startingScale);
   // check some branching possible
   if(tmax<=tmin) return ShoKinPtr();
   // perform the evolution
   Energy2 t(tmin),pt2(-MeV2);
   do {
     if(!guessDecay(t,tmax,minmass,enhance,detuning)) break;
     pt2 = QTildeKinematics::pT2_Decay(t,z(),masssquared_[0],masssquared_[2]);
   }
   while(SplittingFnVeto((1.-z())*t/z(),ids,true,rho,detuning)|| 
 	alphaSVeto(splittingFn()->pTScale() ? sqr(1.-z())*t : (1.-z())*t ) ||
 	pt2<cutoff_->pT2min() ||
 	t*(1.-z())>masssquared_[0]-sqr(minmass));
   if(t > ZERO) {
     q_ = sqrt(t);
     pT_ = sqrt(pt2);
   }
   else return ShoKinPtr();
   phi_ = 0.;
   // create the ShowerKinematics object
   return new_ptr(Decay_QTildeShowerKinematics1to2(q_,z(),phi(),pT(),this)); 
 }
 
 bool SudakovFormFactor::guessDecay(Energy2 &t,Energy2 tmax, Energy minmass,
 			       double enhance, double detune) {
   // previous scale
   Energy2 told = t;
   // overestimated limits on z
   if(tmax<masssquared_[0]) {
     t=-1.0*GeV2;
     return false;
   }
   Energy2 tm2 = tmax-masssquared_[0];
   Energy tm  = sqrt(tm2); 
   zlimits_ = make_pair(sqr(minmass/masses_[0]),
 				       1.-sqrt(masssquared_[2]+cutoff_->pT2min()+
 					       0.25*sqr(masssquared_[2])/tm2)/tm
 				       +0.5*masssquared_[2]/tm2);
   if(zlimits_.second<zlimits_.first) {
     t=-1.0*GeV2;
     return false;
   }
   // guess values of t and z
   guesstz(told,2,ids_,enhance,ids_[1]==ids_[2],detune,t,z_);
   // actual values for z-limits
   if(t<masssquared_[0])  {
     t=-1.0*GeV2;
     return false;
   }
   tm2 = t-masssquared_[0];
   tm  = sqrt(tm2); 
   zlimits_ = make_pair(sqr(minmass/masses_[0]),
 		   1.-sqrt(masssquared_[2]+cutoff_->pT2min()+
 			   0.25*sqr(masssquared_[2])/tm2)/tm
 		   +0.5*masssquared_[2]/tm2);
   if(t>tmax||zlimits_.second<zlimits_.first) {
     t=-1.0*GeV2;
     return false;
   }
   else
     return true; 
 } 
 
 bool SudakovFormFactor::computeTimeLikeLimits(Energy2 & t) {
   if (t < 1e-20 * GeV2) {
     t=-1.*GeV2;
     return false;
   }
   const Energy2 pT2min = cutoff_->pT2min();
   // special case for gluon radiating
   if(ids_[0]->id()==ParticleID::g||ids_[0]->id()==ParticleID::gamma) {
     // no emission possible
     if(t<16.*(masssquared_[1]+pT2min)) {
       t=-1.*GeV2;
       return false;
     }
     // overestimate of the limits
     zlimits_.first  = 0.5*(1.-sqrt(1.-4.*sqrt((masssquared_[1]+pT2min)/t)));
     zlimits_.second = 1.-zlimits_.first;
   }
   // special case for radiated particle is gluon 
   else if(ids_[2]->id()==ParticleID::g||ids_[2]->id()==ParticleID::gamma) {
     zlimits_.first  =    sqrt((masssquared_[1]+pT2min)/t);
     zlimits_.second = 1.-sqrt((masssquared_[2]+pT2min)/t);
   }
   else if(ids_[1]->id()==ParticleID::g||ids_[1]->id()==ParticleID::gamma) {
     zlimits_.second  =    sqrt((masssquared_[2]+pT2min)/t);
     zlimits_.first   = 1.-sqrt((masssquared_[1]+pT2min)/t);
   }
   else {
     zlimits_.first  =    (masssquared_[1]+pT2min)/t;
     zlimits_.second = 1.-(masssquared_[2]+pT2min)/t; 
   }
   if(zlimits_.first>=zlimits_.second) {
     t=-1.*GeV2;
     return false;
   }
   return true;
 }
 
 bool SudakovFormFactor::computeSpaceLikeLimits(Energy2 & t, double x) {
   if (t < 1e-20 * GeV2) {
     t=-1.*GeV2;
     return false;
   }
   // compute the limits
   zlimits_.first = x;
   double yy = 1.+0.5*masssquared_[2]/t;
   zlimits_.second = yy - sqrt(sqr(yy)-1.+cutoff_->pT2min()/t); 
   // return false if lower>upper
   if(zlimits_.second<zlimits_.first) {
     t=-1.*GeV2;
     return false;
   }
   else
     return true;
 }
 
 namespace {
 
 tShowerParticlePtr findCorrelationPartner(ShowerParticle & particle,
 					  bool forward,
 					  ShowerInteraction inter) {
   tPPtr child = &particle;
   tShowerParticlePtr mother;
   if(forward) {
     mother = !particle.parents().empty() ? 
       dynamic_ptr_cast<tShowerParticlePtr>(particle.parents()[0]) : tShowerParticlePtr();
   }
   else {
     mother = particle.children().size()==2 ?
       dynamic_ptr_cast<tShowerParticlePtr>(&particle) : tShowerParticlePtr();
   }
   tShowerParticlePtr partner;
   while(mother) {
     tPPtr otherChild;
     if(forward) {
       for (unsigned int ix=0;ix<mother->children().size();++ix) {
 	if(mother->children()[ix]!=child) {
 	  otherChild = mother->children()[ix];
 	  break;
 	}
       }
     }
     else {
       otherChild = mother->children()[1];
     }
     tShowerParticlePtr other = dynamic_ptr_cast<tShowerParticlePtr>(otherChild);
     if((inter==ShowerInteraction::QCD && otherChild->dataPtr()->coloured()) ||
        (inter==ShowerInteraction::QED && otherChild->dataPtr()->charged())) {
       partner = other;
       break;
     }
     if(forward && !other->isFinalState()) {
       partner = dynamic_ptr_cast<tShowerParticlePtr>(mother);
       break;
     }
     child = mother;
     if(forward) {
       mother = ! mother->parents().empty() ?
 	dynamic_ptr_cast<tShowerParticlePtr>(mother->parents()[0]) : tShowerParticlePtr();
     }
     else {
       if(mother->children()[0]->children().size()!=2)
 	break;
       tShowerParticlePtr mtemp = 
 	dynamic_ptr_cast<tShowerParticlePtr>(mother->children()[0]);
       if(!mtemp)
 	break;
       else
 	mother=mtemp;
     }
   }
   if(!partner) {
     if(forward) {
       partner = dynamic_ptr_cast<tShowerParticlePtr>( child)->partner();
     }
     else {
       if(mother) {
 	tShowerParticlePtr parent;
 	if(!mother->children().empty()) {
 	  parent = dynamic_ptr_cast<tShowerParticlePtr>(mother->children()[0]);
 	}
 	if(!parent) {
 	  parent = dynamic_ptr_cast<tShowerParticlePtr>(mother);
 	}
 	partner = parent->partner();
       }
       else {
 	partner = dynamic_ptr_cast<tShowerParticlePtr>(&particle)->partner();
       }
     }
   }
   return partner;
 }
 
 pair<double,double> softPhiMin(double phi0, double phi1, double A, double B, double C, double D) {
   double c01 = cos(phi0 - phi1);
   double s01 = sin(phi0 - phi1);
   double s012(sqr(s01)), c012(sqr(c01));
   double A2(A*A), B2(B*B), C2(C*C), D2(D*D);
   if(abs(B/A)<1e-10 && abs(D/C)<1e-10) return make_pair(phi0,phi0+Constants::pi);
   double root = sqr(B2)*C2*D2*sqr(s012) + 2.*A*B2*B*C2*C*D*c01*s012 + 2.*A*B2*B*C*D2*D*c01*s012
 		     + 4.*A2*B2*C2*D2*c012 - A2*B2*C2*D2*s012 - A2*B2*sqr(D2)*s012 - sqr(B2)*sqr(C2)*s012 
 		     - sqr(B2)*C2*D2*s012 - 4.*A2*A*B*C*D2*D*c01 - 4.*A*B2*B*C2*C*D*c01 + sqr(A2)*sqr(D2)
 		     + 2.*A2*B2*C2*D2 + sqr(B2)*sqr(C2);
   if(root<0.) return make_pair(phi0,phi0+Constants::pi);
   root = sqrt(root);
   double denom  = (-2.*A*B*C*D*c01 + A2*D2 + B2*C2);
   double denom2 = (-B*C*c01 + A*D);
 
   double num    = B2*C*D*s012;
   double y1 = B*s01*(-C*(num + root) + D*denom) / denom2;
   double y2 = B*s01*(-C*(num - root) + D*denom) / denom2;
   double x1 = -(num + root );
   double x2 = -(num - root );
   if(denom<0.) {
     y1*=-1.;
     y2*=-1.;
     x1*=-1.;
     x2*=-1.;
   }
   return make_pair(atan2(y1,x1) + phi0,atan2(y2,x2) + phi0);
 }
 
 }
 
 double SudakovFormFactor::generatePhiForward(ShowerParticle & particle,
 					 const IdList & ids,
 					 ShoKinPtr kinematics,
 					 const RhoDMatrix & rho) {
   // no correlations, return flat phi
   if(! dynamic_ptr_cast<tcQTildeShowerHandlerPtr>(ShowerHandler::currentHandler())->correlations())
     return Constants::twopi*UseRandom::rnd();
   // get the kinematic variables
   double  z = kinematics->z();
   Energy2 t = z*(1.-z)*sqr(kinematics->scale());
   Energy pT = kinematics->pT();
   // if soft correlations
   Energy2 pipj,pik;
   bool canBeSoft[2] = {ids[1]->id()==ParticleID::g || ids[1]->id()==ParticleID::gamma,
 		       ids[2]->id()==ParticleID::g || ids[2]->id()==ParticleID::gamma };
   array<Energy2,3> pjk;
   array<Energy,3> Ek;
   Energy Ei,Ej;
   Energy2 m12(ZERO),m22(ZERO);
   InvEnergy2 aziMax(ZERO);
   bool softAllowed = dynamic_ptr_cast<tcQTildeShowerHandlerPtr>(ShowerHandler::currentHandler())->softCorrelations()&&
     (canBeSoft[0] || canBeSoft[1]);
   if(softAllowed) {
     // find the partner for the soft correlations
     tShowerParticlePtr partner=findCorrelationPartner(particle,true,splittingFn()->interactionType());
     // remember we want the softer gluon 
     bool swapOrder = !canBeSoft[1] || (canBeSoft[0] && canBeSoft[1] && z < 0.5);
     double zFact = !swapOrder ? (1.-z) : z;
     // compute the transforms to the shower reference frame
     // first the boost
     Lorentz5Momentum pVect = particle.showerBasis()->pVector();
     Lorentz5Momentum nVect = particle.showerBasis()->nVector();
     Boost beta_bb;
     if(particle.showerBasis()->frame()==ShowerBasis::BackToBack) {
       beta_bb = -(pVect + nVect).boostVector();
     }
     else if(particle.showerBasis()->frame()==ShowerBasis::Rest) {
       beta_bb = -pVect.boostVector();
     }
     else
       assert(false);
     pVect.boost(beta_bb);
     nVect.boost(beta_bb);
     Axis axis;
     if(particle.showerBasis()->frame()==ShowerBasis::BackToBack) {
       axis = pVect.vect().unit();
     }
     else if(particle.showerBasis()->frame()==ShowerBasis::Rest) {
       axis = nVect.vect().unit();
     }
     else
       assert(false);
     // and then the rotation
     LorentzRotation rot;
     if(axis.perp2()>0.) {
       double sinth(sqrt(sqr(axis.x())+sqr(axis.y())));
       rot.rotate(acos(axis.z()),Axis(-axis.y()/sinth,axis.x()/sinth,0.));
     }
     else if(axis.z()<0.) {
       rot.rotate(Constants::pi,Axis(1.,0.,0.));
     }
     rot.invert();
     pVect *= rot;
     nVect *= rot;
     // shower parameters
     Energy2 pn = pVect*nVect, m2 = pVect.m2();
     double alpha0 = particle.showerParameters().alpha;
     double  beta0 = 0.5/alpha0/pn*
       (sqr(particle.dataPtr()->mass())-sqr(alpha0)*m2+sqr(particle.showerParameters().pt));
     Lorentz5Momentum qperp0(particle.showerParameters().ptx,
 			    particle.showerParameters().pty,ZERO,ZERO);
     assert(partner);
     Lorentz5Momentum pj = partner->momentum();
     pj.boost(beta_bb);
     pj *= rot;
     // compute the two phi independent dot products
     pik = 0.5*zFact*(sqr(alpha0)*m2 - sqr(particle.showerParameters().pt) + 2.*alpha0*beta0*pn )
       +0.5*sqr(pT)/zFact;
     Energy2 dot1 = pj*pVect;
     Energy2 dot2 = pj*nVect;
     Energy2 dot3 = pj*qperp0;
     pipj = alpha0*dot1+beta0*dot2+dot3;
     // compute the constants for the phi dependent dot product
     pjk[0] = zFact*(alpha0*dot1+dot3-0.5*dot2/pn*(alpha0*m2-sqr(particle.showerParameters().pt)/alpha0))
       +0.5*sqr(pT)*dot2/pn/zFact/alpha0;
     pjk[1] = (pj.x() - dot2/alpha0/pn*qperp0.x())*pT;
     pjk[2] = (pj.y() - dot2/alpha0/pn*qperp0.y())*pT;
     m12 = sqr(particle.dataPtr()->mass());
     m22 = sqr(partner->dataPtr()->mass());
     if(swapOrder) {
       pjk[1] *= -1.;
       pjk[2] *= -1.;
     }
     Ek[0] = zFact*(alpha0*pVect.t()-0.5*nVect.t()/pn*(alpha0*m2-sqr(particle.showerParameters().pt)/alpha0))
       +0.5*sqr(pT)*nVect.t()/pn/zFact/alpha0;
     Ek[1] = -nVect.t()/alpha0/pn*qperp0.x()*pT;
     Ek[2] = -nVect.t()/alpha0/pn*qperp0.y()*pT;
     if(swapOrder) {
       Ek[1] *= -1.;
       Ek[2] *= -1.;
     }
     Energy mag2=sqrt(sqr(Ek[1])+sqr(Ek[2]));
     Ei = alpha0*pVect.t()+beta0*nVect.t();
     Ej = pj.t();
     double phi0 = atan2(-pjk[2],-pjk[1]);
     if(phi0<0.) phi0 += Constants::twopi;
     double phi1 = atan2(-Ek[2],-Ek[1]);
     if(phi1<0.) phi1 += Constants::twopi;
     double xi_min = pik/Ei/(Ek[0]+mag2), xi_max = pik/Ei/(Ek[0]-mag2), xi_ij = pipj/Ei/Ej;
     if(xi_min>xi_max) swap(xi_min,xi_max);
     if(xi_min>xi_ij) softAllowed = false;
     Energy2 mag = sqrt(sqr(pjk[1])+sqr(pjk[2]));
     if(dynamic_ptr_cast<tcQTildeShowerHandlerPtr>(ShowerHandler::currentHandler())->softCorrelations()==1) {
       aziMax = -m12/sqr(pik) -m22/sqr(pjk[0]+mag) +2.*pipj/pik/(pjk[0]-mag);
     }
     else if(dynamic_ptr_cast<tcQTildeShowerHandlerPtr>(ShowerHandler::currentHandler())->softCorrelations()==2) {
       double A = (pipj*Ek[0]- Ej*pik)/Ej/sqr(Ej);
       double B = -sqrt(sqr(pipj)*(sqr(Ek[1])+sqr(Ek[2])))/Ej/sqr(Ej);
       double C = pjk[0]/sqr(Ej);
       double D = -sqrt(sqr(pjk[1])+sqr(pjk[2]))/sqr(Ej);
       pair<double,double> minima = softPhiMin(phi0,phi1,A,B,C,D);
       aziMax = 0.5/pik/(Ek[0]-mag2)*(Ei-m12*(Ek[0]-mag2)/pik  + max(Ej*(A+B*cos(minima.first -phi1))/(C+D*cos(minima.first -phi0)),
 								    Ej*(A+B*cos(minima.second-phi1))/(C+D*cos(minima.second-phi0))));
     }
     else
       assert(false);
   }
   // if spin correlations
   vector<pair<int,Complex> > wgts;     
   if(dynamic_ptr_cast<tcQTildeShowerHandlerPtr>(ShowerHandler::currentHandler())->spinCorrelations()) {
     // calculate the weights
     wgts = splittingFn()->generatePhiForward(z,t,ids,rho);
   }
   else {
     wgts = {{ {0, 1.} }};
   }
   // generate the azimuthal angle
   double phi,wgt;
   static const Complex ii(0.,1.);
   unsigned int ntry(0);
   double phiMax(0.),wgtMax(0.);
   do {
     phi = Constants::twopi*UseRandom::rnd();
     // first the spin correlations bit (gives 1 if correlations off)
     Complex spinWgt = 0.;
     for(unsigned int ix=0;ix<wgts.size();++ix) {
       if(wgts[ix].first==0)
   	spinWgt += wgts[ix].second;
       else
   	spinWgt += exp(double(wgts[ix].first)*ii*phi)*wgts[ix].second;
     }
     wgt = spinWgt.real();
     if(wgt-1.>1e-10) {
       generator()->log() << "Forward spin weight problem " << wgt << " " << wgt-1. 
 			 << " " << ids[0]->id() << " " << ids[1]->id() << " " << ids[2]->id() << " " << " " << phi << "\n";
       generator()->log() << "Weights \n";
       for(unsigned int ix=0;ix<wgts.size();++ix)
 	generator()->log() << wgts[ix].first << " " << wgts[ix].second << "\n";
     }
     // soft correlations bit
     double aziWgt = 1.;
     if(softAllowed) {
       Energy2 dot = pjk[0]+pjk[1]*cos(phi)+pjk[2]*sin(phi);
       Energy  Eg  = Ek[0]+Ek[1]*cos(phi)+Ek[2]*sin(phi);
       if(pipj*Eg>pik*Ej) {
 	if(dynamic_ptr_cast<tcQTildeShowerHandlerPtr>(ShowerHandler::currentHandler())->softCorrelations()==1) {
 	  aziWgt = (-m12/sqr(pik) -m22/sqr(dot) +2.*pipj/pik/dot)/aziMax;
 	}
 	else if(dynamic_ptr_cast<tcQTildeShowerHandlerPtr>(ShowerHandler::currentHandler())->softCorrelations()==2) {
 	  aziWgt = max(ZERO,0.5/pik/Eg*(Ei-m12*Eg/pik  + (pipj*Eg - Ej*pik)/dot)/aziMax);
 	}
 	if(aziWgt-1.>1e-10||aziWgt<-1e-10) {
 	  generator()->log() << "Forward soft weight problem " << aziWgt << " " << aziWgt-1. 
 			     << " " << ids[0]->id() << " " << ids[1]->id() << " " << ids[2]->id() << " " << " " << phi << "\n";
 	}
       }
       else {
 	aziWgt = 0.;
       }
     }
     wgt *= aziWgt;
     if(wgt>wgtMax) {
       phiMax = phi;
       wgtMax = wgt;
     }
     ++ntry;
   }
   while(wgt<UseRandom::rnd()&&ntry<10000);
   if(ntry==10000) {
     generator()->log() << "Too many tries to generate phi in forward evolution\n";
     phi = phiMax;
   }
   // return the azimuthal angle
   return phi;
 }
 
 double SudakovFormFactor::generatePhiBackward(ShowerParticle & particle,
 					  const IdList & ids,
 					  ShoKinPtr kinematics,
 					  const RhoDMatrix & rho) {
   // no correlations, return flat phi
   if(! dynamic_ptr_cast<tcQTildeShowerHandlerPtr>(ShowerHandler::currentHandler())->correlations())
     return Constants::twopi*UseRandom::rnd();
   // get the kinematic variables
   double z = kinematics->z();
   Energy2 t = (1.-z)*sqr(kinematics->scale())/z;
   Energy pT = kinematics->pT();
   // if soft correlations 
   bool softAllowed = dynamic_ptr_cast<tcQTildeShowerHandlerPtr>(ShowerHandler::currentHandler())->softCorrelations() &&
     (ids[2]->id()==ParticleID::g || ids[2]->id()==ParticleID::gamma);
   Energy2 pipj,pik,m12(ZERO),m22(ZERO);
   array<Energy2,3> pjk;
   Energy Ei,Ej,Ek;
   InvEnergy2 aziMax(ZERO);
   if(softAllowed) {
     // find the partner for the soft correlations
     tShowerParticlePtr partner=findCorrelationPartner(particle,false,splittingFn()->interactionType());
     double zFact = (1.-z);
     // compute the transforms to the shower reference frame
     // first the boost
     Lorentz5Momentum pVect = particle.showerBasis()->pVector();
     Lorentz5Momentum nVect = particle.showerBasis()->nVector();
     assert(particle.showerBasis()->frame()==ShowerBasis::BackToBack);
     Boost beta_bb = -(pVect + nVect).boostVector();
     pVect.boost(beta_bb);
     nVect.boost(beta_bb);
     Axis axis = pVect.vect().unit();
     // and then the rotation
     LorentzRotation rot;
     if(axis.perp2()>0.) {
       double sinth(sqrt(sqr(axis.x())+sqr(axis.y())));
       rot.rotate(acos(axis.z()),Axis(-axis.y()/sinth,axis.x()/sinth,0.));
     }
     else if(axis.z()<0.) {
       rot.rotate(Constants::pi,Axis(1.,0.,0.));
     }
     rot.invert();
     pVect *= rot;
     nVect *= rot;
     // shower parameters
     Energy2 pn = pVect*nVect;
     Energy2 m2 = pVect.m2();
     double alpha0 = particle.x();
     double  beta0 = -0.5/alpha0/pn*sqr(alpha0)*m2;
     Lorentz5Momentum pj = partner->momentum();
     pj.boost(beta_bb);
     pj *= rot;
     double beta2 = 0.5*(1.-zFact)*(sqr(alpha0*zFact/(1.-zFact))*m2+sqr(pT))/alpha0/zFact/pn; 
     // compute the two phi independent dot products
     Energy2 dot1 = pj*pVect;
     Energy2 dot2 = pj*nVect;
     pipj = alpha0*dot1+beta0*dot2;
     pik  = alpha0*(alpha0*zFact/(1.-zFact)*m2+pn*(beta2+zFact/(1.-zFact)*beta0));
     // compute the constants for the phi dependent dot product
     pjk[0] = alpha0*zFact/(1.-zFact)*dot1+beta2*dot2;
     pjk[1] = pj.x()*pT;
     pjk[2] = pj.y()*pT;
     m12 = ZERO;
     m22 = sqr(partner->dataPtr()->mass());
     Energy2 mag = sqrt(sqr(pjk[1])+sqr(pjk[2]));
     if(dynamic_ptr_cast<tcQTildeShowerHandlerPtr>(ShowerHandler::currentHandler())->softCorrelations()==1) {
       aziMax = -m12/sqr(pik) -m22/sqr(pjk[0]+mag) +2.*pipj/pik/(pjk[0]-mag);
     }
     else if(dynamic_ptr_cast<tcQTildeShowerHandlerPtr>(ShowerHandler::currentHandler())->softCorrelations()==2) {
       Ek = alpha0*zFact/(1.-zFact)*pVect.t()+beta2*nVect.t();
       Ei = alpha0*pVect.t()+beta0*nVect.t();
       Ej = pj.t();
       if(pipj*Ek> Ej*pik) {
 	aziMax = 0.5/pik/Ek*(Ei-m12*Ek/pik  + (pipj*Ek- Ej*pik)/(pjk[0]-mag));
       }
       else {
 	aziMax = 0.5/pik/Ek*(Ei-m12*Ek/pik);
       }
     }
     else {
       assert(dynamic_ptr_cast<tcQTildeShowerHandlerPtr>(ShowerHandler::currentHandler())->softCorrelations()==0);
     }
   }
   // if spin correlations
   vector<pair<int,Complex> > wgts;
   if(dynamic_ptr_cast<tcQTildeShowerHandlerPtr>(ShowerHandler::currentHandler())->spinCorrelations()) {
     // get the weights
     wgts = splittingFn()->generatePhiBackward(z,t,ids,rho);
   }
   else {
     wgts = {{ {0, 1.} }};
   }
   // generate the azimuthal angle
   double phi,wgt;
   static const Complex ii(0.,1.);
   unsigned int ntry(0);
   double phiMax(0.),wgtMax(0.);
   do {
     phi = Constants::twopi*UseRandom::rnd();
     Complex spinWgt = 0.;
     for(unsigned int ix=0;ix<wgts.size();++ix) {
       if(wgts[ix].first==0)
   	spinWgt += wgts[ix].second;
       else
   	spinWgt += exp(double(wgts[ix].first)*ii*phi)*wgts[ix].second;
     }
     wgt = spinWgt.real();
     if(wgt-1.>1e-10) {
       generator()->log() << "Backward weight problem " << wgt << " " << wgt-1. 
 			 << " " << ids[0]->id() << " " << ids[1]->id() << " " << ids[2]->id() << " " << " " << z << " " << phi << "\n";
       generator()->log() << "Weights \n";
       for(unsigned int ix=0;ix<wgts.size();++ix)
   	generator()->log() << wgts[ix].first << " " << wgts[ix].second << "\n";
     }
     // soft correlations bit
     double aziWgt = 1.;
     if(softAllowed) {
       Energy2 dot = pjk[0]+pjk[1]*cos(phi)+pjk[2]*sin(phi);
       if(dynamic_ptr_cast<tcQTildeShowerHandlerPtr>(ShowerHandler::currentHandler())->softCorrelations()==1) {
 	aziWgt = (-m12/sqr(pik) -m22/sqr(dot) +2.*pipj/pik/dot)/aziMax;
       }
       else if(dynamic_ptr_cast<tcQTildeShowerHandlerPtr>(ShowerHandler::currentHandler())->softCorrelations()==2) {
 	aziWgt = max(ZERO,0.5/pik/Ek*(Ei-m12*Ek/pik  + pipj*Ek/dot - Ej*pik/dot)/aziMax);
       }
       if(aziWgt-1.>1e-10||aziWgt<-1e-10) {
  	generator()->log() << "Backward soft weight problem " << aziWgt << " " << aziWgt-1. 
  			   << " " << ids[0]->id() << " " << ids[1]->id() << " " << ids[2]->id() << " " << " " << phi << "\n";
       }
     }
     wgt *= aziWgt;
     if(wgt>wgtMax) {
       phiMax = phi;
       wgtMax = wgt;
     }
     ++ntry;
   }
   while(wgt<UseRandom::rnd()&&ntry<10000);
   if(ntry==10000) {
     generator()->log() << "Too many tries to generate phi in backward evolution\n";
     phi = phiMax;
   }
   // return the azimuthal angle
   return phi;
 }
 
 double SudakovFormFactor::generatePhiDecay(ShowerParticle & particle,
 				       const IdList & ids,
 				       ShoKinPtr kinematics,
 				       const RhoDMatrix &) {
   // only soft correlations in this case
   // no correlations, return flat phi
   if( !(dynamic_ptr_cast<tcQTildeShowerHandlerPtr>(ShowerHandler::currentHandler())->softCorrelations() &&
 	(ids[2]->id()==ParticleID::g || ids[2]->id()==ParticleID::gamma )))
     return Constants::twopi*UseRandom::rnd();
   // get the kinematic variables
   double  z = kinematics->z();
   Energy pT = kinematics->pT();
   // if soft correlations
   // find the partner for the soft correlations
   tShowerParticlePtr partner = findCorrelationPartner(particle,true,splittingFn()->interactionType());
   double zFact(1.-z);
   // compute the transforms to the shower reference frame
   // first the boost
   Lorentz5Momentum pVect = particle.showerBasis()->pVector();
   Lorentz5Momentum nVect = particle.showerBasis()->nVector();
   assert(particle.showerBasis()->frame()==ShowerBasis::Rest);
   Boost beta_bb = -pVect.boostVector();
   pVect.boost(beta_bb);
   nVect.boost(beta_bb);
   Axis axis = nVect.vect().unit();
   // and then the rotation
   LorentzRotation rot;
   if(axis.perp2()>0.) {
     double sinth(sqrt(sqr(axis.x())+sqr(axis.y())));
     rot.rotate(acos(axis.z()),Axis(-axis.y()/sinth,axis.x()/sinth,0.));
   }
   else if(axis.z()<0.) {
     rot.rotate(Constants::pi,Axis(1.,0.,0.));
   }
   rot.invert();
   pVect *= rot;
   nVect *= rot;
   // shower parameters
   Energy2 pn = pVect*nVect;
   Energy2 m2 = pVect.m2();
   double alpha0 = particle.showerParameters().alpha;
   double  beta0 = 0.5/alpha0/pn*
     (sqr(particle.dataPtr()->mass())-sqr(alpha0)*m2+sqr(particle.showerParameters().pt));
   Lorentz5Momentum qperp0(particle.showerParameters().ptx,
 			  particle.showerParameters().pty,ZERO,ZERO);
   Lorentz5Momentum pj = partner->momentum();
   pj.boost(beta_bb);
   pj *= rot;
   // compute the two phi independent dot products
   Energy2 pik = 0.5*zFact*(sqr(alpha0)*m2 - sqr(particle.showerParameters().pt) + 2.*alpha0*beta0*pn )
     +0.5*sqr(pT)/zFact;
   Energy2 dot1 = pj*pVect;
   Energy2 dot2 = pj*nVect;
   Energy2 dot3 = pj*qperp0;
   Energy2 pipj = alpha0*dot1+beta0*dot2+dot3;
   // compute the constants for the phi dependent dot product
   array<Energy2,3> pjk;
   pjk[0] = zFact*(alpha0*dot1+dot3-0.5*dot2/pn*(alpha0*m2-sqr(particle.showerParameters().pt)/alpha0))
     +0.5*sqr(pT)*dot2/pn/zFact/alpha0;
   pjk[1] = (pj.x() - dot2/alpha0/pn*qperp0.x())*pT;
   pjk[2] = (pj.y() - dot2/alpha0/pn*qperp0.y())*pT;
   Energy2 m12 = sqr(particle.dataPtr()->mass());
   Energy2 m22 = sqr(partner->dataPtr()->mass());
   Energy2 mag = sqrt(sqr(pjk[1])+sqr(pjk[2]));
   InvEnergy2 aziMax;
   array<Energy,3> Ek;
   Energy Ei,Ej;
   if(dynamic_ptr_cast<tcQTildeShowerHandlerPtr>(ShowerHandler::currentHandler())->softCorrelations()==1) {
     aziMax = -m12/sqr(pik) -m22/sqr(pjk[0]+mag) +2.*pipj/pik/(pjk[0]-mag);
   }
   else if(dynamic_ptr_cast<tcQTildeShowerHandlerPtr>(ShowerHandler::currentHandler())->softCorrelations()==2) {
     Ek[0] = zFact*(alpha0*pVect.t()+-0.5*nVect.t()/pn*(alpha0*m2-sqr(particle.showerParameters().pt)/alpha0))
       +0.5*sqr(pT)*nVect.t()/pn/zFact/alpha0;
     Ek[1] = -nVect.t()/alpha0/pn*qperp0.x()*pT;
     Ek[2] = -nVect.t()/alpha0/pn*qperp0.y()*pT;
     Energy mag2=sqrt(sqr(Ek[1])+sqr(Ek[2]));
     Ei = alpha0*pVect.t()+beta0*nVect.t();
     Ej = pj.t();
     aziMax = 0.5/pik/(Ek[0]-mag2)*(Ei-m12*(Ek[0]-mag2)/pik  + pipj*(Ek[0]+mag2)/(pjk[0]-mag) - Ej*pik/(pjk[0]-mag) );
   }
   else
     assert(dynamic_ptr_cast<tcQTildeShowerHandlerPtr>(ShowerHandler::currentHandler())->softCorrelations()==0);
   // generate the azimuthal angle
   double phi,wgt(0.);
   unsigned int ntry(0);
   double phiMax(0.),wgtMax(0.);
   do {
     phi = Constants::twopi*UseRandom::rnd();
     Energy2 dot = pjk[0]+pjk[1]*cos(phi)+pjk[2]*sin(phi);
     if(dynamic_ptr_cast<tcQTildeShowerHandlerPtr>(ShowerHandler::currentHandler())->softCorrelations()==1) {
       wgt = (-m12/sqr(pik) -m22/sqr(dot) +2.*pipj/pik/dot)/aziMax;
     }
     else if(dynamic_ptr_cast<tcQTildeShowerHandlerPtr>(ShowerHandler::currentHandler())->softCorrelations()==2) {
       if(qperp0.m2()==ZERO) {
 	wgt = 1.;
       }
       else {
 	Energy Eg = Ek[0]+Ek[1]*cos(phi)+Ek[2]*sin(phi);
 	wgt = max(ZERO,0.5/pik/Eg*(Ei-m12*Eg/pik  + (pipj*Eg - Ej*pik)/dot)/aziMax);
       }	
     }
     if(wgt-1.>1e-10||wgt<-1e-10) {
       generator()->log() << "Decay soft weight problem " << wgt << " " << wgt-1. 
 			 << " " << ids[0]->id() << " " << ids[1]->id() << " " << ids[2]->id() << " " << " " << phi << "\n";
     }
     if(wgt>wgtMax) {
       phiMax = phi;
       wgtMax = wgt;
     }
     ++ntry;
   }
   while(wgt<UseRandom::rnd()&&ntry<10000);
   if(ntry==10000) {
     phi = phiMax;
     generator()->log() << "Too many tries to generate phi\n";
   }
   // return the azimuthal angle
   return phi;
 }
 
 
 Energy SudakovFormFactor::calculateScale(double zin, Energy pt, IdList ids,
 				     unsigned int iopt) {
   Energy2 tmin;
   initialize(ids,tmin);
   // final-state branching
   if(iopt==0) {
     Energy2 scale=(sqr(pt)+masssquared_[1]*(1.-zin)+masssquared_[2]*zin);
     if(ids[0]->id()!=ParticleID::g) scale -= zin*(1.-zin)*masssquared_[0];
     scale /= sqr(zin*(1-zin));
     return scale<=ZERO ? sqrt(tmin) : sqrt(scale);
   }
   else if(iopt==1) {
     Energy2 scale=(sqr(pt)+zin*masssquared_[2])/sqr(1.-zin);
     return scale<=ZERO ? sqrt(tmin) : sqrt(scale);
   }
   else if(iopt==2) {
     Energy2 scale = (sqr(pt)+zin*masssquared_[2])/sqr(1.-zin)+masssquared_[0];
     return scale<=ZERO ? sqrt(tmin) : sqrt(scale);
   }
   else {
     throw Exception() << "Unknown option in SudakovFormFactor::calculateScale() "
 		      << "iopt = " << iopt << Exception::runerror;
   }
 }
diff --git a/Tests/Makefile.am b/Tests/Makefile.am
--- a/Tests/Makefile.am
+++ b/Tests/Makefile.am
@@ -1,392 +1,370 @@
 AM_LDFLAGS += -module -avoid-version -rpath /dummy/path/not/used
 
 EXTRA_DIST = Inputs python Rivet 
 
 EXTRA_LTLIBRARIES = LeptonTest.la GammaTest.la HadronTest.la DISTest.la
 
 if WANT_LIBFASTJET
 EXTRA_LTLIBRARIES += HadronJetTest.la LeptonJetTest.la
 HadronJetTest_la_SOURCES = \
 Hadron/VHTest.h Hadron/VHTest.cc\
 Hadron/VTest.h Hadron/VTest.cc\
 Hadron/HTest.h Hadron/HTest.cc
 HadronJetTest_la_CPPFLAGS = $(AM_CPPFLAGS) $(FASTJETINCLUDE) \
 -I$(FASTJETPATH)
 HadronJetTest_la_LIBADD = $(FASTJETLIBS) 
 LeptonJetTest_la_SOURCES = \
 Lepton/TopDecay.h Lepton/TopDecay.cc
 LeptonJetTest_la_CPPFLAGS = $(AM_CPPFLAGS) $(FASTJETINCLUDE) \
 -I$(FASTJETPATH)
 LeptonJetTest_la_LIBADD = $(FASTJETLIBS) 
 endif
 
 LeptonTest_la_SOURCES = \
 Lepton/VVTest.h Lepton/VVTest.cc \
 Lepton/VBFTest.h Lepton/VBFTest.cc \
 Lepton/VHTest.h Lepton/VHTest.cc \
 Lepton/FermionTest.h Lepton/FermionTest.cc
 
 GammaTest_la_SOURCES = \
 Gamma/GammaMETest.h  Gamma/GammaMETest.cc \
 Gamma/GammaPMETest.h Gamma/GammaPMETest.cc
 
 DISTest_la_SOURCES = \
 DIS/DISTest.h  DIS/DISTest.cc
 
 HadronTest_la_SOURCES = \
 Hadron/HadronVVTest.h  Hadron/HadronVVTest.cc\
 Hadron/HadronVBFTest.h  Hadron/HadronVBFTest.cc\
 Hadron/WHTest.h  Hadron/WHTest.cc\
 Hadron/ZHTest.h  Hadron/ZHTest.cc\
 Hadron/VGammaTest.h  Hadron/VGammaTest.cc\
 Hadron/ZJetTest.h  Hadron/ZJetTest.cc\
 Hadron/WJetTest.h  Hadron/WJetTest.cc\
 Hadron/QQHTest.h  Hadron/QQHTest.cc
 
 
 REPO = $(top_builddir)/src/HerwigDefaults.rpo
 HERWIG = $(top_builddir)/src/Herwig
 HWREAD = $(HERWIG) read --repo $(REPO) -L $(builddir)/.libs -i $(top_builddir)/src
 HWBUILD = $(HERWIG) build --repo $(REPO) -L $(builddir)/.libs -i $(top_builddir)/src
 HWINTEGRATE = $(HERWIG) integrate
 HWRUN = $(HERWIG) run -N $${NUMEVENTS:-10000}
 
 
 tests : tests-LEP tests-DIS tests-LHC tests-Gamma
 
 
 LEPDEPS = \
 test-LEP-VV \
 test-LEP-VH \
 test-LEP-VBF \
 test-LEP-BB \
 test-LEP-Quarks \
 test-LEP-Leptons
 
 if WANT_LIBFASTJET
 LEPDEPS += test-LEP-TopDecay
 endif
 
 tests-LEP : $(LEPDEPS)
 
 tests-DIS : test-DIS-Charged test-DIS-Neutral
 
 
 LHCDEPS = \
 test-LHC-WW test-LHC-WZ test-LHC-ZZ \
 test-LHC-ZGamma test-LHC-WGamma \
 test-LHC-ZH test-LHC-WH \
 test-LHC-ZJet test-LHC-WJet \
 test-LHC-Z test-LHC-W \
 test-LHC-ZZVBF test-LHC-VBF \
 test-LHC-WWVBF \
 test-LHC-bbH test-LHC-ttH \
 test-LHC-GammaGamma test-LHC-GammaJet \
 test-LHC-Higgs test-LHC-HiggsJet \
 test-LHC-QCDFast test-LHC-QCD \
 test-LHC-Top
 
 
 if WANT_LIBFASTJET
 LHCDEPS += \
 test-LHC-Bottom \
 test-LHC-WHJet test-LHC-ZHJet test-LHC-HJet \
 test-LHC-ZShower test-LHC-WShower \
 test-LHC-WHJet-Powheg test-LHC-ZHJet-Powheg test-LHC-HJet-Powheg \
 test-LHC-ZShower-Powheg test-LHC-WShower-Powheg
 endif
 
 tests-LHC : $(LHCDEPS) 
 
 tests-Gamma : test-Gamma-FF test-Gamma-WW test-Gamma-P
 
 
 
 LEPLIBS = LeptonTest.la
 HADLIBS = HadronTest.la
 
 if WANT_LIBFASTJET 
 LEPLIBS += LeptonJetTest.la
 HADLIBS += HadronJetTest.la
 endif
 
 
 test-LEP-% : Inputs/LEP-%.in $(LEPLIBS)
 	$(HWREAD) $<
 	$(HWRUN) $(notdir $(subst .in,.run,$<))
 
 test-Gamma-% : Inputs/Gamma-%.in GammaTest.la
 	$(HWREAD) $<
 	$(HWRUN) $(notdir $(subst .in,.run,$<))
 
 test-DIS-% : Inputs/DIS-%.in DISTest.la
 	$(HWREAD) $<
 	$(HWRUN) $(notdir $(subst .in,.run,$<))
 
 test-LHC-% : Inputs/LHC-%.in GammaTest.la $(HADLIBS)
 	$(HWREAD) $<
 	$(HWRUN) $(notdir $(subst .in,.run,$<))
 
 
 
 
 
 
 
 tests-Rivet : Rivet-LEP Rivet-BFactory Rivet-DIS Rivet-Star Rivet-SppS \
 		Rivet-TVT-WZ Rivet-TVT-Photon Rivet-TVT-Jets \
 		Rivet-LHC-Jets Rivet-LHC-EW Rivet-LHC-Photon Rivet-LHC-Higgs
 
 
 
 Rivet-%.run : Rivet/%.in
 	$(HWBUILD) -c .cache/$(subst .run,,$@) $<
 
 Rivet-Matchbox-%.yoda : Rivet-Matchbox-%.run
 	$(HWINTEGRATE) -c .cache/$(subst .run,,$<) $<
 	$(HWRUN)       -c .cache/$(subst .run,,$<) $<
 
 Rivet-%.yoda : Rivet-%.run
 	$(HWRUN) $<
 
 Rivet/%.in :
 	python/make_input_files.py $(notdir $(subst .in,,$@))
 
 
 
 Rivet-inputfiles: $(shell echo Rivet/LEP{,-Powheg,-Matchbox,-Dipole,-Dipole-MCatNLO,-Dipole-Matchbox-Powheg,-Matchbox-Powheg,-Merging}-{9.4,12,13,17,27.6,29,30.2,30.7,30.75,30,31.3,34.8,43.6,50,52,55,56,57,60.8,60,61.4,10,12.8,22,26.8,35,44,48.0,91,93.0,130,133,136,161,172,177,183,189,192,196,197,200,202,206,91-nopi}.in) \
                   $(shell echo Rivet/LEP{,-Dipole,-Dipole-MCatNLO,-Dipole-Matchbox-Powheg,-Powheg,-Matchbox-Powheg}-14.in) \
 	          $(shell echo Rivet/LEP{,-Dipole}-{10.5,11.96,12.8,13.96,16.86,21.84,26.8,28.48,35.44,48.0,97.0}-gg.in) \
                   $(shell echo Rivet/BFactory{,-Powheg,-Matchbox,-Dipole,-Dipole-MCatNLO,-Dipole-Matchbox-Powheg,-Matchbox-Powheg}-{10.52,10.52-sym,10.54,10.45}.in) \
                   $(shell echo Rivet/BFactory{,-Dipole}-{Upsilon,Upsilon2,Upsilon4,Tau,10.58-res}.in) \
                   $(shell echo Rivet/DIS{,-NoME,-Powheg,-Matchbox,-Dipole,-Dipole-MCatNLO,-Dipole-Matchbox-Powheg,-Matchbox-Powheg,-Merging}-{e--LowQ2,e+-LowQ2,e+-HighQ2}.in) \
                   $(shell echo Rivet/TVT{,-Powheg,-Matchbox,-Dipole,-Dipole-MCatNLO,-Dipole-Matchbox-Powheg,-Matchbox-Powheg,-Merging}-{Run-I-Z,Run-I-W,Run-I-WZ,Run-II-Z-e,Run-II-Z-{,LowMass-,HighMass-}mu,Run-II-W}.in) \
 	          $(shell echo Rivet/TVT{,-Dipole}-Run-II-{DiPhoton-GammaGamma,DiPhoton-GammaJet,PromptPhoton}.in) \
 	          $(shell echo Rivet/TVT-Powheg-Run-II-{DiPhoton-GammaGamma,DiPhoton-GammaJet}.in) \
                   $(shell echo Rivet/TVT{,-Dipole,-Dipole-MCatNLO,-Dipole-Matchbox-Powheg,-Matchbox,-Matchbox-Powheg,-Merging}-{Run-II-Jets-{0..11},Run-I-Jets-{1..8}}.in ) \
 	          $(shell echo Rivet/TVT{,-Dipole,-Dipole-MCatNLO,-Dipole-Matchbox-Powheg,-Matchbox,-Matchbox-Powheg,-Merging}-{630-Jets-{1..3},300-Jets-1,900-Jets-1}.in ) \
                   $(shell echo Rivet/TVT{,-Dipole}-{Run-I,Run-II,300,630,900}-UE.in) \
                   $(shell echo Rivet/LHC{,-Dipole,-Dipole-MCatNLO,-Dipole-Matchbox-Powheg,-Matchbox,-Matchbox-Powheg,-Merging}-7-DiJets-{1..7}-{A,B,C}.in ) \
                   $(shell echo Rivet/LHC{,-Dipole,-Dipole-MCatNLO,-Dipole-Matchbox-Powheg,-Matchbox,-Matchbox-Powheg,-Merging}-{7,8,13}-Jets-{0..10}.in ) \
 	          $(shell echo Rivet/LHC{,-Dipole}-{900,2360,2760,7,8,13}-UE.in ) \
 	          $(shell echo Rivet/LHC{,-Dipole}-{900,7,13}-UE-Long.in ) \
 		  $(shell echo Rivet/LHC{,-Dipole,-Dipole-MCatNLO,-Dipole-Matchbox-Powheg,-Matchbox,-Matchbox-Powheg,-Merging}-7-Charm-{1..5}.in) \
 		  $(shell echo Rivet/LHC{,-Dipole,-Dipole-MCatNLO,-Dipole-Matchbox-Powheg,-Matchbox,-Matchbox-Powheg,-Merging}-7-Bottom-{0..8}.in) \
-		  $(shell echo Rivet/LHC{,-Dipole,-Dipole-MCatNLO,-Dipole-Matchbox-Powheg,-Matchbox,-Matchbox-Powheg,-Merging}-{7,8,13}-Top-{All,L,SL}.in) \
+		  $(shell echo Rivet/LHC{,-Dipole,-Dipole-MCatNLO,-Dipole-Matchbox-Powheg,-Matchbox,-Matchbox-Powheg,-Merging}-7-Top-{L,SL}.in) \
+		  $(shell echo Rivet/LHC{,-Dipole,-Dipole-MCatNLO,-Dipole-Matchbox-Powheg,-Matchbox,-Matchbox-Powheg,-Merging}-{8,13}-Top-{All,L,SL}.in) \
                   $(shell echo Rivet/Star{,-Dipole}-{UE,Jets-{1..4}}.in ) \
 	          $(shell echo Rivet/SppS{,-Dipole}-{200,500,900,546}-UE.in ) \
                   $(shell echo Rivet/LHC{,-Matchbox,-Matchbox-Powheg,-Powheg,-Dipole,-Dipole-MCatNLO,-Dipole-Matchbox-Powheg,-Merging}-{W-{e,mu},13-Z-{e,mu},Z-HighMass{1,2}-e,{8,13}-W-mu,8-Z-Mass{1..4}-{e,mu},Z-{e,mu,mu-SOPHTY},Z-LowMass-{e,mu},Z-MedMass-e,WZ,WW-{emu,ll},ZZ-{ll,lv},{8,13}-WZ,8-ZZ-lv,8-WW-ll,W-Z-{e,mu}}.in) \
                   $(shell echo Rivet/LHC{,-Dipole}-7-{W,Z}Gamma-{e,mu}.in) \
 	          $(shell echo Rivet/LHC{,-Matchbox,-Matchbox-Powheg,-Dipole,-Dipole-MCatNLO,-Dipole-Matchbox-Powheg,-Merging}-{7-W-Jet-{1..3}-e,7-Z-Jet-{0..3}-e,7-Z-Jet-0-mu}.in) \
 	          $(shell echo Rivet/LHC{-Matchbox,-Matchbox-Powheg,-Dipole-MCatNLO,-Dipole-Matchbox-Powheg,-Merging}-{Z-b,Z-bb,8-Z-b,8-Z-bb,W-b,8-Z-jj}.in) \
-		  $(shell echo Rivet/LHC{,-Dipole}-{7,8}-PromptPhoton-{1..4}.in) Rivet/LHC-GammaGamma-7.in \
+		  $(shell echo Rivet/LHC{,-Dipole}-{7,8,13}-PromptPhoton-{1..4}.in) Rivet/LHC-GammaGamma-7.in \
 	          $(shell echo Rivet/LHC{,-Powheg}-{7,8}-{DiPhoton-GammaGamma,DiPhoton-GammaJet}.in) \
 	          $(shell echo Rivet/LHC{,-Powheg,-Matchbox,-Matchbox-Powheg,-Dipole,-Dipole-MCatNLO,-Dipole-Matchbox-Powheg,-Merging}-{ggH,VBF,WH,ZH}.in) \
                   $(shell echo Rivet/LHC{,-Powheg,-Matchbox,-Matchbox-Powheg,-Dipole,-Dipole-MCatNLO,-Dipole-Matchbox-Powheg,-Merging}-8-{{ggH,VBF,WH,ZH}{,-GammaGamma},ggH-WW}.in) \
                   $(shell echo Rivet/LHC{,-Matchbox,-Matchbox-Powheg,-Dipole,-Dipole-MCatNLO,-Dipole-Matchbox-Powheg,-Merging}-ggHJet.in)
 #                  $(shell echo Rivet/ISR-{30,44,53,62}-UE.in ) $(shell echo Rivet/SppS-{53,63}-UE.in )
 
 
 
 Rivet-LEP : Rivet-LEP/done
 	touch $@
 
 Rivet-LEP/done : $(shell echo Rivet-LEP-{9.4,12,13,14,17,27.6,29,30.2,30.7,30.75,30,31.3,34.8,43.6,50,52,55,56,57,60.8,60,61.4,10,12.8,22,26.8,35,44,48.0,91,93.0,130,133,136,161,172,177,183,189,192,196,197,200,202,206,91-nopi}.yoda) \
 	   $(shell echo Rivet-LEP-{10.5,11.96,12.8,13.96,16.86,21.84,26.8,28.48,35.44,48.0,97.0}-gg.yoda)
 	rm -rf Rivet-LEP
 	python/merge-LEP --with-gg LEP
 	rivet-mkhtml -o Rivet-LEP LEP.yoda:Hw 
 	touch $@
 
 
 
 
 Rivet-BFactory : Rivet-BFactory/done
 	touch $@
 
 Rivet-BFactory/done: $(shell echo Rivet-BFactory-{10.52,10.52-sym,10.54,10.45,Upsilon,Upsilon2,Upsilon4,Tau,10.58-res,10.58}.yoda)
 	rm -rf Rivet-BFactory
 	python/merge-BFactory BFactory
 	rivet-mkhtml -o Rivet-BFactory BFactory.yoda:Hw
 	touch $@
 
 
 
 Rivet-DIS : Rivet-DIS/done
 	touch $@
 
 Rivet-DIS/done: $(shell echo Rivet{-DIS,-DIS-NoME,-Powheg-DIS,-Matchbox-DIS,-Dipole-DIS}-{e--LowQ2,e+-LowQ2,e+-HighQ2}.yoda)
 	rm -rf Rivet-DIS
 	python/merge-DIS DIS 
 	python/merge-DIS Powheg-DIS
 	python/merge-DIS DIS-NoME
 	python/merge-DIS Matchbox-DIS
 	python/merge-DIS Dipole-DIS
 	rivet-mkhtml -o Rivet-DIS DIS.yoda:Hw Powheg-DIS.yoda:Hw-Powheg DIS-NoME.yoda:Hw-NoME Matchbox-DIS.yoda:Hw-Matchbox Dipole-DIS.yoda:Hw-Dipole
 	touch $@
 
 
 
 Rivet-TVT-EW : Rivet-TVT-EW/done
 	touch $@
 
-Rivet-TVT-EW/done:  $(shell echo Rivet{,-Powheg,-Matchbox,-Dipole}-TVT-{Run-I-Z,Run-I-W,Run-I-WZ,Run-II-Z-{e,{,LowMass-,HighMass-}mu},Run-II-W}.yoda)
-	rm -rf Rivet-TVT-WZ
+Rivet-TVT-EW/done:  $(shell echo Rivet{,-Powheg}-TVT-{Run-I-Z,Run-I-W,Run-I-WZ,Run-II-Z-{e,{,LowMass-,HighMass-}mu},Run-II-W}.yoda)
+	rm -rf Rivet-TVT-EW
 	python/merge-TVT-EW TVT
-	python/merge-TVT-EW TVT-Powheg
-	python/merge-TVT-EW TVT-Matchbox
-	python/merge-TVT-EW TVT-Dipole
-	rivet-mkhtml -o Rivet-TVT-EW TVT-EW.yoda:Hw TVT-Powheg-EW.yoda:Hw-Powheg TVT-Matchbox-EW.yoda:Hw-Matchbox TVT-Dipole-EW.yoda:Hw-Dipole
+	python/merge-TVT-EW Powheg-TVT
+	rivet-mkhtml -o Rivet-TVT-EW TVT-EW.yoda:Hw Powheg-TVT-EW.yoda:Hw-Powheg
 	touch $@
 
-
-
 Rivet-TVT-Photon : Rivet-TVT-Photon/done
 	touch $@
 
-Rivet-TVT-Photon/done: $(shell echo Rivet-TVT-Run-II-{DiPhoton-GammaGamma,DiPhoton-GammaJet,PromptPhoton}.yoda) \
-                  $(shell echo Rivet-Powheg-TVT-Run-II-{DiPhoton-GammaGamma,DiPhoton-GammaJet}.yoda)
+Rivet-TVT-Photon/done: $(shell echo Rivet{,-Powheg}-TVT-Run-II-{DiPhoton-GammaGamma,DiPhoton-GammaJet}.yoda Rivet-TVT-Run-II-PromptPhoton.yoda)
 	rm -rf Rivet-TVT-Photon
 	python/merge-TVT-Photon TVT
-	python/merge-TVT-Photon TVT-Powheg
-	rivet-mkhtml -o Rivet-TVT-Photon TVT-Photon.yoda:Hw TVT-Powheg-Photon.yoda:Hw-Powheg
+	python/merge-TVT-Photon Powheg-TVT
+	rivet-mkhtml -o Rivet-TVT-Photon TVT-Photon.yoda:Hw Powheg-TVT-Photon.yoda:Hw-Powheg
 	touch $@
 
 
 
 Rivet-TVT-Jets : Rivet-TVT-Jets/done
 	touch $@
 
 Rivet-TVT-Jets/done:  $(shell echo Rivet-TVT-{Run-II-Jets-{0..11},Run-I-Jets-{1..8}}.yoda ) \
 	         $(shell echo Rivet-TVT-{630-Jets-{1..3},300-Jets-1,900-Jets-1}.yoda ) \
                  $(shell echo Rivet-TVT-{Run-I,Run-II,300,630,900}-UE.yoda)
 	rm -rf Rivet-TVT-Jets
 	python/merge-TVT-Jets TVT
 	rivet-mkhtml -o Rivet-TVT-Jets TVT-Jets.yoda:Hw
 	touch $@
 
-
-
-
-#python/merge-TVT-Energy TVT
-#rivet-merge-CDF_2012_NOTE10874 TVT-300-Energy.yoda TVT-900-Energy.yoda TVT-1960-Energy.yoda
-#flat2yoda RatioPlots.dat -o TVT-RatioPlots.yoda
-
-
-
-
-
 Rivet-Star : Rivet-Star/done
 	touch $@
 
 Rivet-Star/done : $(shell echo Rivet-Star-{UE,Jets-{1..4}}.yoda ) 
 	rm -rf Rivet-Star
 	python/merge-Star Star
-	## broken DVI? ## rivet-mkhtml -v -o Rivet-Star Star.yoda
-	mkdir -p Rivet-Star # remove when fixed
+	rivet-mkhtml -o Rivet-Star Star.yoda
 	touch $@
 
 
 
 Rivet-SppS : Rivet-SppS/done
 	touch $@
 
 ## $(shell echo Rivet-ISR-{30,44,53,62}-UE.yoda ) \
 ## {53,63,200,500,900,546}
 
 Rivet-SppS/done : $(shell echo Rivet-SppS-{200,500,900,546}-UE.yoda )
 	rm -rf Rivet-SppS
 	python/merge-SppS SppS
 	rivet-mkhtml -o Rivet-SppS SppS.yoda
 	touch $@
 
 
 
 
 
 
 Rivet-LHC-Jets : Rivet-LHC-Jets/done
 	touch $@
 
 Rivet-LHC-Jets/done : \
 			$(shell echo Rivet-LHC-7-DiJets-{1..7}-{A,B,C}.yoda   ) \
 	        $(shell echo Rivet-LHC-{7,8,13}-Jets-{0..10}.yoda     ) \
+	        $(shell echo Rivet-LHC-2760-Jets-{1..3}.yoda     ) \
 	        $(shell echo Rivet-LHC-{900,2360,2760,7,8,13}-UE.yoda ) \
 	        $(shell echo Rivet-LHC-{900,7,13}-UE-Long.yoda        ) \
 		$(shell echo Rivet-LHC-7-Charm-{1..5}.yoda            ) \
 		$(shell echo Rivet-LHC-7-Bottom-{0..8}.yoda           ) \
 		$(shell echo Rivet-LHC-{7,8,13}-Top-{L,SL}.yoda ) \
-		$(shell echo Rivet-LHC-{7,8}-Top-All.yoda )
+		$(shell echo Rivet-LHC-{8,13}-Top-All.yoda )
 	rm -rf Rivet-LHC-Jets
 	python/merge-LHC-Jets LHC
 	rivet-mkhtml -o Rivet-LHC-Jets LHC-Jets.yoda:Hw
 	touch $@
 
 
 
 Rivet-LHC-EW : Rivet-LHC-EW/done
 	touch $@
 
 Rivet-LHC-EW/done: \
-		$(shell echo Rivet{,-Matchbox,-Powheg,-Dipole}-LHC-{13-Z-{e,mu},{8,13}-W-mu,Z-HighMass{1,2}-e,8-Z-Mass{1..4}-{e,mu},W-{e,mu},Z-{e,mu,mu-SOPHTY},Z-LowMass-{e,mu},Z-MedMass-e,WZ,WW-{emu,ll},ZZ-{ll,lv},{8,13}-WZ,8-ZZ-lv,8-WW-ll,W-Z-{e,mu}}.yoda) \
-		$(shell echo Rivet{,-Matchbox,-Dipole}-LHC-{7-W-Jet-{1..3}-e,7-Z-Jet-{0..3}-e,7-Z-Jet-0-mu}.yoda) \
-		$(shell echo Rivet{-Matchbox,-Dipole}-LHC-{Z-b,Z-bb,8-Z-b,8-Z-bb,W-b,8-Z-jj}.yoda) \
+		$(shell echo Rivet{,-Powheg}-LHC-{13-Z-{e,mu},{8,13}-W-mu,Z-HighMass{1,2}-e,8-Z-Mass{1..4}-{e,mu},W-{e,mu},Z-{e,mu,mu-SOPHTY},Z-LowMass-{e,mu},Z-MedMass-e,WZ,WW-{emu,ll},ZZ-{ll,lv},{8,13}-WZ,8-ZZ-lv,8-WW-ll,W-Z-{e,mu}}.yoda) \
+		$(shell echo Rivet-LHC-{7-W-Jet-{1..3}-e,7-Z-Jet-{0..3}-e,7-Z-Jet-0-mu}.yoda) \
 		$(shell echo Rivet-LHC-7-{W,Z}Gamma-{e,mu}.yoda) 
 	rm -rf Rivet-LHC-EW;
 	python/merge-LHC-EW LHC
-	python/merge-LHC-EW LHC-Matchbox
-	python/merge-LHC-EW LHC-Dipole
-	python/merge-LHC-EW LHC-Powheg
-	rivet-mkhtml -o Rivet-LHC-EW LHC-EW.yoda:Hw LHC-Powheg-EW.yoda:Hw-Powheg LHC-Matchbox-EW.yoda:Hw-Matchbox LHC-Matchbox-Z-b.yoda:Hw-Matchbox-Zb \
-                                     LHC-Matchbox-Z-bb.yoda:Hw-Matchbox-Zbb LHC-Matchbox-W-b.yoda:Hw-Matchbox-W-bb LHC-Dipole-EW.yoda:Hw-Dipole \
-                                     LHC-Dipole-Z-b.yoda:Hw-Dipole-Zb LHC-Dipole-Z-bb.yoda:Hw-Dipole-Zbb LHC-Dipole-W-b.yoda:Hw-Dipole-W-bb \
-                                     LHC-Z-mu-SOPHTY.yoda:Hw LHC-Powheg-Z-mu-SOPHTY.yoda:Hw-Powheg LHC-Matchbox-Z-mu-SOPHTY.yoda:Hw-Matchbox \
-                                     LHC-Matchbox-8-Z-b.yoda:Hw-Matchbox-Zb LHC-Matchbox-8-Z-bb.yoda:Hw-Matchbox-Zbb \
-                                     LHC-Dipole-8-Z-b.yoda:Hw-Dipole-Zb LHC-Dipole-8-Z-bb.yoda:Hw-Dipole-Zbb
+	python/merge-LHC-EW Powheg-LHC
+	rivet-mkhtml -o Rivet-LHC-EW LHC-EW.yoda:Hw Powheg-LHC-EW.yoda:Hw-Powheg \
+                                     LHC-Z-mu-SOPHTY.yoda:Hw Powheg-LHC-Z-mu-SOPHTY.yoda:Hw-Powheg
 	touch $@
 
 
 
 
 Rivet-LHC-Photon : Rivet-LHC-Photon/done
 	touch $@
 
 Rivet-LHC-Photon/done: \
-		$(shell echo Rivet-LHC-{7,8}-PromptPhoton-{1..4}.yoda) \
+		$(shell echo Rivet-LHC-{7,8,13}-PromptPhoton-{1..4}.yoda) \
 		Rivet-LHC-GammaGamma-7.yoda \
 	    $(shell echo Rivet{,-Powheg}-LHC-{7,8}-{DiPhoton-GammaGamma,DiPhoton-GammaJet}.yoda)
 	rm -rf Rivet-LHC-Photon
 	python/merge-LHC-Photon LHC
-	python/merge-LHC-Photon LHC-Powheg
-	rivet-mkhtml -o Rivet-LHC-Photon LHC-Photon.yoda:Hw LHC-Powheg-Photon.yoda:Hw-Powheg
+	python/merge-LHC-Photon Powheg-LHC
+	rivet-mkhtml -o Rivet-LHC-Photon LHC-Photon.yoda:Hw Powheg-LHC-Photon.yoda:Hw-Powheg
 	touch $@
 
 
 
 
 Rivet-LHC-Higgs : Rivet-LHC-Higgs/done
 	touch $@
 
 Rivet-LHC-Higgs/done:  \
 		$(shell echo Rivet{,-Powheg}-LHC-{ggH,VBF,WH,ZH}.yoda) \
         $(shell echo Rivet{,-Powheg}-LHC-8-{{ggH,VBF,WH,ZH}{,-GammaGamma},ggH-WW}.yoda) \
         Rivet-LHC-ggHJet.yoda
-	yodamerge Rivet-Powheg-LHC-8-{ggH{-GammaGamma,-WW,},{VBF,ZH,WH}{,-GammaGamma}}.yoda -o LHC-Powheg-Higgs.yoda
+	yodamerge Rivet-Powheg-LHC-8-{ggH{-GammaGamma,-WW,},{VBF,ZH,WH}{,-GammaGamma}}.yoda -o Powheg-LHC-Higgs.yoda
 	yodamerge Rivet-LHC-8-{ggH{-GammaGamma,-WW,},{VBF,ZH,WH}{,-GammaGamma}}.yoda -o LHC-Higgs.yoda
 	rm -rf Rivet-LHC-Higgs
-	rivet-mkhtml -o Rivet-LHC-Higgs LHC-Powheg-Higgs.yoda:Hw-Powheg LHC-Higgs.yoda:Hw\
+	rivet-mkhtml -o Rivet-LHC-Higgs Powheg-LHC-Higgs.yoda:Hw-Powheg LHC-Higgs.yoda:Hw\
 	                Rivet-Powheg-LHC-ggH.yoda:gg-Powheg Rivet-LHC-ggH.yoda:gg Rivet-LHC-ggHJet.yoda:HJet \
                         Rivet-Powheg-LHC-VBF.yoda:VBF-Powheg Rivet-LHC-VBF.yoda:VBF Rivet-LHC-WH.yoda:WH Rivet-LHC-ZH.yoda:ZH \
                         Rivet-Powheg-LHC-WH.yoda:WH-Powheg Rivet-Powheg-LHC-ZH.yoda:ZH-Powheg
 	touch $@
 
 
 
 
 
 clean-local:
 	rm -f *.out *.log *.tex *.top *.run *.dump *.mult *.Bmult *.yoda Rivet/*.in 
 	rm -rf Rivet-*
 
 distclean-local:
 	rm -rf .cache
diff --git a/Tests/Rivet/LHC/LHC-8-PromptPhoton-1.in b/Tests/Rivet/LHC/LHC-13-PromptPhoton-1.in
copy from Tests/Rivet/LHC/LHC-8-PromptPhoton-1.in
copy to Tests/Rivet/LHC/LHC-13-PromptPhoton-1.in
--- a/Tests/Rivet/LHC/LHC-8-PromptPhoton-1.in
+++ b/Tests/Rivet/LHC/LHC-13-PromptPhoton-1.in
@@ -1,7 +1,5 @@
 ##################################################
 # select the analyses
 ##################################################
 # ATLAS prompt photon
-insert /Herwig/Analysis/RivetAnalysis:Analyses 0 ATLAS_2016_I1457605
-# ATLAS prompt photon + heavy flavour
-insert /Herwig/Analysis/RivetAnalysis:Analyses 0 ATLAS_2017_I1632756
+insert /Herwig/Analysis/RivetAnalysis:Analyses 0 ATLAS_2017_I1645627
diff --git a/Tests/Rivet/LHC/LHC-8-PromptPhoton-1.in b/Tests/Rivet/LHC/LHC-13-PromptPhoton-2.in
copy from Tests/Rivet/LHC/LHC-8-PromptPhoton-1.in
copy to Tests/Rivet/LHC/LHC-13-PromptPhoton-2.in
--- a/Tests/Rivet/LHC/LHC-8-PromptPhoton-1.in
+++ b/Tests/Rivet/LHC/LHC-13-PromptPhoton-2.in
@@ -1,7 +1,5 @@
 ##################################################
 # select the analyses
 ##################################################
 # ATLAS prompt photon
-insert /Herwig/Analysis/RivetAnalysis:Analyses 0 ATLAS_2016_I1457605
-# ATLAS prompt photon + heavy flavour
-insert /Herwig/Analysis/RivetAnalysis:Analyses 0 ATLAS_2017_I1632756
+insert /Herwig/Analysis/RivetAnalysis:Analyses 0 ATLAS_2017_I1645627
diff --git a/Tests/Rivet/LHC/LHC-8-PromptPhoton-1.in b/Tests/Rivet/LHC/LHC-13-PromptPhoton-3.in
copy from Tests/Rivet/LHC/LHC-8-PromptPhoton-1.in
copy to Tests/Rivet/LHC/LHC-13-PromptPhoton-3.in
--- a/Tests/Rivet/LHC/LHC-8-PromptPhoton-1.in
+++ b/Tests/Rivet/LHC/LHC-13-PromptPhoton-3.in
@@ -1,7 +1,5 @@
 ##################################################
 # select the analyses
 ##################################################
 # ATLAS prompt photon
-insert /Herwig/Analysis/RivetAnalysis:Analyses 0 ATLAS_2016_I1457605
-# ATLAS prompt photon + heavy flavour
-insert /Herwig/Analysis/RivetAnalysis:Analyses 0 ATLAS_2017_I1632756
+insert /Herwig/Analysis/RivetAnalysis:Analyses 0 ATLAS_2017_I1645627
diff --git a/Tests/Rivet/LHC/LHC-8-PromptPhoton-1.in b/Tests/Rivet/LHC/LHC-13-PromptPhoton-4.in
copy from Tests/Rivet/LHC/LHC-8-PromptPhoton-1.in
copy to Tests/Rivet/LHC/LHC-13-PromptPhoton-4.in
--- a/Tests/Rivet/LHC/LHC-8-PromptPhoton-1.in
+++ b/Tests/Rivet/LHC/LHC-13-PromptPhoton-4.in
@@ -1,7 +1,5 @@
 ##################################################
 # select the analyses
 ##################################################
 # ATLAS prompt photon
-insert /Herwig/Analysis/RivetAnalysis:Analyses 0 ATLAS_2016_I1457605
-# ATLAS prompt photon + heavy flavour
-insert /Herwig/Analysis/RivetAnalysis:Analyses 0 ATLAS_2017_I1632756
+insert /Herwig/Analysis/RivetAnalysis:Analyses 0 ATLAS_2017_I1645627
diff --git a/Tests/Rivet/LHC/LHC-2760-Jets-1.in b/Tests/Rivet/LHC/LHC-2760-Jets-1.in
new file mode 100644
--- /dev/null
+++ b/Tests/Rivet/LHC/LHC-2760-Jets-1.in
@@ -0,0 +1,5 @@
+##################################################
+# select the analyses
+##################################################
+# underlying event
+insert /Herwig/Analysis/RivetAnalysis:Analyses 0 CMS_2015_I1385107
diff --git a/Tests/Rivet/LHC/LHC-2760-Jets-2.in b/Tests/Rivet/LHC/LHC-2760-Jets-2.in
new file mode 100644
--- /dev/null
+++ b/Tests/Rivet/LHC/LHC-2760-Jets-2.in
@@ -0,0 +1,5 @@
+##################################################
+# select the analyses
+##################################################
+# underlying event
+insert /Herwig/Analysis/RivetAnalysis:Analyses 0 CMS_2015_I1385107
diff --git a/Tests/Rivet/LHC/LHC-2760-Jets-3.in b/Tests/Rivet/LHC/LHC-2760-Jets-3.in
new file mode 100644
--- /dev/null
+++ b/Tests/Rivet/LHC/LHC-2760-Jets-3.in
@@ -0,0 +1,5 @@
+##################################################
+# select the analyses
+##################################################
+# underlying event
+insert /Herwig/Analysis/RivetAnalysis:Analyses 0 CMS_2015_I1385107
diff --git a/Tests/Rivet/LHC/LHC-7-Jets-0.in b/Tests/Rivet/LHC/LHC-7-Jets-0.in
--- a/Tests/Rivet/LHC/LHC-7-Jets-0.in
+++ b/Tests/Rivet/LHC/LHC-7-Jets-0.in
@@ -1,17 +1,15 @@
 ##################################################
 # select the analyses
 ##################################################
 # CMS jet cross section
 insert /Herwig/Analysis/RivetAnalysis:Analyses 0 CMS_2011_S9086218
 # ATLAS track jet
 insert /Herwig/Analysis/RivetAnalysis:Analyses 0 ATLAS_2011_I919017
 # CMS central and forward jets
 insert /Herwig/Analysis/RivetAnalysis:Analyses 0 CMS_2012_I1087342
 # ATLAS charged particle in min bias
 insert /Herwig/Analysis/RivetAnalysis:Analyses 0 ATLAS_2012_I1125575
-# CMS Jet/UE properties
-insert /Herwig/Analysis/RivetAnalysis:Analyses 0 CMS_2013_I1261026
 # ATLAS leading jet UE
 insert /Herwig/Analysis/RivetAnalysis:Analyses 0 ATLAS_2014_I1298811
 # CMS Jets
 insert /Herwig/Analysis/RivetAnalysis:Analyses 0 CMS_2013_I1208923
\ No newline at end of file
diff --git a/Tests/Rivet/LHC/LHC-7-Top-All.in b/Tests/Rivet/LHC/LHC-7-Top-All.in
deleted file mode 100644
--- a/Tests/Rivet/LHC/LHC-7-Top-All.in
+++ /dev/null
@@ -1,7 +0,0 @@
-##################################################
-# select the analyses
-##################################################
-# ATLAS b-jet shapes in top events
-insert /Herwig/Analysis/RivetAnalysis:Analyses 0 ATLAS_2014_I1304688
-# ATLAS top cross sections
-insert /Herwig/Analysis/RivetAnalysis:Analyses 0 ATLAS_2015_I1345452
diff --git a/Tests/Rivet/LHC/LHC-7-Top-SL.in b/Tests/Rivet/LHC/LHC-7-Top-SL.in
--- a/Tests/Rivet/LHC/LHC-7-Top-SL.in
+++ b/Tests/Rivet/LHC/LHC-7-Top-SL.in
@@ -1,7 +1,14 @@
 ##################################################
 # select the analyses
 ##################################################
 # MC analysis
 insert /Herwig/Analysis/RivetAnalysis:Analyses 0 MC_TTBAR
 # ATLAS b-jet shapes in top events
 insert /Herwig/Analysis/RivetAnalysis:Analyses 0 ATLAS_2013_I1243871
+##################################################
+# select the analyses
+##################################################
+# ATLAS b-jet shapes in top events
+insert /Herwig/Analysis/RivetAnalysis:Analyses 0 ATLAS_2014_I1304688
+# ATLAS top cross sections
+insert /Herwig/Analysis/RivetAnalysis:Analyses 0 ATLAS_2015_I1345452
diff --git a/Tests/Rivet/LHC/LHC-7-WGamma-e.in b/Tests/Rivet/LHC/LHC-7-WGamma-e.in
--- a/Tests/Rivet/LHC/LHC-7-WGamma-e.in
+++ b/Tests/Rivet/LHC/LHC-7-WGamma-e.in
@@ -1,3 +1,2 @@
 # ATLAS W Gamma analysis
-insert /Herwig/Analysis/RivetAnalysis:Analyses 0 ATLAS_2013_I1217863_W 
-insert /Herwig/Analysis/RivetAnalysis:Analyses 0 ATLAS_2013_I1217863_W_EL 
\ No newline at end of file
+insert /Herwig/Analysis/RivetAnalysis:Analyses 0 ATLAS_2013_I1217863:LMODE=WEL 
\ No newline at end of file
diff --git a/Tests/Rivet/LHC/LHC-7-WGamma-mu.in b/Tests/Rivet/LHC/LHC-7-WGamma-mu.in
--- a/Tests/Rivet/LHC/LHC-7-WGamma-mu.in
+++ b/Tests/Rivet/LHC/LHC-7-WGamma-mu.in
@@ -1,2 +1,2 @@
 # ATLAS W Gamma analysis
-insert /Herwig/Analysis/RivetAnalysis:Analyses 0 ATLAS_2013_I1217863_W_MU 
\ No newline at end of file
+insert /Herwig/Analysis/RivetAnalysis:Analyses 0 ATLAS_2013_I1217863:LMODE=WMU 
\ No newline at end of file
diff --git a/Tests/Rivet/LHC/LHC-7-ZGamma-e.in b/Tests/Rivet/LHC/LHC-7-ZGamma-e.in
--- a/Tests/Rivet/LHC/LHC-7-ZGamma-e.in
+++ b/Tests/Rivet/LHC/LHC-7-ZGamma-e.in
@@ -1,3 +1,2 @@
 # ATLAS Z Gamma analysis
-insert /Herwig/Analysis/RivetAnalysis:Analyses 0 ATLAS_2013_I1217863_Z
-insert /Herwig/Analysis/RivetAnalysis:Analyses 0 ATLAS_2013_I1217863_Z_EL
+insert /Herwig/Analysis/RivetAnalysis:Analyses 0 ATLAS_2013_I1217863:LMODE=ZEL
diff --git a/Tests/Rivet/LHC/LHC-7-ZGamma-mu.in b/Tests/Rivet/LHC/LHC-7-ZGamma-mu.in
--- a/Tests/Rivet/LHC/LHC-7-ZGamma-mu.in
+++ b/Tests/Rivet/LHC/LHC-7-ZGamma-mu.in
@@ -1,2 +1,2 @@
 # ATLAS Z Gamma analysis
-insert /Herwig/Analysis/RivetAnalysis:Analyses 0 ATLAS_2013_I1217863_Z_MU
+insert /Herwig/Analysis/RivetAnalysis:Analyses 0 ATLAS_2013_I1217863:LMODE=ZMU
diff --git a/Tests/Rivet/LHC/LHC-8-Top-L.in b/Tests/Rivet/LHC/LHC-8-Top-L.in
--- a/Tests/Rivet/LHC/LHC-8-Top-L.in
+++ b/Tests/Rivet/LHC/LHC-8-Top-L.in
@@ -1,18 +1,17 @@
 ##################################################
 # select the analyses
 ##################################################
 # ATLAS top + b jet
 insert /Herwig/Analysis/RivetAnalysis:Analyses 0 ATLAS_2015_I1390114
 # CMS
 insert /Herwig/Analysis/RivetAnalysis:Analyses 0 CMS_2015_I1397174
 # ATLAS l +jets
 insert /Herwig/Analysis/RivetAnalysis:Analyses 0 ATLAS_2015_I1397635 
 # ATLAS charge asymmetry
 insert /Herwig/Analysis/RivetAnalysis:Analyses 0 ATLAS_2016_I1449082
 # CMS diplepton charge asym
 insert /Herwig/Analysis/RivetAnalysis:Analyses 0 CMS_2016_I1430892
 # CMS spin correlations
 insert /Herwig/Analysis/RivetAnalysis:Analyses 0 CMS_2016_I1413748
-insert /Herwig/Analysis/RivetAnalysis:Analyses 0 ATLAS_2015_I1404878
 # ATLAS lepton distributions
 insert /Herwig/Analysis/RivetAnalysis:Analyses 0 ATLAS_2017_I1626105
diff --git a/Tests/Rivet/LHC/LHC-8-Z-Mass1-e.in b/Tests/Rivet/LHC/LHC-8-Z-Mass1-e.in
--- a/Tests/Rivet/LHC/LHC-8-Z-Mass1-e.in
+++ b/Tests/Rivet/LHC/LHC-8-Z-Mass1-e.in
@@ -1,5 +1,5 @@
 ##################################################
 # select the analyses
 ##################################################
 # ATLAS Z pT and phi*
-insert /Herwig/Analysis/RivetAnalysis:Analyses 0 ATLAS_2015_I1408516_EL
+insert /Herwig/Analysis/RivetAnalysis:Analyses 0 ATLAS_2015_I1408516:LMODE=EL
diff --git a/Tests/Rivet/LHC/LHC-8-Z-Mass1-mu.in b/Tests/Rivet/LHC/LHC-8-Z-Mass1-mu.in
--- a/Tests/Rivet/LHC/LHC-8-Z-Mass1-mu.in
+++ b/Tests/Rivet/LHC/LHC-8-Z-Mass1-mu.in
@@ -1,5 +1,5 @@
 ##################################################
 # select the analyses
 ##################################################
 # ATLAS Z pT and phi*
-insert /Herwig/Analysis/RivetAnalysis:Analyses 0 ATLAS_2015_I1408516_MU
+insert /Herwig/Analysis/RivetAnalysis:Analyses 0 ATLAS_2015_I1408516:LMODE=MU
diff --git a/Tests/Rivet/LHC/LHC-8-Z-Mass2-e.in b/Tests/Rivet/LHC/LHC-8-Z-Mass2-e.in
--- a/Tests/Rivet/LHC/LHC-8-Z-Mass2-e.in
+++ b/Tests/Rivet/LHC/LHC-8-Z-Mass2-e.in
@@ -1,5 +1,5 @@
 ##################################################
 # select the analyses
 ##################################################
 # ATLAS Z pT and phi*
-insert /Herwig/Analysis/RivetAnalysis:Analyses 0 ATLAS_2015_I1408516_EL
+insert /Herwig/Analysis/RivetAnalysis:Analyses 0 ATLAS_2015_I1408516:LMODE=EL
diff --git a/Tests/Rivet/LHC/LHC-8-Z-Mass2-mu.in b/Tests/Rivet/LHC/LHC-8-Z-Mass2-mu.in
--- a/Tests/Rivet/LHC/LHC-8-Z-Mass2-mu.in
+++ b/Tests/Rivet/LHC/LHC-8-Z-Mass2-mu.in
@@ -1,5 +1,5 @@
 ##################################################
 # select the analyses
 ##################################################
 # ATLAS Z pT and phi*
-insert /Herwig/Analysis/RivetAnalysis:Analyses 0 ATLAS_2015_I1408516_MU
+insert /Herwig/Analysis/RivetAnalysis:Analyses 0 ATLAS_2015_I1408516:LMODE=MU
diff --git a/Tests/Rivet/LHC/LHC-8-Z-Mass3-e.in b/Tests/Rivet/LHC/LHC-8-Z-Mass3-e.in
--- a/Tests/Rivet/LHC/LHC-8-Z-Mass3-e.in
+++ b/Tests/Rivet/LHC/LHC-8-Z-Mass3-e.in
@@ -1,11 +1,11 @@
 ##################################################
 # select the analyses
 ##################################################
 # ATLAS Z pT and phi*
-insert /Herwig/Analysis/RivetAnalysis:Analyses 0 ATLAS_2015_I1408516_EL
+insert /Herwig/Analysis/RivetAnalysis:Analyses 0 ATLAS_2015_I1408516:LMODE=EL
 # ATLAS high mass drell-yan
-insert /Herwig/Analysis/RivetAnalysis:Analyses 0 ATLAS_2016_I1467454_EL
+insert /Herwig/Analysis/RivetAnalysis:Analyses 0 ATLAS_2016_I1467454:LMODE=EL
 # ATLAS splittings
-insert /Herwig/Analysis/RivetAnalysis:Analyses 0 ATLAS_2017_I1589844_EL
+insert /Herwig/Analysis/RivetAnalysis:Analyses 0 ATLAS_2017_I1589844:LMODE=EL
 # CMS Z+b
 insert /Herwig/Analysis/RivetAnalysis:Analyses 0 CMS_2017_I1499471
\ No newline at end of file
diff --git a/Tests/Rivet/LHC/LHC-8-Z-Mass3-mu.in b/Tests/Rivet/LHC/LHC-8-Z-Mass3-mu.in
--- a/Tests/Rivet/LHC/LHC-8-Z-Mass3-mu.in
+++ b/Tests/Rivet/LHC/LHC-8-Z-Mass3-mu.in
@@ -1,11 +1,11 @@
 ##################################################
 # select the analyses
 ##################################################
 # ATLAS Z + dijets
 insert /Herwig/Analysis/RivetAnalysis:Analyses 0 ATLAS_2014_I1279489
 # ATLAS Z pT and phi*
-insert /Herwig/Analysis/RivetAnalysis:Analyses 0 ATLAS_2015_I1408516_MU
+insert /Herwig/Analysis/RivetAnalysis:Analyses 0 ATLAS_2015_I1408516:LMODE=MU
 # ATLAS high mass drell-yan
-insert /Herwig/Analysis/RivetAnalysis:Analyses 0 ATLAS_2016_I1467454_MU
+insert /Herwig/Analysis/RivetAnalysis:Analyses 0 ATLAS_2016_I1467454:LMODE=MU
 # ATLAS splittings rivet problem with this at the moment)
-#insert /Herwig/Analysis/RivetAnalysis:Analyses 0 ATLAS_2017_I1589844_MU
\ No newline at end of file
+#insert /Herwig/Analysis/RivetAnalysis:Analyses 0 ATLAS_2017_I1589844:LMODE=MU
\ No newline at end of file
diff --git a/Tests/Rivet/LHC/LHC-8-Z-Mass4-e.in b/Tests/Rivet/LHC/LHC-8-Z-Mass4-e.in
--- a/Tests/Rivet/LHC/LHC-8-Z-Mass4-e.in
+++ b/Tests/Rivet/LHC/LHC-8-Z-Mass4-e.in
@@ -1,8 +1,8 @@
 ##################################################
 # select the analyses
 ##################################################
 # ATLAS Z pT and phi*
-insert /Herwig/Analysis/RivetAnalysis:Analyses 0 ATLAS_2015_I1408516_EL
+insert /Herwig/Analysis/RivetAnalysis:Analyses 0 ATLAS_2015_I1408516:LMODE=EL
 # ATLAS high mass drell-yan
-insert /Herwig/Analysis/RivetAnalysis:Analyses 0 ATLAS_2016_I1467454_EL
+insert /Herwig/Analysis/RivetAnalysis:Analyses 0 ATLAS_2016_I1467454:LMODE=EL
 
diff --git a/Tests/Rivet/LHC/LHC-8-Z-Mass4-mu.in b/Tests/Rivet/LHC/LHC-8-Z-Mass4-mu.in
--- a/Tests/Rivet/LHC/LHC-8-Z-Mass4-mu.in
+++ b/Tests/Rivet/LHC/LHC-8-Z-Mass4-mu.in
@@ -1,8 +1,8 @@
 ##################################################
 # select the analyses
 ##################################################
 # ATLAS Z pT and phi*
-insert /Herwig/Analysis/RivetAnalysis:Analyses 0 ATLAS_2015_I1408516_MU
+insert /Herwig/Analysis/RivetAnalysis:Analyses 0 ATLAS_2015_I1408516:LMODE=MU
 # ATLAS high mass drell-yan
-insert /Herwig/Analysis/RivetAnalysis:Analyses 0 ATLAS_2016_I1467454_MU
+insert /Herwig/Analysis/RivetAnalysis:Analyses 0 ATLAS_2016_I1467454:LMODE=MU
 
diff --git a/Tests/Rivet/LHC/LHC-900-UE.in b/Tests/Rivet/LHC/LHC-900-UE.in
--- a/Tests/Rivet/LHC/LHC-900-UE.in
+++ b/Tests/Rivet/LHC/LHC-900-UE.in
@@ -1,53 +1,53 @@
 ##################################################
 # select the analyses
 ##################################################
 # ATLAS UE
 insert /Herwig/Analysis/RivetAnalysis:Analyses 0 ATLAS_2011_S8994773
 # ATLAS UE
 insert /Herwig/Analysis/RivetAnalysis:Analyses 0 ATLAS_2010_S8918562
 # ATLAS UE
 insert /Herwig/Analysis/RivetAnalysis:Analyses 0 ATLAS_2010_S8894728
 # ATLAS charged particles
 insert /Herwig/Analysis/RivetAnalysis:Analyses 0 ATLAS_2010_S8591806
 # ALICE charged particles
 insert /Herwig/Analysis/RivetAnalysis:Analyses 0 ALICE_2010_S8706239
 # ALICE charged particles
 insert /Herwig/Analysis/RivetAnalysis:Analyses 0 ALICE_2010_S8625980
 # ALICE charged particles
 insert /Herwig/Analysis/RivetAnalysis:Analyses 0 ALICE_2010_S8624100
 # ALICE particle spectra
 insert /Herwig/Analysis/RivetAnalysis:Analyses 0 ALICE_2011_S8945144
 # ALICE strange particle production
 insert /Herwig/Analysis/RivetAnalysis:Analyses 0 ALICE_2011_S8909580
 # CMS particle spectra
 insert /Herwig/Analysis/RivetAnalysis:Analyses 0 CMS_2011_S8978280
 # CMS charged particle multiplicity
 insert /Herwig/Analysis/RivetAnalysis:Analyses 0 CMS_2011_S8884919
 # CMS charged particle pT and rapidity
 insert /Herwig/Analysis/RivetAnalysis:Analyses 0 CMS_2010_S8547297
 # CMS UE
 insert /Herwig/Analysis/RivetAnalysis:Analyses 0 CMS_2011_S9120041
 # LHCB k_s0
 insert /Herwig/Analysis/RivetAnalysis:Analyses 0 LHCB_2010_S8758301
 # LHCB promt hadron production
 insert /Herwig/Analysis/RivetAnalysis:Analyses 0 LHCB_2012_I1119400
 # CMS forward energy flow
 insert /Herwig/Analysis/RivetAnalysis:Analyses 0 CMS_2011_S9215166
 # LHC K0s/Lambda
 insert /Herwig/Analysis/RivetAnalysis:Analyses 0 LHCB_2011_I917009
 # ATLAS Azimuthal ordering of charged hadrons
 insert /Herwig/Analysis/RivetAnalysis:Analyses 0 ATLAS_2012_I1091481
 # ALICE single/double diffractive and inelastic sigma
 insert /Herwig/Analysis/RivetAnalysis:Analyses 0 ALICE_2012_I1181770
 # ATLAS inelastic cross section
 insert /Herwig/Analysis/RivetAnalysis:Analyses 0 ATLAS_2011_I894867
 # underlying event forward rapidities
 insert /Herwig/Analysis/RivetAnalysis:Analyses 0 CMS_2013_I1218372
 # ATLAS two particle correlation
 #insert /Herwig/Analysis/RivetAnalysis:Analyses 0 ATLAS_2012_I1094061
 # ATLAS correlations
 insert /Herwig/Analysis/RivetAnalysis:Analyses 0 ATLAS_2012_I1093734
 # ALICE pion and eta pT
 insert /Herwig/Analysis/RivetAnalysis:Analyses 0 ALICE_2012_I1116147
 # CMS charged particle rapidity
-insert /Herwig/Analysis/RivetAnalysis:Analyses 0 CMS_QCD_10_024
+insert /Herwig/Analysis/RivetAnalysis:Analyses 0 CMS_2010_PAS_QCD_10_024
diff --git a/Tests/Rivet/LHC/LHC-W-e.in b/Tests/Rivet/LHC/LHC-W-e.in
--- a/Tests/Rivet/LHC/LHC-W-e.in
+++ b/Tests/Rivet/LHC/LHC-W-e.in
@@ -1,25 +1,24 @@
 ##################################################
 # select the analyses
 ##################################################
 # general analysis
 insert /Herwig/Analysis/RivetAnalysis:Analyses 0 MC_WJETS
 insert /Herwig/Analysis/RivetAnalysis:Analyses 0 MC_WPOL
 # ATLAS W+jets
 insert /Herwig/Analysis/RivetAnalysis:Analyses 0 ATLAS_2010_S8919674
 # ATLAS W pT
 insert /Herwig/Analysis/RivetAnalysis:Analyses 0 ATLAS_2011_I925932
 # ATLAS W kT scales
 insert /Herwig/Analysis/RivetAnalysis:Analyses 0 ATLAS_2013_I1217867
 # W DPI
 insert /Herwig/Analysis/RivetAnalysis:Analyses 0 ATLAS_2013_I1216670
 # W +b 
-insert /Herwig/Analysis/RivetAnalysis:Analyses 0 ATLAS_2013_I1219109_EL
+insert /Herwig/Analysis/RivetAnalysis:Analyses 0 ATLAS_2013_I1219109:LMODE=EL
 # ATLAS W
 insert /Herwig/Analysis/RivetAnalysis:Analyses 0 ATLAS_2011_I928289_W
 # ATLAS W+jets
-insert /Herwig/Analysis/RivetAnalysis:Analyses 0 ATLAS_2014_I1319490
-insert /Herwig/Analysis/RivetAnalysis:Analyses 0 ATLAS_2014_I1319490_EL
+insert /Herwig/Analysis/RivetAnalysis:Analyses 0 ATLAS_2014_I1319490:LMODE=EL
 # ATLAS W+charm
 insert /Herwig/Analysis/RivetAnalysis:Analyses 0 ATLAS_2014_I1282447
 # ATLAS W inclusive cross section
-insert /Herwig/Analysis/RivetAnalysis:Analyses 0 ATLAS_2016_I1502620_W_EL
\ No newline at end of file
+insert /Herwig/Analysis/RivetAnalysis:Analyses 0 ATLAS_2016_I1502620:LMODE=WEL
\ No newline at end of file
diff --git a/Tests/Rivet/LHC/LHC-W-mu.in b/Tests/Rivet/LHC/LHC-W-mu.in
--- a/Tests/Rivet/LHC/LHC-W-mu.in
+++ b/Tests/Rivet/LHC/LHC-W-mu.in
@@ -1,29 +1,29 @@
 ##################################################
 # select the analyses
 ##################################################
 # ATLAS W asymetry
 insert /Herwig/Analysis/RivetAnalysis:Analyses 0 ATLAS_2011_S9002537
 # ATLAS W+jets
 insert /Herwig/Analysis/RivetAnalysis:Analyses 0 ATLAS_2010_S8919674
 # ATLAS W pT
 insert /Herwig/Analysis/RivetAnalysis:Analyses 0 ATLAS_2011_I925932
 # ATLAS W+jets
 insert /Herwig/Analysis/RivetAnalysis:Analyses 0 ATLAS_2012_I1083318
 # ATLAS W kT scales
 insert /Herwig/Analysis/RivetAnalysis:Analyses 0 ATLAS_2013_I1217867
 # CMS double parton scattering
 insert /Herwig/Analysis/RivetAnalysis:Analyses 0 CMS_2013_I1272853
 # W DPI
 insert /Herwig/Analysis/RivetAnalysis:Analyses 0 ATLAS_2013_I1216670
 # CMS W+ jets
 insert /Herwig/Analysis/RivetAnalysis:Analyses 0 CMS_2014_I1303894
 # ATLAS W
 insert /Herwig/Analysis/RivetAnalysis:Analyses 0 ATLAS_2011_I928289_W
 # ATLAS W+jets
-insert /Herwig/Analysis/RivetAnalysis:Analyses 0 ATLAS_2014_I1319490_MU
+insert /Herwig/Analysis/RivetAnalysis:Analyses 0 ATLAS_2014_I1319490:LMODE=MU
 # W +b 
-insert /Herwig/Analysis/RivetAnalysis:Analyses 0 ATLAS_2013_I1219109_MU
+insert /Herwig/Analysis/RivetAnalysis:Analyses 0 ATLAS_2013_I1219109:LMODE=MU
 # ATLAS W+charm
 insert /Herwig/Analysis/RivetAnalysis:Analyses 0 ATLAS_2014_I1282447
 # ATLAS W inclusive cross section
-insert /Herwig/Analysis/RivetAnalysis:Analyses 0 ATLAS_2016_I1502620_W_MU
+insert /Herwig/Analysis/RivetAnalysis:Analyses 0 ATLAS_2016_I1502620:LMODE=WMU
diff --git a/Tests/Rivet/LHC/LHC-Z-e.in b/Tests/Rivet/LHC/LHC-Z-e.in
--- a/Tests/Rivet/LHC/LHC-Z-e.in
+++ b/Tests/Rivet/LHC/LHC-Z-e.in
@@ -1,34 +1,34 @@
 ##################################################
 # select the analyses
 ##################################################
 # General analysis
 insert /Herwig/Analysis/RivetAnalysis:Analyses 0 MC_ZINC
 insert /Herwig/Analysis/RivetAnalysis:Analyses 0 MC_ZJETS
 # ATLAS pT
 insert /Herwig/Analysis/RivetAnalysis:Analyses 0 ATLAS_2011_S9131140
 insert /Herwig/Analysis/RivetAnalysis:Analyses 0 ATLAS_2014_I1300647
 # ATLAS Z+jets
 insert /Herwig/Analysis/RivetAnalysis:Analyses 0 ATLAS_2011_I945498
 insert /Herwig/Analysis/RivetAnalysis:Analyses 0 ATLAS_2013_I1230812
 # ATLAS phi*
 insert /Herwig/Analysis/RivetAnalysis:Analyses 0 ATLAS_2012_I1204784
 # CMS Z + b-hadron
 insert /Herwig/Analysis/RivetAnalysis:Analyses 0 CMS_2013_I1256943
 # CMS Z pt and y
 insert /Herwig/Analysis/RivetAnalysis:Analyses 0 CMS_2012_I941555
 # ATLAS Z + bjets
 insert /Herwig/Analysis/RivetAnalysis:Analyses 0 ATLAS_2014_I1306294
 # ATLAS Z
 insert /Herwig/Analysis/RivetAnalysis:Analyses 0 ATLAS_2011_I928289_Z
 # CMS Z AFB
 insert /Herwig/Analysis/RivetAnalysis:Analyses 0 CMS_2013_I1122847
 # CMS Z+jets
 insert /Herwig/Analysis/RivetAnalysis:Analyses 0 CMS_2015_I1310737
 # ATLAS event shapes in Z events
 insert /Herwig/Analysis/RivetAnalysis:Analyses 0 ATLAS_2016_I1424838
 # ATLAS forwrd backward
 insert /Herwig/Analysis/RivetAnalysis:Analyses 0 ATLAS_2015_I1351916_EL
 # ATLAS forward backward
 insert /Herwig/Analysis/RivetAnalysis:Analyses 0 ATLAS_2013_I1234228
 # ATLAS Z inclusive cross section
-insert /Herwig/Analysis/RivetAnalysis:Analyses 0 ATLAS_2016_I1502620_Z_EL
\ No newline at end of file
+insert /Herwig/Analysis/RivetAnalysis:Analyses 0 ATLAS_2016_I1502620:LMODE=ZEL
\ No newline at end of file
diff --git a/Tests/Rivet/LHC/LHC-Z-mu.in b/Tests/Rivet/LHC/LHC-Z-mu.in
--- a/Tests/Rivet/LHC/LHC-Z-mu.in
+++ b/Tests/Rivet/LHC/LHC-Z-mu.in
@@ -1,35 +1,35 @@
 ##################################################
 # select the analyses
 ##################################################
 # ATLAS Z pt
 insert /Herwig/Analysis/RivetAnalysis:Analyses 0 ATLAS_2011_S9131140
 insert /Herwig/Analysis/RivetAnalysis:Analyses 0 ATLAS_2014_I1300647
 # ATLAS Z+jets
 insert /Herwig/Analysis/RivetAnalysis:Analyses 0 ATLAS_2011_I945498
 # ATLAS phi*
 insert /Herwig/Analysis/RivetAnalysis:Analyses 0 ATLAS_2012_I1204784
 # Z and real photon + jet
 insert /Herwig/Analysis/RivetAnalysis:Analyses 0 CMS_2013_I1258128
 # CMS Z + b-hadron
 insert /Herwig/Analysis/RivetAnalysis:Analyses 0 CMS_2013_I1256943
 # CMS Z pt and y
 insert /Herwig/Analysis/RivetAnalysis:Analyses 0 CMS_2012_I941555
 # ATLAS MPI in Z events
 insert /Herwig/Analysis/RivetAnalysis:Analyses 0 ATLAS_2014_I1315949
 # ATLAS Z
 insert /Herwig/Analysis/RivetAnalysis:Analyses 0 ATLAS_2011_I928289_Z
 # CMS Z AFB
 insert /Herwig/Analysis/RivetAnalysis:Analyses 0 CMS_2013_I1122847
 # CMS Z+jets
 insert /Herwig/Analysis/RivetAnalysis:Analyses 0 CMS_2015_I1310737
 # ATLAS event shapes in Z events
 insert /Herwig/Analysis/RivetAnalysis:Analyses 0 ATLAS_2016_I1424838
 # CMS photon radiation in Z decays
 insert /Herwig/Analysis/RivetAnalysis:Analyses 0 CMS_2015_I1346843
 # ATLAS forwrd backward
 insert /Herwig/Analysis/RivetAnalysis:Analyses 0 ATLAS_2015_I1351916_MU
 # LHCB forward Z+jet
 insert /Herwig/Analysis/RivetAnalysis:Analyses 0 LHCB_2014_I1262703 
 # ATLAS Z inclusive cross section
-insert /Herwig/Analysis/RivetAnalysis:Analyses 0 ATLAS_2016_I1502620_Z_MU
+insert /Herwig/Analysis/RivetAnalysis:Analyses 0 ATLAS_2016_I1502620:LMODE=ZMU
 
diff --git a/Tests/python/make_input_files.py b/Tests/python/make_input_files.py
--- a/Tests/python/make_input_files.py
+++ b/Tests/python/make_input_files.py
@@ -1,1842 +1,1844 @@
 #! /usr/bin/env python
 import logging,sys,os
 from string import strip, Template
 
 import sys
 if sys.version_info[:3] < (2,4,0):
     print "rivet scripts require Python version >= 2.4.0... exiting"
     sys.exit(1)
 
 if __name__ == "__main__":
     import logging
     from optparse import OptionParser, OptionGroup
     parser = OptionParser(usage="%prog name [...]")
 
 
 simulation=""
 
 numberOfAddedProcesses=0
 def addProcess(thefactory,theProcess,Oas,Oew,scale,mergedlegs,NLOprocesses):
     global numberOfAddedProcesses
     global simulation
     numberOfAddedProcesses+=1
     res ="set "+thefactory+":OrderInAlphaS "+Oas+"\n"
     res+="set "+thefactory+":OrderInAlphaEW "+Oew+"\n"
     res+="do "+thefactory+":Process "+theProcess+" "
     if ( mergedlegs != 0 ):
       if simulation!="Merging":
           print "simulation is not Merging, trying to add merged legs."
           sys.exit(1)
       res+="["
       for j in range(mergedlegs):
         res+=" j "
       res+="]"
     res+="\n"
     if (NLOprocesses!=0):
        if simulation!="Merging":
           print "simulation is not Merging, trying to add NLOProcesses."
           sys.exit(1)
        res+="set MergingFactory:NLOProcesses %s \n" % NLOprocesses
     if ( scale != "" ):
       res+="set "+thefactory+":ScaleChoice /Herwig/MatrixElements/Matchbox/Scales/"+scale+"\n"
     return res
 
 
 def addLeptonPairCut(minmass,maxmass):
     return "set /Herwig/Cuts/LeptonPairMassCut:MinMass "+minmass+"*GeV\nset /Herwig/Cuts/LeptonPairMassCut:MaxMass "+maxmass+"*GeV\n"
 
 didaddfirstjet=False
 def addFirstJet(ptcut):
     global didaddfirstjet
     if(didaddfirstjet):
       logging.error("Can only add jetcut once.")
       sys.exit(1)
   
     res="set  /Herwig/Cuts/Cuts:JetFinder  /Herwig/Cuts/JetFinder\n"
     res+="insert  /Herwig/Cuts/Cuts:MultiCuts 0  /Herwig/Cuts/JetCuts\n"
     res+="insert  /Herwig/Cuts/JetCuts:JetRegions 0  /Herwig/Cuts/FirstJet\n"
     if(ptcut!=""):
         res+="set /Herwig/Cuts/FirstJet:PtMin "+ptcut+".*GeV\n"
     didaddfirstjet=True
     return res
 
 
 
 didaddsecondjet=False
 def addSecondJet(ptcut):
     global didaddsecondjet
     if(didaddsecondjet):
       logging.error("Can only add second jetcut once.")
       sys.exit(1)
     res="insert /Herwig/Cuts/JetCuts:JetRegions 0  /Herwig/Cuts/SecondJet\n"
     res+="set /Herwig/Cuts/SecondJet:PtMin "+ptcut+".*GeV\n"
     didaddsecondjet=True
     return res
 
 
 didaddjetpair=False
 def addJetPairCut(minmass):
   global didaddjetpair
   if(didaddjetpair):
       logging.error("Can only add second jetcut once.")
       sys.exit(1)
   res="""\
 create ThePEG::JetPairRegion /Herwig/Cuts/JetPairMass JetCuts.so
 set /Herwig/Cuts/JetPairMass:FirstRegion /Herwig/Cuts/FirstJet
 set /Herwig/Cuts/JetPairMass:SecondRegion /Herwig/Cuts/SecondJet
 insert /Herwig/Cuts/JetCuts:JetPairRegions 0  /Herwig/Cuts/JetPairMass
 set /Herwig/Cuts/JetPairMass:MassMin {mm}.*GeV
 """.format(mm=minmass)
   didaddjetpair=True
   return res
 
 addedBRReweighter=False
 def addBRReweighter():
   global addedBRReweighter
   if(addedBRReweighter):
     logging.error("Can only add BRReweighter once.")
     sys.exit(1)
   res="create Herwig::BranchingRatioReweighter /Herwig/Generators/BRReweighter\n"
   res+="insert /Herwig/Generators/EventGenerator:EventHandler:PostHadronizationHandlers 0 /Herwig/Generators/BRReweighter\n"
   addedBRReweighter=True
   return res
 
 def setHardProcessWidthToZero(list1):
   res=""
   for i in list1:
     res+="set /Herwig/Particles/"+i+":HardProcessWidth 0.\n"
   return res
 
 selecteddecaymode=False
 def selectDecayMode(particle,decaymodes):
   global selecteddecaymode
   res="do /Herwig/Particles/"+particle+":SelectDecayModes"
   for decay in decaymodes:
     res+=" /Herwig/Particles/"+particle+"/"+decay
   res+="\n"
   selecteddecaymode=True
   return res
 
 def jet_kt_cut(energy):
     return "set /Herwig/Cuts/JetKtCut:MinKT {E}*GeV\n".format(E=energy)
 
 def mhatmin_cut(energy):
     return "set /Herwig/Cuts/Cuts:MHatMin {E}*GeV\n".format(E=energy)
 
 def mhat_minm_maxm(e1,e2,e3):
     return """\
 set /Herwig/Cuts/Cuts:MHatMin {e1}*GeV
 set /Herwig/Cuts/MassCut:MinM {e2}*GeV
 set /Herwig/Cuts/MassCut:MaxM {e3}*GeV
 """.format(**locals())
 
 def collider_lumi(energy):
     return "set /Herwig/Generators/EventGenerator:EventHandler:LuminosityFunction:Energy {E}*GeV\n".format(E=energy)
 
 def insert_ME(me,process=None,ifname='Process'):
     result = "insert /Herwig/MatrixElements/SubProcess:MatrixElements 0 /Herwig/MatrixElements/{me}\n".format(**locals())
     if process is not None:
         result += "set /Herwig/MatrixElements/{me}:{ifname} {process}".format(**locals())
     return result
 
 def particlegroup(name,*particles):
     result = ["do /Herwig/MatrixElements/Matchbox/Factory:StartParticleGroup {n}".format(n=name)]
     for p in particles:
         result.append(
             "insert /Herwig/MatrixElements/Matchbox/Factory:ParticleGroup 0 /Herwig/Particles/{p}".format(p=p)
         )
     result.append("do /Herwig/MatrixElements/Matchbox/Factory:EndParticleGroup")
     return '\n'.join(result)
 
 # settings for four flavour scheme
 fourFlavour="""
 read Matchbox/FourFlavourScheme.in
 {bjetgroup}
 set /Herwig/Cuts/MatchboxJetMatcher:Group bjet
 """.format(bjetgroup=particlegroup('bjet','b','bbar','c', 'cbar',
                                    's','sbar','d','dbar','u','ubar','g'))
 
 ME_Upsilon = """\
 create Herwig::MEee2VectorMeson /Herwig/MatrixElements/MEUpsilon HwMELepton.so
 set /Herwig/MatrixElements/MEUpsilon:VectorMeson /Herwig/Particles/Upsilon(4S)
 set /Herwig/MatrixElements/MEUpsilon:Coupling 0.0004151809
 """ + insert_ME("MEUpsilon")
 
 
 (opts, args) = parser.parse_args()
 ## Check args
 if len(args) != 1:
     logging.error("Must specify at least input file")
     sys.exit(1)
 
 name = args[0]
 print name
 
 
 # select the template to load
 # collider
 KNOWN_COLLIDERS = [
     "BFactory",
     "LEP",
     "DIS",
     "TVT",
     "LHC-GammaGamma",
     "LHC",
     "ISR",
     "SppS",
     "Star",
 ]
 collider = ""
 for cand_collider in KNOWN_COLLIDERS:
     if cand_collider in name:
         collider = cand_collider
         break
 del cand_collider
 assert collider
 have_hadronic_collider = collider in ["TVT","LHC","ISR","SppS","Star"]
 
 
 thefactory="Factory"
 
 parameters = { 
     'shower'  : '',
     'bscheme' : '',
 }
 # istart determines how many name parts need to be skipped
 istart = 1
 # Dipole shower with Matchbox Powheg
 if "Dipole-Matchbox-Powheg" in name :
     istart = 4
     simulation="Matchbox"
     parameters["shower"]  = "read Matchbox/Powheg-DipoleShower.in\n"
 
     # Dipole shower with internal Powheg - Todo: Finish modifying template files.
     '''
     elif "Dipole-Powheg" in name :
     istart = 3
     simulation="Powheg"
     parameters["shower"]  = "set /Herwig/EventHandlers/EventHandler:CascadeHandler /Herwig/DipoleShower/DipoleShowerHandler\nread snippets/Dipole_AutoTune_prel.in\n"
     '''
 
 # Dipole shower with MCatNLO
 elif "Dipole-MCatNLO" in name :
     istart = 3
     simulation="Matchbox"
     parameters["shower"]  = "read Matchbox/MCatNLO-DipoleShower.in\n" 
 
 # Dipole shower with Matchbox LO
 elif "Dipole-Matchbox-LO" in name :
     istart = 4
     simulation="Matchbox"
     parameters["shower"]  = "read Matchbox/LO-DipoleShower.in\n" 
 
 # Dipole shower with internal LO
 elif "Dipole" in name :
     istart = 2
     simulation=""
     parameters["shower"]  = "set /Herwig/EventHandlers/EventHandler:CascadeHandler /Herwig/DipoleShower/DipoleShowerHandler\nread snippets/Dipole_AutoTune_prel.in\n"
     
 # AO shower with Matchbox Powheg
 elif "Matchbox-Powheg" in name :
     istart = 3
     simulation="Matchbox"
     parameters["shower"] = "read Matchbox/Powheg-DefaultShower.in\n"
 
 # AO shower with MCatNLO
 elif "Matchbox" in name :
     istart = 2
     simulation="Matchbox"
     parameters["shower"] = "read Matchbox/MCatNLO-DefaultShower.in\n"
 
 # AO shower with inernal Powheg    
 elif "Powheg" in name :
     istart = 2
     simulation="Powheg"
 
 # Dipole shower with merging    
 elif "Merging" in name :
     istart = 2
     simulation="Merging"
     thefactory="MergingFactory"
     
 # Flavour settings for Matchbox    
 if simulation=="Matchbox" :
     parameters["bscheme"] = "read Matchbox/FiveFlavourScheme.in\n"
     
     if "Dipole" in parameters["shower"] :
         parameters["bscheme"] += "read Matchbox/FiveFlavourNoBMassScheme.in\n"
         
     if collider not in ['DIS','LEP'] :
         parameters["nlo"] = "read Matchbox/MadGraph-OpenLoops.in\n"
 
 # Flavour settings for dipole shower with internal ME
 if simulation=="" and "Dipole" in parameters["shower"] :
     parameters["bscheme"] = "read snippets/DipoleShowerFiveFlavours.in"
     
 
 
 # find the template
 if simulation=="" :
     if collider=="LHC-GammaGamma" :
         istart += 1
         templateName="Hadron-Gamma.in"
     elif have_hadronic_collider :
         templateName="Hadron.in"
     elif collider != "BFactory" :
         templateName= "%s.in" % collider
     else :
         templateName= "LEP.in"
 else :
     if have_hadronic_collider :
         templateName= "Hadron-%s.in" % simulation 
     elif collider != "BFactory" :
         templateName= "%s-%s.in" % (collider,simulation) 
     else :
         templateName= "LEP-%s.in" % simulation 
 
 # work out the name of the parameter file
 parameterName="-".join(name.split("-")[istart:])
 del istart
 
 class StringBuilder(object):
     """
     Avoid expensive string additions until the end
     by building up a list first.
 
     This helper class avoids rewriting all the += lower down
     to list operations.
     """
     def __init__(self, init = None):
         self.lines = [] if init is None else [init]
 
     def __iadd__(self, line):
         self.lines.append(line)
         return self
 
     def __str__(self):
         return '\n'.join(self.lines)
 
 # work out the process and parameters
 process=StringBuilder()
 # Bfactory
 if(collider=="BFactory") :
     if(simulation=="") :
         if(parameterName=="10.58-res") :
             process += ME_Upsilon
         elif(parameterName=="10.58") :
             process += ME_Upsilon
             process += "set /Herwig/MatrixElements/MEee2gZ2qq:MaximumFlavour 4\n"
         else :
             process+=insert_ME("MEee2gZ2qq")
             process+= "set /Herwig/MatrixElements/MEee2gZ2qq:MaximumFlavour 4\n"
     elif(simulation=="Powheg") :
         process = StringBuilder("set /Herwig/MatrixElements/PowhegMEee2gZ2qq:MaximumFlavour 4\n")
     elif(simulation=="Matchbox" ) :
         process = StringBuilder(addProcess(thefactory,"e- e+ -> u ubar","0","2","",0,0))
         process+=addProcess(thefactory,"e- e+ -> d dbar","0","2","",0,0)
         process+=addProcess(thefactory,"e- e+ -> c cbar","0","2","",0,0)
         process+=addProcess(thefactory,"e- e+ -> s sbar","0","2","",0,0)
     elif(simulation=="Merging" ) :
         logging.warning("BFactory not explicitly tested for %s " % simulation)
         sys.exit(0)
 
 # DIS
 elif(collider=="DIS") :
     if(simulation=="") :
         if "NoME" in parameterName :
             process = StringBuilder("set /Herwig/Shower/ShowerHandler:HardEmission None")
             parameterName=parameterName.replace("NoME-","")
         else :
             process = StringBuilder("")
     elif(simulation=="Powheg") :
         process = StringBuilder("")
     elif(simulation=="Matchbox" ) :
       if "e-" in parameterName :
             process = StringBuilder(addProcess(thefactory,"e- p -> e- j","0","2","",0,0))
       else :
             process = StringBuilder(addProcess(thefactory,"e+ p -> e+ j","0","2","",0,0))
     elif(simulation=="Merging" ) :
         if "e-" in parameterName :
             process = StringBuilder(addProcess(thefactory,"e- p -> e- j","0","2","",2,2))
         else :
             process = StringBuilder(addProcess(thefactory,"e+ p -> e+ j","0","2","",2,2))
 
 # LEP
 elif(collider=="LEP") :
     if(simulation=="") :
         if "gg" in parameterName :
             process = StringBuilder("create Herwig::MEee2Higgs2SM /Herwig/MatrixElements/MEee2Higgs2SM\n")
             process+=insert_ME("MEee2Higgs2SM","Gluon","Allowed")
         else :
             process = StringBuilder(insert_ME("MEee2gZ2qq"))
             if(parameterName=="10") :
                 process+="set /Herwig/MatrixElements/MEee2gZ2qq:MaximumFlavour 4"
     elif(simulation=="Powheg") :
         process = StringBuilder()
         if(parameterName=="10") :
             process = StringBuilder("set /Herwig/MatrixElements/PowhegMEee2gZ2qq:MaximumFlavour 4")
     elif(simulation=="Matchbox" ) :
         if(parameterName=="10") :
             process = StringBuilder(addProcess(thefactory,"e- e+ -> u ubar","0","2","",0,0))
             process+=addProcess(thefactory,"e- e+ -> d dbar","0","2","",0,0)
             process+=addProcess(thefactory,"e- e+ -> c cbar","0","2","",0,0)
             process+=addProcess(thefactory,"e- e+ -> s sbar","0","2","",0,0)
         else :
             process = StringBuilder(addProcess(thefactory,"e- e+ -> j j","0","2","",0,0))
 
     elif(simulation=="Merging" ) :
         if(parameterName=="10") :
           process = StringBuilder(addProcess(thefactory,"e- e+ -> j j","0","2","",2,2))
           process+="read Matchbox/FourFlavourScheme.in"
         else :
           process = StringBuilder(addProcess(thefactory,"e- e+ -> j j","0","2","",2,2))
 # TVT
 elif(collider=="TVT") :
     process = StringBuilder("set /Herwig/Generators/EventGenerator:EventHandler:BeamB /Herwig/Particles/pbar-\n")
     if "Run-II" in parameterName :  process+=collider_lumi(1960.0)
     elif "Run-I" in parameterName : process+=collider_lumi(1800.0)
     elif "900" in parameterName :   process+=collider_lumi(900.0)
     elif "630" in parameterName :   process+=collider_lumi(630.0)
     elif "300" in parameterName :   process+=collider_lumi(300.0)
 
     if(simulation=="") :
         if "PromptPhoton" in parameterName :
             process+=insert_ME("MEGammaJet")
             process+="set /Herwig/Cuts/PhotonKtCut:MinKT 15.\n"
         elif "DiPhoton-GammaGamma" in parameterName :
             process+=insert_ME("MEGammaGamma")
             process+="set /Herwig/Cuts/PhotonKtCut:MinKT 5.\n"
             parameterName=parameterName.replace("-GammaGamma","")
         elif "DiPhoton-GammaJet" in parameterName :
             process+=insert_ME("MEGammaJet")
             process+="set /Herwig/Cuts/PhotonKtCut:MinKT 5.\n"
             parameterName=parameterName.replace("-GammaJet","")
         elif "UE" in parameterName :
             if "Dipole" in parameters["shower"]:
                 process+="read snippets/MB-DipoleShower.in\n"
             else:
                 process+="read snippets/MB.in\n"
             process+="read snippets/Diffraction.in\n"
                 
             process += "set /Herwig/Decays/DecayHandler:LifeTimeOption 0\n"
             process += "set /Herwig/Decays/DecayHandler:MaxLifeTime 10*mm\n"
         elif "Jets" in parameterName :
             process+=insert_ME("MEQCD2to2")
             process+="set /Herwig/UnderlyingEvent/MPIHandler:IdenticalToUE 0\n"
             if "Run-II-Jets-10" in parameterName :  process+=jet_kt_cut( 30.)+mhatmin_cut(500.)
             elif "Run-II-Jets-11" in parameterName: process+=jet_kt_cut( 30.)+mhatmin_cut(900.)
             elif "Run-I-Jets-1" in parameterName :  process+=jet_kt_cut( 20.)
             elif "Run-I-Jets-2" in parameterName :  process+=jet_kt_cut( 40.)
             elif "Run-I-Jets-3" in parameterName :  process+=jet_kt_cut( 65.)
             elif "Run-I-Jets-4" in parameterName :  process+=jet_kt_cut( 90.)
             elif "Run-I-Jets-5" in parameterName :  process+=jet_kt_cut(160.)
             elif "Run-I-Jets-6" in parameterName :  process+=jet_kt_cut( 30.)+mhatmin_cut(100.)
             elif "Run-I-Jets-7" in parameterName :  process+=jet_kt_cut( 30.)+mhatmin_cut(400.)
             elif "Run-I-Jets-8" in parameterName :  process+=jet_kt_cut( 30.)+mhatmin_cut(700.)
             elif "Run-II-Jets-0" in parameterName : process+=jet_kt_cut( 15.)
             elif "Run-II-Jets-1" in parameterName : process+=jet_kt_cut( 25.)
             elif "Run-II-Jets-2" in parameterName : process+=jet_kt_cut( 40.)
             elif "Run-II-Jets-3" in parameterName : process+=jet_kt_cut( 60.)
             elif "Run-II-Jets-4" in parameterName : process+=jet_kt_cut( 85.)
             elif "Run-II-Jets-5" in parameterName : process+=jet_kt_cut(110.)
             elif "Run-II-Jets-6" in parameterName : process+=jet_kt_cut(160.)
             elif "Run-II-Jets-7" in parameterName : process+=jet_kt_cut(250.)
             elif "Run-II-Jets-8" in parameterName : process+=jet_kt_cut( 30.)+mhatmin_cut(100.)
             elif "Run-II-Jets-9" in parameterName : process+=jet_kt_cut( 30.)+mhatmin_cut(300.)
             elif "900-Jets-1" in parameterName :    process+=jet_kt_cut( 10.)
             elif "300-Jets-1" in parameterName :    process+=jet_kt_cut(  6.)
             elif "630-Jets-1" in parameterName :    process+=jet_kt_cut( 20.)
             elif "630-Jets-2" in parameterName :    process+=jet_kt_cut( 40.)
             elif "630-Jets-3" in parameterName :    process+=jet_kt_cut( 75.)
             elif "900-Jets-1" in parameterName :    process+=jet_kt_cut( 10.)
         elif "Run-I-WZ" in parameterName :
             process+=insert_ME("MEqq2W2ff","Electron")
             process+=insert_ME("MEqq2gZ2ff","Electron")
         elif "Run-II-W" in parameterName or "Run-I-W" in parameterName :
             process+=insert_ME("MEqq2W2ff","Electron")
         elif "Run-II-Z-e" in parameterName or "Run-I-Z" in parameterName :
             process +=insert_ME("MEqq2gZ2ff","Electron")
         elif "Run-II-Z-LowMass-mu" in parameterName :
             process +=insert_ME("MEqq2gZ2ff","Muon")
             process+=addLeptonPairCut("25","70")
         elif "Run-II-Z-HighMass-mu" in parameterName :
             process +=insert_ME("MEqq2gZ2ff","Muon")
             process+=addLeptonPairCut("150","600")
         elif "Run-II-Z-mu" in parameterName :
             process +=insert_ME("MEqq2gZ2ff","Muon")
     elif(simulation=="Powheg") :
         if "Run-I-WZ" in parameterName :
             process+=insert_ME("PowhegMEqq2W2ff","Electron")
             process+=insert_ME("PowhegMEqq2gZ2ff","Electron")
         elif "Run-II-W" in parameterName or "Run-I-W" in parameterName :
             process+=insert_ME("PowhegMEqq2W2ff","Electron")
         elif "Run-II-Z-e" in parameterName or "Run-I-Z" in parameterName :
             process+=insert_ME("PowhegMEqq2gZ2ff","Electron")
         elif "Run-II-Z-LowMass-mu" in parameterName :
             process+=insert_ME("PowhegMEqq2gZ2ff","Muon")
             process+=addLeptonPairCut("25","70")
         elif "Run-II-Z-HighMass-mu" in parameterName :
             process+=insert_ME("PowhegMEqq2gZ2ff","Muon")
             process+=addLeptonPairCut("150","600")
         elif "Run-II-Z-mu" in parameterName :
             process+=insert_ME("PowhegMEqq2gZ2ff","Muon")
         elif "DiPhoton-GammaGamma" in parameterName :
             process+=insert_ME("MEGammaGammaPowheg","GammaGamma")
             process+=insert_ME("MEGammaGamma","gg")
             process+="set /Herwig/Cuts/PhotonKtCut:MinKT 5.\n"
             process+=jet_kt_cut(5.)
             parameterName=parameterName.replace("-GammaGamma","")
         elif "DiPhoton-GammaJet" in parameterName :
             process+=insert_ME("MEGammaGammaPowheg","VJet")
             process+="set /Herwig/Cuts/PhotonKtCut:MinKT 5.\n"
             process+=jet_kt_cut(5.)
             parameterName=parameterName.replace("-GammaJet","")
     elif(simulation=="Matchbox" or simulation=="Merging" ) :
         if "Jets" in parameterName :
             if(simulation=="Matchbox"):
                 process+=addProcess(thefactory,"p p -> j j","2","0","MaxJetPtScale",0,0)
             elif(simulation=="Merging"):
                 process+=addProcess(thefactory,"p p -> j j","2","0","MaxJetPtScale",1,0)
             process+="set /Herwig/UnderlyingEvent/MPIHandler:IdenticalToUE 0\n"
             if "Run-II-Jets-10" in parameterName :
                 process+=addFirstJet("30")
                 process+=addSecondJet("25")
                 process+=addJetPairCut("500")
             elif "Run-II-Jets-11" in parameterName :
                 process+=addFirstJet("30")
                 process+=addSecondJet("25")
                 process+=addJetPairCut("900")
             elif "Run-II-Jets-12" in parameterName :
                 process+=addFirstJet("30")
                 process+=addSecondJet("25")
                 process+=addJetPairCut("300")
             elif "Run-I-Jets-1" in parameterName : process+=addFirstJet("20")
             elif "Run-I-Jets-2" in parameterName : process+=addFirstJet("40")
             elif "Run-I-Jets-3" in parameterName : process+=addFirstJet("65")
             elif "Run-I-Jets-4" in parameterName : process+=addFirstJet("90")
             elif "Run-I-Jets-5" in parameterName : process+=addFirstJet("160")
             elif "Run-I-Jets-6" in parameterName : process+=addFirstJet("30")+addSecondJet("25")+addJetPairCut("100")
             elif "Run-I-Jets-7" in parameterName : process+=addFirstJet("30")+addSecondJet("25")+addJetPairCut("400")
             elif "Run-I-Jets-8" in parameterName : process+=addFirstJet("30")+addSecondJet("25")+addJetPairCut("700")
             elif "Run-II-Jets-0" in parameterName : process+=addFirstJet("15")
             elif "Run-II-Jets-1" in parameterName : process+=addFirstJet("25")
             elif "Run-II-Jets-2" in parameterName : process+=addFirstJet("40")
             elif "Run-II-Jets-3" in parameterName : process+=addFirstJet("60")
             elif "Run-II-Jets-4" in parameterName : process+=addFirstJet("85")
             elif "Run-II-Jets-5" in parameterName : process+=addFirstJet("110")
             elif "Run-II-Jets-6" in parameterName : process+=addFirstJet("160")
             elif "Run-II-Jets-7" in parameterName : process+=addFirstJet("250")
             elif "Run-II-Jets-8" in parameterName : process+=addFirstJet("30")+addSecondJet("25")+addJetPairCut("100")
             elif "Run-II-Jets-9" in parameterName : process+=addFirstJet("30")+addSecondJet("25")+addJetPairCut("300")
             elif "900-Jets-1" in parameterName : process+=addFirstJet("10")
             elif "300-Jets-1" in parameterName : process+=addFirstJet("6")
             elif "630-Jets-1" in parameterName : process+=addFirstJet("20")
             elif "630-Jets-2" in parameterName : process+=addFirstJet("40")
             elif "630-Jets-3" in parameterName : process+=addFirstJet("75")
             elif "900-Jets-1" in parameterName : process+=addFirstJet("10")
             else :
                 logging.error("Exit 00007")
                 sys.exit(1)
         elif "Run-I-WZ" in parameterName :
             if(simulation=="Matchbox"):
                 process+=addProcess(thefactory,"p pbar e+ e-","0","2","LeptonPairMassScale",0,0)
                 process+=addProcess(thefactory,"p pbar e+ nu","0","2","LeptonPairMassScale",0,0)
                 process+=addProcess(thefactory,"p pbar e- nu","0","2","LeptonPairMassScale",0,0)
             elif(simulation=="Merging"):
                 process+=particlegroup('epm','e+','e-')
                 process+=particlegroup('epmnu','e+','e-','nu_e','nu_ebar')
                 process+=addProcess(thefactory,"p pbar epm epmnu","0","2","LeptonPairMassScale",2,2)
             process+=addLeptonPairCut("60","120")
         elif "Run-II-W" in parameterName or "Run-I-W" in parameterName :
             if(simulation=="Matchbox"):
                 process+=addProcess(thefactory,"p pbar e+ nu","0","2","LeptonPairMassScale",0,0)
                 process+=addProcess(thefactory,"p pbar e- nu","0","2","LeptonPairMassScale",0,0)
             elif(simulation=="Merging"):
                 process+=particlegroup('epm','e+','e-')
                 process+=addProcess(thefactory,"p pbar epm nu","0","2","LeptonPairMassScale",2,2)
             process+=addLeptonPairCut("60","120")
         elif "Run-II-Z-e" in parameterName or "Run-I-Z" in parameterName :
             if(simulation=="Matchbox"):
                 process+=addProcess(thefactory,"p pbar e+ e-","0","2","LeptonPairMassScale",0,0)
             elif(simulation=="Merging"):
                 process+=addProcess(thefactory,"p pbar e+ e-","0","2","LeptonPairMassScale",2,2)
             process+=addLeptonPairCut("60","120")
         elif "Run-II-Z-LowMass-mu" in parameterName :
             if(simulation=="Matchbox"):
                 process+=addProcess(thefactory,"p pbar mu+ mu-","0","2","LeptonPairMassScale",0,0)
             elif(simulation=="Merging"):
                 process+=addProcess(thefactory,"p pbar mu+ mu-","0","2","LeptonPairMassScale",2,2)
             process+=addLeptonPairCut("25","70")
         elif "Run-II-Z-HighMass-mu" in parameterName :
             if(simulation=="Matchbox"):
                 process+=addProcess(thefactory,"p pbar mu+ mu-","0","2","LeptonPairMassScale",0,0)
             elif(simulation=="Merging"):
                 process+=addProcess(thefactory,"p pbar mu+ mu-","0","2","LeptonPairMassScale",2,2)
             process+=addLeptonPairCut("150","600")
         elif "Run-II-Z-mu" in parameterName :
             if(simulation=="Matchbox"):
                 process+=addProcess(thefactory,"p pbar mu+ mu-","0","2","LeptonPairMassScale",0,0)
             elif(simulation=="Merging"):
                 process+=addProcess(thefactory,"p pbar mu+ mu-","0","2","LeptonPairMassScale",2,2)
             process+=addLeptonPairCut("60","120")
 # Star
 elif(collider=="Star" ) :
     process = StringBuilder("set /Herwig/Decays/DecayHandler:LifeTimeOption 0\n")
     process+= "set /Herwig/Decays/DecayHandler:MaxLifeTime 10*mm\n"
     process+= "set /Herwig/Generators/EventGenerator:EventHandler:BeamB /Herwig/Particles/p+\n"
     process+= collider_lumi(200.0)
     process+= "set /Herwig/Cuts/Cuts:X2Min 0.01\n"
     if(simulation=="") :
         if "UE" in parameterName :
             if "Dipole" in parameters["shower"]:
                 process+="read snippets/MB-DipoleShower.in\n"
             else:
                 process+="read snippets/MB.in\n"    
             process+="read snippets/Diffraction.in\n"
             
             
         else :
             process+=insert_ME("MEQCD2to2")
             process+="set /Herwig/UnderlyingEvent/MPIHandler:IdenticalToUE 0\n"
             if "Jets-1" in parameterName :   process+=jet_kt_cut(2.)
             elif "Jets-2" in parameterName : process+=jet_kt_cut(5.)
             elif "Jets-3" in parameterName : process+=jet_kt_cut(20.)
             elif "Jets-4" in parameterName : process+=jet_kt_cut(25.)
     else :
         logging.error("Star not supported for %s " % simulation)
         sys.exit(1)
 # ISR and SppS
 elif(collider=="ISR" or collider =="SppS" ) :
     process = StringBuilder("set /Herwig/Decays/DecayHandler:LifeTimeOption 0\n")
     process+="set /Herwig/Decays/DecayHandler:MaxLifeTime 10*mm\n"
     if(collider=="SppS") :
         process = StringBuilder("set /Herwig/Generators/EventGenerator:EventHandler:BeamB /Herwig/Particles/pbar-\n")
     if    "30" in parameterName : process+=collider_lumi( 30.4)
     elif  "44" in parameterName : process+=collider_lumi( 44.4)
     elif  "53" in parameterName : process+=collider_lumi( 53.0)
     elif  "62" in parameterName : process+=collider_lumi( 62.2)
     elif  "63" in parameterName : process+=collider_lumi( 63.0)
     elif "200" in parameterName : process+=collider_lumi(200.0)
     elif "500" in parameterName : process+=collider_lumi(500.0)
     elif "546" in parameterName : process+=collider_lumi(546.0)
     elif "900" in parameterName : process+=collider_lumi(900.0)
     if(simulation=="") :
         if "Dipole" in parameters["shower"]:
             process+="read snippets/MB-DipoleShower.in\n"
         else:
             process+="read snippets/MB.in\n"
         process+="read snippets/Diffraction.in\n"
     else :
         logging.error(" SppS and ISR not supported for %s " % simulation)
         sys.exit(1)
 # LHC
 elif(collider=="LHC") :
     if   parameterName.startswith("7-")   : process = StringBuilder(collider_lumi(7000.0))
     elif parameterName.startswith("8-")   : process = StringBuilder(collider_lumi(8000.0))
     elif parameterName.startswith("13-")  : process = StringBuilder(collider_lumi(13000.0))
     elif parameterName.startswith("900")  : process = StringBuilder(collider_lumi(900.0))
     elif parameterName.startswith("2360") : process = StringBuilder(collider_lumi(2360.0))
     elif parameterName.startswith("2760") : process = StringBuilder(collider_lumi(2760.0))
     else                                  : process = StringBuilder(collider_lumi(7000.0))
     if(simulation=="") :
         if "VBF" in parameterName :
             process+=insert_ME("MEPP2HiggsVBF")
             if "GammaGamma" in parameterName :
                process+=selectDecayMode("h0",["h0->gamma,gamma;"])
                addedBRReweighter = True
             elif "WW" in parameterName :
                process+=selectDecayMode("h0",["h0->W+,W-;"])
                addedBRReweighter = True
             elif "ZZ" in parameterName :
                process+=selectDecayMode("h0",["h0->Z0,Z0;"])
                addedBRReweighter = True
             elif "8-" not in parameterName :
                 process+=selectDecayMode("h0",["h0->tau-,tau+;"])
                 addedBRReweighter = True
                 process+="set /Herwig/Particles/tau-:Stable Stable\n"
                 
         elif "ggHJet" in parameterName :
             process+=selectDecayMode("h0",["h0->tau-,tau+;"])
             addedBRReweighter = True
             process+="set /Herwig/Particles/tau-:Stable Stable\n"
             process+=insert_ME("MEHiggsJet")
             process+=jet_kt_cut(20.)
         elif "ggH" in parameterName :
             process+=insert_ME("MEHiggs")
             process+=insert_ME("MEHiggsJet","qqbar")
             process+=jet_kt_cut(0.0)
             if "GammaGamma" in parameterName :
                process+=selectDecayMode("h0",["h0->gamma,gamma;"])
                addedBRReweighter = True
             elif "WW" in parameterName :
                process+=selectDecayMode("h0",["h0->W+,W-;"])
                addedBRReweighter = True
             elif "ZZ" in parameterName :
                process+=selectDecayMode("h0",["h0->Z0,Z0;"])
                addedBRReweighter = True
             elif "8-" not in parameterName :
                 process+=selectDecayMode("h0",["h0->tau-,tau+;"])
                 addedBRReweighter = True
                 process+="set /Herwig/Particles/tau-:Stable Stable\n"
                 
         elif "PromptPhoton" in parameterName :
             process+=insert_ME("MEGammaJet")
             if "PromptPhoton-1" in parameterName :
                 process+="set /Herwig/Cuts/PhotonKtCut:MinKT 5.\n"
             elif "PromptPhoton-2" in parameterName :
                 process+="set /Herwig/Cuts/PhotonKtCut:MinKT 25.\n"
             elif "PromptPhoton-3" in parameterName :
                 process+="set /Herwig/Cuts/PhotonKtCut:MinKT 80.\n"
             elif "PromptPhoton-4" in parameterName :
                 process+="set /Herwig/Cuts/PhotonKtCut:MinKT 150.\n"
         elif "DiPhoton-GammaGamma" in parameterName :
             process+=insert_ME("MEGammaGamma")
             process+="set /Herwig/Cuts/PhotonKtCut:MinKT 5.\n"
             parameterName=parameterName.replace("-GammaGamma","")
         elif "DiPhoton-GammaJet" in parameterName :
             process+=insert_ME("MEGammaJet")
             process+="set /Herwig/Cuts/PhotonKtCut:MinKT 5.\n"
             parameterName=parameterName.replace("-GammaJet","")
         elif "8-WH" in parameterName :
             process+=insert_ME("MEPP2WH")
             process+=jet_kt_cut(0.0)
             if "GammaGamma" in parameterName :
                process+=selectDecayMode("h0",["h0->gamma,gamma;"])
                addedBRReweighter = True
             elif "WW" in parameterName :
                process+=selectDecayMode("h0",["h0->W+,W-;"])
                addedBRReweighter = True
             elif "ZZ" in parameterName :
                process+=selectDecayMode("h0",["h0->Z0,Z0;"])
                addedBRReweighter = True
         elif "8-ZH" in parameterName :
             process+=insert_ME("MEPP2ZH")
             process+=jet_kt_cut(0.0)
             if "GammaGamma" in parameterName :
                process+=selectDecayMode("h0",["h0->gamma,gamma;"])
                addedBRReweighter = True
             elif "WW" in parameterName :
                process+=selectDecayMode("h0",["h0->W+,W-;"])
                addedBRReweighter = True
             elif "ZZ" in parameterName :
                process+=selectDecayMode("h0",["h0->Z0,Z0;"])
                addedBRReweighter = True
         elif "WH" in parameterName :
             process+=selectDecayMode("h0",["h0->b,bbar;"])
             process+=selectDecayMode("W+",["W+->nu_e,e+;",
                                            "W+->nu_mu,mu+;"])
             addedBRReweighter = True
             process+=insert_ME("MEPP2WH")
             process+=jet_kt_cut(0.0)
         elif "ZH" in parameterName :
             process+=selectDecayMode("h0",["h0->b,bbar;"])
             process+=selectDecayMode("Z0",["Z0->e-,e+;",
                                            "Z0->mu-,mu+;"])
             addedBRReweighter = True
             process+=insert_ME("MEPP2ZH")
             process+=jet_kt_cut(0.0)
         elif "UE" in parameterName :
             if "Dipole" in parameters["shower"]:
                 process+="read snippets/MB-DipoleShower.in\n"
             else:
                 process+="set /Herwig/Shower/ShowerHandler:IntrinsicPtGaussian 2.2*GeV\n"                
                 process+="read snippets/MB.in\n"
             process+="read snippets/Diffraction.in\n"
             if "Long" in parameterName :
                 process += "set /Herwig/Decays/DecayHandler:MaxLifeTime 100*mm\n"
         elif "8-DiJets" in parameterName or "7-DiJets" in parameterName :
             process+=insert_ME("MEQCD2to2")
             process+="set MEQCD2to2:MaximumFlavour 5\n"
             process+="set /Herwig/UnderlyingEvent/MPIHandler:IdenticalToUE 0\n"
             if "-A" in parameterName :
                process+=jet_kt_cut(45.)
                process+="set /Herwig/Cuts/JetKtCut:MinEta -3.\n"
                process+="set /Herwig/Cuts/JetKtCut:MaxEta  3.\n"
             elif "-B" in parameterName :
                process+=jet_kt_cut(20.)
                process+="set /Herwig/Cuts/JetKtCut:MinEta -2.7\n"
                process+="set /Herwig/Cuts/JetKtCut:MaxEta  2.7\n"
             elif "-C" in parameterName :
                process+=jet_kt_cut(20.)
                process+="set /Herwig/Cuts/JetKtCut:MinEta -4.8\n"
                process+="set /Herwig/Cuts/JetKtCut:MaxEta  4.8\n"
             if "DiJets-1" in parameterName   : process+=mhatmin_cut(90.)
             elif "DiJets-2" in parameterName : process+=mhatmin_cut(200.)
             elif "DiJets-3" in parameterName : process+=mhatmin_cut(450.)
             elif "DiJets-4" in parameterName : process+=mhatmin_cut(750.)
             elif "DiJets-5" in parameterName : process+=mhatmin_cut(950.)
             elif "DiJets-6" in parameterName : process+=mhatmin_cut(1550.)
             elif "DiJets-7" in parameterName : process+=mhatmin_cut(2150.)
             elif "DiJets-8" in parameterName : process+=mhatmin_cut(2750.)
         elif(      "7-Jets" in parameterName 
                or  "8-Jets" in parameterName 
                or "13-Jets" in parameterName 
+               or "2760-Jets" in parameterName 
             ) :
             process+=insert_ME("MEQCD2to2")
             process+="set MEQCD2to2:MaximumFlavour 5\n"
             process+="set /Herwig/UnderlyingEvent/MPIHandler:IdenticalToUE 0\n"
             if "Jets-10" in parameterName  : process+=jet_kt_cut(1800.)
             elif "Jets-0" in parameterName : process+=jet_kt_cut(5.)
             elif "Jets-1" in parameterName : process+=jet_kt_cut(10.)
             elif "Jets-2" in parameterName : process+=jet_kt_cut(20.)
             elif "Jets-3" in parameterName : process+=jet_kt_cut(40.)
             elif "Jets-4" in parameterName : process+=jet_kt_cut(70.)
             elif "Jets-5" in parameterName : process+=jet_kt_cut(150.)
             elif "Jets-6" in parameterName : process+=jet_kt_cut(200.)
             elif "Jets-7" in parameterName : process+=jet_kt_cut(300.)
             elif "Jets-8" in parameterName : process+=jet_kt_cut(500.)
             elif "Jets-9" in parameterName : process+=jet_kt_cut(800.)
         elif(    "7-Charm" in parameterName  or "7-Bottom" in parameterName
              or "8-Bottom" in parameterName) :
             
             if("8-Bottom" in parameterName) :
                 addBRReweighter()
                 process+=selectDecayMode("Jpsi",["Jpsi->mu-,mu+;"])
                 
             if "Bottom" in parameterName :
                 process+="cp MEHeavyQuark MEBottom\n" 
                 process+="set MEBottom:QuarkType Bottom\n"
                 process+=insert_ME("MEBottom")
             else : 
                 process+="cp MEHeavyQuark MECharm\n" 
                 process+="set MECharm:QuarkType Charm\n"
                 process+=insert_ME("MECharm")
             process+="set /Herwig/UnderlyingEvent/MPIHandler:IdenticalToUE 0\n"
             if "-0" in parameterName :
                 if "Bottom" in parameterName :
                     process+="set MEBottom:Process Pair\n" 
                 process+=jet_kt_cut(0.)
             elif "-1" in parameterName : process+=jet_kt_cut(5.)
             elif "-2" in parameterName : process+=jet_kt_cut(20.)
             elif "-3" in parameterName : process+=jet_kt_cut(50.)
             elif "-4" in parameterName : process+=jet_kt_cut(80.)
             elif "-5" in parameterName : process+=jet_kt_cut(110.)
             elif "-6" in parameterName : process+=jet_kt_cut(30.)+mhatmin_cut(90.)
             elif "-7" in parameterName : process+=jet_kt_cut(30.)+mhatmin_cut(340.)
             elif "-8" in parameterName : process+=jet_kt_cut(30.)+mhatmin_cut(500.)
         elif "Top-L" in parameterName :
             process+="set MEHeavyQuark:QuarkType Top\n"
             process+=insert_ME("MEHeavyQuark")
             process+=selectDecayMode("t",["t->nu_e,e+,b;",
                                           "t->nu_mu,mu+,b;"])
             process+=addBRReweighter()
             
         elif "Top-SL" in parameterName :
             process+="set MEHeavyQuark:QuarkType Top\n"
             process+=insert_ME("MEHeavyQuark")
             process+="set /Herwig/Particles/t:Synchronized Not_synchronized\n"
             process+="set /Herwig/Particles/tbar:Synchronized Not_synchronized\n"
             process+=selectDecayMode("t",["t->nu_e,e+,b;","t->nu_mu,mu+,b;"])
             process+=selectDecayMode("tbar",["tbar->b,bbar,cbar;",
                                              "tbar->bbar,cbar,d;",
                                              "tbar->bbar,cbar,s;",
                                              "tbar->bbar,s,ubar;",
                                              "tbar->bbar,ubar,d;"])
             process+=addBRReweighter()
             
         elif "Top-All" in parameterName :
             process+="set MEHeavyQuark:QuarkType Top\n"
             process+=insert_ME("MEHeavyQuark")
         elif "WZ" in parameterName :
             process+=insert_ME("MEPP2VV","WZ")
             process+=selectDecayMode("W+",["W+->nu_e,e+;",
                                            "W+->nu_mu,mu+;"])
             process+=selectDecayMode("W-",["W-->nu_ebar,e-;",
                                            "W-->nu_mubar,mu-;"])
             process+=selectDecayMode("Z0",["Z0->e-,e+;",
                                            "Z0->mu-,mu+;"])
             addedBRReweighter = True
             
         elif "WW-emu" in parameterName :
             process+=insert_ME("MEPP2VV","WW")
             process+="set /Herwig/Particles/W+:Synchronized 0\n"
             process+="set /Herwig/Particles/W-:Synchronized 0\n"
             process+=selectDecayMode("W+",["W+->nu_e,e+;"])
             process+=selectDecayMode("W-",["W-->nu_mubar,mu-;"])
             addedBRReweighter = True
             
         elif "WW-ll" in parameterName :
             process+=insert_ME("MEPP2VV","WW")
             process+=selectDecayMode("W+",["W+->nu_e,e+;","W+->nu_mu,mu+;","W+->nu_tau,tau+;"])
             addedBRReweighter = True
             
         elif "ZZ-ll" in parameterName :
             process+=insert_ME("MEPP2VV","ZZ")
             process+=selectDecayMode("Z0",["Z0->e-,e+;",
                                            "Z0->mu-,mu+;",
                                            "Z0->tau-,tau+;"])
             addedBRReweighter = True
 
         elif "ZZ-lv" in parameterName :
             process+=insert_ME("MEPP2VV","ZZ")
             process+=selectDecayMode("Z0",["Z0->e-,e+;",
                                            "Z0->mu-,mu+;",
                                            "Z0->tau-,tau+;",
                                            "Z0->nu_e,nu_ebar;",
                                            "Z0->nu_mu,nu_mubar;",
                                            "Z0->nu_tau,nu_taubar;"])
             addedBRReweighter = True
             
         elif "W-Z-e" in parameterName :
             process+=insert_ME("MEqq2gZ2ff","Electron")
             process+=insert_ME("MEqq2W2ff","Electron")
         elif "W-Z-mu" in parameterName :
             process+=insert_ME("MEqq2gZ2ff","Muon")
             process+=insert_ME("MEqq2W2ff","Muon")
         elif "W-e" in parameterName :
             process+=insert_ME("MEqq2W2ff","Electron")
         elif "W-mu" in parameterName :
             process+=insert_ME("MEqq2W2ff","Muon")
         elif "Z-e" in parameterName :
             process+=insert_ME("MEqq2gZ2ff","Electron")
         elif "Z-mu" in parameterName :
             process+=insert_ME("MEqq2gZ2ff","Muon")
         elif "Z-LowMass-e" in parameterName :
             process+=insert_ME("MEqq2gZ2ff","Electron")
             process+=mhat_minm_maxm(20,20,70)
         elif "Z-MedMass-e" in parameterName :
             process+=insert_ME("MEqq2gZ2ff","Electron")
             process+=mhat_minm_maxm(40,40,130)
         elif "Z-LowMass-mu" in parameterName :
             process+=insert_ME("MEqq2gZ2ff","Muon")
             process+=mhat_minm_maxm(10,10,70)
         elif "Z-Mass1" in parameterName :
             process+=mhat_minm_maxm(10,10,35)
             if "-e" in parameterName :
                 process+=insert_ME("MEqq2gZ2ff","Electron")
             else :
                 process+=insert_ME("MEqq2gZ2ff","Muon")
         elif "Z-Mass2" in parameterName :
             process+=mhat_minm_maxm(25,25,70)
             if "-e" in parameterName :
                 process+=insert_ME("MEqq2gZ2ff","Electron")
             else :
                 process+=insert_ME("MEqq2gZ2ff","Muon")
         elif "Z-Mass3" in parameterName :
             process+=mhat_minm_maxm(60,60,120)
             if "-e" in parameterName :
                 process+=insert_ME("MEqq2gZ2ff","Electron")
             else :
                 process+=insert_ME("MEqq2gZ2ff","Muon")
         elif "Z-Mass4" in parameterName :
             process+=mhat_minm_maxm(110,110,8000)
             if "-e" in parameterName :
                 process+=insert_ME("MEqq2gZ2ff","Electron")
             else :
                 process+=insert_ME("MEqq2gZ2ff","Muon")
         elif "Z-HighMass1" in parameterName :
             process+=mhat_minm_maxm(116,116,400)
             if "-e" in parameterName :
                 process+=insert_ME("MEqq2gZ2ff","Electron")
             else :
                 process+=insert_ME("MEqq2gZ2ff","Muon")
         elif "Z-HighMass2" in parameterName :
             process+=mhat_minm_maxm(400,400,7000)
             if "-e" in parameterName :
                 process+=insert_ME("MEqq2gZ2ff","Electron")
             else :
                 process+=insert_ME("MEqq2gZ2ff","Muon")
         elif "W-Jet" in parameterName :
             process+=insert_ME("MEWJet","Electron","WDecay")
             if "W-Jet-1-e" in parameterName :
                 process+="set /Herwig/Cuts/WBosonKtCut:MinKT 100.0*GeV\n"
                 parameterName=parameterName.replace("W-Jet-1-e","W-Jet-e")
             elif "W-Jet-2-e" in parameterName :
                 process+="set /Herwig/Cuts/WBosonKtCut:MinKT 190.0*GeV\n"
                 parameterName=parameterName.replace("W-Jet-2-e","W-Jet-e")
             elif "W-Jet-3-e" in parameterName :
                 process+="set /Herwig/Cuts/WBosonKtCut:MinKT 270.0*GeV\n"
                 parameterName=parameterName.replace("W-Jet-3-e","W-Jet-e")
         elif "Z-Jet" in parameterName :
             if "-e" in parameterName :
                 process+=insert_ME("MEZJet","Electron","ZDecay")
                 if "Z-Jet-0-e" in parameterName :
                     process+="set /Herwig/Cuts/ZBosonKtCut:MinKT 35.0*GeV\n"
                     parameterName=parameterName.replace("Z-Jet-0-e","Z-Jet-e")
                 elif "Z-Jet-1-e" in parameterName :
                     process+="set /Herwig/Cuts/ZBosonKtCut:MinKT 100.0*GeV\n"
                     parameterName=parameterName.replace("Z-Jet-1-e","Z-Jet-e")
                 elif "Z-Jet-2-e" in parameterName :
                     process+="set /Herwig/Cuts/ZBosonKtCut:MinKT 190.0*GeV\n"
                     parameterName=parameterName.replace("Z-Jet-2-e","Z-Jet-e")
                 elif "Z-Jet-3-e" in parameterName :
                     process+="set /Herwig/Cuts/ZBosonKtCut:MinKT 270.0*GeV\n"
                     parameterName=parameterName.replace("Z-Jet-3-e","Z-Jet-e")
             else :
                 process+=insert_ME("MEZJet","Muon","ZDecay")
                 process+="set /Herwig/Cuts/ZBosonKtCut:MinKT 35.0*GeV\n"
                 parameterName=parameterName.replace("Z-Jet-0-mu","Z-Jet-mu")
         elif "WGamma" in parameterName :
             process+=insert_ME("MEPP2VGamma","1")
             process+="set MEPP2VGamma:MassOption 1"
             process+="set /Herwig/Cuts/PhotonKtCut:MinKT 10.\n"
             
             
             if "-e" in parameterName :
                 process+=selectDecayMode("W+",["W+->nu_e,e+;"])
                 process+=addBRReweighter()
             else :
                 process+=selectDecayMode("W+",["W+->nu_mu,mu+;"])
                 process+=addBRReweighter()
         elif "ZGamma" in parameterName :
             process+=insert_ME("MEPP2VGamma","2")
             process+="set /Herwig/Cuts/PhotonKtCut:MinKT 10.\n"
             if "-e" in parameterName :
                 process+=selectDecayMode("Z0",["Z0->e-,e+;"])
                 process+=addBRReweighter()
             else :
                 process+=selectDecayMode("Z0",["Z0->mu-,mu+;"])
                 process+=addBRReweighter()
         else :
             logging.error(" Process %s not supported for internal matrix elements" % name)
             sys.exit(1)
     elif(simulation=="Powheg") :
         if "VBF" in parameterName :
             process+=insert_ME("PowhegMEPP2HiggsVBF")
             if "GammaGamma" in parameterName :
                process+=selectDecayMode("h0",["h0->gamma,gamma;"])
                addedBRReweighter = True
             elif "WW" in parameterName :
                process+=selectDecayMode("h0",["h0->W+,W-;"])
                addedBRReweighter = True
             elif "ZZ" in parameterName :
                process+=selectDecayMode("h0",["h0->Z0,Z0;"])
                addedBRReweighter = True
             elif "8-" not in parameterName :
                 process+=selectDecayMode("h0",["h0->tau-,tau+;"])
                 addedBRReweighter = True
                 process+="set /Herwig/Particles/tau-:Stable Stable\n"
             
         elif "ggHJet" in parameterName :
             logging.error(" Process %s not supported for POWHEG matrix elements" % name)
             sys.exit(1)
         elif "ggH" in parameterName :
             process+=insert_ME("PowhegMEHiggs")
             if "GammaGamma" in parameterName :
                process+=selectDecayMode("h0",["h0->gamma,gamma;"])
                addedBRReweighter = True
             elif "WW" in parameterName :
                process+=selectDecayMode("h0",["h0->W+,W-;"])
                addedBRReweighter = True
             elif "ZZ" in parameterName :
                process+=selectDecayMode("h0",["h0->Z0,Z0;"])
                addedBRReweighter = True
             elif "8-" not in parameterName :
                 process+=selectDecayMode("h0",["h0->tau-,tau+;"])
                 addedBRReweighter = True
                 process+="set /Herwig/Particles/tau-:Stable Stable\n"
         elif "8-WH" in parameterName :
             process+=insert_ME("PowhegMEPP2WH")
             process+=jet_kt_cut(0.0)
             if "GammaGamma" in parameterName :
                process+=selectDecayMode("h0",["h0->gamma,gamma;"])
                addedBRReweighter = True
             elif "WW" in parameterName :
                process+=selectDecayMode("h0",["h0->W+,W-;"])
                addedBRReweighter = True
             elif "ZZ" in parameterName :
                process+=selectDecayMode("h0",["h0->Z0,Z0;"])
                addedBRReweighter = True
         elif "8-ZH" in parameterName :
             process+=insert_ME("PowhegMEPP2ZH")
             process+=jet_kt_cut(0.0)
             if "GammaGamma" in parameterName :
                process+=selectDecayMode("h0",["h0->gamma,gamma;"])
                addedBRReweighter = True
             elif "WW" in parameterName :
                process+=selectDecayMode("h0",["h0->W+,W-;"])
                addedBRReweighter = True
             elif "ZZ" in parameterName :
                process+=selectDecayMode("h0",["h0->Z0,Z0;"])
                addedBRReweighter = True
         elif "WH" in parameterName :
             process+=selectDecayMode("h0",["h0->b,bbar;"])
             process+=selectDecayMode("W+",["W+->nu_e,e+;",
                                            "W+->nu_mu,mu+;"])
             addedBRReweighter = True
             process+=insert_ME("PowhegMEPP2WH")
             process+=jet_kt_cut(0.0)
         elif "ZH" in parameterName :
             process+=selectDecayMode("h0",["h0->b,bbar;"])
             process+=selectDecayMode("Z0",["Z0->e-,e+;",
                                            "Z0->mu-,mu+;"])
             addedBRReweighter = True
             process+=insert_ME("PowhegMEPP2ZH")
             process+=jet_kt_cut(0.0)
         elif "UE" in parameterName :
             logging.error(" Process %s not supported for powheg matrix elements" % name)
             sys.exit(1)
         elif "WZ" in parameterName :
             process+="create Herwig::HwDecayHandler /Herwig/NewPhysics/DecayHandler\n"
             process+="set /Herwig/NewPhysics/DecayHandler:NewStep No\n"
             process+="set /Herwig/Shower/ShowerHandler:SplitHardProcess No\n";
             process+="set /Herwig/Decays/ZDecayer:PhotonGenerator NULL\n";
             process+="set /Herwig/Decays/WDecayer:PhotonGenerator NULL\n";
             process+="insert /Herwig/NewPhysics/DecayHandler:Excluded 0 /Herwig/Particles/tau-\n"
             process+="insert /Herwig/NewPhysics/DecayHandler:Excluded 1 /Herwig/Particles/tau+\n"
             process+="insert /Herwig/Generators/EventGenerator:EventHandler:PreCascadeHandlers 0 /Herwig/NewPhysics/DecayHandler\n"
             process+=insert_ME("PowhegMEPP2VV","WZ")
             process+=selectDecayMode("W+",["W+->nu_e,e+;",
                                            "W+->nu_mu,mu+;"])
             process+=selectDecayMode("W-",["W-->nu_ebar,e-;",
                                            "W-->nu_mubar,mu-;"])
             process+=selectDecayMode("Z0",["Z0->e-,e+;",
                                            "Z0->mu-,mu+;"])
             addedBRReweighter = True
             
         elif "WW-emu" in parameterName :
             process+="create Herwig::HwDecayHandler /Herwig/NewPhysics/DecayHandler\n"
             process+="set /Herwig/NewPhysics/DecayHandler:NewStep No\n"
             process+="set /Herwig/Shower/ShowerHandler:SplitHardProcess No\n";
             process+="set /Herwig/Decays/ZDecayer:PhotonGenerator NULL\n";
             process+="set /Herwig/Decays/WDecayer:PhotonGenerator NULL\n";
             process+="insert /Herwig/NewPhysics/DecayHandler:Excluded 0 /Herwig/Particles/tau-\n"
             process+="insert /Herwig/NewPhysics/DecayHandler:Excluded 1 /Herwig/Particles/tau+\n"
             process+="insert /Herwig/Generators/EventGenerator:EventHandler:PreCascadeHandlers 0 /Herwig/NewPhysics/DecayHandler\n"
             process+=insert_ME("PowhegMEPP2VV","WW")
             process+="set /Herwig/Particles/W+:Synchronized 0\n"
             process+="set /Herwig/Particles/W-:Synchronized 0\n"
             process+=selectDecayMode("W+",["W+->nu_e,e+;"])
             process+=selectDecayMode("W-",["W-->nu_mubar,mu-;"])
             addedBRReweighter = True
             
         elif "WW-ll" in parameterName :
             process+="create Herwig::HwDecayHandler /Herwig/NewPhysics/DecayHandler\n"
             process+="set /Herwig/NewPhysics/DecayHandler:NewStep No\n"
             process+="set /Herwig/Shower/ShowerHandler:SplitHardProcess No\n";
             process+="set /Herwig/Decays/ZDecayer:PhotonGenerator NULL\n";
             process+="set /Herwig/Decays/WDecayer:PhotonGenerator NULL\n";
             process+="insert /Herwig/NewPhysics/DecayHandler:Excluded 0 /Herwig/Particles/tau-\n"
             process+="insert /Herwig/NewPhysics/DecayHandler:Excluded 1 /Herwig/Particles/tau+\n"
             process+="insert /Herwig/Generators/EventGenerator:EventHandler:PreCascadeHandlers 0 /Herwig/NewPhysics/DecayHandler\n"
             process+=insert_ME("PowhegMEPP2VV","WW")
             process+=selectDecayMode("W+",["W+->nu_e,e+;",
                                            "W+->nu_mu,mu+;",
                                            "W+->nu_tau,tau+;"])
             addedBRReweighter = True
             
         elif "ZZ-ll" in parameterName :
             process+="create Herwig::HwDecayHandler /Herwig/NewPhysics/DecayHandler\n"
             process+="set /Herwig/NewPhysics/DecayHandler:NewStep No\n"
             process+="set /Herwig/Shower/ShowerHandler:SplitHardProcess No\n";
             process+="set /Herwig/Decays/ZDecayer:PhotonGenerator NULL\n";
             process+="set /Herwig/Decays/WDecayer:PhotonGenerator NULL\n";
             process+="insert /Herwig/NewPhysics/DecayHandler:Excluded 0 /Herwig/Particles/tau-\n"
             process+="insert /Herwig/NewPhysics/DecayHandler:Excluded 1 /Herwig/Particles/tau+\n"
             process+="insert /Herwig/Generators/EventGenerator:EventHandler:PreCascadeHandlers 0 /Herwig/NewPhysics/DecayHandler\n"
             process+=insert_ME("PowhegMEPP2VV","ZZ")
             process+=selectDecayMode("Z0",["Z0->e-,e+;",
                                            "Z0->mu-,mu+;",
                                            "Z0->tau-,tau+;"])
             addedBRReweighter = True
             
         elif "ZZ-lv" in parameterName :
             process+="create Herwig::HwDecayHandler /Herwig/NewPhysics/DecayHandler\n"
             process+="set /Herwig/NewPhysics/DecayHandler:NewStep No\n"
             process+="set /Herwig/Shower/ShowerHandler:SplitHardProcess No\n";
             process+="set /Herwig/Decays/ZDecayer:PhotonGenerator NULL\n";
             process+="set /Herwig/Decays/WDecayer:PhotonGenerator NULL\n";
             process+="insert /Herwig/NewPhysics/DecayHandler:Excluded 0 /Herwig/Particles/tau-\n"
             process+="insert /Herwig/NewPhysics/DecayHandler:Excluded 1 /Herwig/Particles/tau+\n"
             process+="insert /Herwig/Generators/EventGenerator:EventHandler:PreCascadeHandlers 0 /Herwig/NewPhysics/DecayHandler\n"
             process+=insert_ME("PowhegMEPP2VV","ZZ")
             process+=selectDecayMode("Z0",["Z0->e-,e+;",
                                            "Z0->mu-,mu+;",
                                            "Z0->tau-,tau+;",
                                            "Z0->nu_e,nu_ebar;",
                                            "Z0->nu_mu,nu_mubar;",
                                            "Z0->nu_tau,nu_taubar;"])
             addedBRReweighter = True
             
         elif "W-Z-e" in parameterName :
             process+=insert_ME("PowhegMEqq2gZ2ff","Electron")
             process+=insert_ME("PowhegMEqq2W2ff","Electron")
         elif "W-Z-mu" in parameterName :
             process+=insert_ME("MEqq2gZ2ff","Muon")
             process+=insert_ME("MEqq2W2ff","Muon")
         elif "W-e" in parameterName :
             process+=insert_ME("PowhegMEqq2W2ff","Electron")
         elif "W-mu" in parameterName :
             process+=insert_ME("PowhegMEqq2W2ff","Muon")
         elif "Z-e" in parameterName :
             process+=insert_ME("PowhegMEqq2gZ2ff","Electron")
         elif "Z-mu" in parameterName :
             process+=insert_ME("PowhegMEqq2gZ2ff","Muon")
         elif "Z-LowMass-e" in parameterName :
             process+=insert_ME("PowhegMEqq2gZ2ff","Electron")
             process+=mhat_minm_maxm(20,20,70)
         elif "Z-MedMass-e" in parameterName :
             process+=insert_ME("PowhegMEqq2gZ2ff","Electron")
             process+=mhat_minm_maxm(40,40,130)
         elif "Z-LowMass-mu" in parameterName :
             process+=insert_ME("PowhegMEqq2gZ2ff","Muon")
             process+=mhat_minm_maxm(10,10,70)
         elif "Z-Mass1" in parameterName :
             process+=mhat_minm_maxm(10,10,35)
             if "-e" in parameterName :
                 process+=insert_ME("PowhegMEqq2gZ2ff","Electron")
             else :
                 process+=insert_ME("PowhegMEqq2gZ2ff","Muon")
         elif "Z-Mass2" in parameterName :
             process+=mhat_minm_maxm(25,25,70)
             if "-e" in parameterName :
                 process+=insert_ME("PowhegMEqq2gZ2ff","Electron")
             else :
                 process+=insert_ME("PowhegMEqq2gZ2ff","Muon")
         elif "Z-Mass3" in parameterName :
             process+=mhat_minm_maxm(60,60,120)
             if "-e" in parameterName :
                 process+=insert_ME("PowhegMEqq2gZ2ff","Electron")
             else :
                 process+=insert_ME("PowhegMEqq2gZ2ff","Muon")
         elif "Z-Mass4" in parameterName :
             process+=mhat_minm_maxm(110,110,8000)
             if "-e" in parameterName :
                 process+=insert_ME("PowhegMEqq2gZ2ff","Electron")
             else :
                 process+=insert_ME("PowhegMEqq2gZ2ff","Muon")
         elif "Z-HighMass1" in parameterName :
             process+=mhat_minm_maxm(116,116,400)
             if "-e" in parameterName :
                 process+=insert_ME("PowhegMEqq2gZ2ff","Electron")
             else :
                 process+=insert_ME("PowhegMEqq2gZ2ff","Muon")
         elif "Z-HighMass2" in parameterName :
             process+=mhat_minm_maxm(400,400,7000)
             if "-e" in parameterName :
                 process+=insert_ME("PowhegMEqq2gZ2ff","Electron")
             else :
                 process+=insert_ME("PowhegMEqq2gZ2ff","Muon")
         elif "DiPhoton-GammaGamma" in parameterName :
             process+=insert_ME("MEGammaGammaPowheg","GammaGamma")
             process+=insert_ME("MEGammaGamma","gg")
             process+="set /Herwig/Cuts/PhotonKtCut:MinKT 5.\n"
             process+=jet_kt_cut(5.)
             parameterName=parameterName.replace("-GammaGamma","")
         elif "DiPhoton-GammaJet" in parameterName :
             process+=insert_ME("MEGammaGammaPowheg","VJet")
             process+="set /Herwig/Cuts/PhotonKtCut:MinKT 5.\n"
             process+=jet_kt_cut(5.)
             parameterName=parameterName.replace("-GammaJet","")
         else :
             logging.error(" Process %s not supported for internal POWHEG matrix elements" % name)
             sys.exit(1)
             
     elif( simulation=="Matchbox" or simulation=="Merging" ) :
         if "VBF" in parameterName :
             parameters["nlo"] = "read Matchbox/VBFNLO.in\n"
             if(simulation=="Merging"):
                 process+="cd /Herwig/Merging/\n"
             process+="insert "+thefactory+":DiagramGenerator:RestrictLines 0 /Herwig/Particles/Z0\n"
             process+="insert "+thefactory+":DiagramGenerator:RestrictLines 0 /Herwig/Particles/W+\n"
             process+="insert "+thefactory+":DiagramGenerator:RestrictLines 0 /Herwig/Particles/W-\n"
             process+="insert "+thefactory+":DiagramGenerator:RestrictLines 0 /Herwig/Particles/gamma\n"
             process+="do "+thefactory+":DiagramGenerator:TimeLikeRange 0 0\n"
             if(simulation=="Matchbox"):
                 process+=addProcess(thefactory,"p p h0 j j","0","3","FixedScale",0,0)
             elif(simulation=="Merging"):
                 process+=addProcess(thefactory,"p p h0 j j","0","3","FixedScale",1,1)
             process+=setHardProcessWidthToZero(["h0"])
             process+="set /Herwig/MatrixElements/Matchbox/Scales/FixedScale:FixedScale 125.7\n"
             if "GammaGamma" in parameterName :
                process+=selectDecayMode("h0",["h0->gamma,gamma;"])
                process+=addBRReweighter()
             elif "WW" in parameterName :
                process+=selectDecayMode("h0",["h0->W+,W-;"])
                process+=addBRReweighter()
             elif "ZZ" in parameterName :
                process+=selectDecayMode("h0",["h0->Z0,Z0;"])
                process+=addBRReweighter()
             elif "8-" not in parameterName :
                 process+=selectDecayMode("h0",["h0->tau-,tau+;"])
                 process+=addBRReweighter()
                 process+="set /Herwig/Particles/tau-:Stable Stable\n"
         elif "ggHJet" in parameterName :
             if(simulation=="Merging"):
                logging.warning("ggHJet not explicitly tested for %s " % simulation)
                sys.exit(0)
             parameters["nlo"] = "read Matchbox/MadGraph-GoSam.in\nread Matchbox/HiggsEffective.in\n"
             process+=selectDecayMode("h0",["h0->tau-,tau+;"])
             process+=addBRReweighter()
             process+="set /Herwig/Particles/tau-:Stable Stable\n"
             process+=setHardProcessWidthToZero(["h0"])
             process+=addProcess(thefactory,"p p h0 j","3","1","FixedScale",0,0)
             process+=addFirstJet("20")
             process+="set "+thefactory+":ScaleChoice /Herwig/MatrixElements/Matchbox/Scales/FixedScale\n"
             process+="set /Herwig/MatrixElements/Matchbox/Scales/FixedScale:FixedScale 125.7\n"
         elif "ggH" in parameterName :
             parameters["nlo"] = "read Matchbox/MadGraph-GoSam.in\nread Matchbox/HiggsEffective.in\n"
             if(simulation=="Merging"):
                 process+= "cd /Herwig/MatrixElements/Matchbox/Amplitudes\nset OpenLoops:HiggsEff On\nset MadGraph:Model heft\n"
                 process+="cd /Herwig/Merging/\n"
             process+=setHardProcessWidthToZero(["h0"])
             if(simulation=="Matchbox"):
                 process+=addProcess(thefactory,"p p h0","2","1","FixedScale",0,0)
             elif(simulation=="Merging"):
                 process+=addProcess(thefactory,"p p h0","2","1","FixedScale",2,2)
             process+="set /Herwig/MatrixElements/Matchbox/Scales/FixedScale:FixedScale 125.7\n"
             if "GammaGamma" in parameterName :
                process+=selectDecayMode("h0",["h0->gamma,gamma;"])
                process+=addBRReweighter()
             elif "WW" in parameterName :
                process+=selectDecayMode("h0",["h0->W+,W-;"])
                process+=addBRReweighter()
             elif "ZZ" in parameterName :
                process+=selectDecayMode("h0",["h0->Z0,Z0;"])
                process+=addBRReweighter()
             elif "8-" not in parameterName :
                 process+=selectDecayMode("h0",["h0->tau-,tau+;"])
                 process+=addBRReweighter()
                 process+="set /Herwig/Particles/tau-:Stable Stable\n"
         elif "8-WH" in parameterName :
             if(simulation=="Merging"):
               logging.warning("8-WH not explicitly tested for %s " % simulation)
               sys.exit(0)
             process+=setHardProcessWidthToZero(["h0","W+","W-"])
             process+=addProcess(thefactory,"p p W+ h0","0","2","FixedScale",0,0)
             process+=addProcess(thefactory,"p p W- h0","0","2","FixedScale",0,0)
             process+="set /Herwig/MatrixElements/Matchbox/Scales/FixedScale:FixedScale 125.7\n"
             if "GammaGamma" in parameterName :
                process+=selectDecayMode("h0",["h0->gamma,gamma;"])
                process+=addBRReweighter()
             elif "WW" in parameterName :
                process+=selectDecayMode("h0",["h0->W+,W-;"])
                process+=addBRReweighter()
             elif "ZZ" in parameterName :
                process+=selectDecayMode("h0",["h0->Z0,Z0;"])
                process+=addBRReweighter()
                
         elif "8-ZH" in parameterName :
             if(simulation=="Merging"):
               logging.warning("8-ZH not explicitly tested for %s " % simulation)
               sys.exit(0)
             process+=setHardProcessWidthToZero(["h0","Z0"])
             process+=addProcess(thefactory,"p p Z0 h0","0","2","FixedScale",0,0)
             process+="set /Herwig/MatrixElements/Matchbox/Scales/FixedScale:FixedScale 125.7\n"
             if "GammaGamma" in parameterName :
                process+=selectDecayMode("h0",["h0->gamma,gamma;"])
                process+=addBRReweighter()
             elif "WW" in parameterName :
                process+=selectDecayMode("h0",["h0->W+,W-;"])
                process+=addBRReweighter()
             elif "ZZ" in parameterName :
                process+=selectDecayMode("h0",["h0->Z0,Z0;"])
                process+=addBRReweighter()
                
         elif "WH" in parameterName :
             if(simulation=="Merging"):
               logging.warning("WH not explicitly tested for %s " % simulation)
               sys.exit(0)
             process+=selectDecayMode("h0",["h0->b,bbar;"])
             process+=addBRReweighter()
             process+=setHardProcessWidthToZero(["h0"])
             process+=addProcess(thefactory,"p p e+ nu h0","0","3","LeptonPairMassScale",0,0)
             process+=addProcess(thefactory,"p p e- nu h0","0","3","LeptonPairMassScale",0,0)
             process+=addProcess(thefactory,"p p mu+ nu h0","0","3","LeptonPairMassScale",0,0)
             process+=addProcess(thefactory,"p p mu- nu h0","0","3","LeptonPairMassScale",0,0)
             process+=addLeptonPairCut("60","120")
         elif "ZH" in parameterName :
             if(simulation=="Merging"):
               logging.warning("ZH not explicitly tested for %s " % simulation)
               sys.exit(0)
             process+=selectDecayMode("h0",["h0->b,bbar;"])
             process+=addBRReweighter()
             process+=setHardProcessWidthToZero(["h0"])
             process+=addProcess(thefactory,"p p e+ e- h0","0","3","LeptonPairMassScale",0,0)
             process+=addProcess(thefactory,"p p mu+ mu- h0","0","3","LeptonPairMassScale",0,0)
             process+=addLeptonPairCut("60","120")
         elif "UE" in parameterName :
             logging.error(" Process %s not supported for Matchbox matrix elements" % name)
             sys.exit(1)
         elif "8-DiJets" in parameterName or "7-DiJets" in parameterName :
             if(simulation=="Matchbox"):
               process+=addProcess(thefactory,"p p j j","2","0","MaxJetPtScale",0,0)
             elif(simulation=="Merging"):
               process+=addProcess(thefactory,"p p j j","2","0","MaxJetPtScale",1,1)
             process+="set /Herwig/UnderlyingEvent/MPIHandler:IdenticalToUE 0\n"
             if "-A" in parameterName :
                  process+=addFirstJet("45")
                  process+=addSecondJet("25")
                  process+="set /Herwig/Cuts/FirstJet:YRange  -3. 3.\n"
                  process+="set /Herwig/Cuts/SecondJet:YRange -3. 3.\n"
             elif "-B" in parameterName :
                  process+=addFirstJet("20")
                  process+=addSecondJet("15")
                  process+="set /Herwig/Cuts/FirstJet:YRange  -2.7 2.7\n"
                  process+="set /Herwig/Cuts/SecondJet:YRange -2.7 2.7\n"
             elif "-C" in parameterName :
                  process+=addFirstJet("20")
                  process+=addSecondJet("15")
                  process+="set /Herwig/Cuts/FirstJet:YRange  -4.8 4.8\n"
                  process+="set /Herwig/Cuts/SecondJet:YRange -4.8 4.8\n"
             else :
                  logging.error("Exit 00001")
                  sys.exit(1)
             if "DiJets-1" in parameterName   : process+=addJetPairCut("90")
             elif "DiJets-2" in parameterName : process+=addJetPairCut("200")
             elif "DiJets-3" in parameterName : process+=addJetPairCut("450")
             elif "DiJets-4" in parameterName : process+=addJetPairCut("750")
             elif "DiJets-5" in parameterName : process+=addJetPairCut("950")
             elif "DiJets-6" in parameterName : process+=addJetPairCut("1550")
             elif "DiJets-7" in parameterName : process+=addJetPairCut("2150")
             elif "DiJets-8" in parameterName : process+=addJetPairCut("2750")
             else :
                 logging.error("Exit 00002")
                 sys.exit(1)
 
 
         elif(      "7-Jets" in parameterName 
                or  "8-Jets" in parameterName 
                or "13-Jets" in parameterName 
+               or "2760-Jets" in parameterName 
             ) :
             if(simulation=="Matchbox"):
                 process+=addProcess(thefactory,"p p j j","2","0","MaxJetPtScale",0,0)
             elif(simulation=="Merging"):
                 process+=addProcess(thefactory,"p p j j","2","0","MaxJetPtScale",1,1)
             process+="set /Herwig/UnderlyingEvent/MPIHandler:IdenticalToUE 0\n"
             if "Jets-10" in parameterName  : process+=addFirstJet("1800")
             elif "Jets-0" in parameterName : process+=addFirstJet("5")
             elif "Jets-1" in parameterName : process+=addFirstJet("10")
             elif "Jets-2" in parameterName : process+=addFirstJet("20")
             elif "Jets-3" in parameterName : process+=addFirstJet("40")
             elif "Jets-4" in parameterName : process+=addFirstJet("70")
             elif "Jets-5" in parameterName : process+=addFirstJet("150")
             elif "Jets-6" in parameterName : process+=addFirstJet("200")
             elif "Jets-7" in parameterName : process+=addFirstJet("300")
             elif "Jets-8" in parameterName : process+=addFirstJet("500")
             elif "Jets-9" in parameterName : process+=addFirstJet("800")
             else :
                 logging.error("Exit 00003")
                 sys.exit(1)
         elif(     "7-Charm" in parameterName or "7-Bottom" in parameterName
               or "8-Bottom" in parameterName) :
             parameters["bscheme"]=fourFlavour
             process+="set /Herwig/Particles/b:HardProcessMass 4.2*GeV\n"
             process+="set /Herwig/Particles/bbar:HardProcessMass 4.2*GeV\n"
             
             if("8-Bottom" in parameterName) :
                 addBRReweighter()
                 process+=selectDecayMode("Jpsi",["Jpsi->mu-,mu+;"])
             
             if "Bottom" in parameterName :
                 if(simulation=="Matchbox"):
                     process+=addProcess(thefactory,"p p b bbar","2","0","MaxJetPtScale",0,0)
                 elif(simulation=="Merging"):
                     process+=addProcess(thefactory,"p p b bbar","2","0","MaxJetPtScale",1,0)
             else:
                 if(simulation=="Matchbox"):
                     process+=addProcess(thefactory,"p p c cbar","2","0","MaxJetPtScale",0,0)
                 elif(simulation=="Merging"):
                     process+=addProcess(thefactory,"p p c cbar","2","0","MaxJetPtScale",1,0)
 
             process+="set /Herwig/UnderlyingEvent/MPIHandler:IdenticalToUE 0\n"
             if "-0" in parameterName   : process+=addFirstJet("0")
             elif "-1" in parameterName : process+=addFirstJet("5")
             elif "-2" in parameterName : process+=addFirstJet("20")
             elif "-3" in parameterName : process+=addFirstJet("50")
             elif "-4" in parameterName : process+=addFirstJet("80")
             elif "-5" in parameterName : process+=addFirstJet("110")
             elif "-6" in parameterName :
                 process+=addFirstJet("30")
                 process+=addSecondJet("25")
                 process+=addJetPairCut("90")
             elif "-7" in parameterName :
                 process+=addFirstJet("30")
                 process+=addSecondJet("25")
                 process+=addJetPairCut("340")
             elif "-8" in parameterName :
                 process+=addFirstJet("30")
                 process+=addSecondJet("25")
                 process+=addJetPairCut("500")
             else :
                 logging.error("Exit 00004")
                 sys.exit(1)
                   
         elif "Top-L" in parameterName :
             process+=setHardProcessWidthToZero(["t","tbar"])
             if(simulation=="Matchbox"):
                 process+=addProcess(thefactory,"p p t tbar","2","0","TopPairMTScale",0,0)
             elif(simulation=="Merging"):
                 process+=addProcess(thefactory,"p p t tbar","2","0","TopPairMTScale",2,2)
             process+=selectDecayMode("t",["t->nu_e,e+,b;",
                                           "t->nu_mu,mu+,b;"])
             process+=addBRReweighter()
             
         elif "Top-SL" in parameterName :
             process+=setHardProcessWidthToZero(["t","tbar"])
             if(simulation=="Matchbox"):
                 process+=addProcess(thefactory,"p p t tbar","2","0","TopPairMTScale",0,0)
             elif(simulation=="Merging"):
                 process+=addProcess(thefactory,"p p t tbar","2","0","TopPairMTScale",2,2)
             process+="set /Herwig/Particles/t:Synchronized Not_synchronized\n"
             process+="set /Herwig/Particles/tbar:Synchronized Not_synchronized\n"
             process+=selectDecayMode("t",["t->nu_e,e+,b;",
                                           "t->nu_mu,mu+,b;"])
             process+=selectDecayMode("tbar",["tbar->b,bbar,cbar;",
                                              "tbar->bbar,cbar,d;",
                                              "tbar->bbar,cbar,s;",
                                              "tbar->bbar,s,ubar;",
                                              "tbar->bbar,ubar,d;"])
             process+=addBRReweighter()
             
         elif "Top-All" in parameterName :
             process+=setHardProcessWidthToZero(["t","tbar"])
             if(simulation=="Matchbox"):
                 process+=addProcess(thefactory,"p p t tbar","2","0","TopPairMTScale",0,0)
             elif(simulation=="Merging"):
                 process+=addProcess(thefactory,"p p t tbar","2","0","TopPairMTScale",2,2)
         elif "WZ" in parameterName :
             if(simulation=="Merging"):
               logging.warning("WZ not explicitly tested for %s " % simulation)
               sys.exit(0)
             process+=setHardProcessWidthToZero(["W+","W-","Z0"])
             process+=addProcess(thefactory,"p p W+ Z0","0","2","FixedScale",0,0)
             process+=addProcess(thefactory,"p p W- Z0","0","2","FixedScale",0,0)
             process+="set /Herwig/MatrixElements/Matchbox/Scales/FixedScale:FixedScale 171.6*GeV\n\n"
             process+=selectDecayMode("W+",["W+->nu_e,e+;",
                                            "W+->nu_mu,mu+;"])
             process+=selectDecayMode("W-",["W-->nu_ebar,e-;",
                                            "W-->nu_mubar,mu-;"])
             process+=selectDecayMode("Z0",["Z0->e-,e+;",
                                            "Z0->mu-,mu+;"])
             process+=addBRReweighter()
             process+=addLeptonPairCut("60","120")
         elif "WW-emu" in parameterName :
             if(simulation=="Merging"):
               logging.warning("WW-emu not explicitly tested for %s " % simulation)
               sys.exit(0)
             
             process+=setHardProcessWidthToZero(["W+","W-","Z0"])
             process+=addProcess(thefactory,"p p W+ W-","0","2","FixedScale",0,0)
             process+="set /Herwig/MatrixElements/Matchbox/Scales/FixedScale:FixedScale 160.8*GeV\n"
             process+="set /Herwig/Particles/W+:Synchronized 0\n"
             process+="set /Herwig/Particles/W-:Synchronized 0\n"
             process+=selectDecayMode("W+",["W+->nu_e,e+;"])
             process+=selectDecayMode("W-",["W-->nu_mubar,mu-;"])
             process+=addBRReweighter()
             parameters["bscheme"] = "read Matchbox/FourFlavourScheme.in\n"
             
             process+=addLeptonPairCut("60","120")
         elif "WW-ll" in parameterName :
             if(simulation=="Merging"):
               logging.warning("WW-ll not explicitly tested for %s " % simulation)
               sys.exit(0)
             process+=setHardProcessWidthToZero(["W+","W-","Z0"])
             process+=addProcess(thefactory,"p p W+ W-","0","2","FixedScale",0,0)
             process+="set /Herwig/MatrixElements/Matchbox/Scales/FixedScale:FixedScale 160.8*GeV\n"
             process+=selectDecayMode("W+",["W+->nu_e,e+;",
                                            "W+->nu_mu,mu+;",
                                            "W+->nu_tau,tau+;"])
             process+=addBRReweighter()
             process+=addLeptonPairCut("60","120")
             parameters["bscheme"] = "read Matchbox/FourFlavourScheme.in\n"
 
         elif "ZZ-ll" in parameterName :
             if(simulation=="Merging"):
               logging.warning("ZZ-ll not explicitly tested for %s " % simulation)
               sys.exit(0)
             process+=setHardProcessWidthToZero(["W+","W-","Z0"])
             process+=addProcess(thefactory,"p p Z0 Z0","0","2","FixedScale",0,0)
             process+="set /Herwig/MatrixElements/Matchbox/Scales/FixedScale:FixedScale 182.2*GeV\n"
             process+=selectDecayMode("Z0",["Z0->e-,e+;",
                                            "Z0->mu-,mu+;",
                                            "Z0->tau-,tau+;"])
             process+=addBRReweighter()
             process+=addLeptonPairCut("60","120")
         elif "ZZ-lv" in parameterName :
             if(simulation=="Merging"):
               logging.warning("ZZ-lv not explicitly tested for %s " % simulation)
               sys.exit(0)
             process+=setHardProcessWidthToZero(["W+","W-","Z0"])
             process+=addProcess(thefactory,"p p Z0 Z0","0","2","FixedScale",0,0)
             process+="set /Herwig/MatrixElements/Matchbox/Scales/FixedScale:FixedScale 182.2*GeV\n"
             process+=selectDecayMode("Z0",["Z0->e-,e+;",
                                            "Z0->mu-,mu+;",
                                            "Z0->tau-,tau+;",
                                            "Z0->nu_e,nu_ebar;",
                                            "Z0->nu_mu,nu_mubar;",
                                            "Z0->nu_tau,nu_taubar;"])
             process+=addBRReweighter()
             process+=addLeptonPairCut("60","120")
         elif "W-Z-e" in parameterName :
             if(simulation=="Matchbox"):
               process+=addProcess(thefactory,"p p e+ e-","0","2","LeptonPairMassScale",0,0)
               process+=addProcess(thefactory,"p p e+ nu","0","2","LeptonPairMassScale",0,0)
               process+=addProcess(thefactory,"p p e- nu","0","2","LeptonPairMassScale",0,0)
             elif(simulation=="Merging"):
               process+=particlegroup('epm','e+','e-')
               process+=particlegroup('epmnu','e+','e-','nu_e','nu_ebar')
               process+=addProcess(thefactory,"p p epm epmnu","0","2","LeptonPairMassScale",2,2)
             process+=addLeptonPairCut("60","120")
         elif "W-Z-mu" in parameterName :
             if(simulation=="Matchbox"):
               process+=addProcess(thefactory,"p p mu+ mu-","0","2","LeptonPairMassScale",0,0)
               process+=addProcess(thefactory,"p p mu+ nu","0","2","LeptonPairMassScale",0,0)
               process+=addProcess(thefactory,"p p mu- nu","0","2","LeptonPairMassScale",0,0)
             elif(simulation=="Merging"):
               process+=particlegroup('mupm','mu+','mu-')
               process+=particlegroup('mupmnu','mu+','mu-','nu_mu','nu_mubar')
               process+=addProcess(thefactory,"p p mupm mupmnu","0","2","LeptonPairMassScale",2,2)
             process+=addLeptonPairCut("60","120")
         elif "W-e" in parameterName :
             if(simulation=="Matchbox"):
                 process+=addProcess(thefactory,"p p e+ nu","0","2","LeptonPairMassScale",0,0)
                 process+=addProcess(thefactory,"p p e- nu","0","2","LeptonPairMassScale",0,0)
             elif(simulation=="Merging"):
                 process+=particlegroup('epm','e+','e-')
                 process+=addProcess(thefactory,"p p epm nu","0","2","LeptonPairMassScale",2,2)
             process+=addLeptonPairCut("60","120")
 
         elif "W-mu" in parameterName :
             if(simulation=="Matchbox"):
                 process+=addProcess(thefactory,"p p mu+ nu","0","2","LeptonPairMassScale",0,0)
                 process+=addProcess(thefactory,"p p mu- nu","0","2","LeptonPairMassScale",0,0)
             elif(simulation=="Merging"):
                 process+=particlegroup('mupm','mu+','mu-')
                 process+=addProcess(thefactory,"p p mupm nu","0","2","LeptonPairMassScale",2,2)
             process+=addLeptonPairCut("60","120")
 
         elif "Z-e" in parameterName :
             if(simulation=="Matchbox"):
                 process+=addProcess(thefactory,"p p e+ e-","0","2","LeptonPairMassScale",0,0)
             elif(simulation=="Merging"):
                 process+=addProcess(thefactory,"p p e+ e-","0","2","LeptonPairMassScale",2,2)
             process+=addLeptonPairCut("60","120")
         elif "Z-mu" in parameterName :
             if(simulation=="Matchbox"):
                 process+=addProcess(thefactory,"p p mu+ mu-","0","2","LeptonPairMassScale",0,0)
             elif(simulation=="Merging"):
                 process+=addProcess(thefactory,"p p mu+ mu-","0","2","LeptonPairMassScale",2,2)
             process+=addLeptonPairCut("60","120")
         elif "Z-jj" in parameterName :
             if(simulation=="Merging"):
               logging.warning("Z-jj not explicitly tested for %s " % simulation)
               sys.exit(0)
             process+=addProcess(thefactory,"p p e+ e- j j","2","2","LeptonPairMassScale",0,0)
             process+=addFirstJet("40")
             process+=addSecondJet("30")
             process+=addLeptonPairCut("60","120")
         elif "Z-LowMass-e" in parameterName :
             if(simulation=="Matchbox"):
                process+=addProcess(thefactory,"p p e+ e-","0","2","LeptonPairMassScale",0,0)
             elif(simulation=="Merging"):
                process+=addProcess(thefactory,"p p e+ e-","0","2","LeptonPairMassScale",2,2)
             process+=addLeptonPairCut("20","70")
         elif "Z-MedMass-e" in parameterName :
             if(simulation=="Matchbox"):
                 process+=addProcess(thefactory,"p p e+ e-","0","2","LeptonPairMassScale",0,0)
             elif(simulation=="Merging"):
                 process+=addProcess(thefactory,"p p e+ e-","0","2","LeptonPairMassScale",2,2)
             process+=addLeptonPairCut("40","130")
         elif "Z-LowMass-mu" in parameterName :
             if(simulation=="Matchbox"):
                 process+=addProcess(thefactory,"p p mu+ mu-","0","2","LeptonPairMassScale",0,0)
             elif(simulation=="Merging"):
                 process+=addProcess(thefactory,"p p mu+ mu-","0","2","LeptonPairMassScale",2,2)
             process+=addLeptonPairCut("10","70")
         elif "Z-Mass1" in parameterName :
             process+=addLeptonPairCut("10","35")
             if "-e" in parameterName :
                 if(simulation=="Matchbox"):
                     process+=addProcess(thefactory,"p p e+ e-","0","2","LeptonPairMassScale",0,0)
                 elif(simulation=="Merging"):
                     process+=addProcess(thefactory,"p p e+ e-","0","2","LeptonPairMassScale",2,2)
             else :
                 if(simulation=="Matchbox"):
                     process+=addProcess(thefactory,"p p mu+ mu-","0","2","LeptonPairMassScale",0,0)
                 elif(simulation=="Merging"):
                     process+=addProcess(thefactory,"p p mu+ mu-","0","2","LeptonPairMassScale",2,2)
         elif "Z-Mass2" in parameterName :
             process+=addLeptonPairCut("25","70")
             if "-e" in parameterName :
                 if(simulation=="Matchbox"):
                     process+=addProcess(thefactory,"p p e+ e-","0","2","LeptonPairMassScale",0,0)
                 elif(simulation=="Merging"):
                     process+=addProcess(thefactory,"p p e+ e-","0","2","LeptonPairMassScale",2,2)
             else :
                 if(simulation=="Matchbox"):
                     process+=addProcess(thefactory,"p p mu+ mu-","0","2","LeptonPairMassScale",0,0)
                 elif(simulation=="Merging"):
                     process+=addProcess(thefactory,"p p mu+ mu-","0","2","LeptonPairMassScale",2,2)
         elif "Z-Mass3" in parameterName :
             process+=addLeptonPairCut("60","120")
             if "-e" in parameterName :
                 if(simulation=="Matchbox"):
                     process+=addProcess(thefactory,"p p e+ e-","0","2","LeptonPairMassScale",0,0)
                 elif(simulation=="Merging"):
                     process+=addProcess(thefactory,"p p e+ e-","0","2","LeptonPairMassScale",2,2)
             else :
                 if(simulation=="Matchbox"):
                     process+=addProcess(thefactory,"p p mu+ mu-","0","2","LeptonPairMassScale",0,0)
                 elif(simulation=="Merging"):
                     process+=addProcess(thefactory,"p p mu+ mu-","0","2","LeptonPairMassScale",2,2)
         elif "Z-Mass4" in parameterName :
             process+=addLeptonPairCut("115","8000")
             if "-e" in parameterName :
                 if(simulation=="Matchbox"):
                   process+=addProcess(thefactory,"p p e+ e-","0","2","LeptonPairMassScale",0,0)
                 elif(simulation=="Merging"):
                   process+=addProcess(thefactory,"p p e+ e-","0","2","LeptonPairMassScale",2,2)
             else :
                 if(simulation=="Matchbox"):
                   process+=addProcess(thefactory,"p p mu+ mu-","0","2","LeptonPairMassScale",0,0)
                 elif(simulation=="Merging"):
                   process+=addProcess(thefactory,"p p mu+ mu-","0","2","LeptonPairMassScale",2,2)
         elif "Z-HighMass1" in parameterName :
             process+=addLeptonPairCut("116","400")
             if "-e" in parameterName :
                 if(simulation=="Matchbox"):
                   process+=addProcess(thefactory,"p p e+ e-","0","2","LeptonPairMassScale",0,0)
                 elif(simulation=="Merging"):
                   process+=addProcess(thefactory,"p p e+ e-","0","2","LeptonPairMassScale",2,2)
             else :
                 if(simulation=="Matchbox"):
                   process+=addProcess(thefactory,"p p mu+ mu-","0","2","LeptonPairMassScale",0,0)
                 elif(simulation=="Merging"):
                   process+=addProcess(thefactory,"p p mu+ mu-","0","2","LeptonPairMassScale",2,2)
         elif "Z-HighMass2" in parameterName :
             process+=addLeptonPairCut("400","7000")
             if "-e" in parameterName :
                 if(simulation=="Matchbox"):
                   process+=addProcess(thefactory,"p p e+ e-","0","2","LeptonPairMassScale",0,0)
                 elif(simulation=="Merging"):
                   process+=addProcess(thefactory,"p p e+ e-","0","2","LeptonPairMassScale",2,2)
             else :
                 if(simulation=="Matchbox"):
                   process+=addProcess(thefactory,"p p mu+ mu-","0","2","LeptonPairMassScale",0,0)
                 elif(simulation=="Merging"):
                   process+=addProcess(thefactory,"p p mu+ mu-","0","2","LeptonPairMassScale",2,2)
         elif "W-Jet" in parameterName :
             if(simulation=="Merging"):
               logging.warning("W-Jet not explicitly tested for %s " % simulation)
               sys.exit(0)
             
             process+=addProcess(thefactory,"p p e+ nu j","1","2","HTScale",0,0)
             process+=addProcess(thefactory,"p p e- nu j","1","2","HTScale",0,0)
             
             process+=addLeptonPairCut("60","120")
             if "W-Jet-1-e" in parameterName :
                 process+=addFirstJet("100")
                 parameterName=parameterName.replace("W-Jet-1-e","W-Jet-e")
             elif "W-Jet-2-e" in parameterName :
                 process+=addFirstJet("190")
                 parameterName=parameterName.replace("W-Jet-2-e","W-Jet-e")
             elif "W-Jet-3-e" in parameterName :
                 process+=addFirstJet("270")
                 parameterName=parameterName.replace("W-Jet-3-e","W-Jet-e")
             else :
                 logging.error("Exit 00005")
                 sys.exit(1)
         elif "Z-Jet" in parameterName :
             if(simulation=="Merging"):
               logging.warning("Z-Jet not explicitly tested for %s " % simulation)
               sys.exit(0)
             
             
             if "-e" in parameterName :
                 process+=addProcess(thefactory,"p p e+ e- j","1","2","HTScale",0,0)
                 if "Z-Jet-0-e" in parameterName :
                     process+=addFirstJet("35")
                     parameterName=parameterName.replace("Z-Jet-0-e","Z-Jet-e")
                 elif "Z-Jet-1-e" in parameterName :
                     process+=addFirstJet("100")
                     parameterName=parameterName.replace("Z-Jet-1-e","Z-Jet-e")
                 elif "Z-Jet-2-e" in parameterName :
                     process+=addFirstJet("190")
                     parameterName=parameterName.replace("Z-Jet-2-e","Z-Jet-e")
                 elif "Z-Jet-3-e" in parameterName :
                     process+=addFirstJet("270")
                     parameterName=parameterName.replace("Z-Jet-3-e","Z-Jet-e")
                 else :
                     logging.error("Exit 00006")
                     sys.exit(1)
             else :
                 process+=addProcess(thefactory,"p p mu+ mu- j","1","2","HTScale",0,0)
                 process+=addFirstJet("35")
                 parameterName=parameterName.replace("Z-Jet-0-mu","Z-Jet-mu")
             process+=addLeptonPairCut("60","120")
         elif "Z-bb" in parameterName :
             if(simulation=="Merging"):
               logging.warning("Z-bb not explicitly tested for %s " % simulation)
               sys.exit(0)
             parameters["bscheme"]=fourFlavour
             process+="set /Herwig/Particles/b:HardProcessMass 4.2*GeV\nset /Herwig/Particles/bbar:HardProcessMass 4.2*GeV\n"
             process+=addProcess(thefactory,"p p e+ e- b bbar","2","2","FixedScale",0,0)
             process+=addLeptonPairCut("66","116")
             process+=addFirstJet("18")
             process+=addSecondJet("15")
             process+=addLeptonPairCut("60","120")
         elif "Z-b" in parameterName :
             if(simulation=="Merging"):
               logging.warning("Z-b not explicitly tested for %s " % simulation)
               sys.exit(0)
             process+=particlegroup('bjet','b','bbar')
             process+=addProcess(thefactory,"p p e+ e- bjet","1","2","FixedScale",0,0)
             process+="set /Herwig/MatrixElements/Matchbox/Scales/FixedScale:FixedScale 91.2*GeV\n"
             process+=addLeptonPairCut("60","120")
             process+=addFirstJet("15")
         elif "W-b" in parameterName :
             if(simulation=="Merging"):
               logging.warning("W-b not explicitly tested for %s " % simulation)
               sys.exit(0)
             parameters["bscheme"]=fourFlavour
             process += "set /Herwig/Particles/b:HardProcessMass 4.2*GeV\nset /Herwig/Particles/bbar:HardProcessMass 4.2*GeV\n"
             process+=addProcess(thefactory,"p p e-  nu b bbar","2","2","FixedScale",0,0)
             process+=addProcess(thefactory,"p p mu+ nu b bbar","2","2","FixedScale",0,0)
             process += "set /Herwig/MatrixElements/Matchbox/Scales/FixedScale:FixedScale 80.4*GeV\n"
             process+=addFirstJet("30")
             process+=addLeptonPairCut("60","120")
         else :
             logging.error(" Process %s not supported for Matchbox matrix elements" % name)
             sys.exit(1)
 # LHC-GammaGamma
 elif(collider=="LHC-GammaGamma" ) :
     if   "-7-" in parameterName : process = StringBuilder(collider_lumi(7000.0))
     elif "-8-" in parameterName : process = StringBuilder(collider_lumi(8000.0))
     else :                        process = StringBuilder(collider_lumi(7000.0))
     if(simulation=="") :
         if "7" in parameterName : process += insert_ME("MEgg2ff","Muon")
         else :
             logging.error(" Process %s not supported for default matrix elements" % name)
             sys.exit(1)
     else :
         logging.error("LHC-GammaGamma not supported for %s " % simulation)
         sys.exit(1)
 
 
 parameters['parameterFile'] = os.path.join(collider,"{c}-{pn}.in".format(c=collider, pn=parameterName))
 parameters['runname'] = 'Rivet-%s' % name
 parameters['process'] = str(process)
 
 
 #check if selecteddecaymode and addedBRReweighter is consistent
 
 if selecteddecaymode and not addedBRReweighter:
     logging.error("Decaymode was selected but no BRReweighter was added.")
     sys.exit(1)
 
 if addedBRReweighter and not selecteddecaymode:
     logging.error("BRReweighter was added but no Decaymode was selected.")
     sys.exit(1)
 
 # check that we only add one process if in merging mode:
 
 if numberOfAddedProcesses > 1 and simulation =="Merging":
     logging.error("In Merging only one process is allowed at the moment. See ticket #403.")
     sys.exit(1)
 
 # Check if a process was added for Merging or Matchbox:
 
 if numberOfAddedProcesses == 0 and (simulation =="Merging" or simulation =="Matchbox"):
     logging.error("No process was selected.")
     sys.exit(1)
 
 # get template and write the file
 
 with open(os.path.join("Rivet/Templates",templateName), 'r') as f:
     templateText = f.read()
 
 template = Template( templateText )
 
 with open(os.path.join("Rivet",name+".in"), 'w') as f:
         f.write( template.substitute(parameters) )
diff --git a/Tests/python/merge-BFactory b/Tests/python/merge-BFactory
--- a/Tests/python/merge-BFactory
+++ b/Tests/python/merge-BFactory
@@ -1,213 +1,214 @@
 #! /usr/bin/env python
 import logging
 import sys
 
 if sys.version_info[:3] < (2,4,0):
     print "rivet scripts require Python version >= 2.4.0... exiting"
     sys.exit(1)
 
 import os, yoda
 
 # #############################################
 
 def fillAbove(desthisto, sourcehistosbysqrts):
     for sqrts, h in sorted(sourcehistosbysqrts.iteritems()) :
         for i in range(0,h.numPoints) :
             if(h.points[i].x-0.01<sqrts and
                h.points[i].x+0.01>sqrts) :
                 desthisto.addPoint(h.points[i])
 
 def merge(hpath):
     global inhistos
     global outhistos
     try:
         fillAbove(outhistos[hpath], inhistos[hpath])
     except:
         logging.error("Unknown analysis object" + hpath)
         sys.exit(1)
 
 def useOne(hpath, sqrts):
     global inhistos
     global outhistos
     try:
         outhistos[hpath] =  inhistos[hpath][float(sqrts)]
     except:
         pass
 
 if __name__ == "__main__":
     import logging
     from optparse import OptionParser, OptionGroup
     parser = OptionParser(usage="%prog name")
     verbgroup = OptionGroup(parser, "Verbosity control")
     verbgroup.add_option("-v", "--verbose", action="store_const", const=logging.DEBUG, dest="LOGLEVEL",
                          default=logging.INFO, help="print debug (very verbose) messages")
     verbgroup.add_option("-q", "--quiet", action="store_const", const=logging.WARNING, dest="LOGLEVEL",
                          default=logging.INFO, help="be very quiet")
     parser.add_option_group(verbgroup)
     (opts, args) = parser.parse_args()
     logging.basicConfig(level=opts.LOGLEVEL, format="%(message)s")
 
     ## Check args
     if len(args) < 1:
         logging.error("Must specify at least the name of the files")
         sys.exit(1)
 
 # #######################################
 
 yodafiles=["-10.52","-10.52-sym","-10.54",
            "-10.58-res","-10.58","-Upsilon",
            "-Upsilon2","-Upsilon4","-10.45","-Tau"]
 
 ## Get histos
 inhistos = {}
 outhistos={}
 weights = {}
 for f in yodafiles:
     file = "Rivet-%s%s.yoda" % (args[0], f)
     if(file.find("10.45")>0) :
         sqrts=10.45
     elif(file.find("10.52")>0) :
         sqrts=10.52
     elif(file.find("10.54")>0) :
         sqrts=10.54
     elif(file.find("10.58")>0) :
         sqrts=10.58
     elif(file.find("Tau")>0) :
         sqrts=10.58
     elif(file.find("Upsilon4")>0) :
         sqrts=10.58
     elif(file.find("Upsilon2")>0) :
         sqrts=10.02
     elif(file.find("Upsilon")>0) :
         sqrts=9.46
     if not os.access(file, os.R_OK):
         if(file.find("Upsilon")>=0 or file.find("Tau")>=0) : continue
         logging.error("%s can not be read" % file)
         continue
     try:
         aos = yoda.read(file)
     except:
         logging.error("%s can not be parsed as yoda" % file)
         continue
     ## Get histos from this YODA file
     for aopath, ao in aos.iteritems() :
+        if("RAW" in aopath) :continue
         # jet shapes
         if(aopath.find("6265367")>0 or aopath.find("6895344")>0 or
            aopath.find("6181155")>0 or aopath.find("2789213")>0 or
            aopath.find("2669951")>0) :
            if not inhistos.has_key(aopath):
                inhistos[aopath] = {}
            tmpE = inhistos[aopath]
            sqrttemp=sqrts
            if(aopath.find("2669951")>0 and aopath.find("d01")>0 and 
               sqrts==10.45) :
                sqrts=9.9
            
            if not tmpE.has_key(sqrts):
                tmpE[sqrts] = ao
            else:
                raise Exception("A set with sqrts = %s already exists" % ( sqrts))
            sqrts=sqrttemp
         else :
             outhistos[aopath] = ao
 
 ## Make empty output histos if needed
 for hpath,hsets in inhistos.iteritems():
     if( hpath.find("2669951")>0) :
         if(type(hsets.values()[0])==yoda.core.Scatter2D) :
             outhistos[hpath] = yoda.core.Scatter2D(hsets.values()[0].path,hsets.values()[0].title)
         else :
             outhistos[hpath] = hsets.values()[0]
 
 # BELLE
 useOne("/BELLE_2006_S6265367/d01-x01-y01","10.52")
 useOne("/BELLE_2006_S6265367/d01-x01-y02","10.52")
 useOne("/BELLE_2006_S6265367/d01-x01-y03","10.52")
 useOne("/BELLE_2006_S6265367/d01-x01-y04","10.52")
 useOne("/BELLE_2006_S6265367/d01-x01-y05","10.52")
 useOne("/BELLE_2006_S6265367/d01-x01-y06","10.52")
 useOne("/BELLE_2006_S6265367/d01-x01-y07","10.52")
 useOne("/BELLE_2006_S6265367/d01-x01-y08","10.52")
 useOne("/BELLE_2006_S6265367/d02-x01-y01","10.52")
 useOne("/BELLE_2006_S6265367/d02-x01-y02","10.52")
 useOne("/BELLE_2006_S6265367/d03-x01-y01","10.52")
 useOne("/BELLE_2006_S6265367/d03-x01-y02","10.52")
 useOne("/BELLE_2006_S6265367/d04-x01-y01","10.52")
 useOne("/BELLE_2006_S6265367/d04-x01-y02","10.52")
 useOne("/BELLE_2006_S6265367/d05-x01-y01","10.52")
 useOne("/BELLE_2006_S6265367/d05-x01-y02","10.52")
 useOne("/BELLE_2006_S6265367/d06-x01-y01","10.52")
 useOne("/BELLE_2006_S6265367/d06-x01-y02","10.52")
 useOne("/BELLE_2006_S6265367/d07-x01-y01","10.52")
 useOne("/BELLE_2006_S6265367/d07-x01-y02","10.52")
 useOne("/BELLE_2006_S6265367/d08-x01-y01","10.52")
 useOne("/BELLE_2006_S6265367/d08-x01-y02","10.52")
 useOne("/BELLE_2006_S6265367/d09-x01-y01","10.58")
 useOne("/BELLE_2006_S6265367/d09-x01-y02","10.58")
 useOne("/BELLE_2006_S6265367/d10-x01-y01","10.58")
 useOne("/BELLE_2006_S6265367/d10-x01-y02","10.58")
 useOne("/BELLE_2006_S6265367/d11-x01-y01","10.58")
 useOne("/BELLE_2006_S6265367/d11-x01-y02","10.58")
 useOne("/BELLE_2006_S6265367/d12-x01-y01","10.58")
 useOne("/BELLE_2006_S6265367/d12-x01-y02","10.58")
 useOne("/BELLE_2006_S6265367/d13-x01-y01","10.58")
 useOne("/BELLE_2006_S6265367/d13-x01-y02","10.58")
 useOne("/BELLE_2006_S6265367/d14-x01-y01","10.58")
 useOne("/BELLE_2006_S6265367/d14-x01-y02","10.58")
 useOne("/BELLE_2006_S6265367/d15-x01-y01","10.58")
 useOne("/BELLE_2006_S6265367/d15-x01-y02","10.58")
 # BABAR
 useOne("/BABAR_2007_S6895344/d01-x01-y01","10.54")
 useOne("/BABAR_2007_S6895344/d02-x01-y01","10.54")
 useOne("/BABAR_2007_S6895344/d03-x01-y01","10.58")
 useOne("/BABAR_2007_S6895344/d04-x01-y01","10.58")
 # BABAR
 useOne("/BABAR_2005_S6181155/d01-x01-y01","10.58")
 useOne("/BABAR_2005_S6181155/d02-x01-y01","10.58")
 useOne("/BABAR_2005_S6181155/d02-x01-y02","10.54")
 useOne("/BABAR_2005_S6181155/d03-x01-y01","10.54")
 useOne("/BABAR_2005_S6181155/d04-x01-y01","10.58")
 useOne("/BABAR_2005_S6181155/d05-x01-y01","10.58")
 useOne("/BABAR_2005_S6181155/d05-x01-y02","10.54")
 # ARGUS
 useOne("/ARGUS_1993_S2789213/d01-x01-y01","10.45")
 useOne("/ARGUS_1993_S2789213/d01-x01-y02","10.45")
 useOne("/ARGUS_1993_S2789213/d01-x01-y03","10.45")
 useOne("/ARGUS_1993_S2789213/d01-x01-y04","10.45")
 useOne("/ARGUS_1993_S2789213/d01-x01-y05","10.45")
 useOne("/ARGUS_1993_S2789213/d02-x01-y01", "9.46")
 useOne("/ARGUS_1993_S2789213/d02-x01-y02", "9.46")
 useOne("/ARGUS_1993_S2789213/d02-x01-y03", "9.46")
 useOne("/ARGUS_1993_S2789213/d02-x01-y04", "9.46")
 useOne("/ARGUS_1993_S2789213/d02-x01-y05", "9.46")
 useOne("/ARGUS_1993_S2789213/d03-x01-y01","10.58")
 useOne("/ARGUS_1993_S2789213/d03-x01-y02","10.58")
 useOne("/ARGUS_1993_S2789213/d03-x01-y03","10.58")
 useOne("/ARGUS_1993_S2789213/d03-x01-y04","10.58")
 useOne("/ARGUS_1993_S2789213/d03-x01-y05","10.58")
 useOne("/ARGUS_1993_S2789213/d04-x01-y01","10.45")
 useOne("/ARGUS_1993_S2789213/d05-x01-y01", "9.46")
 useOne("/ARGUS_1993_S2789213/d06-x01-y01","10.58")
 useOne("/ARGUS_1993_S2789213/d07-x01-y01","10.45")
 useOne("/ARGUS_1993_S2789213/d08-x01-y01", "9.46")
 useOne("/ARGUS_1993_S2789213/d09-x01-y01","10.58")
 useOne("/ARGUS_1993_S2789213/d10-x01-y01","10.45")
 useOne("/ARGUS_1993_S2789213/d11-x01-y01", "9.46")
 useOne("/ARGUS_1993_S2789213/d12-x01-y01","10.58")
 useOne("/ARGUS_1993_S2789213/d13-x01-y01","10.45")
 useOne("/ARGUS_1993_S2789213/d14-x01-y01", "9.46")
 useOne("/ARGUS_1993_S2789213/d15-x01-y01","10.58")
 
 if("/ARGUS_1993_S2669951/d04-x01-y01" in outhistos) :
     useOne("/ARGUS_1993_S2669951/d02-x01-y01","10.45")
     useOne("/ARGUS_1993_S2669951/d03-x01-y01","9.46")
     useOne("/ARGUS_1993_S2669951/d04-x01-y01","10.02")
     merge("/ARGUS_1993_S2669951/d01-x01-y01")
     merge("/ARGUS_1993_S2669951/d01-x01-y02")
     merge("/ARGUS_1993_S2669951/d05-x01-y01")
 
 # Choose output file
 name = args[0]+".yoda"
 # output the yoda file
 yoda.writeYODA(outhistos,name)
 sys.exit(0)
diff --git a/Tests/python/merge-DIS b/Tests/python/merge-DIS
--- a/Tests/python/merge-DIS
+++ b/Tests/python/merge-DIS
@@ -1,154 +1,155 @@
 #! /usr/bin/env python
 import logging
 import sys
 
 if sys.version_info[:3] < (2,4,0):
     print "rivet scripts require Python version >= 2.4.0... exiting"
     sys.exit(1)
 
 import os, yoda
 
 # #############################################
 
 def fillAbove(desthisto, sourcehistosbyq2):
     q2high=1e100
     q2low=-1e100
     for q2,h in  sorted(sourcehistosbyq2.iteritems(),reverse=True) :
         q2low=q2
         for i in range(0,h.numBins) :
             if(h.bins[i].xMin  >= q2low and 
                h.bins[i].xMin  <  q2high ) :
                 desthisto.bins[i] += h.bins[i]
         q2high=q2
 
 def merge(hpath):
     global inhistos
     global outhistos
     try:
         fillAbove(outhistos[hpath], inhistos[hpath])
     except:
         pass
 
 def useOne(hpath, q2):
     global inhistos
     global outhistos
     try:
         outhistos[hpath] =  inhistos[hpath][float(q2)]
     except:
         pass
 
 if __name__ == "__main__":
     import logging
     from optparse import OptionParser, OptionGroup
     parser = OptionParser(usage="%prog name")
     verbgroup = OptionGroup(parser, "Verbosity control")
     verbgroup.add_option("-v", "--verbose", action="store_const", const=logging.DEBUG, dest="LOGLEVEL",
                          default=logging.INFO, help="print debug (very verbose) messages")
     verbgroup.add_option("-q", "--quiet", action="store_const", const=logging.WARNING, dest="LOGLEVEL",
                          default=logging.INFO, help="be very quiet")
     parser.add_option_group(verbgroup)
     (opts, args) = parser.parse_args()
     logging.basicConfig(level=opts.LOGLEVEL, format="%(message)s")
 
     ## Check args
     if len(args) < 1:
         logging.error("Must specify at least the name of the files")
         sys.exit(1)
 
 # #######################################
 
 yodafiles=["-e--LowQ2","-e+-LowQ2","-e+-HighQ2"]
 
 ## Get histos
 inhistos = {}
 outhistos={}
 weights = {}
 
 for f in yodafiles:
     file = "Rivet-%s%s.yoda" % (args[0], f)
     if(file.find("Low")> 0) :
         q2=0
     elif(file.find("High")>0) :
         q2=50
 
     if not os.access(file, os.R_OK):
         logging.error("%s can not be read" % file)
         break
     try:
         aos = yoda.read(file)
     except:
         logging.error("%s can not be parsed as YODA" % file)
         break
     ## Get histos from this YODA file
     for aopath, ao in aos.iteritems() :
+        if("RAW" in aopath) :continue
         if(aopath.find("4129130")>0 ) :
            if not inhistos.has_key(aopath):
                inhistos[aopath] = {}
            tmpE = inhistos[aopath]
            if not tmpE.has_key(q2):
                tmpE[q2] = ao
            else:
                 raise Exception("A set with q2    = %s already exists" % ( q2   ))
         elif(aopath.find("2919893")>0 ) :
             outhistos[aopath] = ao
         elif(aopath.find("_XSEC")>=0 or aopath.find("_EVTCOUNT")>=0) :
             continue
         else :
             logging.error("Analysis %s is unknown" % aopath)
             sys.exit(1)
 
 ## Make empty output histos if needed
 for hpath,hsets in inhistos.iteritems():
     if( hpath.find("4129130")>0 and (hpath.find("d33")>0 or hpath.find("d34")>0)) :
         if(type(hsets.values()[0])==yoda.core.Scatter2D) :
             outhistos[hpath] = yoda.core.Scatter2D(hsets.values()[0].path,hsets.values()[0].title)
         elif(type(hsets.values()[0])==yoda.core.Profile1D) :
             outhistos[hpath] = yoda.core.Profile1D(hsets.values()[0].path,hsets.values()[0].title)
             for i in range(0,hsets.values()[0].numBins) :
                 outhistos[hpath].addBin(hsets.values()[0].bins[i].xMin,hsets.values()[0].bins[i].xMax)
         else :
             logging.error("Histogram %s is of unknown type" % hpath)
             sys.exit(1)
 
 # H1 transverse energy
 useOne("/H1_2000_S4129130/d01-x01-y01","0")
 useOne("/H1_2000_S4129130/d02-x01-y01","0")
 useOne("/H1_2000_S4129130/d03-x01-y01","0")
 useOne("/H1_2000_S4129130/d04-x01-y01","0")
 useOne("/H1_2000_S4129130/d05-x01-y01","0")
 useOne("/H1_2000_S4129130/d06-x01-y01","0")
 useOne("/H1_2000_S4129130/d07-x01-y01","0")
 useOne("/H1_2000_S4129130/d08-x01-y01","0")
 useOne("/H1_2000_S4129130/d09-x01-y01","0")
 useOne("/H1_2000_S4129130/d10-x01-y01","0")
 useOne("/H1_2000_S4129130/d11-x01-y01","0")
 useOne("/H1_2000_S4129130/d12-x01-y01","0")
 useOne("/H1_2000_S4129130/d13-x01-y01","0")
 useOne("/H1_2000_S4129130/d14-x01-y01","0")
 useOne("/H1_2000_S4129130/d15-x01-y01","0")
 useOne("/H1_2000_S4129130/d16-x01-y01","50")
 useOne("/H1_2000_S4129130/d17-x01-y01","50")
 useOne("/H1_2000_S4129130/d18-x01-y01","50")
 useOne("/H1_2000_S4129130/d19-x01-y01","50")
 useOne("/H1_2000_S4129130/d20-x01-y01","50")
 useOne("/H1_2000_S4129130/d21-x01-y01","50")
 useOne("/H1_2000_S4129130/d22-x01-y01","50")
 useOne("/H1_2000_S4129130/d23-x01-y01","50")
 useOne("/H1_2000_S4129130/d24-x01-y01","50")
 useOne("/H1_2000_S4129130/d25-x01-y01","0")
 useOne("/H1_2000_S4129130/d26-x01-y01","0")
 useOne("/H1_2000_S4129130/d27-x01-y01","0")
 useOne("/H1_2000_S4129130/d28-x01-y01","0")
 useOne("/H1_2000_S4129130/d29-x01-y01","50")
 useOne("/H1_2000_S4129130/d30-x01-y01","50")
 useOne("/H1_2000_S4129130/d31-x01-y01","50")
 useOne("/H1_2000_S4129130/d32-x01-y01","50")
 
 merge("/H1_2000_S4129130/d33-x01-y01")
 merge("/H1_2000_S4129130/d34-x01-y01")
 
 # Choose output file
 name = args[0]+".yoda"
 # output the yoda file
 yoda.writeYODA(outhistos,name)
 sys.exit(0)
diff --git a/Tests/python/merge-LEP b/Tests/python/merge-LEP
--- a/Tests/python/merge-LEP
+++ b/Tests/python/merge-LEP
@@ -1,888 +1,889 @@
 #! /usr/bin/env python
 # import lighthisto
 import logging
 import sys
 
 if sys.version_info[:3] < (2,4,0):
     print "rivet scripts require Python version >= 2.4.0... exiting"
     sys.exit(1)
 
 import os, yoda, copy
 
 # # #############################################
 
 def fillAbove(desthisto, sourcehistosbysqrts):
     if type(desthisto) is yoda.core.Scatter2D :
         if(desthisto.numPoints!=1) :
             logging.error("Must have one bin for a specific sqrt(s) for %s" % desthisto.path)
             sys.exit(1)
         for sqrts, h in sorted(sourcehistosbysqrts.iteritems()) :
             if(h.numPoints!=1) :
                 continue
             if(desthisto.points[0].x != h.points[0].x) :
                 desthisto.addPoint(h.points[0])
 
     elif(type(desthisto)==yoda.core.Profile1D) :
         for sqrts, h in sorted(sourcehistosbysqrts.iteritems()) :
             for i in range(0,h.numBins) :
                 if(sqrts>=h.bins[i].xMin and \
                    sqrts<=h.bins[i].xMax) :
                     desthisto.bins[i] += h.bins[i]
                     break
     else :
         logging.error("Unknown analysis object" + desthisto.path)
         sys.exit(1)
 
 def merge(hpath):
     global inhistos
     global outhistos
     try:
         fillAbove(outhistos[hpath], inhistos[hpath])
     except:
         pass
 
 def useOne(hpath, sqrts):
     global inhistos
     global outhistos
     try:
         outhistos[hpath] =  inhistos[hpath][float(sqrts)]
     except:
         pass
 
 if __name__ == "__main__":
     import logging
     from optparse import OptionParser, OptionGroup
     parser = OptionParser(usage="%prog name")
     verbgroup = OptionGroup(parser, "Verbosity control")
     verbgroup.add_option("-v", "--verbose", action="store_const", const=logging.DEBUG, dest="LOGLEVEL",
                          default=logging.INFO, help="print debug (very verbose) messages")
     verbgroup.add_option("-q", "--quiet", action="store_const", const=logging.WARNING, dest="LOGLEVEL",
                          default=logging.INFO, help="be very quiet")
     parser.add_option_group(verbgroup)
     parser.add_option("--with-gg",
                       action='store_true' ,
                       dest="gg",
                       default=False,
                       help="Include gg analyese")
     parser.add_option("--without-gg",
                       action='store_false',
                       dest="gg",
                       default=False,
                       help="Don\'t include gg analyses")
     (opts, args) = parser.parse_args()
     logging.basicConfig(level=opts.LOGLEVEL, format="%(message)s")
     ## Check args
     if len(args) < 1:
         logging.error("Must specify at least the name of the files")
         sys.exit(1)
 
 #######################################
 
 yodafiles=["-130","-133","-136","-177","-192",
            "-196","-202","-206","-91" ,"-91-nopi" ,\
            "-161","-183","-197","-35" ,"-172",\
            "-189","-200","-44","-14","-22","-10",\
            "-12.8","-26.8","-48.0","-93.0",\
            "-12","-13","-17","-27.6","-29","-30.2","-30.75",\
            "-30.7","-30","-31.3","-34.8","-43.6","-50","-52",\
            "-55","-56","-57","-60.8","-60","-61.4","-9.4" ]
 # add gg if needed
 if(opts.gg) :
     yodafiles += ["-10.5-gg","-12.8-gg","-16.86-gg","-26.8-gg",\
                   "-35.44-gg","-97.0-gg","-11.96-gg","-13.96-gg",\
                   "-21.84-gg","-28.48-gg","-48.0-gg"]
 ## Get histos
 inhistos = {}
 outhistos={}
 for f in yodafiles:
     file = "Rivet-%s%s.yoda" % (args[0], f)
     sqrts=float(f.split("-")[1].replace(".yoda",""))
     if not os.access(file, os.R_OK):
         logging.error("%s cannot be read" % file)
         continue
     try:
         aos = yoda.read(file)
     except:
         logging.error("%s cannot be parsed as yoda" % file)
         continue
     ## Get histos from this YODA file
     for aopath, ao in aos.iteritems() :
+        if("RAW" in aopath) :continue
         # jet shapes
         if(aopath.find("4300807")>0 or aopath.find("6132243")>0 or
            aopath.find("5765862")>0 or aopath.find("3612880")>0 or
            aopath.find("4328825")>0 or aopath.find("5361494")>0 or
            aopath.find("2148048")>0 or aopath.find("295160")>0  or
            aopath.find("190818" )>0 or aopath.find("154270")>0 or
            aopath.find("277658")>0 or
            aopath.find("MULTIPLICITIES")>0) :
             if not inhistos.has_key(aopath):
                 inhistos[aopath] = {}
             if not inhistos[aopath].has_key(sqrts):
                 inhistos[aopath][sqrts] = ao
             else:
                 raise Exception("A set with sqrts = %s already exists" % ( sqrts))
         elif(aopath.find("OPAL_2004_I648738")>=0) :
             if(file.find("gg")>=0) :
                 if(aopath.find("y03")>=0) :
                     outhistos[aopath] = ao
             else :
                 if(aopath.find("y03")<0) :
                     outhistos[aopath] = ao
         else :
             outhistos[aopath] = ao
 
 # ## Make empty output histos if needed
 for hpath,hsets in inhistos.iteritems():
     if( hpath.find("4300807")>0 or hpath.find("6132243")>0 or 
         hpath.find("5765862")>0 or hpath.find("295160")>0 or
         hpath.find("4328825")>0 or hpath.find("5361494")>0 or
         hpath.find("190818")>0 or hpath.find("154270")>0 or
         hpath.find("277658")>0) :
         # workhisto = copy.deepcopy(hsets.values()[0])
         # outhistos[hpath] = workhisto
         outhistos[hpath] = hsets.values()[0]
 
 # tasso
 useOne("/TASSO_1990_S2148048/d06-x01-y01","14")
 useOne("/TASSO_1990_S2148048/d07-x01-y01","14")
 useOne("/TASSO_1990_S2148048/d08-x01-y01","14")
 useOne("/TASSO_1990_S2148048/d06-x01-y02","22")
 useOne("/TASSO_1990_S2148048/d07-x01-y02","22")
 useOne("/TASSO_1990_S2148048/d08-x01-y02","22")
 useOne("/TASSO_1990_S2148048/d06-x01-y03","35")
 useOne("/TASSO_1990_S2148048/d07-x01-y03","35")
 useOne("/TASSO_1990_S2148048/d08-x01-y03","35")
 useOne("/TASSO_1990_S2148048/d06-x01-y04","44")
 useOne("/TASSO_1990_S2148048/d07-x01-y04","44")
 useOne("/TASSO_1990_S2148048/d08-x01-y04","44")
 # jade
 useOne("/JADE_1998_S3612880/d02-x01-y01","44")
 useOne("/JADE_1998_S3612880/d03-x01-y01","44")
 useOne("/JADE_1998_S3612880/d04-x01-y01","44")
 useOne("/JADE_1998_S3612880/d05-x01-y01","44")
 useOne("/JADE_1998_S3612880/d06-x01-y01","35")
 useOne("/JADE_1998_S3612880/d07-x01-y01","35")
 useOne("/JADE_1998_S3612880/d08-x01-y01","35")
 useOne("/JADE_1998_S3612880/d09-x01-y01","35")
 useOne("/JADE_1998_S3612880/d10-x01-y01","44")
 useOne("/JADE_1998_S3612880/d11-x01-y01","35")
 useOne("/JADE_1998_S3612880/d12-x01-y01","22")
 # opal/jade
 useOne("/JADE_OPAL_2000_S4300807/d07-x01-y01","35")
 useOne("/JADE_OPAL_2000_S4300807/d07-x01-y02","35")
 useOne("/JADE_OPAL_2000_S4300807/d07-x01-y03","35")
 useOne("/JADE_OPAL_2000_S4300807/d07-x01-y04","35")
 useOne("/JADE_OPAL_2000_S4300807/d07-x01-y05","35")
 useOne("/JADE_OPAL_2000_S4300807/d08-x01-y01","44")
 useOne("/JADE_OPAL_2000_S4300807/d08-x01-y02","44")
 useOne("/JADE_OPAL_2000_S4300807/d08-x01-y03","44")
 useOne("/JADE_OPAL_2000_S4300807/d08-x01-y04","44")
 useOne("/JADE_OPAL_2000_S4300807/d08-x01-y05","44")
 useOne("/JADE_OPAL_2000_S4300807/d09-x01-y01","91")
 useOne("/JADE_OPAL_2000_S4300807/d09-x01-y02","91")
 useOne("/JADE_OPAL_2000_S4300807/d09-x01-y03","91")
 useOne("/JADE_OPAL_2000_S4300807/d09-x01-y04","91")
 useOne("/JADE_OPAL_2000_S4300807/d09-x01-y05","91")
 useOne("/JADE_OPAL_2000_S4300807/d10-x01-y01","133")
 useOne("/JADE_OPAL_2000_S4300807/d10-x01-y02","133")
 useOne("/JADE_OPAL_2000_S4300807/d10-x01-y03","133")
 useOne("/JADE_OPAL_2000_S4300807/d10-x01-y04","133")
 useOne("/JADE_OPAL_2000_S4300807/d10-x01-y05","133")
 useOne("/JADE_OPAL_2000_S4300807/d11-x01-y01","161")
 useOne("/JADE_OPAL_2000_S4300807/d11-x01-y02","161")
 useOne("/JADE_OPAL_2000_S4300807/d11-x01-y03","161")
 useOne("/JADE_OPAL_2000_S4300807/d11-x01-y04","161")
 useOne("/JADE_OPAL_2000_S4300807/d11-x01-y05","161")
 useOne("/JADE_OPAL_2000_S4300807/d12-x01-y01","172")
 useOne("/JADE_OPAL_2000_S4300807/d12-x01-y02","172")
 useOne("/JADE_OPAL_2000_S4300807/d12-x01-y03","172")
 useOne("/JADE_OPAL_2000_S4300807/d12-x01-y04","172")
 useOne("/JADE_OPAL_2000_S4300807/d12-x01-y05","172")
 useOne("/JADE_OPAL_2000_S4300807/d13-x01-y01","183")
 useOne("/JADE_OPAL_2000_S4300807/d13-x01-y02","183")
 useOne("/JADE_OPAL_2000_S4300807/d13-x01-y03","183")
 useOne("/JADE_OPAL_2000_S4300807/d13-x01-y04","183")
 useOne("/JADE_OPAL_2000_S4300807/d13-x01-y05","183")
 useOne("/JADE_OPAL_2000_S4300807/d14-x01-y01","189")
 useOne("/JADE_OPAL_2000_S4300807/d14-x01-y02","189")
 useOne("/JADE_OPAL_2000_S4300807/d14-x01-y03","189")
 useOne("/JADE_OPAL_2000_S4300807/d14-x01-y04","189")
 useOne("/JADE_OPAL_2000_S4300807/d14-x01-y05","189")
 useOne("/JADE_OPAL_2000_S4300807/d16-x01-y01","35") 
 useOne("/JADE_OPAL_2000_S4300807/d16-x01-y02","35") 
 useOne("/JADE_OPAL_2000_S4300807/d16-x01-y03","35") 
 useOne("/JADE_OPAL_2000_S4300807/d16-x01-y04","35") 
 useOne("/JADE_OPAL_2000_S4300807/d16-x01-y05","35") 
 useOne("/JADE_OPAL_2000_S4300807/d17-x01-y01","44") 
 useOne("/JADE_OPAL_2000_S4300807/d17-x01-y02","44") 
 useOne("/JADE_OPAL_2000_S4300807/d17-x01-y03","44") 
 useOne("/JADE_OPAL_2000_S4300807/d17-x01-y04","44") 
 useOne("/JADE_OPAL_2000_S4300807/d17-x01-y05","44") 
 useOne("/JADE_OPAL_2000_S4300807/d18-x01-y01","91") 
 useOne("/JADE_OPAL_2000_S4300807/d18-x01-y02","91") 
 useOne("/JADE_OPAL_2000_S4300807/d18-x01-y03","91") 
 useOne("/JADE_OPAL_2000_S4300807/d18-x01-y04","91") 
 useOne("/JADE_OPAL_2000_S4300807/d18-x01-y05","91") 
 useOne("/JADE_OPAL_2000_S4300807/d19-x01-y01","133")
 useOne("/JADE_OPAL_2000_S4300807/d19-x01-y02","133")
 useOne("/JADE_OPAL_2000_S4300807/d19-x01-y03","133")
 useOne("/JADE_OPAL_2000_S4300807/d19-x01-y04","133")
 useOne("/JADE_OPAL_2000_S4300807/d19-x01-y05","133")
 useOne("/JADE_OPAL_2000_S4300807/d20-x01-y01","161")
 useOne("/JADE_OPAL_2000_S4300807/d20-x01-y02","161")
 useOne("/JADE_OPAL_2000_S4300807/d20-x01-y03","161")
 useOne("/JADE_OPAL_2000_S4300807/d20-x01-y04","161")
 useOne("/JADE_OPAL_2000_S4300807/d20-x01-y05","161")
 useOne("/JADE_OPAL_2000_S4300807/d21-x01-y01","172")
 useOne("/JADE_OPAL_2000_S4300807/d21-x01-y02","172")
 useOne("/JADE_OPAL_2000_S4300807/d21-x01-y03","172")
 useOne("/JADE_OPAL_2000_S4300807/d21-x01-y04","172")
 useOne("/JADE_OPAL_2000_S4300807/d21-x01-y05","172")
 useOne("/JADE_OPAL_2000_S4300807/d22-x01-y01","183")
 useOne("/JADE_OPAL_2000_S4300807/d22-x01-y02","183")
 useOne("/JADE_OPAL_2000_S4300807/d22-x01-y03","183")
 useOne("/JADE_OPAL_2000_S4300807/d22-x01-y04","183")
 useOne("/JADE_OPAL_2000_S4300807/d22-x01-y05","183")
 useOne("/JADE_OPAL_2000_S4300807/d23-x01-y01","189")
 useOne("/JADE_OPAL_2000_S4300807/d23-x01-y02","189")
 useOne("/JADE_OPAL_2000_S4300807/d23-x01-y03","189")
 useOne("/JADE_OPAL_2000_S4300807/d23-x01-y04","189")
 useOne("/JADE_OPAL_2000_S4300807/d23-x01-y05","189")
 useOne("/JADE_OPAL_2000_S4300807/d24-x01-y01","35")
 useOne("/JADE_OPAL_2000_S4300807/d24-x01-y02","35")
 useOne("/JADE_OPAL_2000_S4300807/d24-x01-y03","35")
 useOne("/JADE_OPAL_2000_S4300807/d24-x01-y04","35")
 useOne("/JADE_OPAL_2000_S4300807/d25-x01-y01","44")
 useOne("/JADE_OPAL_2000_S4300807/d25-x01-y02","44")
 useOne("/JADE_OPAL_2000_S4300807/d25-x01-y03","44")
 useOne("/JADE_OPAL_2000_S4300807/d25-x01-y04","44")
 useOne("/JADE_OPAL_2000_S4300807/d26-x01-y01","91") 
 useOne("/JADE_OPAL_2000_S4300807/d26-x01-y02","91") 
 useOne("/JADE_OPAL_2000_S4300807/d26-x01-y03","91") 
 useOne("/JADE_OPAL_2000_S4300807/d26-x01-y04","91") 
 useOne("/JADE_OPAL_2000_S4300807/d27-x01-y01","133")
 useOne("/JADE_OPAL_2000_S4300807/d27-x01-y02","133")
 useOne("/JADE_OPAL_2000_S4300807/d27-x01-y03","133")
 useOne("/JADE_OPAL_2000_S4300807/d27-x01-y04","133")
 useOne("/JADE_OPAL_2000_S4300807/d28-x01-y01","161")
 useOne("/JADE_OPAL_2000_S4300807/d28-x01-y02","161")
 useOne("/JADE_OPAL_2000_S4300807/d28-x01-y03","161")
 useOne("/JADE_OPAL_2000_S4300807/d28-x01-y04","161")
 useOne("/JADE_OPAL_2000_S4300807/d29-x01-y01","172")
 useOne("/JADE_OPAL_2000_S4300807/d29-x01-y02","172")
 useOne("/JADE_OPAL_2000_S4300807/d29-x01-y03","172")
 useOne("/JADE_OPAL_2000_S4300807/d29-x01-y04","172")
 useOne("/JADE_OPAL_2000_S4300807/d30-x01-y01","183")
 useOne("/JADE_OPAL_2000_S4300807/d30-x01-y02","183")
 useOne("/JADE_OPAL_2000_S4300807/d30-x01-y03","183")
 useOne("/JADE_OPAL_2000_S4300807/d30-x01-y04","183")
 useOne("/JADE_OPAL_2000_S4300807/d31-x01-y01","189")
 useOne("/JADE_OPAL_2000_S4300807/d31-x01-y02","189")
 useOne("/JADE_OPAL_2000_S4300807/d31-x01-y03","189")
 useOne("/JADE_OPAL_2000_S4300807/d31-x01-y04","189")
 
 useOne("/OPAL_2004_S6132243/d01-x01-y01","91")
 useOne("/OPAL_2004_S6132243/d01-x01-y02","133")
 useOne("/OPAL_2004_S6132243/d01-x01-y03","177")
 useOne("/OPAL_2004_S6132243/d01-x01-y04","197")
 useOne("/OPAL_2004_S6132243/d02-x01-y01","91") 
 useOne("/OPAL_2004_S6132243/d02-x01-y02","133")
 useOne("/OPAL_2004_S6132243/d02-x01-y03","177")
 useOne("/OPAL_2004_S6132243/d02-x01-y04","197")
 useOne("/OPAL_2004_S6132243/d03-x01-y01","91") 
 useOne("/OPAL_2004_S6132243/d03-x01-y02","133")
 useOne("/OPAL_2004_S6132243/d03-x01-y03","177")
 useOne("/OPAL_2004_S6132243/d03-x01-y04","197")
 useOne("/OPAL_2004_S6132243/d04-x01-y01","91") 
 useOne("/OPAL_2004_S6132243/d04-x01-y02","133")
 useOne("/OPAL_2004_S6132243/d04-x01-y03","177")
 useOne("/OPAL_2004_S6132243/d04-x01-y04","197")
 useOne("/OPAL_2004_S6132243/d05-x01-y01","91") 
 useOne("/OPAL_2004_S6132243/d05-x01-y02","133")
 useOne("/OPAL_2004_S6132243/d05-x01-y03","177")
 useOne("/OPAL_2004_S6132243/d05-x01-y04","197")
 useOne("/OPAL_2004_S6132243/d06-x01-y01","91") 
 useOne("/OPAL_2004_S6132243/d06-x01-y02","133")
 useOne("/OPAL_2004_S6132243/d06-x01-y03","177")
 useOne("/OPAL_2004_S6132243/d06-x01-y04","197")
 useOne("/OPAL_2004_S6132243/d07-x01-y01","91") 
 useOne("/OPAL_2004_S6132243/d07-x01-y02","133")
 useOne("/OPAL_2004_S6132243/d07-x01-y03","177")
 useOne("/OPAL_2004_S6132243/d07-x01-y04","197")
 useOne("/OPAL_2004_S6132243/d08-x01-y01","91") 
 useOne("/OPAL_2004_S6132243/d08-x01-y02","133")
 useOne("/OPAL_2004_S6132243/d08-x01-y03","177")
 useOne("/OPAL_2004_S6132243/d08-x01-y04","197")
 useOne("/OPAL_2004_S6132243/d09-x01-y01","91") 
 useOne("/OPAL_2004_S6132243/d09-x01-y02","133")
 useOne("/OPAL_2004_S6132243/d09-x01-y03","177")
 useOne("/OPAL_2004_S6132243/d09-x01-y04","197")
 useOne("/OPAL_2004_S6132243/d10-x01-y01","91") 
 useOne("/OPAL_2004_S6132243/d10-x01-y02","133")
 useOne("/OPAL_2004_S6132243/d10-x01-y03","177")
 useOne("/OPAL_2004_S6132243/d10-x01-y04","197")
 useOne("/OPAL_2004_S6132243/d11-x01-y01","91") 
 useOne("/OPAL_2004_S6132243/d11-x01-y02","133")
 useOne("/OPAL_2004_S6132243/d11-x01-y03","177")
 useOne("/OPAL_2004_S6132243/d11-x01-y04","197")
 useOne("/OPAL_2004_S6132243/d12-x01-y01","91") 
 useOne("/OPAL_2004_S6132243/d12-x01-y02","133")
 useOne("/OPAL_2004_S6132243/d12-x01-y03","177")
 useOne("/OPAL_2004_S6132243/d12-x01-y04","197")
 useOne("/OPAL_2004_S6132243/d13-x01-y01","91") 
 useOne("/OPAL_2004_S6132243/d13-x01-y02","133")
 useOne("/OPAL_2004_S6132243/d13-x01-y03","177")
 useOne("/OPAL_2004_S6132243/d13-x01-y04","197")
 useOne("/OPAL_2004_S6132243/d14-x01-y01","91") 
 useOne("/OPAL_2004_S6132243/d14-x01-y02","133")
 useOne("/OPAL_2004_S6132243/d14-x01-y03","177")
 useOne("/OPAL_2004_S6132243/d14-x01-y04","197")
 useOne("/OPAL_2004_S6132243/d15-x01-y01","91") 
 useOne("/OPAL_2004_S6132243/d15-x01-y02","133")
 useOne("/OPAL_2004_S6132243/d15-x01-y03","177")
 useOne("/OPAL_2004_S6132243/d15-x01-y04","197")
 useOne("/OPAL_2004_S6132243/d16-x01-y01","91") 
 useOne("/OPAL_2004_S6132243/d16-x01-y02","133")
 useOne("/OPAL_2004_S6132243/d16-x01-y03","177")
 useOne("/OPAL_2004_S6132243/d16-x01-y04","197")
 useOne("/OPAL_2004_S6132243/d17-x01-y01","91") 
 useOne("/OPAL_2004_S6132243/d17-x01-y02","133")
 useOne("/OPAL_2004_S6132243/d17-x01-y03","177")
 useOne("/OPAL_2004_S6132243/d17-x01-y04","197")
 useOne("/OPAL_2004_S6132243/d18-x01-y01","91") 
 useOne("/OPAL_2004_S6132243/d18-x01-y02","133")
 useOne("/OPAL_2004_S6132243/d18-x01-y03","177")
 useOne("/OPAL_2004_S6132243/d18-x01-y04","197")
 useOne("/OPAL_2004_S6132243/d19-x01-y01","91") 
 useOne("/OPAL_2004_S6132243/d19-x01-y02","133")
 useOne("/OPAL_2004_S6132243/d19-x01-y03","177")
 useOne("/OPAL_2004_S6132243/d19-x01-y04","197")
 useOne("/OPAL_2004_S6132243/d20-x01-y01","91") 
 useOne("/OPAL_2004_S6132243/d20-x01-y02","133")
 useOne("/OPAL_2004_S6132243/d20-x01-y03","177")
 useOne("/OPAL_2004_S6132243/d20-x01-y04","197")
 useOne("/OPAL_2004_S6132243/d21-x01-y01","91") 
 useOne("/OPAL_2004_S6132243/d21-x01-y02","133")
 useOne("/OPAL_2004_S6132243/d21-x01-y03","177")
 useOne("/OPAL_2004_S6132243/d21-x01-y04","197")
 useOne("/OPAL_2004_S6132243/d22-x01-y01","91") 
 useOne("/OPAL_2004_S6132243/d22-x01-y02","133")
 useOne("/OPAL_2004_S6132243/d22-x01-y03","177")
 useOne("/OPAL_2004_S6132243/d22-x01-y04","197")
 useOne("/OPAL_2004_S6132243/d23-x01-y01","91") 
 useOne("/OPAL_2004_S6132243/d23-x01-y02","133")
 useOne("/OPAL_2004_S6132243/d23-x01-y03","177")
 useOne("/OPAL_2004_S6132243/d23-x01-y04","197")
 useOne("/OPAL_2004_S6132243/d24-x01-y01","91") 
 useOne("/OPAL_2004_S6132243/d24-x01-y02","133")
 useOne("/OPAL_2004_S6132243/d24-x01-y03","177")
 useOne("/OPAL_2004_S6132243/d24-x01-y04","197")
 useOne("/OPAL_2004_S6132243/d25-x01-y01","91") 
 useOne("/OPAL_2004_S6132243/d25-x01-y02","133")
 useOne("/OPAL_2004_S6132243/d25-x01-y03","177")
 useOne("/OPAL_2004_S6132243/d25-x01-y04","197")
 useOne("/OPAL_2004_S6132243/d26-x01-y01","91") 
 useOne("/OPAL_2004_S6132243/d26-x01-y02","133")
 useOne("/OPAL_2004_S6132243/d26-x01-y03","177")
 useOne("/OPAL_2004_S6132243/d26-x01-y04","197")
 
 merge(  "/OPAL_2002_S5361494/d01-x01-y01")
 merge(  "/OPAL_2002_S5361494/d01-x01-y02")
 merge(  "/OPAL_2002_S5361494/d01-x01-y03")
 merge(  "/OPAL_2002_S5361494/d01-x01-y04")
 merge("/DELPHI_2000_S4328825/d01-x01-y01")
 merge("/DELPHI_2000_S4328825/d01-x01-y02")
 merge("/DELPHI_2000_S4328825/d01-x01-y03")
 merge("/DELPHI_2000_S4328825/d01-x01-y04")
 merge("/ALEPH_2004_S5765862/d01-x01-y01")
 useOne("/ALEPH_2004_S5765862/d02-x01-y01","133")
 useOne("/ALEPH_2004_S5765862/d03-x01-y01","161")
 useOne("/ALEPH_2004_S5765862/d04-x01-y01","172")
 useOne("/ALEPH_2004_S5765862/d05-x01-y01","183")
 useOne("/ALEPH_2004_S5765862/d06-x01-y01","189")
 useOne("/ALEPH_2004_S5765862/d07-x01-y01","196")
 useOne("/ALEPH_2004_S5765862/d08-x01-y01","200")
 useOne("/ALEPH_2004_S5765862/d09-x01-y01","206")
 
 useOne("/ALEPH_2004_S5765862/d11-x01-y01","133")
 useOne("/ALEPH_2004_S5765862/d12-x01-y01","161")
 useOne("/ALEPH_2004_S5765862/d13-x01-y01","172")
 useOne("/ALEPH_2004_S5765862/d14-x01-y01","183")
 useOne("/ALEPH_2004_S5765862/d15-x01-y01","189")
 useOne("/ALEPH_2004_S5765862/d16-x01-y01","196")
 useOne("/ALEPH_2004_S5765862/d17-x01-y01","200")
 useOne("/ALEPH_2004_S5765862/d18-x01-y01","206")
 useOne("/ALEPH_2004_S5765862/d19-x01-y01","133")
 useOne("/ALEPH_2004_S5765862/d20-x01-y01","161")
 useOne("/ALEPH_2004_S5765862/d21-x01-y01","172")
 useOne("/ALEPH_2004_S5765862/d22-x01-y01","183")
 useOne("/ALEPH_2004_S5765862/d23-x01-y01","189")
 useOne("/ALEPH_2004_S5765862/d24-x01-y01","196")
 useOne("/ALEPH_2004_S5765862/d25-x01-y01","200")
 useOne("/ALEPH_2004_S5765862/d26-x01-y01","206")
 useOne("/ALEPH_2004_S5765862/d27-x01-y01","133")
 useOne("/ALEPH_2004_S5765862/d28-x01-y01","161")
 useOne("/ALEPH_2004_S5765862/d29-x01-y01","172")
 useOne("/ALEPH_2004_S5765862/d30-x01-y01","183")
 useOne("/ALEPH_2004_S5765862/d31-x01-y01","189")
 useOne("/ALEPH_2004_S5765862/d32-x01-y01","196")
 useOne("/ALEPH_2004_S5765862/d33-x01-y01","200")
 useOne("/ALEPH_2004_S5765862/d34-x01-y01","206")
 useOne("/ALEPH_2004_S5765862/d35-x01-y01","206")
 useOne("/ALEPH_2004_S5765862/d36-x01-y01","133")
 useOne("/ALEPH_2004_S5765862/d37-x01-y01","161")
 useOne("/ALEPH_2004_S5765862/d38-x01-y01","172")
 useOne("/ALEPH_2004_S5765862/d39-x01-y01","183")
 useOne("/ALEPH_2004_S5765862/d40-x01-y01","189")
 useOne("/ALEPH_2004_S5765862/d41-x01-y01","196")
 useOne("/ALEPH_2004_S5765862/d42-x01-y01","200")
 useOne("/ALEPH_2004_S5765862/d43-x01-y01","206")
 useOne("/ALEPH_2004_S5765862/d44-x01-y01","133")
 useOne("/ALEPH_2004_S5765862/d45-x01-y01","161")
 useOne("/ALEPH_2004_S5765862/d46-x01-y01","172")
 useOne("/ALEPH_2004_S5765862/d47-x01-y01","183")
 useOne("/ALEPH_2004_S5765862/d48-x01-y01","189")
 useOne("/ALEPH_2004_S5765862/d49-x01-y01","196")
 useOne("/ALEPH_2004_S5765862/d50-x01-y01","200")
 useOne("/ALEPH_2004_S5765862/d51-x01-y01","206")
 useOne("/ALEPH_2004_S5765862/d54-x01-y01","91")
 useOne("/ALEPH_2004_S5765862/d55-x01-y01","133")
 useOne("/ALEPH_2004_S5765862/d56-x01-y01","161")
 useOne("/ALEPH_2004_S5765862/d57-x01-y01","172")
 useOne("/ALEPH_2004_S5765862/d58-x01-y01","183")
 useOne("/ALEPH_2004_S5765862/d59-x01-y01","189")
 useOne("/ALEPH_2004_S5765862/d60-x01-y01","200")
 useOne("/ALEPH_2004_S5765862/d61-x01-y01","206")
 useOne("/ALEPH_2004_S5765862/d62-x01-y01","91") 
 useOne("/ALEPH_2004_S5765862/d63-x01-y01","133")
 useOne("/ALEPH_2004_S5765862/d64-x01-y01","161")
 useOne("/ALEPH_2004_S5765862/d65-x01-y01","172")
 useOne("/ALEPH_2004_S5765862/d66-x01-y01","183")
 useOne("/ALEPH_2004_S5765862/d67-x01-y01","189")
 useOne("/ALEPH_2004_S5765862/d68-x01-y01","200")
 useOne("/ALEPH_2004_S5765862/d69-x01-y01","206")
 useOne("/ALEPH_2004_S5765862/d70-x01-y01","91") 
 useOne("/ALEPH_2004_S5765862/d71-x01-y01","133")
 useOne("/ALEPH_2004_S5765862/d72-x01-y01","161")
 useOne("/ALEPH_2004_S5765862/d73-x01-y01","172")
 useOne("/ALEPH_2004_S5765862/d74-x01-y01","183")
 useOne("/ALEPH_2004_S5765862/d75-x01-y01","189")
 useOne("/ALEPH_2004_S5765862/d76-x01-y01","200")
 useOne("/ALEPH_2004_S5765862/d77-x01-y01","206")
 useOne("/ALEPH_2004_S5765862/d78-x01-y01","91") 
 useOne("/ALEPH_2004_S5765862/d79-x01-y01","133")
 useOne("/ALEPH_2004_S5765862/d80-x01-y01","161")
 useOne("/ALEPH_2004_S5765862/d81-x01-y01","172")
 useOne("/ALEPH_2004_S5765862/d82-x01-y01","183")
 useOne("/ALEPH_2004_S5765862/d83-x01-y01","189")
 useOne("/ALEPH_2004_S5765862/d84-x01-y01","200")
 useOne("/ALEPH_2004_S5765862/d85-x01-y01","206")
 useOne("/ALEPH_2004_S5765862/d86-x01-y01","91") 
 useOne("/ALEPH_2004_S5765862/d87-x01-y01","133")
 useOne("/ALEPH_2004_S5765862/d88-x01-y01","161")
 useOne("/ALEPH_2004_S5765862/d89-x01-y01","172")
 useOne("/ALEPH_2004_S5765862/d90-x01-y01","183")
 useOne("/ALEPH_2004_S5765862/d91-x01-y01","189")
 useOne("/ALEPH_2004_S5765862/d92-x01-y01","200")
 useOne("/ALEPH_2004_S5765862/d93-x01-y01","206")
 useOne("/ALEPH_2004_S5765862/d94-x01-y01","91") 
 useOne("/ALEPH_2004_S5765862/d95-x01-y01","133")
 useOne("/ALEPH_2004_S5765862/d96-x01-y01","161")
 useOne("/ALEPH_2004_S5765862/d97-x01-y01","172")
 useOne("/ALEPH_2004_S5765862/d98-x01-y01","183")
 useOne("/ALEPH_2004_S5765862/d99-x01-y01","189")
 useOne("/ALEPH_2004_S5765862/d100-x01-y01","200")
 useOne("/ALEPH_2004_S5765862/d101-x01-y01","206")
 useOne("/ALEPH_2004_S5765862/d102-x01-y01","91")
 useOne("/ALEPH_2004_S5765862/d103-x01-y01","133")
 useOne("/ALEPH_2004_S5765862/d104-x01-y01","161")
 useOne("/ALEPH_2004_S5765862/d105-x01-y01","172")
 useOne("/ALEPH_2004_S5765862/d106-x01-y01","183")
 useOne("/ALEPH_2004_S5765862/d107-x01-y01","189")
 useOne("/ALEPH_2004_S5765862/d108-x01-y01","200")
 useOne("/ALEPH_2004_S5765862/d109-x01-y01","206")
 useOne("/ALEPH_2004_S5765862/d110-x01-y01","91") 
 useOne("/ALEPH_2004_S5765862/d111-x01-y01","133")
 useOne("/ALEPH_2004_S5765862/d112-x01-y01","161")
 useOne("/ALEPH_2004_S5765862/d113-x01-y01","172")
 useOne("/ALEPH_2004_S5765862/d114-x01-y01","183")
 useOne("/ALEPH_2004_S5765862/d115-x01-y01","189")
 useOne("/ALEPH_2004_S5765862/d116-x01-y01","200")
 useOne("/ALEPH_2004_S5765862/d117-x01-y01","206")
 useOne("/ALEPH_2004_S5765862/d118-x01-y01","91") 
 useOne("/ALEPH_2004_S5765862/d119-x01-y01","133")
 useOne("/ALEPH_2004_S5765862/d120-x01-y01","161")
 useOne("/ALEPH_2004_S5765862/d121-x01-y01","172")
 useOne("/ALEPH_2004_S5765862/d122-x01-y01","183")
 useOne("/ALEPH_2004_S5765862/d123-x01-y01","189")
 useOne("/ALEPH_2004_S5765862/d124-x01-y01","200")
 useOne("/ALEPH_2004_S5765862/d125-x01-y01","206")
 useOne("/ALEPH_2004_S5765862/d126-x01-y01","133")
 useOne("/ALEPH_2004_S5765862/d127-x01-y01","161")
 useOne("/ALEPH_2004_S5765862/d128-x01-y01","172")
 useOne("/ALEPH_2004_S5765862/d129-x01-y01","183")
 useOne("/ALEPH_2004_S5765862/d130-x01-y01","189")
 useOne("/ALEPH_2004_S5765862/d131-x01-y01","200")
 useOne("/ALEPH_2004_S5765862/d132-x01-y01","206")
 useOne("/ALEPH_2004_S5765862/d133-x01-y01","91") 
 useOne("/ALEPH_2004_S5765862/d134-x01-y01","133")
 useOne("/ALEPH_2004_S5765862/d135-x01-y01","161")
 useOne("/ALEPH_2004_S5765862/d136-x01-y01","172")
 useOne("/ALEPH_2004_S5765862/d137-x01-y01","183")
 useOne("/ALEPH_2004_S5765862/d138-x01-y01","189")
 useOne("/ALEPH_2004_S5765862/d139-x01-y01","200")
 useOne("/ALEPH_2004_S5765862/d140-x01-y01","206")
 useOne("/ALEPH_2004_S5765862/d141-x01-y01","91") 
 useOne("/ALEPH_2004_S5765862/d142-x01-y01","133")
 useOne("/ALEPH_2004_S5765862/d143-x01-y01","161")
 useOne("/ALEPH_2004_S5765862/d144-x01-y01","172")
 useOne("/ALEPH_2004_S5765862/d145-x01-y01","183")
 useOne("/ALEPH_2004_S5765862/d146-x01-y01","189")
 useOne("/ALEPH_2004_S5765862/d147-x01-y01","200")
 useOne("/ALEPH_2004_S5765862/d148-x01-y01","206")
 useOne("/ALEPH_2004_S5765862/d149-x01-y01","91") 
 useOne("/ALEPH_2004_S5765862/d150-x01-y01","133")
 useOne("/ALEPH_2004_S5765862/d151-x01-y01","161")
 useOne("/ALEPH_2004_S5765862/d152-x01-y01","172")
 useOne("/ALEPH_2004_S5765862/d153-x01-y01","183")
 useOne("/ALEPH_2004_S5765862/d154-x01-y01","189")
 useOne("/ALEPH_2004_S5765862/d155-x01-y01","200")
 useOne("/ALEPH_2004_S5765862/d156-x01-y01","206")
 useOne("/ALEPH_2004_S5765862/d157-x01-y01","91") 
 useOne("/ALEPH_2004_S5765862/d158-x01-y01","133")
 useOne("/ALEPH_2004_S5765862/d159-x01-y01","161")
 useOne("/ALEPH_2004_S5765862/d160-x01-y01","172")
 useOne("/ALEPH_2004_S5765862/d161-x01-y01","183")
 useOne("/ALEPH_2004_S5765862/d162-x01-y01","189")
 useOne("/ALEPH_2004_S5765862/d163-x01-y01","200")
 useOne("/ALEPH_2004_S5765862/d164-x01-y01","206")
 useOne("/ALEPH_2004_S5765862/d165-x01-y01","91") 
 useOne("/ALEPH_2004_S5765862/d166-x01-y01","133")
 useOne("/ALEPH_2004_S5765862/d167-x01-y01","161")
 useOne("/ALEPH_2004_S5765862/d168-x01-y01","172")
 useOne("/ALEPH_2004_S5765862/d169-x01-y01","183")
 useOne("/ALEPH_2004_S5765862/d170-x01-y01","189")
 
 useOne("/ALEPH_2004_S5765862/d172-x01-y01","206")
 useOne("/ALEPH_2004_S5765862/d173-x01-y01","91") 
 useOne("/ALEPH_2004_S5765862/d174-x01-y01","133")
 useOne("/ALEPH_2004_S5765862/d175-x01-y01","161")
 useOne("/ALEPH_2004_S5765862/d176-x01-y01","172")
 useOne("/ALEPH_2004_S5765862/d177-x01-y01","183")
 useOne("/ALEPH_2004_S5765862/d178-x01-y01","189")
 useOne("/ALEPH_2004_S5765862/d179-x01-y01","200")
 useOne("/ALEPH_2004_S5765862/d180-x01-y01","91") 
 useOne("/ALEPH_2004_S5765862/d181-x01-y01","133")
 useOne("/ALEPH_2004_S5765862/d182-x01-y01","161")
 useOne("/ALEPH_2004_S5765862/d183-x01-y01","172")
 useOne("/ALEPH_2004_S5765862/d184-x01-y01","183")
 useOne("/ALEPH_2004_S5765862/d185-x01-y01","189")
 useOne("/ALEPH_2004_S5765862/d186-x01-y01","200")
 useOne("/ALEPH_2004_S5765862/d187-x01-y01","91") 
 useOne("/ALEPH_2004_S5765862/d188-x01-y01","133")
 useOne("/ALEPH_2004_S5765862/d189-x01-y01","161")
 useOne("/ALEPH_2004_S5765862/d190-x01-y01","172")
 useOne("/ALEPH_2004_S5765862/d191-x01-y01","183")
 useOne("/ALEPH_2004_S5765862/d192-x01-y01","189")
 useOne("/ALEPH_2004_S5765862/d193-x01-y01","200")
 useOne("/ALEPH_2004_S5765862/d194-x01-y01","206")
 useOne("/ALEPH_2004_S5765862/d195-x01-y01","91") 
 useOne("/ALEPH_2004_S5765862/d196-x01-y01","133")
 useOne("/ALEPH_2004_S5765862/d197-x01-y01","161")
 useOne("/ALEPH_2004_S5765862/d198-x01-y01","172")
 useOne("/ALEPH_2004_S5765862/d199-x01-y01","183")
 useOne("/ALEPH_2004_S5765862/d200-x01-y01","189")
 useOne("/ALEPH_2004_S5765862/d201-x01-y01","200")
 useOne("/ALEPH_2004_S5765862/d202-x01-y01","206")
 useOne("/ALEPH_2004_S5765862/d203-x01-y01","91") 
 useOne("/ALEPH_2004_S5765862/d204-x01-y01","133")
 useOne("/ALEPH_2004_S5765862/d205-x01-y01","161")
 useOne("/ALEPH_2004_S5765862/d206-x01-y01","172")
 useOne("/ALEPH_2004_S5765862/d207-x01-y01","183")
 useOne("/ALEPH_2004_S5765862/d208-x01-y01","189")
 useOne("/ALEPH_2004_S5765862/d209-x01-y01","200")
 useOne("/ALEPH_2004_S5765862/d210-x01-y01","206")
 useOne("/ALEPH_2004_S5765862/d211-x01-y01","91") 
 useOne("/ALEPH_2004_S5765862/d212-x01-y01","133")
 useOne("/ALEPH_2004_S5765862/d213-x01-y01","161")
 useOne("/ALEPH_2004_S5765862/d214-x01-y01","172")
 useOne("/ALEPH_2004_S5765862/d215-x01-y01","183")
 useOne("/ALEPH_2004_S5765862/d216-x01-y01","189")
 useOne("/ALEPH_2004_S5765862/d217-x01-y01","200")
 useOne("/ALEPH_2004_S5765862/d218-x01-y01","206")
 useOne("/ALEPH_2004_S5765862/d219-x01-y01","91") 
 useOne("/ALEPH_2004_S5765862/d220-x01-y01","133")
 useOne("/ALEPH_2004_S5765862/d221-x01-y01","161")
 useOne("/ALEPH_2004_S5765862/d222-x01-y01","172")
 useOne("/ALEPH_2004_S5765862/d223-x01-y01","183")
 useOne("/ALEPH_2004_S5765862/d224-x01-y01","189")
 useOne("/ALEPH_2004_S5765862/d225-x01-y01","200")
 useOne("/ALEPH_2004_S5765862/d226-x01-y01","206")
 useOne("/ALEPH_2004_S5765862/d227-x01-y01","91") 
 useOne("/ALEPH_2004_S5765862/d228-x01-y01","133")
 useOne("/ALEPH_2004_S5765862/d229-x01-y01","161")
 useOne("/ALEPH_2004_S5765862/d230-x01-y01","172")
 useOne("/ALEPH_2004_S5765862/d231-x01-y01","183")
 useOne("/ALEPH_2004_S5765862/d232-x01-y01","189")
 useOne("/ALEPH_2004_S5765862/d233-x01-y01","200")
 useOne("/ALEPH_2004_S5765862/d234-x01-y01","206")
 
 # hadron multiplicities
 useOne("/PDG_HADRON_MULTIPLICITIES/d01-x01-y01","10")
 useOne("/PDG_HADRON_MULTIPLICITIES/d02-x01-y01","10")
 useOne("/PDG_HADRON_MULTIPLICITIES/d03-x01-y01","10")
 useOne("/PDG_HADRON_MULTIPLICITIES/d04-x01-y01","10")
 useOne("/PDG_HADRON_MULTIPLICITIES/d05-x01-y01","10")
 useOne("/PDG_HADRON_MULTIPLICITIES/d06-x01-y01","10")
 useOne("/PDG_HADRON_MULTIPLICITIES/d07-x01-y01","10")
 useOne("/PDG_HADRON_MULTIPLICITIES/d08-x01-y01","10")
 useOne("/PDG_HADRON_MULTIPLICITIES/d09-x01-y01","10")
 useOne("/PDG_HADRON_MULTIPLICITIES/d13-x01-y01","10")
 useOne("/PDG_HADRON_MULTIPLICITIES/d15-x01-y01","10")
 useOne("/PDG_HADRON_MULTIPLICITIES/d17-x01-y01","10")
 useOne("/PDG_HADRON_MULTIPLICITIES/d18-x01-y01","10")
 useOne("/PDG_HADRON_MULTIPLICITIES/d19-x01-y01","10")
 useOne("/PDG_HADRON_MULTIPLICITIES/d20-x01-y01","10")
 useOne("/PDG_HADRON_MULTIPLICITIES/d21-x01-y01","10")
 useOne("/PDG_HADRON_MULTIPLICITIES/d22-x01-y01","10")
 useOne("/PDG_HADRON_MULTIPLICITIES/d23-x01-y01","10")
 useOne("/PDG_HADRON_MULTIPLICITIES/d25-x01-y01","10")
 useOne("/PDG_HADRON_MULTIPLICITIES/d31-x01-y01","10")
 useOne("/PDG_HADRON_MULTIPLICITIES/d38-x01-y01","10")
 useOne("/PDG_HADRON_MULTIPLICITIES/d39-x01-y01","10")
 useOne("/PDG_HADRON_MULTIPLICITIES/d40-x01-y01","10")
 useOne("/PDG_HADRON_MULTIPLICITIES/d44-x01-y01","10")
 useOne("/PDG_HADRON_MULTIPLICITIES/d45-x01-y01","10")
 useOne("/PDG_HADRON_MULTIPLICITIES/d46-x01-y01","10")
 useOne("/PDG_HADRON_MULTIPLICITIES/d47-x01-y01","10")
 useOne("/PDG_HADRON_MULTIPLICITIES/d48-x01-y01","10")
 useOne("/PDG_HADRON_MULTIPLICITIES/d49-x01-y01","10")
 useOne("/PDG_HADRON_MULTIPLICITIES/d50-x01-y01","10")
 useOne("/PDG_HADRON_MULTIPLICITIES/d51-x01-y01","10")
 useOne("/PDG_HADRON_MULTIPLICITIES/d53-x01-y01","10")
 useOne("/PDG_HADRON_MULTIPLICITIES/d54-x01-y01","10")
 
 useOne("/PDG_HADRON_MULTIPLICITIES/d01-x01-y02","35")
 useOne("/PDG_HADRON_MULTIPLICITIES/d02-x01-y02","35")
 useOne("/PDG_HADRON_MULTIPLICITIES/d03-x01-y02","35")
 useOne("/PDG_HADRON_MULTIPLICITIES/d04-x01-y02","35")
 useOne("/PDG_HADRON_MULTIPLICITIES/d05-x01-y02","35")
 useOne("/PDG_HADRON_MULTIPLICITIES/d06-x01-y02","35")
 useOne("/PDG_HADRON_MULTIPLICITIES/d07-x01-y02","35")
 useOne("/PDG_HADRON_MULTIPLICITIES/d08-x01-y02","35")
 useOne("/PDG_HADRON_MULTIPLICITIES/d09-x01-y02","35")
 useOne("/PDG_HADRON_MULTIPLICITIES/d13-x01-y02","35")
 useOne("/PDG_HADRON_MULTIPLICITIES/d15-x01-y02","35")
 useOne("/PDG_HADRON_MULTIPLICITIES/d18-x01-y02","35")
 useOne("/PDG_HADRON_MULTIPLICITIES/d19-x01-y02","35")
 useOne("/PDG_HADRON_MULTIPLICITIES/d20-x01-y02","35")
 useOne("/PDG_HADRON_MULTIPLICITIES/d21-x01-y02","35")
 useOne("/PDG_HADRON_MULTIPLICITIES/d22-x01-y02","35")
 useOne("/PDG_HADRON_MULTIPLICITIES/d31-x01-y02","35")
 useOne("/PDG_HADRON_MULTIPLICITIES/d33-x01-y01","35")
 useOne("/PDG_HADRON_MULTIPLICITIES/d34-x01-y01","35")
 useOne("/PDG_HADRON_MULTIPLICITIES/d38-x01-y02","35")
 useOne("/PDG_HADRON_MULTIPLICITIES/d39-x01-y02","35")
 useOne("/PDG_HADRON_MULTIPLICITIES/d44-x01-y02","35")
 useOne("/PDG_HADRON_MULTIPLICITIES/d46-x01-y02","35")
 useOne("/PDG_HADRON_MULTIPLICITIES/d47-x01-y02","35")
 useOne("/PDG_HADRON_MULTIPLICITIES/d48-x01-y02","35")
 useOne("/PDG_HADRON_MULTIPLICITIES/d50-x01-y02","35")
 useOne("/PDG_HADRON_MULTIPLICITIES/d51-x01-y02","35")
 
 useOne("/PDG_HADRON_MULTIPLICITIES/d01-x01-y03","91")
 useOne("/PDG_HADRON_MULTIPLICITIES/d02-x01-y03","91")
 useOne("/PDG_HADRON_MULTIPLICITIES/d03-x01-y03","91")
 useOne("/PDG_HADRON_MULTIPLICITIES/d04-x01-y03","91")
 useOne("/PDG_HADRON_MULTIPLICITIES/d05-x01-y03","91")
 useOne("/PDG_HADRON_MULTIPLICITIES/d06-x01-y03","91")
 useOne("/PDG_HADRON_MULTIPLICITIES/d07-x01-y03","91")
 useOne("/PDG_HADRON_MULTIPLICITIES/d08-x01-y03","91")
 useOne("/PDG_HADRON_MULTIPLICITIES/d09-x01-y03","91")
 useOne("/PDG_HADRON_MULTIPLICITIES/d10-x01-y01","91")
 useOne("/PDG_HADRON_MULTIPLICITIES/d11-x01-y01","91")
 useOne("/PDG_HADRON_MULTIPLICITIES/d12-x01-y01","91")
 useOne("/PDG_HADRON_MULTIPLICITIES/d13-x01-y03","91")
 useOne("/PDG_HADRON_MULTIPLICITIES/d14-x01-y01","91")
 useOne("/PDG_HADRON_MULTIPLICITIES/d15-x01-y03","91")
 useOne("/PDG_HADRON_MULTIPLICITIES/d16-x01-y01","91")
 useOne("/PDG_HADRON_MULTIPLICITIES/d17-x01-y02","91")
 useOne("/PDG_HADRON_MULTIPLICITIES/d18-x01-y03","91")
 useOne("/PDG_HADRON_MULTIPLICITIES/d19-x01-y03","91")
 useOne("/PDG_HADRON_MULTIPLICITIES/d20-x01-y03","91")
 useOne("/PDG_HADRON_MULTIPLICITIES/d21-x01-y03","91")
 useOne("/PDG_HADRON_MULTIPLICITIES/d23-x01-y02","91")
 useOne("/PDG_HADRON_MULTIPLICITIES/d24-x01-y01","91")
 useOne("/PDG_HADRON_MULTIPLICITIES/d25-x01-y02","91")
 useOne("/PDG_HADRON_MULTIPLICITIES/d26-x01-y01","91")
 useOne("/PDG_HADRON_MULTIPLICITIES/d27-x01-y01","91")
 useOne("/PDG_HADRON_MULTIPLICITIES/d28-x01-y01","91")
 useOne("/PDG_HADRON_MULTIPLICITIES/d29-x01-y01","91")
 useOne("/PDG_HADRON_MULTIPLICITIES/d30-x01-y01","91")
 useOne("/PDG_HADRON_MULTIPLICITIES/d31-x01-y03","91")
 useOne("/PDG_HADRON_MULTIPLICITIES/d32-x01-y01","91")
 useOne("/PDG_HADRON_MULTIPLICITIES/d34-x01-y02","91")
 useOne("/PDG_HADRON_MULTIPLICITIES/d35-x01-y01","91")
 useOne("/PDG_HADRON_MULTIPLICITIES/d36-x01-y01","91")
 useOne("/PDG_HADRON_MULTIPLICITIES/d37-x01-y01","91")
 useOne("/PDG_HADRON_MULTIPLICITIES/d38-x01-y03","91")
 useOne("/PDG_HADRON_MULTIPLICITIES/d39-x01-y03","91")
 useOne("/PDG_HADRON_MULTIPLICITIES/d40-x01-y02","91")
 useOne("/PDG_HADRON_MULTIPLICITIES/d41-x01-y01","91")
 useOne("/PDG_HADRON_MULTIPLICITIES/d42-x01-y01","91")
 useOne("/PDG_HADRON_MULTIPLICITIES/d43-x01-y01","91")
 useOne("/PDG_HADRON_MULTIPLICITIES/d44-x01-y03","91")
 useOne("/PDG_HADRON_MULTIPLICITIES/d45-x01-y02","91")
 useOne("/PDG_HADRON_MULTIPLICITIES/d46-x01-y03","91")
 useOne("/PDG_HADRON_MULTIPLICITIES/d47-x01-y03","91")
 useOne("/PDG_HADRON_MULTIPLICITIES/d48-x01-y03","91")
 useOne("/PDG_HADRON_MULTIPLICITIES/d49-x01-y02","91")
 useOne("/PDG_HADRON_MULTIPLICITIES/d50-x01-y03","91")
 useOne("/PDG_HADRON_MULTIPLICITIES/d51-x01-y03","91")
 useOne("/PDG_HADRON_MULTIPLICITIES/d52-x01-y01","91")
 useOne("/PDG_HADRON_MULTIPLICITIES/d54-x01-y02","91")
 useOne("/PDG_HADRON_MULTIPLICITIES/d01-x01-y04","177")
 useOne("/PDG_HADRON_MULTIPLICITIES/d03-x01-y04","177")
 useOne("/PDG_HADRON_MULTIPLICITIES/d04-x01-y04","177")
 useOne("/PDG_HADRON_MULTIPLICITIES/d38-x01-y04","177")
 useOne("/PDG_HADRON_MULTIPLICITIES/d39-x01-y04","177")
 
 useOne("/PDG_HADRON_MULTIPLICITIES_RATIOS/d02-x01-y01","10")
 useOne("/PDG_HADRON_MULTIPLICITIES_RATIOS/d03-x01-y01","10")
 useOne("/PDG_HADRON_MULTIPLICITIES_RATIOS/d04-x01-y01","10")
 useOne("/PDG_HADRON_MULTIPLICITIES_RATIOS/d05-x01-y01","10")
 useOne("/PDG_HADRON_MULTIPLICITIES_RATIOS/d06-x01-y01","10")
 useOne("/PDG_HADRON_MULTIPLICITIES_RATIOS/d07-x01-y01","10")
 useOne("/PDG_HADRON_MULTIPLICITIES_RATIOS/d08-x01-y01","10")
 useOne("/PDG_HADRON_MULTIPLICITIES_RATIOS/d09-x01-y01","10")
 useOne("/PDG_HADRON_MULTIPLICITIES_RATIOS/d13-x01-y01","10")
 useOne("/PDG_HADRON_MULTIPLICITIES_RATIOS/d15-x01-y01","10")
 useOne("/PDG_HADRON_MULTIPLICITIES_RATIOS/d17-x01-y01","10")
 useOne("/PDG_HADRON_MULTIPLICITIES_RATIOS/d18-x01-y01","10")
 useOne("/PDG_HADRON_MULTIPLICITIES_RATIOS/d19-x01-y01","10")
 useOne("/PDG_HADRON_MULTIPLICITIES_RATIOS/d20-x01-y01","10")
 useOne("/PDG_HADRON_MULTIPLICITIES_RATIOS/d21-x01-y01","10")
 useOne("/PDG_HADRON_MULTIPLICITIES_RATIOS/d22-x01-y01","10")
 useOne("/PDG_HADRON_MULTIPLICITIES_RATIOS/d23-x01-y01","10")
 useOne("/PDG_HADRON_MULTIPLICITIES_RATIOS/d25-x01-y01","10")
 useOne("/PDG_HADRON_MULTIPLICITIES_RATIOS/d31-x01-y01","10")
 useOne("/PDG_HADRON_MULTIPLICITIES_RATIOS/d38-x01-y01","10" )
 useOne("/PDG_HADRON_MULTIPLICITIES_RATIOS/d39-x01-y01","10")
 useOne("/PDG_HADRON_MULTIPLICITIES_RATIOS/d40-x01-y01","10")
 useOne("/PDG_HADRON_MULTIPLICITIES_RATIOS/d44-x01-y01","10")
 useOne("/PDG_HADRON_MULTIPLICITIES_RATIOS/d45-x01-y01","10")
 useOne("/PDG_HADRON_MULTIPLICITIES_RATIOS/d46-x01-y01","10")
 useOne("/PDG_HADRON_MULTIPLICITIES_RATIOS/d47-x01-y01","10")
 useOne("/PDG_HADRON_MULTIPLICITIES_RATIOS/d48-x01-y01","10")
 useOne("/PDG_HADRON_MULTIPLICITIES_RATIOS/d49-x01-y01","10")
 useOne("/PDG_HADRON_MULTIPLICITIES_RATIOS/d50-x01-y01","10")
 useOne("/PDG_HADRON_MULTIPLICITIES_RATIOS/d51-x01-y01","10")
 useOne("/PDG_HADRON_MULTIPLICITIES_RATIOS/d53-x01-y01","10")
 useOne("/PDG_HADRON_MULTIPLICITIES_RATIOS/d54-x01-y01","10")
 useOne("/PDG_HADRON_MULTIPLICITIES_RATIOS/d02-x01-y02","35")
 useOne("/PDG_HADRON_MULTIPLICITIES_RATIOS/d03-x01-y02","35")
 useOne("/PDG_HADRON_MULTIPLICITIES_RATIOS/d04-x01-y02","35")
 useOne("/PDG_HADRON_MULTIPLICITIES_RATIOS/d05-x01-y02","35")
 useOne("/PDG_HADRON_MULTIPLICITIES_RATIOS/d06-x01-y02","35")
 useOne("/PDG_HADRON_MULTIPLICITIES_RATIOS/d07-x01-y02","35")
 useOne("/PDG_HADRON_MULTIPLICITIES_RATIOS/d08-x01-y02","35")
 useOne("/PDG_HADRON_MULTIPLICITIES_RATIOS/d09-x01-y02","35")
 useOne("/PDG_HADRON_MULTIPLICITIES_RATIOS/d13-x01-y02","35")
 useOne("/PDG_HADRON_MULTIPLICITIES_RATIOS/d15-x01-y02","35")
 useOne("/PDG_HADRON_MULTIPLICITIES_RATIOS/d18-x01-y02","35")
 useOne("/PDG_HADRON_MULTIPLICITIES_RATIOS/d19-x01-y02","35")
 useOne("/PDG_HADRON_MULTIPLICITIES_RATIOS/d20-x01-y02","35")
 useOne("/PDG_HADRON_MULTIPLICITIES_RATIOS/d21-x01-y02","35")
 useOne("/PDG_HADRON_MULTIPLICITIES_RATIOS/d22-x01-y02","35")
 useOne("/PDG_HADRON_MULTIPLICITIES_RATIOS/d31-x01-y02","35")
 useOne("/PDG_HADRON_MULTIPLICITIES_RATIOS/d33-x01-y01","35")
 useOne("/PDG_HADRON_MULTIPLICITIES_RATIOS/d34-x01-y01","35")
 useOne("/PDG_HADRON_MULTIPLICITIES_RATIOS/d38-x01-y02","35")
 useOne("/PDG_HADRON_MULTIPLICITIES_RATIOS/d39-x01-y02","35")
 useOne("/PDG_HADRON_MULTIPLICITIES_RATIOS/d44-x01-y02","35")
 useOne("/PDG_HADRON_MULTIPLICITIES_RATIOS/d46-x01-y02","35")
 useOne("/PDG_HADRON_MULTIPLICITIES_RATIOS/d47-x01-y02","35")
 useOne("/PDG_HADRON_MULTIPLICITIES_RATIOS/d48-x01-y02","35")
 useOne("/PDG_HADRON_MULTIPLICITIES_RATIOS/d50-x01-y02","35")
 useOne("/PDG_HADRON_MULTIPLICITIES_RATIOS/d51-x01-y02","35")
 useOne("/PDG_HADRON_MULTIPLICITIES_RATIOS/d02-x01-y03","91")
 useOne("/PDG_HADRON_MULTIPLICITIES_RATIOS/d03-x01-y03","91")
 useOne("/PDG_HADRON_MULTIPLICITIES_RATIOS/d04-x01-y03","91")
 useOne("/PDG_HADRON_MULTIPLICITIES_RATIOS/d05-x01-y03","91")
 useOne("/PDG_HADRON_MULTIPLICITIES_RATIOS/d06-x01-y03","91")
 useOne("/PDG_HADRON_MULTIPLICITIES_RATIOS/d07-x01-y03","91")
 useOne("/PDG_HADRON_MULTIPLICITIES_RATIOS/d08-x01-y03","91")
 useOne("/PDG_HADRON_MULTIPLICITIES_RATIOS/d09-x01-y03","91")
 useOne("/PDG_HADRON_MULTIPLICITIES_RATIOS/d10-x01-y01","91")
 useOne("/PDG_HADRON_MULTIPLICITIES_RATIOS/d11-x01-y01","91")
 useOne("/PDG_HADRON_MULTIPLICITIES_RATIOS/d12-x01-y01","91")
 useOne("/PDG_HADRON_MULTIPLICITIES_RATIOS/d13-x01-y03","91")
 useOne("/PDG_HADRON_MULTIPLICITIES_RATIOS/d14-x01-y01","91")
 useOne("/PDG_HADRON_MULTIPLICITIES_RATIOS/d15-x01-y03","91")
 useOne("/PDG_HADRON_MULTIPLICITIES_RATIOS/d16-x01-y01","91")
 useOne("/PDG_HADRON_MULTIPLICITIES_RATIOS/d17-x01-y02","91")
 useOne("/PDG_HADRON_MULTIPLICITIES_RATIOS/d18-x01-y03","91")
 useOne("/PDG_HADRON_MULTIPLICITIES_RATIOS/d19-x01-y03","91")
 useOne("/PDG_HADRON_MULTIPLICITIES_RATIOS/d20-x01-y03","91")
 useOne("/PDG_HADRON_MULTIPLICITIES_RATIOS/d21-x01-y03","91")
 useOne("/PDG_HADRON_MULTIPLICITIES_RATIOS/d23-x01-y02","91")
 useOne("/PDG_HADRON_MULTIPLICITIES_RATIOS/d24-x01-y01","91")
 useOne("/PDG_HADRON_MULTIPLICITIES_RATIOS/d25-x01-y02","91")
 useOne("/PDG_HADRON_MULTIPLICITIES_RATIOS/d26-x01-y01","91")
 useOne("/PDG_HADRON_MULTIPLICITIES_RATIOS/d27-x01-y01","91")
 useOne("/PDG_HADRON_MULTIPLICITIES_RATIOS/d28-x01-y01","91")
 useOne("/PDG_HADRON_MULTIPLICITIES_RATIOS/d29-x01-y01","91")
 useOne("/PDG_HADRON_MULTIPLICITIES_RATIOS/d30-x01-y01","91")
 useOne("/PDG_HADRON_MULTIPLICITIES_RATIOS/d31-x01-y03","91")
 useOne("/PDG_HADRON_MULTIPLICITIES_RATIOS/d32-x01-y01","91")
 useOne("/PDG_HADRON_MULTIPLICITIES_RATIOS/d34-x01-y02","91")
 useOne("/PDG_HADRON_MULTIPLICITIES_RATIOS/d35-x01-y01","91")
 useOne("/PDG_HADRON_MULTIPLICITIES_RATIOS/d36-x01-y01","91")
 useOne("/PDG_HADRON_MULTIPLICITIES_RATIOS/d37-x01-y01","91")
 useOne("/PDG_HADRON_MULTIPLICITIES_RATIOS/d38-x01-y03","91")
 useOne("/PDG_HADRON_MULTIPLICITIES_RATIOS/d39-x01-y03","91")
 useOne("/PDG_HADRON_MULTIPLICITIES_RATIOS/d40-x01-y02","91")
 useOne("/PDG_HADRON_MULTIPLICITIES_RATIOS/d41-x01-y01","91")
 useOne("/PDG_HADRON_MULTIPLICITIES_RATIOS/d42-x01-y01","91")
 useOne("/PDG_HADRON_MULTIPLICITIES_RATIOS/d43-x01-y01","91")
 useOne("/PDG_HADRON_MULTIPLICITIES_RATIOS/d44-x01-y03","91")
 useOne("/PDG_HADRON_MULTIPLICITIES_RATIOS/d45-x01-y02","91")
 useOne("/PDG_HADRON_MULTIPLICITIES_RATIOS/d46-x01-y03","91")
 useOne("/PDG_HADRON_MULTIPLICITIES_RATIOS/d47-x01-y03","91")
 useOne("/PDG_HADRON_MULTIPLICITIES_RATIOS/d48-x01-y03","91")
 useOne("/PDG_HADRON_MULTIPLICITIES_RATIOS/d49-x01-y02","91")
 useOne("/PDG_HADRON_MULTIPLICITIES_RATIOS/d50-x01-y03","91")
 useOne("/PDG_HADRON_MULTIPLICITIES_RATIOS/d51-x01-y03","91")
 useOne("/PDG_HADRON_MULTIPLICITIES_RATIOS/d52-x01-y01","91")
 useOne("/PDG_HADRON_MULTIPLICITIES_RATIOS/d54-x01-y02","91")
 useOne("/PDG_HADRON_MULTIPLICITIES_RATIOS/d03-x01-y04","177")
 useOne("/PDG_HADRON_MULTIPLICITIES_RATIOS/d04-x01-y04","177")
 useOne("/PDG_HADRON_MULTIPLICITIES_RATIOS/d38-x01-y04","177")
 useOne("/PDG_HADRON_MULTIPLICITIES_RATIOS/d39-x01-y04","177")
 # AMY analysis
 useOne("/AMY_1990_I295160/d01-x01-y01","50")
 useOne("/AMY_1990_I295160/d01-x01-y02","52")
 useOne("/AMY_1990_I295160/d01-x01-y03","55")
 useOne("/AMY_1990_I295160/d01-x01-y04","56")
 useOne("/AMY_1990_I295160/d01-x01-y05","57")
 useOne("/AMY_1990_I295160/d01-x01-y06","60")
 useOne("/AMY_1990_I295160/d01-x01-y07","60.8")
 useOne("/AMY_1990_I295160/d01-x01-y08","61.4")
 useOne("/AMY_1990_I295160/d01-x01-y09","57")
 useOne("/AMY_1990_I295160/d02-x02-y01","57")
 merge("/AMY_1990_I295160/d02-x01-y01")
 merge("/JADE_1983_I190818/d01-x01-y01")
 useOne("/PLUTO_1980_I154270/d01-x02-y01","30.75")
 merge("/PLUTO_1980_I154270/d01-x01-y01")
 
 merge("/TASSO_1989_I277658/d02-x01-y01")
 useOne("/TASSO_1989_I277658/d05-x01-y01","14")
 useOne("/TASSO_1989_I277658/d05-x01-y02","22")
 useOne("/TASSO_1989_I277658/d05-x01-y03","34.8")
 useOne("/TASSO_1989_I277658/d05-x01-y04","43.6")
 # Choose output file
 name = args[0]+".yoda"
 # output the yoda file
 # print "Write yoda to ",name
 yoda.writeYODA(outhistos,name)
 sys.exit(0)
diff --git a/Tests/python/merge-LHC-EW b/Tests/python/merge-LHC-EW
--- a/Tests/python/merge-LHC-EW
+++ b/Tests/python/merge-LHC-EW
@@ -1,401 +1,402 @@
 #! /usr/bin/env python
 import logging
 import sys
 import os, yoda
 
 """%prog
 
 Script for merging aida files
 
 """
 
 def fillAbove(scale,desthisto, sourcehistosbyptmin) :
     pthigh= 1e100
     ptlow =-1e100
     for pt, h in sorted(sourcehistosbyptmin.iteritems(),reverse=True):
         ptlow=pt
         if(type(desthisto)==yoda.core.Scatter2D) :
             for i in range(0,h.numPoints) :
                 xMin = h.points[i].x-h.points[i].xErrs.minus
                 if( xMin*scale >= ptlow and 
                     xMin*scale <  pthigh ) :
                     desthisto.addPoint(h.points[i])
         elif(type(desthisto)==yoda.core.Profile1D) :
             for i in range(0,h.numBins) :
                 if(h.bins[i].xMin*scale  >= ptlow and 
                    h.bins[i].xMin*scale  <  pthigh ) :
                     desthisto.bins[i] += h.bins[i]
         elif(type(desthisto)==yoda.core.Histo1D) :
             for i in range(0,h.numBins) :
                 if(h.bins[i].xMin*scale  >= ptlow and 
                    h.bins[i].xMin*scale  <  pthigh ) :
                     desthisto.bins[i] += h.bins[i]
         else :
             logging.error("Can't merge %s, unknown type" % desthisto.path)
             sys.exit(1)
         pthigh=pt
 
 def mergeByMass(hpath, sqrts, scale=1.):
     global inhistos_mass
     global outhistos
     try:
         fillAbove(scale,outhistos[hpath], inhistos_mass[hpath][float(sqrts)])
     except:
         pass
 
 def useOneMass(hpath, sqrts, ptmin):
     global inhistos_mass
     global outhistos
     try:
        ## Find best pT_min match
         ptmins = inhistos_mass[hpath][float(sqrts)].keys()
         closest_ptmin = None
         for ptm in ptmins:
             if closest_ptmin is None or \
                     abs(ptm-float(ptmin)) < abs(closest_ptmin-float(ptmin)):
                 closest_ptmin = ptm
         if closest_ptmin != float(ptmin):
             logging.warning("Inexact match for requested pTmin=%s: " % ptmin + \
                                 "using pTmin=%e instead" % closest_ptmin)
         outhistos[hpath] =  inhistos_mass[hpath][float(sqrts)][closest_ptmin]
     except:
         pass
 
 import sys
 if sys.version_info[:3] < (2,4,0):
     print "rivet scripts require Python version >= 2.4.0... exiting"
     sys.exit(1)
 
 if __name__ == "__main__":
     import logging
     from optparse import OptionParser, OptionGroup
     parser = OptionParser(usage="%prog base")
     verbgroup = OptionGroup(parser, "Verbosity control")
     verbgroup.add_option("-v", "--verbose", action="store_const", const=logging.DEBUG, dest="LOGLEVEL",
                          default=logging.INFO, help="print debug (very verbose) messages")
     verbgroup.add_option("-q", "--quiet", action="store_const", const=logging.WARNING, dest="LOGLEVEL",
                          default=logging.INFO, help="be very quiet")
     parser.add_option_group(verbgroup)
     (opts, args) = parser.parse_args()
     logging.basicConfig(level=opts.LOGLEVEL, format="%(message)s")
 
     ## Check args
     if len(args) < 1:
         logging.error("Must specify at least the name of the files")
         sys.exit(1)
 
     yodafiles=["-13-Z-e","-13-Z-mu","-Z-HighMass1-e","-Z-HighMass2-e",
                "-8-Z-Mass1-e","-8-Z-Mass1-mu","-8-Z-Mass2-e","-8-Z-Mass2-mu","-8-Z-Mass3-e","-8-Z-Mass3-mu","-8-Z-Mass4-e","-8-Z-Mass4-mu",
                "-W-e","-W-mu","-Z-e","-Z-mu","-Z-mu-Short","-Z-LowMass-e","-Z-LowMass-mu",
                "-Z-MedMass-e","-W-Z-e","-W-Z-mu",
                "-WW-emu","-WW-ll","-WZ","-ZZ-ll","-ZZ-lv","-8-WZ","-13-WZ","-8-ZZ-lv","-8-WW-ll",
                "-7-W-Jet-1-e","-7-W-Jet-2-e","-7-W-Jet-3-e","-7-Z-Jet-1-e","-7-Z-Jet-2-e","-7-Z-Jet-3-e",
                "-7-WGamma-e","-7-WGamma-mu","-7-ZGamma-e","-7-ZGamma-mu"]
     ## Get histos
     outhistos={}
 
     inhistos_mass = {}
     for f in yodafiles:
         file='Rivet-'+args[0]+f+".yoda"
         if not os.access(file, os.R_OK):
             logging.error("%s can not be read" % file)
             break
         try:
             aos = yoda.read(file)
         except:
             logging.error("%s can not be parsed as yoda" % file)
             break
         mass=66
         if(file.find("HighMass1")>=0) :
             mass = 116
         elif(file.find("HighMass2")>=0) :
             mass = 400
         elif(file.find("Mass1")>=0) :
             mass = 12
         elif(file.find("Mass2")>=0) :
             mass = 30
         elif(file.find("Mass3")>=0) :
             mass = 66
         elif(file.find("Mass4")>=0) :
             mass = 116
         ## Get histos from this YODA file
         for aopath, ao in aos.iteritems() :
+            if("RAW" in aopath) :continue
             if(aopath.find("ATLAS_2010_S8919674")>0) :
                 if((aopath.find("d01")>0 or aopath.find("d05")>0 or 
                     aopath.find("d07")>0) and file.find("-e")>0) : 
                     outhistos[aopath] = ao
                 elif((aopath.find("d02")>0 or aopath.find("d06")>0 or 
                       aopath.find("d08")>0) and file.find("-mu")>0) : 
                     outhistos[aopath] = ao
             elif (aopath.find("ATLAS_2011_S9131140")>0) :
                 if(aopath.find("d01")>0 and file.find("-e")>0) : 
                     outhistos[aopath] = ao
                 elif(aopath.find("d02")>0 and file.find("-mu")>0) : 
                     outhistos[aopath] = ao
             elif (aopath.find("ATLAS_2011_I925932")>0) :
                 if(aopath.find("d01")>0 and file.find("-e")>0) : 
                     outhistos[aopath] = ao
                 elif(aopath.find("d02")>0 and file.find("-mu")>0) : 
                     outhistos[aopath] = ao
             elif (aopath.find("ATLAS_2011_I945498")>0) :
                 if(aopath.find("y01")>0 and file.find("-e")>0) : 
                     outhistos[aopath] = ao
                 elif(aopath.find("y02")>0 and file.find("-mu")>0) : 
                     outhistos[aopath] = ao
                 elif(aopath.find("y03")>0 and file.find("-mu")>0) : 
                     outhistos[aopath] = ao
             elif (aopath.find("ATLAS_2013_I1217867")>0) :
                 if(aopath.find("y01")>0 and file.find("-e")>0) : 
                     outhistos[aopath] = ao
                 elif(aopath.find("y02")>0 and file.find("-mu")>0) : 
                     outhistos[aopath] = ao
             elif (aopath.find("CMS_2012_I941555")>0) :
                 if((aopath.find("y01")>0 or aopath.find("y03")>0 ) and file.find("-mu")>0) : 
                     outhistos[aopath] = ao
                 elif(aopath.find("y02")>0 and file.find("-e")>0) : 
                     outhistos[aopath] = ao
             elif (aopath.find("ATLAS_2014_I1300647" )>0) :
                 if(aopath.find("y01")>0 and file.find("-e")>0) : 
                     outhistos[aopath] = ao
                 elif((not aopath.find("y01")>0) and file.find("-mu")>0) :
                     outhistos[aopath] = ao
             elif (aopath.find("ATLAS_2014_I1288706" )>0) :
                 if(aopath.find("y02")>0 and file.find("-e")>0) : 
                     outhistos[aopath] = ao
                 elif(aopath.find("y01")>0 and file.find("-mu")>0) :
                     outhistos[aopath] = ao
             elif (aopath.find("ATLAS_2012_I1204784" )>0) :
                 if( file.find("-e")>0 and
                     ( aopath.find("d03")>0 or 
                       ((aopath.find("d01")>0 or aopath.find("d02")>0) and aopath.find("y01")>0))) : 
                     outhistos[aopath] = ao
                 elif(file.find("-mu")>0 and
                      ( aopath.find("d04")>0 or 
                        ((aopath.find("d01")>0 or aopath.find("d02")>0) and aopath.find("y02")>0))) : 
                     outhistos[aopath] = ao
             elif (aopath.find("ATLAS_2014_I1312627_EL") >0) :
                 if(file.find("-e")>0) :
                     outhistos[aopath] = ao
             elif (aopath.find("ATLAS_2014_I1312627_MU") >0) :
                 if(file.find("-mu")>0) :
                     outhistos[aopath] = ao
             elif (aopath.find("ATLAS_2014_I1312627") >0) :
                 if(file.find("-e")>0) :
                     outhistos[aopath] = ao
             elif (aopath.find("CMS_2013_I1224539_WJET" )>0) :
                 if(file.find("-1-e")>0 and (aopath.find("d52")>0 or aopath.find("d53")>0 or aopath.find("d56")>0 or aopath.find("d57")>0 or aopath.find("d60")>0 or aopath.find("d61")>0 or aopath.find("d64")>0 or aopath.find("d65")>0 or aopath.find("d68")>0 or aopath.find("d69")>0 or aopath.find("d72")>0)) :
                     outhistos[aopath] = ao
                 elif(file.find("-2-e")>0 and (aopath.find("d54")>0 or aopath.find("d58")>0 or aopath.find("d62")>0 or aopath.find("d66")>0 or aopath.find("d70")>0 or aopath.find("d73")>0)) :
                     outhistos[aopath] = ao
                 elif(file.find("-3-e")>0 and (aopath.find("d55")>0 or aopath.find("d59")>0 or aopath.find("d63")>0 or aopath.find("d67")>0 or aopath.find("d71")>0 or aopath.find("d74")>0)) :
                     outhistos[aopath] = ao
             elif (aopath.find("CMS_2013_I1224539_ZJET" )>0) :
                 if(file.find("-1-e")>0 and (aopath.find("d29")>0 or aopath.find("d30")>0 or aopath.find("d33")>0 or aopath.find("d34")>0 or aopath.find("d37")>0 or aopath.find("d38")>0 or aopath.find("d41")>0 or aopath.find("d42")>0 or aopath.find("d45")>0 or aopath.find("d46")>0 or aopath.find("d49")>0)) :
                     outhistos[aopath] = ao
                 elif(file.find("-2-e")>0 and (aopath.find("d31")>0 or aopath.find("d35")>0 or aopath.find("d39")>0 or aopath.find("d43")>0 or aopath.find("d47")>0 or aopath.find("d50")>0)) :
                     outhistos[aopath] = ao
                 elif(file.find("-3-e")>0 and (aopath.find("d32")>0 or aopath.find("d36")>0 or aopath.find("d40")>0 or aopath.find("d44")>0 or aopath.find("d48")>0 or aopath.find("d51")>0)) :
                     outhistos[aopath] = ao
             elif (aopath.find("CMS_2013_I1258128")>0) :
                 if(aopath.find("d01")>0 or aopath.find("d02")>0 or
                    aopath.find("d03")>0 or aopath.find("d04")>0) :
                     outhistos[aopath] = ao
             elif (aopath.find("CMS_2013_I1209721" )>0 and file.find("-0")>0 ) :
                 outhistos[aopath] = ao
             elif (aopath.find("ATLAS_2011_I928289")>0) :
                 if(file.find("-e")>=0 and (aopath.find("y01")>=0 or aopath.find("y02")>=0)) :
                     outhistos[aopath] = ao
                 elif(file.find("-mu")>=0 and (aopath.find("y03")>=0 or aopath.find("y04")>=0)) :
                     outhistos[aopath] = ao
             elif (aopath.find("CMS_2013_I1122847")>0) :
                 if(file.find("-mu")>=0 and aopath.find("d01")>=0 ) :
                     outhistos[aopath] = ao
                 elif(file.find("-e")>=0 and (aopath.find("d02")>=0 or aopath.find("d03")>=0)) :
                     outhistos[aopath] = ao
             elif (aopath.find("ATLAS_2016_I1424838")>0) :
                 if(file.find("-mu")>=0 and aopath.find("x02")>=0 ) :
                     outhistos[aopath] = ao
                 elif(file.find("-e")>=0 and (aopath.find("x01")>=0)) :
                     outhistos[aopath] = ao
             elif (aopath.find("CMS_2015_I1310737")>0) :
                 if aopath in outhistos :
                     outhistos[aopath] += ao
                 else :
                     outhistos[aopath] = ao
             elif (aopath.find("ATLAS_2015_I1351916")>=0) :
                 if(aopath.find("-y01")>=0) :
                     pathBase = aopath.replace("-y01","")
                     hp = aos[pathBase+"-y02"]
                     hm = aos[pathBase+"-y03"]
                     ratio = (hp-hm)/(hp+hm)
                     hnew = yoda.Scatter2D(aopath,ao.title)
                     hnew.combineWith(ratio)
                     outhistos[aopath] = hnew
                 else :
                     continue
             elif (aopath.find("ATLAS_2014_I1282447")>=0) :
                 if((aopath.find("/ATLAS_2014_I1282447/d02-x01-y01")>=0 or
                     aopath.find("/ATLAS_2014_I1282447/d08-x01-y01")>=0 or 
                     aopath.find("/ATLAS_2014_I1282447/d02-x01-y02")>=0 or 
                     aopath.find("/ATLAS_2014_I1282447/d02-x01-y01")>=0 or
                     aopath.find("/ATLAS_2014_I1282447/d05-x01-y02")>=0 or 
                     aopath.find("/ATLAS_2014_I1282447/d05-x01-y03")>=0 or 
                     aopath.find("/ATLAS_2014_I1282447/d06-x01-y01")>=0 or
                     aopath.find("/ATLAS_2014_I1282447/d06-x01-y02")>=0 or 
                     aopath.find("/ATLAS_2014_I1282447/d06-x01-y03")>=0 or 
                     aopath.find("/ATLAS_2014_I1282447/d06-x01-y04")>=0) and 
                    not (aopath.find("plus")>=0 or aopath.find("minus")>=0 or
                         aopath.find("inc")>=0)) :
                     continue
                 if aopath in outhistos :
                     outhistos[aopath] += ao
                 else :
                     outhistos[aopath] = ao
             elif (aopath.find("ATLAS_2015_I1408516")>=0) :
                 if not inhistos_mass.has_key(aopath):
                     inhistos_mass[aopath] = {}
                 tmpE = inhistos_mass[aopath]
                 sqrts=8000
                 if not tmpE.has_key(sqrts):
                     tmpE[sqrts] = {}
                 tmpP = tmpE[sqrts]
                 if not tmpP.has_key(mass):
                     tmpP[mass] = ao
                 else:
                     raise Exception("A set with mass = %s already exists" % ( mass))
             elif (aopath.find("ATLAS_2013_I1234228")>=0) :
                 if not inhistos_mass.has_key(aopath):
                     inhistos_mass[aopath] = {}
                 tmpE = inhistos_mass[aopath]
                 sqrts=7000
                 if not tmpE.has_key(sqrts):
                     tmpE[sqrts] = {}
                 tmpP = tmpE[sqrts]
                 if not tmpP.has_key(mass):
                     tmpP[mass] = ao
                 else:
                     raise Exception("A set with mass = %s already exists" % ( mass))
             else :
                 outhistos[aopath] = ao
     for hpath,hsets in inhistos_mass.iteritems():
         if(hpath!="/ATLAS_2015_I1408516_EL/d41-x01-y01" and
            hpath!="/ATLAS_2015_I1408516_MU/d41-x01-y02" and
            hpath!="/ATLAS_2013_I1234228/d01-x01-y02" ) :
             continue
         if(type(hsets.values()[0].values()[0])==yoda.core.Scatter2D) :
             outhistos[hpath] = yoda.core.Scatter2D(hsets.values()[0].values()[0].path,
                                                    hsets.values()[0].values()[0].title)
         elif(type(hsets.values()[0].values()[0])==yoda.core.Profile1D) :
             outhistos[hpath] = yoda.core.Profile1D(hsets.values()[0].values()[0].path,
                                                    hsets.values()[0].values()[0].title)
             for i in range(0,hsets.values()[0].values()[0].numBins) :
                 outhistos[hpath].addBin(hsets.values()[0].values()[0].bins[i].xMin,
                                         hsets.values()[0].values()[0].bins[i].xMax)
         elif(type(hsets.values()[0].values()[0])==yoda.core.Histo1D) :
             outhistos[hpath] = yoda.core.Histo1D(hsets.values()[0].values()[0].path,
                                                 hsets.values()[0].values()[0].title)
             for i in range(0,hsets.values()[0].values()[0].numBins) :
                 outhistos[hpath].addBin(hsets.values()[0].values()[0].bins[i].xMin,
                                         hsets.values()[0].values()[0].bins[i].xMax)
         else :
             logging.error("Histogram %s is of unknown type" % hpath)
             sys.exit(1)
     # sort out mass bins for ATLAS Z-> e,mu at 8 TeV
     for ltype in ["EL","MU"] :
         if(ltype=="EL") :
             y = "y01"
             mergeByMass("/ATLAS_2015_I1408516_EL/d41-x01-y01", "8000")
         else :
             y = "y04"
             mergeByMass("/ATLAS_2015_I1408516_MU/d41-x01-y02", "8000")
         for d in [2,3,04,14,26,38]:
             useOneMass("/ATLAS_2015_I1408516_%s/d%02d-x01-%s" % (ltype,d,y), "8000", "30" )
         for d in [5,6,7,8,9,10,15,17,18,19,20,21,22,27,29,30,31,32,33,34,39]:
             useOneMass("/ATLAS_2015_I1408516_%s/d%02d-x01-%s" % (ltype,d,y), "8000", "66" )
         for d in [11,12,13,16,28,40]:
             useOneMass("/ATLAS_2015_I1408516_%s/d%02d-x01-%s" % (ltype,d,y), "8000", "116" )
         for d in [23,35]:
             useOneMass("/ATLAS_2015_I1408516_%s/d%02d-x01-%s" % (ltype,d,y), "8000", "12" )
         for d in [24,36]:
             useOneMass("/ATLAS_2015_I1408516_%s/d%02d-x01-%s" % (ltype,d,y), "8000", "12" )
         for d in [25,37]:
             useOneMass("/ATLAS_2015_I1408516_%s/d%02d-x01-%s" % (ltype,d,y), "8000", "30" )
     # sort out ratios for ATLAS W+c
     if("/ATLAS_2014_I1282447/d02-x01-y01_plus" in outhistos and 
        "/ATLAS_2014_I1282447/d02-x01-y01_minus" in outhistos) :
         d02y01_plus  = outhistos["/ATLAS_2014_I1282447/d02-x01-y01_plus"]
         d02y01_minus = outhistos["/ATLAS_2014_I1282447/d02-x01-y01_minus"]
         ratio_d02y01 = d02y01_plus/d02y01_minus
         ratio_d02y01.path = "/ATLAS_2014_I1282447/d02-x01-y01"
         del outhistos["/ATLAS_2014_I1282447/d02-x01-y01_plus"]
         del outhistos["/ATLAS_2014_I1282447/d02-x01-y01_minus"]
         outhistos["/ATLAS_2014_I1282447/d02-x01-y01"] = ratio_d02y01
     if("/ATLAS_2014_I1282447/d02-x01-y02_plus" in outhistos and 
        "/ATLAS_2014_I1282447/d02-x01-y02_minus" in outhistos) :
         d02y02_plus  = outhistos["/ATLAS_2014_I1282447/d02-x01-y02_plus"]
         d02y02_minus = outhistos["/ATLAS_2014_I1282447/d02-x01-y02_minus"]
         ratio_d02y02 = d02y02_plus/d02y02_minus
         ratio_d02y02.path = "/ATLAS_2014_I1282447/d02-x01-y02"
         del outhistos["/ATLAS_2014_I1282447/d02-x01-y02_plus"]
         del outhistos["/ATLAS_2014_I1282447/d02-x01-y02_minus"]
         outhistos["/ATLAS_2014_I1282447/d02-x01-y02"] = ratio_d02y02
     if("/ATLAS_2014_I1282447/d08-x01-y01_plus" in outhistos and 
        "/ATLAS_2014_I1282447/d08-x01-y01_minus" in outhistos) :
         d08y01_plus  = outhistos["/ATLAS_2014_I1282447/d08-x01-y01_plus"]
         d08y01_minus = outhistos["/ATLAS_2014_I1282447/d08-x01-y01_minus"]
         ratio_d08y01 = d08y01_plus/d08y01_minus
         ratio_d08y01.path = "/ATLAS_2014_I1282447/d08-x01-y01"
         del outhistos["/ATLAS_2014_I1282447/d08-x01-y01_plus"]
         del outhistos["/ATLAS_2014_I1282447/d08-x01-y01_minus"]
         outhistos["/ATLAS_2014_I1282447/d08-x01-y01"] = ratio_d08y01
     if ("/ATLAS_2014_I1282447/d05-x01-y01" in outhistos and
         "/ATLAS_2014_I1282447/d01-x01-y02" in outhistos) :
         h_winc = outhistos["/ATLAS_2014_I1282447/d05-x01-y01"]
         h_d    = outhistos["/ATLAS_2014_I1282447/d01-x01-y02"]
         ratio_wd      =  h_d/h_winc
         ratio_wd.path = "/ATLAS_2014_I1282447/d05-x01-y02"
         outhistos["/ATLAS_2014_I1282447/d05-x01-y02"] = ratio_wd
     if ("/ATLAS_2014_I1282447/d05-x01-y01" in outhistos and
         "/ATLAS_2014_I1282447/d01-x01-y03" in outhistos) :
         h_winc = outhistos["/ATLAS_2014_I1282447/d05-x01-y01"]
         h_dstar= outhistos["/ATLAS_2014_I1282447/d01-x01-y03"]
         ratio_wdstar      =  h_dstar/h_winc
         ratio_wdstar.path = "/ATLAS_2014_I1282447/d05-x01-y03"
         outhistos["/ATLAS_2014_I1282447/d05-x01-y03"] = ratio_wdstar
     if("/ATLAS_2014_I1282447/d06-x01-y01_winc" in outhistos and
        "/ATLAS_2014_I1282447/d06-x01-y02_winc" in outhistos) :
         h_winc_plus  = outhistos["/ATLAS_2014_I1282447/d06-x01-y01_winc"]
         h_winc_minus = outhistos["/ATLAS_2014_I1282447/d06-x01-y02_winc"]
         if( "/ATLAS_2014_I1282447/d06-x01-y01_wplus" in outhistos ) :
             h_wd_plus      = outhistos["/ATLAS_2014_I1282447/d06-x01-y01_wplus"]
             ratio_wd_plus       =  h_wd_plus/h_winc_plus
             ratio_wd_plus.path  = "/ATLAS_2014_I1282447/d06-x01-y01"
             outhistos["/ATLAS_2014_I1282447/d06-x01-y01"] = ratio_wd_plus
             del outhistos["/ATLAS_2014_I1282447/d06-x01-y01_wplus"]
         if( "/ATLAS_2014_I1282447/d06-x01-y02_wminus" in outhistos ) :
             h_wd_minus     = outhistos["/ATLAS_2014_I1282447/d06-x01-y02_wminus"]
             ratio_wd_minus      =  h_wd_minus/h_winc_minus
             ratio_wd_minus.path = "/ATLAS_2014_I1282447/d06-x01-y02"
             outhistos["/ATLAS_2014_I1282447/d06-x01-y02"] = ratio_wd_minus
             del outhistos["/ATLAS_2014_I1282447/d06-x01-y02_wminus"]
         if ( "/ATLAS_2014_I1282447/d06-x01-y03_wplus" in outhistos) : 
             h_wdstar_plus  = outhistos["/ATLAS_2014_I1282447/d06-x01-y03_wplus"]
             ratio_wdstar_plus       =  h_wdstar_plus/h_winc_plus
             ratio_wdstar_plus.path  = "/ATLAS_2014_I1282447/d06-x01-y03"
             outhistos["/ATLAS_2014_I1282447/d06-x01-y03"] = ratio_wdstar_plus 
             del outhistos["/ATLAS_2014_I1282447/d06-x01-y03_wplus"]
         if ( "/ATLAS_2014_I1282447/d06-x01-y04_wminus" in outhistos) :
             h_wdstar_minus = outhistos["/ATLAS_2014_I1282447/d06-x01-y04_wminus"]
             ratio_wdstar_minus      =  h_wdstar_minus/h_winc_minus
             ratio_wdstar_minus.path = "/ATLAS_2014_I1282447/d06-x01-y04"
             outhistos["/ATLAS_2014_I1282447/d06-x01-y04"] = ratio_wdstar_minus
             del outhistos["/ATLAS_2014_I1282447/d06-x01-y04_wminus"]
         del outhistos["/ATLAS_2014_I1282447/d06-x01-y01_winc"]
         del outhistos["/ATLAS_2014_I1282447/d06-x01-y02_winc"]
 
         
     mergeByMass("/ATLAS_2013_I1234228/d01-x01-y02", "7000")
     # Choose output file
     name = args[0]+"-EW.yoda"
     yoda.writeYODA(outhistos,name)
     sys.exit(0)
diff --git a/Tests/python/merge-LHC-Jets b/Tests/python/merge-LHC-Jets
--- a/Tests/python/merge-LHC-Jets
+++ b/Tests/python/merge-LHC-Jets
@@ -1,1517 +1,1553 @@
 #! /usr/bin/env python
 import logging
 import sys
 import math
 
 if sys.version_info[:3] < (2,4,0):
     print "rivet scripts require Python version >= 2.4.0... exiting"
     sys.exit(1)
 
 import os, yoda
 
 # #############################################
 
+def rescale(path,scale) :
+    if(path not in outhistos) : return
+    outhistos[path].scaleW(scale)
 
 def fillAbove(scale,desthisto, sourcehistosbyptmin) :
     pthigh= 1e100
     ptlow =-1e100
     for pt, h in sorted(sourcehistosbyptmin.iteritems(),reverse=True):
         ptlow=pt
         if(type(desthisto)==yoda.core.Scatter2D) :
             for i in range(0,h.numPoints) :
                 xMin = h.points[i].x-h.points[i].xErrs.minus
                 if( xMin*scale >= ptlow and 
                     xMin*scale <  pthigh ) :
                     desthisto.addPoint(h.points[i])
         elif(type(desthisto)==yoda.core.Profile1D) :
             for i in range(0,h.numBins) :
                 if(h.bins[i].xMin*scale  >= ptlow and 
                    h.bins[i].xMin*scale  <  pthigh ) :
                     desthisto.bins[i] += h.bins[i]
         elif(type(desthisto)==yoda.core.Histo1D) :
             for i in range(0,h.numBins) :
                 if(h.bins[i].xMin*scale  >= ptlow and 
                    h.bins[i].xMin*scale  <  pthigh ) :
                     desthisto.bins[i] += h.bins[i]
         elif(type(desthisto)==yoda.core.Counter) :
                     desthisto += h
         else :
             logging.error("Can't merge %s, unknown type" % desthisto.path)
             sys.exit(1)
         pthigh=pt
 
 def mergeByPt(hpath, sqrts, scale=1.) :
     global inhistos_pt
     global outhistos
     try:
         fillAbove(scale,outhistos[hpath], inhistos_pt[hpath][float(sqrts)])
     except:
         pass
 
 def mergeByMass(hpath, sqrts, scale=1.):
     global inhistos_mass
     global outhistos
     try:
         fillAbove(scale,outhistos[hpath], inhistos_mass[hpath][float(sqrts)])
     except:
         pass
 
 def useOnePt(hpath, sqrts, ptmin):
     global inhistos_pt
     global outhistos
     try:
        ## Find best pT_min match
         ptmins = inhistos_pt[hpath][float(sqrts)].keys()
         closest_ptmin = None
         for ptm in ptmins:
             if closest_ptmin is None or \
                     abs(ptm-float(ptmin)) < abs(closest_ptmin-float(ptmin)):
                 closest_ptmin = ptm
         if closest_ptmin != float(ptmin):
             logging.warning("Inexact match for requested pTmin=%s: " % ptmin + \
                                 "using pTmin=%e instead" % closest_ptmin)
         outhistos[hpath] =  inhistos_pt[hpath][float(sqrts)][closest_ptmin]
     except:
         pass
 
 def useOneMass(hpath, sqrts, ptmin):
     global inhistos_pt
     global outhistos
     try:
        ## Find best pT_min match
         ptmins = inhistos_mass[hpath][float(sqrts)].keys()
         closest_ptmin = None
         for ptm in ptmins:
             if closest_ptmin is None or \
                     abs(ptm-float(ptmin)) < abs(closest_ptmin-float(ptmin)):
                 closest_ptmin = ptm
         if closest_ptmin != float(ptmin):
             logging.warning("Inexact match for requested mass=%s: " % ptmin + \
                                 "using mass=%e instead" % closest_ptmin)
         outhistos[hpath] =  inhistos_mass[hpath][float(sqrts)][closest_ptmin]
     except:
         pass
 
 # #######################################
 
 if __name__ == "__main__":
     import logging
     from optparse import OptionParser, OptionGroup
     parser = OptionParser(usage="%prog name")
     verbgroup = OptionGroup(parser, "Verbosity control")
     parser.add_option("--with-ue",
                       action='store_true' ,
                       dest="ue",
                       default=True,
                       help="Include UE analyses")
     parser.add_option("--without-ue",
                       action='store_false',
                       dest="ue",
                       default=True,
                       help="Don\'t include UE analyses")
     verbgroup.add_option("-v", "--verbose", action="store_const", const=logging.DEBUG, dest="LOGLEVEL",
                          default=logging.INFO, help="print debug (very verbose) messages")
     verbgroup.add_option("-q", "--quiet", action="store_const", const=logging.WARNING, dest="LOGLEVEL",
                          default=logging.INFO, help="be very quiet")
     parser.add_option_group(verbgroup)
     (opts, args) = parser.parse_args()
     logging.basicConfig(level=opts.LOGLEVEL, format="%(message)s")
 
     (opts, args) = parser.parse_args()
 
     ## Check args
     if len(args) < 1:
         logging.error("Must specify at least the name of the files")
         sys.exit(1)
 yodafiles=["-7-Bottom-0.yoda","-7-Bottom-1.yoda","-7-Bottom-2.yoda",
            "-7-Bottom-3.yoda","-7-Bottom-4.yoda","-7-Bottom-5.yoda",
            "-7-Charm-1.yoda","-7-Charm-2.yoda",
            "-7-Charm-3.yoda","-7-Charm-4.yoda","-7-Charm-5.yoda",
-           "-7-Top-SL.yoda","-7-Top-L.yoda","-7-Top-All.yoda",
+           "-7-Top-SL.yoda","-7-Top-L.yoda",
            "-8-Top-SL.yoda","-8-Top-L.yoda","-8-Top-All.yoda",
-           "-13-Top-L.yoda","-13-Top-SL.yoda"]
+           "-13-Top-L.yoda","-13-Top-SL.yoda","-13-Top-All.yoda"]
 
 for i in range(1,11) :
     for j in [7,8,13] :
         yodafiles.append("-%1.1i-Jets-%1.1i.yoda" % (j,i))
+        
+for i in range(1,3) :
+    yodafiles.append("-2760-Jets-%1.1i.yoda" % i)
 
 if(opts.ue) :
     yodafiles += ["-7-Jets-0.yoda"    ,"-8-Jets-0.yoda" ,
                   "-900-UE.yoda"   ,"-2360-UE.yoda"    ,
                   "-2760-UE.yoda"     ,"-7-UE.yoda"     ,"-900-UE-Long.yoda",
                   "-900-UE-Short.yoda","-8-UE.yoda"     ,
                   "-7-UE-Long.yoda","-13-UE.yoda","-13-UE-Long.yoda"]
 ## Get histos
 inhistos_pt   = {}
 inhistos_mass = {}
 outhistos={}
 weights = {}
 for f in yodafiles:
     file='Rivet-'+args[0]+f
     ptmin=0.
     sqrts=7000
     # CMS energy
     if(file.find("-900-")>0) :
         sqrts=900
     elif(file.find("-2360-")>0) :
         sqrts=2360
     elif(file.find("-2760-")>0) :
         sqrts=2760
     elif(file.find("-7-")>=0) :
         sqrts=7000
     elif(file.find("-8-")>=0) :
         sqrts=8000
     elif(file.find("-13-")>0) :
         sqrts=13000
     # pT min
     if(file.find("UE")>0) :
         ptmin=0.
     elif(file.find("Jets-0")>0) :
         ptmin=4.
     elif(file.find("Jets-10")>0) :
         ptmin=1900.
     elif(file.find("Jets-1")>0) :
         if( not opts.ue) :
             ptmin = 10.
         else :
             ptmin = 20.
     elif(file.find("Jets-2")>0) :
         ptmin=40.
     elif(file.find("Jets-3")>0) :
         ptmin=80.
     elif(file.find("Jets-4")>0) :
         ptmin=110.
     elif(file.find("Jets-5")>0) :
         ptmin=210.
     elif(file.find("Jets-6")>0) :
         ptmin=260.
     elif(file.find("Jets-7")>0) :
         ptmin=400.
     elif(file.find("Jets-8")>0) :
         ptmin=600.
     elif(file.find("Jets-9")>0) :
         ptmin=900.
     elif(file.find("Bottom-0")>0) :
         ptmin=0.
     elif(file.find("Bottom-1")>0 or file.find("Charm-1")>0) :
         ptmin=10.
     elif(file.find("Bottom-2")>0 or file.find("Charm-2")>0) :
         ptmin=30.
     elif(file.find("Bottom-3")>0 or file.find("Charm-3")>0) :
         ptmin=70.
     elif(file.find("Bottom-4")>0 or file.find("Charm-4")>0) :
         ptmin=100.
     elif(file.find("Bottom-5")>0 or file.find("Charm-5")>0) :
         ptmin=130.
     elif(file.find("Top-SL.yoda")>0 or file.find("Top-L.yoda")>0 or \
          file.find("Top-All.yoda")>0):
         ptmin=0.
     if not os.access(file, os.R_OK):
         logging.error("%s can not be read" % file)
         continue
     try:
         aos = yoda.read(file)
     except:
         logging.error("%s can not be parsed as YODA" % file)
         continue
     ## Get histos from this YODA file
     for aopath, ao in aos.iteritems() :
+        if("RAW" in aopath) :continue
         if(aopath.find("S8924791")>0 or aopath.find("S8971293")>0 or
            aopath.find("S8817804")>0 or aopath.find("I1082936")>0 or
            aopath.find("S8994773")>0 or aopath.find("S8918562")>0 or
            aopath.find("S8624100")>0 or aopath.find("S8625980")>0 or
            aopath.find("S8894728")>0 or aopath.find("S8957746")>0 or
            aopath.find("S9126244")>0 or aopath.find("S9120041")>0 or
            aopath.find("S8950903")>0 or aopath.find("S9086218")>0 or
            aopath.find("S9088458")>0 or aopath.find("I919017" )>0 or
            aopath.find("I926145" )>0 or aopath.find("S8941262")>0 or
            aopath.find("S8973270")>0 or aopath.find("I1118269")>0 or
            aopath.find("I1188891")>0 or aopath.find("I1082009")>0 or
            aopath.find("I1087342")>0 or aopath.find("S9035664")>0 or
            aopath.find("I1125575")>0 or aopath.find("I1094564")>0 or
            aopath.find("I930220" )>0 or aopath.find("I1224539")>0 or
            aopath.find("I1273574")>0 or aopath.find("I1261026")>0 or
            aopath.find("I1307243")>0 or aopath.find("I1325553")>0 or
            aopath.find("I1298810")>0 or aopath.find("I1298811")>0 or
            aopath.find("I1208923")>0 or aopath.find("I1305624")>0 or
            aopath.find("I1419070")>0 or aopath.find("I1394679")>0 or
            aopath.find("I929691" )>0 or aopath.find("I1393758")>0 or
            aopath.find("I1459051")>0 or aopath.find("I1487277")>0 or
            aopath.find("I1421646")>0 or aopath.find("I1111014")>0 or
            aopath.find("I1605749")>0 or aopath.find("I1682495")>0 or
+           aopath.find("I1609253")>0 or aopath.find("1385107" )>0 or 
            aopath.find("ATLAS_2016_CONF_2016_092")>0 or
            aopath.find("CMS_2012_PAS_QCD_11_010")>0) :
            if not inhistos_pt.has_key(aopath):
                inhistos_pt[aopath] = {}
            tmpE = inhistos_pt[aopath]
            if not tmpE.has_key(sqrts):
                tmpE[sqrts] = {}
            if not tmpE[sqrts].has_key(ptmin):
                tmpE[sqrts][ptmin] = ao
            else:
                tmpE[sqrts][ptmin] += ao
                #raise Exception("A set with ptmin = %s already exists" % ( ptmin))
         else :
             if(aopath.find("I1243871")>0) :
                 if(aopath.find("x01")>0 and file.find("-7-Top-L.yoda")>0 ) :
                     outhistos[aopath] = ao
                 elif(aopath.find("x02")>0 and file.find("-7-Top-SL.yoda")>0 ) :
                     outhistos[aopath] = ao
             elif(aopath.find("1467230")>0 or aopath.find("1419652")>0) :
                 if(aopath.find("y01")>0 and file.find("Long")>0 ) :
                     outhistos[aopath] = ao
                 elif(aopath.find("y02")>0 and file.find("Long")<0 ) :
                     outhistos[aopath] = ao
             else :
                 outhistos[aopath] = ao
 
 
 
 yodafiles=["-7-Bottom-6.yoda","-7-Bottom-7.yoda","-7-Bottom-8.yoda"]
 for i in range(1,8) :
     yodafiles.append("-7-DiJets-%1.1i-A.yoda" % i)
     yodafiles.append("-7-DiJets-%1.1i-B.yoda" % i)
     yodafiles.append("-7-DiJets-%1.1i-C.yoda" % i)
 
 for f in yodafiles:
     file='Rivet-'+args[0]+f
     if(file.find("-7-Jets-1")>0) :
         sqrts=7000
         mass=0
     if(file.find("-7-DiJets-1")>0) :
         sqrts=7000
         mass=100
     elif(file.find("-7-DiJets-2")>0) :
         sqrts=7000
         mass=250
     elif(file.find("-7-DiJets-3")>0) :
         sqrts=7000
         mass=500
     elif(file.find("-7-DiJets-4")>0) :
         sqrts=7000
         mass=800
     elif(file.find("-7-DiJets-5")>0) :
         sqrts=7000
         mass=1000
     elif(file.find("-7-DiJets-6")>0) :
         sqrts=7000
         mass=1600
     elif(file.find("-7-DiJets-7")>0) :
         sqrts=7000
         mass=2200
     elif(file.find("-7-DiJets-8")>0) :
         sqrts=7000
         mass=2800
     elif(file.find("-7-Bottom-6")>0) :
         sqrts=7000
         mass=110
     elif(file.find("-7-Bottom-7")>0) :
         sqrts=7000
         mass=370
     elif(file.find("-7-Bottom-8")>0) :
         sqrts=7000
         mass=550
     if not os.access(file, os.R_OK):
         logging.error("%s can not be read" % file)
         continue
     try:
         aos = yoda.read(file)
     except:
         logging.error("%s can not be parsed as YODA" % file)
         continue
     ## Get histos from this YODA file
     for aopath, ao in aos.iteritems() :
+        if("RAW" in aopath) :continue
         if(aopath.find("8817804")>0 or
            aopath.find("8968497")>0 or 
            aopath.find("1082936")>0 or
            aopath.find("I930220")>0 or
            aopath.find("1261026")>0 or
            aopath.find("1090423")>0 or
            aopath.find("1268975")>0 or
            aopath.find("CMS_2013_I1208923")>0) :
            if not inhistos_mass.has_key(aopath):
                inhistos_mass[aopath] = {}
            tmpE = inhistos_mass[aopath]
            if not tmpE.has_key(sqrts):
                tmpE[sqrts] = {}
            tmpP = tmpE[sqrts]
            if not tmpP.has_key(mass):
                tmpP[mass] = ao
            else:
                print aopath
                raise Exception("A set with mass = %s already exists" % ( mass))
 
 ## Make empty output histos if needed
 for hpath,hsets in inhistos_pt.iteritems():
     if( hpath.find("8924791")>0  or 
         hpath.find("8971293")>0 or 
         hpath.find("8817804")>0 or 
         hpath.find("8968497")>0 or 
         (hpath.find("9120041")>0 and (hpath.find("d01")>0 or hpath.find("d02")>0)) or 
         hpath.find("9126244")>0 or 
         hpath.find("926145") >0 or 
         hpath.find("9086218")>0 or 
         hpath.find("1082936")>0 or 
         hpath.find("8941262")>0 or 
         hpath.find("1118269")>0 or 
         hpath.find("1087342")>0 or 
         hpath.find("1188891")>0 or
         hpath.find("919017")>0  or
         hpath.find("9035664")>0 or
         hpath.find("1125575")>0 or
         hpath.find("1094564")>0 or
         hpath.find("I930220")>0 or
         hpath.find("S9088458")>0 or 
         hpath.find("I1273574")>0 or 
         hpath.find("I1261026")>0 or 
         hpath.find("I1090423")>0 or
         hpath.find("QCD_11_010")>0 or
         hpath.find("1298811"   )>0 or
         hpath.find("I1325553"  )>0 or
         hpath.find("I1298810"  )>0 or
         hpath.find("1307243"   )>0 or
         hpath.find("I1419070")>0 or
         hpath.find("I1394679")>0 or
         hpath.find("I1487277")>0 or
         hpath.find("CMS_2013_I1208923")>0 or
         hpath.find("1393758")>0 or
         hpath.find("ATLAS_2016_CONF_2016_092")>0 or
-        hpath.find("1111014"   )>0 or
+        hpath.find("1111014"   )>0 or hpath.find("1385107")>0 or
         hpath.find("1459051")>0) :
         if(type(hsets.values()[0].values()[0])==yoda.core.Counter) :
             outhistos[hpath] = yoda.core.Counter(hsets.values()[0].values()[0].path,
                                                  hsets.values()[0].values()[0].title)
         elif(type(hsets.values()[0].values()[0])==yoda.core.Scatter2D) :
             outhistos[hpath] = yoda.core.Scatter2D(hsets.values()[0].values()[0].path,
                                                    hsets.values()[0].values()[0].title)
         elif(type(hsets.values()[0].values()[0])==yoda.core.Profile1D) :
             outhistos[hpath] = yoda.core.Profile1D(hsets.values()[0].values()[0].path,
                                                    hsets.values()[0].values()[0].title)
             for i in range(0,hsets.values()[0].values()[0].numBins) :
                 outhistos[hpath].addBin(hsets.values()[0].values()[0].bins[i].xMin,
                                         hsets.values()[0].values()[0].bins[i].xMax)
         elif(type(hsets.values()[0].values()[0])==yoda.core.Histo1D) :
             outhistos[hpath] = yoda.core.Histo1D(hsets.values()[0].values()[0].path,
                                                 hsets.values()[0].values()[0].title)
             for i in range(0,hsets.values()[0].values()[0].numBins) :
                 outhistos[hpath].addBin(hsets.values()[0].values()[0].bins[i].xMin,
                                         hsets.values()[0].values()[0].bins[i].xMax)
         else :
             logging.error("Histogram %s is of unknown type" % hpath)
             sys.exit(1) 
 
 ## Make empty output histos if needed
 for hpath,hsets in inhistos_mass.iteritems():
     if(hpath.find("1268975")>0) :
         if(type(hsets.values()[0].values()[0])==yoda.core.Counter) :
             outhistos[hpath] = yoda.core.Counter(hsets.values()[0].values()[0].path,
                                                  hsets.values()[0].values()[0].title)
         elif(type(hsets.values()[0].values()[0])==yoda.core.Scatter2D) :
             outhistos[hpath] = yoda.core.Scatter2D(hsets.values()[0].values()[0].path,
                                                    hsets.values()[0].values()[0].title)
         elif(type(hsets.values()[0].values()[0])==yoda.core.Profile1D) :
             outhistos[hpath] = yoda.core.Profile1D(hsets.values()[0].values()[0].path,
                                                    hsets.values()[0].values()[0].title)
             for i in range(0,hsets.values()[0].values()[0].numBins) :
                 outhistos[hpath].addBin(hsets.values()[0].values()[0].bins[i].xMin,
                                         hsets.values()[0].values()[0].bins[i].xMax)
         elif(type(hsets.values()[0].values()[0])==yoda.core.Histo1D) :
             outhistos[hpath] = yoda.core.Histo1D(hsets.values()[0].values()[0].path,
                                                 hsets.values()[0].values()[0].title)
             for i in range(0,hsets.values()[0].values()[0].numBins) :
                 outhistos[hpath].addBin(hsets.values()[0].values()[0].bins[i].xMin,
                                         hsets.values()[0].values()[0].bins[i].xMax)
         else :
             logging.error("Histogram %s is of unknown type" % hpath)
             sys.exit(1)
         
 
 logging.info("Processing CMS_2011_S8957746")
 useOnePt("/CMS_2011_S8957746/d01-x01-y01", "7000", "80" )
 useOnePt("/CMS_2011_S8957746/d02-x01-y01", "7000", "80" )
 useOnePt("/CMS_2011_S8957746/d03-x01-y01", "7000", "110" )
 useOnePt("/CMS_2011_S8957746/d04-x01-y01", "7000", "110" )
 useOnePt("/CMS_2011_S8957746/d05-x01-y01", "7000", "210" )
 useOnePt("/CMS_2011_S8957746/d06-x01-y01", "7000", "210" )
 
 logging.info("Processing ATLAS_2010_S8894728")
 useOnePt("/ATLAS_2010_S8894728/d01-x01-y01",  "900", "0" )
 useOnePt("/ATLAS_2010_S8894728/d01-x01-y02",  "900", "0" )
 useOnePt("/ATLAS_2010_S8894728/d01-x01-y03",  "900", "0" )
 useOnePt("/ATLAS_2010_S8894728/d02-x01-y01", "7000", "0" )
 useOnePt("/ATLAS_2010_S8894728/d02-x01-y02", "7000", "0" )
 useOnePt("/ATLAS_2010_S8894728/d02-x01-y03", "7000", "0" )
 useOnePt("/ATLAS_2010_S8894728/d03-x01-y01",  "900", "0" )
 useOnePt("/ATLAS_2010_S8894728/d03-x01-y02",  "900", "0" )
 useOnePt("/ATLAS_2010_S8894728/d03-x01-y03",  "900", "0" )
 useOnePt("/ATLAS_2010_S8894728/d04-x01-y01", "7000", "0" )
 useOnePt("/ATLAS_2010_S8894728/d04-x01-y02", "7000", "0" )
 useOnePt("/ATLAS_2010_S8894728/d04-x01-y03", "7000", "0" )
 useOnePt("/ATLAS_2010_S8894728/d05-x01-y01",  "900", "0" )
 useOnePt("/ATLAS_2010_S8894728/d06-x01-y01", "7000", "0" )
 useOnePt("/ATLAS_2010_S8894728/d07-x01-y01",  "900", "0" )
 useOnePt("/ATLAS_2010_S8894728/d08-x01-y01", "7000", "0" )
 useOnePt("/ATLAS_2010_S8894728/d09-x01-y01",  "900", "0" )
 useOnePt("/ATLAS_2010_S8894728/d09-x01-y02",  "900", "0" )
 useOnePt("/ATLAS_2010_S8894728/d09-x01-y03",  "900", "0" )
 useOnePt("/ATLAS_2010_S8894728/d10-x01-y01", "7000", "0" )
 useOnePt("/ATLAS_2010_S8894728/d10-x01-y02", "7000", "0" )
 useOnePt("/ATLAS_2010_S8894728/d10-x01-y03", "7000", "0" )
 useOnePt("/ATLAS_2010_S8894728/d11-x01-y01",  "900", "0" )
 useOnePt("/ATLAS_2010_S8894728/d11-x01-y02",  "900", "0" )
 useOnePt("/ATLAS_2010_S8894728/d11-x01-y03",  "900", "0" )
 useOnePt("/ATLAS_2010_S8894728/d12-x01-y01", "7000", "0" )
 useOnePt("/ATLAS_2010_S8894728/d12-x01-y02", "7000", "0" )
 useOnePt("/ATLAS_2010_S8894728/d12-x01-y03", "7000", "0" )
 useOnePt("/ATLAS_2010_S8894728/d13-x01-y01",  "900", "0" )
 useOnePt("/ATLAS_2010_S8894728/d13-x01-y02",  "900", "0" )
 useOnePt("/ATLAS_2010_S8894728/d13-x01-y03",  "900", "0" )
 useOnePt("/ATLAS_2010_S8894728/d13-x01-y04",  "900", "0" )
 useOnePt("/ATLAS_2010_S8894728/d14-x01-y01", "7000", "0" )
 useOnePt("/ATLAS_2010_S8894728/d14-x01-y02", "7000", "0" )
 useOnePt("/ATLAS_2010_S8894728/d14-x01-y03", "7000", "0" )
 useOnePt("/ATLAS_2010_S8894728/d14-x01-y04", "7000", "0" )
 useOnePt("/ATLAS_2010_S8894728/d15-x01-y01",  "900", "0" )
 useOnePt("/ATLAS_2010_S8894728/d15-x01-y02",  "900", "0" )
 useOnePt("/ATLAS_2010_S8894728/d15-x01-y03",  "900", "0" )
 useOnePt("/ATLAS_2010_S8894728/d15-x01-y04",  "900", "0" )
 useOnePt("/ATLAS_2010_S8894728/d16-x01-y01", "7000", "0" )
 useOnePt("/ATLAS_2010_S8894728/d16-x01-y02", "7000", "0" )
 useOnePt("/ATLAS_2010_S8894728/d16-x01-y03", "7000", "0" )
 useOnePt("/ATLAS_2010_S8894728/d16-x01-y04", "7000", "0" )
 useOnePt("/ATLAS_2010_S8894728/d17-x01-y01",  "900", "0" )
 useOnePt("/ATLAS_2010_S8894728/d17-x01-y02",  "900", "0" )
 useOnePt("/ATLAS_2010_S8894728/d17-x01-y03",  "900", "0" )
 useOnePt("/ATLAS_2010_S8894728/d18-x01-y01", "7000", "0" )
 useOnePt("/ATLAS_2010_S8894728/d18-x01-y02", "7000", "0" )
 useOnePt("/ATLAS_2010_S8894728/d18-x01-y03", "7000", "0" )
 useOnePt("/ATLAS_2010_S8894728/d19-x01-y01",  "900", "0" )
 useOnePt("/ATLAS_2010_S8894728/d19-x01-y02",  "900", "0" )
 useOnePt("/ATLAS_2010_S8894728/d19-x01-y03",  "900", "0" )
 useOnePt("/ATLAS_2010_S8894728/d20-x01-y01", "7000", "0" )
 useOnePt("/ATLAS_2010_S8894728/d20-x01-y02", "7000", "0" )
 useOnePt("/ATLAS_2010_S8894728/d20-x01-y03", "7000", "0" )
 useOnePt("/ATLAS_2010_S8894728/d21-x01-y01", "7000", "0" )
 useOnePt("/ATLAS_2010_S8894728/d22-x01-y01", "7000", "0" )
 
 logging.info("Processing ATLAS_2011_S8994773")
 useOnePt("/ATLAS_2011_S8994773/d01-x01-y01", "900", "0" )
 useOnePt("/ATLAS_2011_S8994773/d02-x01-y01", "7000", "0" )
 useOnePt("/ATLAS_2011_S8994773/d03-x01-y01", "900", "0" )
 useOnePt("/ATLAS_2011_S8994773/d04-x01-y01", "7000", "0" )
 useOnePt("/ATLAS_2011_S8994773/d13-x01-y01", "900", "0" )
 useOnePt("/ATLAS_2011_S8994773/d13-x01-y02", "900", "0" )
 useOnePt("/ATLAS_2011_S8994773/d13-x01-y03", "900", "0" )
 useOnePt("/ATLAS_2011_S8994773/d14-x01-y01", "7000", "0" )
 useOnePt("/ATLAS_2011_S8994773/d14-x01-y02", "7000", "0" )
 useOnePt("/ATLAS_2011_S8994773/d14-x01-y03", "7000", "0" )
 
 logging.info("Processing ALICE_2010_S8624100")
 useOnePt("/ALICE_2010_S8624100/d11-x01-y01", "900", "0" )
 useOnePt("/ALICE_2010_S8624100/d12-x01-y01", "900", "0" )
 useOnePt("/ALICE_2010_S8624100/d13-x01-y01", "900", "0" )
 useOnePt("/ALICE_2010_S8624100/d17-x01-y01","2360", "0" )
 useOnePt("/ALICE_2010_S8624100/d18-x01-y01","2360", "0" )
 useOnePt("/ALICE_2010_S8624100/d19-x01-y01","2360", "0" )
 
 logging.info("Processing ALICE_2010_S8625980")
 useOnePt("/ALICE_2010_S8625980/d03-x01-y01", "7000", "0" )
 useOnePt("/ALICE_2010_S8625980/d04-x01-y01",  "900", "0" )
 useOnePt("/ALICE_2010_S8625980/d05-x01-y01", "2360", "0" )
 useOnePt("/ALICE_2010_S8625980/d06-x01-y01", "7000", "0" )
 
 logging.info("Processing ATLAS_2010_S8918562")
 useOnePt("/ATLAS_2010_S8918562/d01-x01-y01",  "900", "0" )
 useOnePt("/ATLAS_2010_S8918562/d02-x01-y01", "2360", "0" )
 useOnePt("/ATLAS_2010_S8918562/d03-x01-y01", "7000", "0" )
 useOnePt("/ATLAS_2010_S8918562/d04-x01-y01",  "900", "0" )
 useOnePt("/ATLAS_2010_S8918562/d05-x01-y01", "7000", "0" )
 useOnePt("/ATLAS_2010_S8918562/d06-x01-y01",  "900", "0" )
 useOnePt("/ATLAS_2010_S8918562/d07-x01-y01", "7000", "0" )
 useOnePt("/ATLAS_2010_S8918562/d08-x01-y01",  "900", "0" )
 useOnePt("/ATLAS_2010_S8918562/d09-x01-y01", "2360", "0" )
 useOnePt("/ATLAS_2010_S8918562/d10-x01-y01", "7000", "0" )
 useOnePt("/ATLAS_2010_S8918562/d11-x01-y01",  "900", "0" )
 useOnePt("/ATLAS_2010_S8918562/d12-x01-y01", "7000", "0" )
 useOnePt("/ATLAS_2010_S8918562/d13-x01-y01",  "900", "0" )
 useOnePt("/ATLAS_2010_S8918562/d14-x01-y01", "7000", "0" )
 useOnePt("/ATLAS_2010_S8918562/d15-x01-y01",  "900", "0" )
 useOnePt("/ATLAS_2010_S8918562/d16-x01-y01", "2360", "0" )
 useOnePt("/ATLAS_2010_S8918562/d17-x01-y01", "7000", "0" )
 
 
 useOnePt("/ATLAS_2010_S8918562/d18-x01-y01",  "900", "0" )
 useOnePt("/ATLAS_2010_S8918562/d19-x01-y01", "7000", "0" )
 useOnePt("/ATLAS_2010_S8918562/d20-x01-y01",  "900", "0" )
 useOnePt("/ATLAS_2010_S8918562/d21-x01-y01", "7000", "0" )
 useOnePt("/ATLAS_2010_S8918562/d22-x01-y01",  "900", "0" )
 useOnePt("/ATLAS_2010_S8918562/d23-x01-y01", "7000", "0" )
 useOnePt("/ATLAS_2010_S8918562/d24-x01-y01",  "900", "0" )
 useOnePt("/ATLAS_2010_S8918562/d25-x01-y01", "7000", "0" )
 useOnePt("/ATLAS_2010_S8918562/d26-x01-y01",  "900", "0" )
 useOnePt("/ATLAS_2010_S8918562/d27-x01-y01", "7000", "0" )
 useOnePt("/ATLAS_2010_S8918562/d28-x01-y01",  "900", "0" )
 useOnePt("/ATLAS_2010_S8918562/d29-x01-y01", "7000", "0" )
 useOnePt("/ATLAS_2010_S8918562/d30-x01-y01",  "900", "0" )
 useOnePt("/ATLAS_2010_S8918562/d31-x01-y01", "7000", "0" )
 useOnePt("/ATLAS_2010_S8918562/d32-x01-y01",  "900", "0" )
 useOnePt("/ATLAS_2010_S8918562/d33-x01-y01", "7000", "0" )
 useOnePt("/ATLAS_2010_S8918562/d34-x01-y01",  "900", "0" )
 useOnePt("/ATLAS_2010_S8918562/d35-x01-y01", "7000", "0" )
 useOnePt("/ATLAS_2010_S8918562/d36-x01-y01",  "900", "0" )
 useOnePt("/ATLAS_2010_S8918562/d37-x01-y01", "7000", "0" )
 useOnePt("/ATLAS_2010_S8918562/d38-x01-y01",  "900", "0" )
 useOnePt("/ATLAS_2010_S8918562/d39-x01-y01", "7000", "0" )
 
 
 
 logging.info("Processing ATLAS_2011_S8971293")
 useOnePt("/ATLAS_2011_S8971293/d01-x01-y01", "7000", "110" )
 useOnePt("/ATLAS_2011_S8971293/d01-x01-y02", "7000", "110" )
 useOnePt("/ATLAS_2011_S8971293/d01-x01-y03", "7000", "210" )
 useOnePt("/ATLAS_2011_S8971293/d01-x01-y04", "7000", "260" )
 useOnePt("/ATLAS_2011_S8971293/d01-x01-y05", "7000", "260" )
 useOnePt("/ATLAS_2011_S8971293/d01-x01-y06", "7000", "400" )
 useOnePt("/ATLAS_2011_S8971293/d01-x01-y07", "7000", "400" )
 useOnePt("/ATLAS_2011_S8971293/d01-x01-y08", "7000", "600" )
 useOnePt("/ATLAS_2011_S8971293/d01-x01-y09", "7000", "600" )
 logging.info("Processing ATLAS_2011_S8924791")
 if( not opts.ue) :
     useOnePt("/ATLAS_2011_S8924791/d01-x01-y01", "7000", "10" )
     useOnePt("/ATLAS_2011_S8924791/d01-x01-y02", "7000", "10" )
     useOnePt("/ATLAS_2011_S8924791/d01-x02-y01", "7000", "10" )
     useOnePt("/ATLAS_2011_S8924791/d01-x02-y02", "7000", "10" )
     useOnePt("/ATLAS_2011_S8924791/d01-x03-y01", "7000", "10" )
     useOnePt("/ATLAS_2011_S8924791/d01-x03-y02", "7000", "10" )
     useOnePt("/ATLAS_2011_S8924791/d01-x04-y01", "7000", "10" )
     useOnePt("/ATLAS_2011_S8924791/d01-x04-y02", "7000", "10" )
     useOnePt("/ATLAS_2011_S8924791/d01-x05-y01", "7000", "10" )
     useOnePt("/ATLAS_2011_S8924791/d01-x05-y02", "7000", "10" )
     useOnePt("/ATLAS_2011_S8924791/d01-x06-y01", "7000", "10" )
     useOnePt("/ATLAS_2011_S8924791/d01-x06-y02", "7000", "10" )
 else :
     useOnePt("/ATLAS_2011_S8924791/d01-x01-y01", "7000", "20" )
     useOnePt("/ATLAS_2011_S8924791/d01-x01-y02", "7000", "20" )
     useOnePt("/ATLAS_2011_S8924791/d01-x02-y01", "7000", "20" )
     useOnePt("/ATLAS_2011_S8924791/d01-x02-y02", "7000", "20" )
     useOnePt("/ATLAS_2011_S8924791/d01-x03-y01", "7000", "20" )
     useOnePt("/ATLAS_2011_S8924791/d01-x03-y02", "7000", "20" )
     useOnePt("/ATLAS_2011_S8924791/d01-x04-y01", "7000", "20" )
     useOnePt("/ATLAS_2011_S8924791/d01-x04-y02", "7000", "20" )
     useOnePt("/ATLAS_2011_S8924791/d01-x05-y01", "7000", "20" )
     useOnePt("/ATLAS_2011_S8924791/d01-x05-y02", "7000", "20" )
     useOnePt("/ATLAS_2011_S8924791/d01-x06-y01", "7000", "20" )
     useOnePt("/ATLAS_2011_S8924791/d01-x06-y02", "7000", "20" )
 
 useOnePt("/ATLAS_2011_S8924791/d02-x01-y01", "7000", "40" )
 useOnePt("/ATLAS_2011_S8924791/d02-x01-y02", "7000", "40" )
 useOnePt("/ATLAS_2011_S8924791/d02-x02-y01", "7000", "40" )
 useOnePt("/ATLAS_2011_S8924791/d02-x02-y02", "7000", "40" )
 useOnePt("/ATLAS_2011_S8924791/d02-x03-y01", "7000", "40" )
 useOnePt("/ATLAS_2011_S8924791/d02-x03-y02", "7000", "40" )
 useOnePt("/ATLAS_2011_S8924791/d02-x04-y01", "7000", "40" )
 useOnePt("/ATLAS_2011_S8924791/d02-x04-y02", "7000", "40" )
 useOnePt("/ATLAS_2011_S8924791/d02-x05-y01", "7000", "40" )
 useOnePt("/ATLAS_2011_S8924791/d02-x05-y02", "7000", "40" )
 useOnePt("/ATLAS_2011_S8924791/d02-x06-y01", "7000", "40" )
 useOnePt("/ATLAS_2011_S8924791/d02-x06-y02", "7000", "40" )
 useOnePt("/ATLAS_2011_S8924791/d03-x01-y01", "7000", "40" )
 useOnePt("/ATLAS_2011_S8924791/d03-x01-y02", "7000", "40" )
 useOnePt("/ATLAS_2011_S8924791/d03-x02-y01", "7000", "40" )
 useOnePt("/ATLAS_2011_S8924791/d03-x02-y02", "7000", "40" )
 useOnePt("/ATLAS_2011_S8924791/d03-x03-y01", "7000", "40" )
 useOnePt("/ATLAS_2011_S8924791/d03-x03-y02", "7000", "40" )
 useOnePt("/ATLAS_2011_S8924791/d03-x04-y01", "7000", "40" )
 useOnePt("/ATLAS_2011_S8924791/d03-x04-y02", "7000", "40" )
 useOnePt("/ATLAS_2011_S8924791/d03-x05-y01", "7000", "40" )
 useOnePt("/ATLAS_2011_S8924791/d03-x05-y02", "7000", "40" )
 useOnePt("/ATLAS_2011_S8924791/d03-x06-y01", "7000", "40" )
 useOnePt("/ATLAS_2011_S8924791/d03-x06-y02", "7000", "40" )
 useOnePt("/ATLAS_2011_S8924791/d04-x01-y01", "7000", "80" )
 useOnePt("/ATLAS_2011_S8924791/d04-x01-y02", "7000", "80" )
 useOnePt("/ATLAS_2011_S8924791/d04-x02-y01", "7000", "80" )
 useOnePt("/ATLAS_2011_S8924791/d04-x02-y02", "7000", "80" )
 useOnePt("/ATLAS_2011_S8924791/d04-x03-y01", "7000", "80" )
 useOnePt("/ATLAS_2011_S8924791/d04-x03-y02", "7000", "80" )
 useOnePt("/ATLAS_2011_S8924791/d04-x04-y01", "7000", "80" )
 useOnePt("/ATLAS_2011_S8924791/d04-x04-y02", "7000", "80" )
 useOnePt("/ATLAS_2011_S8924791/d04-x05-y01", "7000", "80" )
 useOnePt("/ATLAS_2011_S8924791/d04-x05-y02", "7000", "80" )
 useOnePt("/ATLAS_2011_S8924791/d04-x06-y01", "7000", "80" )
 useOnePt("/ATLAS_2011_S8924791/d04-x06-y02", "7000", "80" )
 useOnePt("/ATLAS_2011_S8924791/d05-x01-y01", "7000", "110" )
 useOnePt("/ATLAS_2011_S8924791/d05-x01-y02", "7000", "110" )
 useOnePt("/ATLAS_2011_S8924791/d05-x02-y01", "7000", "110" )
 useOnePt("/ATLAS_2011_S8924791/d05-x02-y02", "7000", "110" )
 useOnePt("/ATLAS_2011_S8924791/d05-x03-y01", "7000", "110" )
 useOnePt("/ATLAS_2011_S8924791/d05-x03-y02", "7000", "110" )
 useOnePt("/ATLAS_2011_S8924791/d05-x04-y01", "7000", "110" )
 useOnePt("/ATLAS_2011_S8924791/d05-x04-y02", "7000", "110" )
 useOnePt("/ATLAS_2011_S8924791/d05-x05-y01", "7000", "110" )
 useOnePt("/ATLAS_2011_S8924791/d05-x05-y02", "7000", "110" )
 useOnePt("/ATLAS_2011_S8924791/d05-x06-y01", "7000", "110" )
 useOnePt("/ATLAS_2011_S8924791/d05-x06-y02", "7000", "110" )
 useOnePt("/ATLAS_2011_S8924791/d06-x01-y01", "7000", "110" )
 useOnePt("/ATLAS_2011_S8924791/d06-x01-y02", "7000", "110" )
 useOnePt("/ATLAS_2011_S8924791/d06-x02-y01", "7000", "110" )
 useOnePt("/ATLAS_2011_S8924791/d06-x02-y02", "7000", "110" )
 useOnePt("/ATLAS_2011_S8924791/d06-x03-y01", "7000", "110" )
 useOnePt("/ATLAS_2011_S8924791/d06-x03-y02", "7000", "110" )
 useOnePt("/ATLAS_2011_S8924791/d06-x04-y01", "7000", "110" )
 useOnePt("/ATLAS_2011_S8924791/d06-x04-y02", "7000", "110" )
 useOnePt("/ATLAS_2011_S8924791/d06-x05-y01", "7000", "110" )
 useOnePt("/ATLAS_2011_S8924791/d06-x05-y02", "7000", "110" )
 useOnePt("/ATLAS_2011_S8924791/d06-x06-y01", "7000", "110" )
 useOnePt("/ATLAS_2011_S8924791/d06-x06-y02", "7000", "110" )
 useOnePt("/ATLAS_2011_S8924791/d07-x01-y01", "7000", "210" )
 useOnePt("/ATLAS_2011_S8924791/d07-x01-y02", "7000", "210" )
 useOnePt("/ATLAS_2011_S8924791/d07-x02-y01", "7000", "210" )
 useOnePt("/ATLAS_2011_S8924791/d07-x02-y02", "7000", "210" )
 useOnePt("/ATLAS_2011_S8924791/d07-x03-y01", "7000", "210" )
 useOnePt("/ATLAS_2011_S8924791/d07-x03-y02", "7000", "210" )
 useOnePt("/ATLAS_2011_S8924791/d07-x04-y01", "7000", "210" )
 useOnePt("/ATLAS_2011_S8924791/d07-x04-y02", "7000", "210" )
 useOnePt("/ATLAS_2011_S8924791/d07-x05-y01", "7000", "210" )
 useOnePt("/ATLAS_2011_S8924791/d07-x05-y02", "7000", "210" )
 useOnePt("/ATLAS_2011_S8924791/d07-x06-y01", "7000", "210" )
 useOnePt("/ATLAS_2011_S8924791/d07-x06-y02", "7000", "210" )
 useOnePt("/ATLAS_2011_S8924791/d08-x01-y01", "7000", "260" )
 useOnePt("/ATLAS_2011_S8924791/d08-x01-y02", "7000", "260" )
 useOnePt("/ATLAS_2011_S8924791/d08-x02-y01", "7000", "260" )
 useOnePt("/ATLAS_2011_S8924791/d08-x02-y02", "7000", "260" )
 useOnePt("/ATLAS_2011_S8924791/d08-x03-y01", "7000", "260" )
 useOnePt("/ATLAS_2011_S8924791/d08-x03-y02", "7000", "260" )
 useOnePt("/ATLAS_2011_S8924791/d08-x04-y01", "7000", "260" )
 useOnePt("/ATLAS_2011_S8924791/d08-x04-y02", "7000", "260" )
 useOnePt("/ATLAS_2011_S8924791/d08-x05-y01", "7000", "260" )
 useOnePt("/ATLAS_2011_S8924791/d08-x05-y02", "7000", "260" )
 useOnePt("/ATLAS_2011_S8924791/d08-x06-y01", "7000", "260" )
 useOnePt("/ATLAS_2011_S8924791/d08-x06-y02", "7000", "260" )
 useOnePt("/ATLAS_2011_S8924791/d09-x01-y01", "7000", "260" )
 useOnePt("/ATLAS_2011_S8924791/d09-x01-y02", "7000", "260" )
 useOnePt("/ATLAS_2011_S8924791/d09-x02-y01", "7000", "260" )
 useOnePt("/ATLAS_2011_S8924791/d09-x02-y02", "7000", "260" )
 useOnePt("/ATLAS_2011_S8924791/d09-x03-y01", "7000", "260" )
 useOnePt("/ATLAS_2011_S8924791/d09-x03-y02", "7000", "260" )
 useOnePt("/ATLAS_2011_S8924791/d09-x04-y01", "7000", "260" )
 useOnePt("/ATLAS_2011_S8924791/d09-x04-y02", "7000", "260" )
 useOnePt("/ATLAS_2011_S8924791/d09-x05-y01", "7000", "260" )
 useOnePt("/ATLAS_2011_S8924791/d09-x05-y02", "7000", "260" )
 useOnePt("/ATLAS_2011_S8924791/d09-x06-y01", "7000", "260" )
 useOnePt("/ATLAS_2011_S8924791/d09-x06-y02", "7000", "260" )
 useOnePt("/ATLAS_2011_S8924791/d10-x01-y01", "7000", "400" )
 useOnePt("/ATLAS_2011_S8924791/d10-x01-y02", "7000", "400" )
 useOnePt("/ATLAS_2011_S8924791/d10-x02-y01", "7000", "400" )
 useOnePt("/ATLAS_2011_S8924791/d10-x02-y02", "7000", "400" )
 useOnePt("/ATLAS_2011_S8924791/d10-x03-y01", "7000", "400" )
 useOnePt("/ATLAS_2011_S8924791/d10-x03-y02", "7000", "400" )
 useOnePt("/ATLAS_2011_S8924791/d10-x04-y01", "7000", "400" )
 useOnePt("/ATLAS_2011_S8924791/d10-x04-y02", "7000", "400" )
 useOnePt("/ATLAS_2011_S8924791/d10-x05-y01", "7000", "400" )
 useOnePt("/ATLAS_2011_S8924791/d10-x05-y02", "7000", "400" )
 useOnePt("/ATLAS_2011_S8924791/d10-x06-y01", "7000", "400" )
 useOnePt("/ATLAS_2011_S8924791/d10-x06-y02", "7000", "400" )
 useOnePt("/ATLAS_2011_S8924791/d11-x01-y01", "7000", "400" )
 useOnePt("/ATLAS_2011_S8924791/d11-x01-y02", "7000", "400" )
 useOnePt("/ATLAS_2011_S8924791/d11-x02-y01", "7000", "400" )
 useOnePt("/ATLAS_2011_S8924791/d11-x02-y02", "7000", "400" )
 useOnePt("/ATLAS_2011_S8924791/d11-x03-y01", "7000", "400" )
 useOnePt("/ATLAS_2011_S8924791/d11-x03-y02", "7000", "400" )
 useOnePt("/ATLAS_2011_S8924791/d11-x04-y01", "7000", "400" )
 useOnePt("/ATLAS_2011_S8924791/d11-x04-y02", "7000", "400" )
 useOnePt("/ATLAS_2011_S8924791/d11-x05-y01", "7000", "400" )
 useOnePt("/ATLAS_2011_S8924791/d11-x05-y02", "7000", "400" )
 useOnePt("/ATLAS_2011_S8924791/d11-x06-y01", "7000", "400" )
 useOnePt("/ATLAS_2011_S8924791/d11-x06-y02", "7000", "400" )
 logging.info("Processing ATLAS_2010_S8817804")
 mergeByPt("/ATLAS_2010_S8817804/d01-x01-y01", "7000")
 mergeByPt("/ATLAS_2010_S8817804/d02-x01-y01", "7000")
 mergeByPt("/ATLAS_2010_S8817804/d03-x01-y01", "7000")
 mergeByPt("/ATLAS_2010_S8817804/d04-x01-y01", "7000")
 mergeByPt("/ATLAS_2010_S8817804/d05-x01-y01", "7000")
 mergeByPt("/ATLAS_2010_S8817804/d06-x01-y01", "7000")
 mergeByPt("/ATLAS_2010_S8817804/d07-x01-y01", "7000")
 mergeByPt("/ATLAS_2010_S8817804/d08-x01-y01", "7000")
 mergeByPt("/ATLAS_2010_S8817804/d09-x01-y01", "7000")
 mergeByPt("/ATLAS_2010_S8817804/d10-x01-y01", "7000")
 
 mergeByMass("/ATLAS_2010_S8817804/d11-x01-y01", "7000")
 mergeByMass("/ATLAS_2010_S8817804/d12-x01-y01", "7000")
 mergeByMass("/ATLAS_2010_S8817804/d13-x01-y01", "7000")
 mergeByMass("/ATLAS_2010_S8817804/d14-x01-y01", "7000")
 mergeByMass("/ATLAS_2010_S8817804/d15-x01-y01", "7000")
 mergeByMass("/ATLAS_2010_S8817804/d16-x01-y01", "7000")
 mergeByMass("/ATLAS_2010_S8817804/d17-x01-y01", "7000")
 mergeByMass("/ATLAS_2010_S8817804/d18-x01-y01", "7000")
 mergeByMass("/ATLAS_2010_S8817804/d19-x01-y01", "7000")
 mergeByMass("/ATLAS_2010_S8817804/d20-x01-y01", "7000")
 
 useOneMass("/ATLAS_2010_S8817804/d21-x01-y01", "7000", "250" )
 useOneMass("/ATLAS_2010_S8817804/d22-x01-y01", "7000", "250" )
 useOneMass("/ATLAS_2010_S8817804/d23-x01-y01", "7000", "650" )
 useOneMass("/ATLAS_2010_S8817804/d24-x01-y01", "7000", "250" )
 useOneMass("/ATLAS_2010_S8817804/d25-x01-y01", "7000", "250" )
 useOneMass("/ATLAS_2010_S8817804/d26-x01-y01", "7000", "650" )
 
 
 logging.info("Processing ATLAS_2011_I930220")
 mergeByPt("/ATLAS_2011_I930220/d01-x01-y01",  "7000" )
 mergeByPt("/ATLAS_2011_I930220/d02-x01-y01",  "7000" )
 mergeByPt("/ATLAS_2011_I930220/d03-x01-y01",  "7000" )
 mergeByPt("/ATLAS_2011_I930220/d04-x01-y01",  "7000" )
 mergeByPt("/ATLAS_2011_I930220/d05-x01-y01",  "7000" )
 mergeByPt("/ATLAS_2011_I930220/d06-x01-y01",  "7000" )
 mergeByMass("/ATLAS_2011_I930220/d07-x01-y01", "7000")
 useOneMass("/ATLAS_2011_I930220/d08-x01-y01", "7000", "110" )
 useOneMass("/ATLAS_2011_I930220/d09-x01-y01", "7000", "110" )
 useOneMass("/ATLAS_2011_I930220/d10-x01-y01", "7000", "370" )
 
 logging.info("Processing ATLAS_2012_I1082936")
 mergeByPt("/ATLAS_2012_I1082936/d01-x01-y01", "7000")
 mergeByPt("/ATLAS_2012_I1082936/d01-x01-y02", "7000")
 mergeByPt("/ATLAS_2012_I1082936/d01-x01-y03", "7000")
 mergeByPt("/ATLAS_2012_I1082936/d01-x01-y04", "7000")
 mergeByPt("/ATLAS_2012_I1082936/d01-x01-y05", "7000")
 mergeByPt("/ATLAS_2012_I1082936/d01-x01-y06", "7000")
 mergeByPt("/ATLAS_2012_I1082936/d01-x01-y07", "7000")
 mergeByPt("/ATLAS_2012_I1082936/d02-x01-y01", "7000")
 mergeByPt("/ATLAS_2012_I1082936/d02-x01-y02", "7000")
 mergeByPt("/ATLAS_2012_I1082936/d02-x01-y03", "7000")
 mergeByPt("/ATLAS_2012_I1082936/d02-x01-y04", "7000")
 mergeByPt("/ATLAS_2012_I1082936/d02-x01-y05", "7000")
 mergeByPt("/ATLAS_2012_I1082936/d02-x01-y06", "7000")
 mergeByPt("/ATLAS_2012_I1082936/d02-x01-y07", "7000")
 
 mergeByMass("/ATLAS_2012_I1082936/d03-x01-y01", "7000", 1000.)
 mergeByMass("/ATLAS_2012_I1082936/d03-x01-y02", "7000", 1000.)
 mergeByMass("/ATLAS_2012_I1082936/d03-x01-y03", "7000", 1000.)
 mergeByMass("/ATLAS_2012_I1082936/d03-x01-y04", "7000", 1000.)
 mergeByMass("/ATLAS_2012_I1082936/d03-x01-y05", "7000", 1000.)
 mergeByMass("/ATLAS_2012_I1082936/d03-x01-y06", "7000", 1000.)
 mergeByMass("/ATLAS_2012_I1082936/d03-x01-y07", "7000", 1000.)
 mergeByMass("/ATLAS_2012_I1082936/d03-x01-y08", "7000", 1000.)
 mergeByMass("/ATLAS_2012_I1082936/d03-x01-y09", "7000", 1000.)
 mergeByMass("/ATLAS_2012_I1082936/d04-x01-y01", "7000", 1000.)
 mergeByMass("/ATLAS_2012_I1082936/d04-x01-y02", "7000", 1000.)
 mergeByMass("/ATLAS_2012_I1082936/d04-x01-y03", "7000", 1000.)
 mergeByMass("/ATLAS_2012_I1082936/d04-x01-y04", "7000", 1000.)
 mergeByMass("/ATLAS_2012_I1082936/d04-x01-y05", "7000", 1000.)
 mergeByMass("/ATLAS_2012_I1082936/d04-x01-y06", "7000", 1000.)
 mergeByMass("/ATLAS_2012_I1082936/d04-x01-y07", "7000", 1000.)
 mergeByMass("/ATLAS_2012_I1082936/d04-x01-y08", "7000", 1000.)
 mergeByMass("/ATLAS_2012_I1082936/d04-x01-y09", "7000", 1000.)
 
 
 logging.info("Processing CMS_2011_S8968497")
 
 useOneMass("/CMS_2011_S8968497/d01-x01-y01", "7000", "1700" )
 useOneMass("/CMS_2011_S8968497/d02-x01-y01", "7000", "1700" )
 useOneMass("/CMS_2011_S8968497/d03-x01-y01", "7000", "1100" )
 useOneMass("/CMS_2011_S8968497/d04-x01-y01", "7000", "1100" )
 useOneMass("/CMS_2011_S8968497/d05-x01-y01", "7000", "650" )
 useOneMass("/CMS_2011_S8968497/d06-x01-y01", "7000", "650" )
 useOneMass("/CMS_2011_S8968497/d07-x01-y01", "7000", "250" )
 useOneMass("/CMS_2011_S8968497/d08-x01-y01", "7000", "250" )
 useOneMass("/CMS_2011_S8968497/d09-x01-y01", "7000", "250" )
 
 
 logging.info("Processing ATLAS_2011_S9126244")
 mergeByPt("/ATLAS_2011_S9126244/d01-x01-y01", "7000")
 mergeByPt("/ATLAS_2011_S9126244/d01-x01-y02", "7000")
 mergeByPt("/ATLAS_2011_S9126244/d02-x01-y01", "7000")
 mergeByPt("/ATLAS_2011_S9126244/d02-x01-y02", "7000")
 mergeByPt("/ATLAS_2011_S9126244/d03-x01-y01", "7000")
 mergeByPt("/ATLAS_2011_S9126244/d03-x01-y02", "7000")
 mergeByPt("/ATLAS_2011_S9126244/d04-x01-y01", "7000")
 mergeByPt("/ATLAS_2011_S9126244/d04-x01-y02", "7000")
 mergeByPt("/ATLAS_2011_S9126244/d05-x01-y01", "7000")
 mergeByPt("/ATLAS_2011_S9126244/d05-x01-y02", "7000")
 
 
 useOnePt("/ATLAS_2011_S9126244/d06-x01-y01", "7000", "40" )
 useOnePt("/ATLAS_2011_S9126244/d06-x01-y02", "7000", "40" )
 useOnePt("/ATLAS_2011_S9126244/d07-x01-y01", "7000", "80" )
 useOnePt("/ATLAS_2011_S9126244/d07-x01-y02", "7000", "80" )
 useOnePt("/ATLAS_2011_S9126244/d08-x01-y01", "7000", "80" )
 useOnePt("/ATLAS_2011_S9126244/d08-x01-y02", "7000", "80" )
 useOnePt("/ATLAS_2011_S9126244/d09-x01-y01", "7000", "110" )
 useOnePt("/ATLAS_2011_S9126244/d09-x01-y02", "7000", "110" )
 useOnePt("/ATLAS_2011_S9126244/d10-x01-y01", "7000", "110" )
 useOnePt("/ATLAS_2011_S9126244/d10-x01-y02", "7000", "110" )
 useOnePt("/ATLAS_2011_S9126244/d11-x01-y01", "7000", "210" )
 useOnePt("/ATLAS_2011_S9126244/d11-x01-y02", "7000", "210" )
 useOnePt("/ATLAS_2011_S9126244/d12-x01-y01", "7000", "210" )
 useOnePt("/ATLAS_2011_S9126244/d12-x01-y02", "7000", "210" )
 useOnePt("/ATLAS_2011_S9126244/d13-x01-y01", "7000", "40" )
 useOnePt("/ATLAS_2011_S9126244/d13-x01-y02", "7000", "40" )
 useOnePt("/ATLAS_2011_S9126244/d14-x01-y01", "7000", "40" )
 useOnePt("/ATLAS_2011_S9126244/d14-x01-y02", "7000", "40" )
 useOnePt("/ATLAS_2011_S9126244/d15-x01-y01", "7000", "110" )
 useOnePt("/ATLAS_2011_S9126244/d15-x01-y02", "7000", "110" )
 useOnePt("/ATLAS_2011_S9126244/d16-x01-y01", "7000", "110" )
 useOnePt("/ATLAS_2011_S9126244/d16-x01-y02", "7000", "110" )
 useOnePt("/ATLAS_2011_S9126244/d17-x01-y01", "7000", "210" )
 useOnePt("/ATLAS_2011_S9126244/d17-x01-y02", "7000", "210" )
 useOnePt("/ATLAS_2011_S9126244/d18-x01-y01", "7000", "210" )
 useOnePt("/ATLAS_2011_S9126244/d18-x01-y02", "7000", "210" )
 useOnePt("/ATLAS_2011_S9126244/d19-x01-y01", "7000", "40" )
 useOnePt("/ATLAS_2011_S9126244/d20-x01-y01", "7000", "80" )
 useOnePt("/ATLAS_2011_S9126244/d21-x01-y01", "7000", "110" )
 useOnePt("/ATLAS_2011_S9126244/d22-x01-y01", "7000", "110" )
 useOnePt("/ATLAS_2011_S9126244/d23-x01-y01", "7000", "110" )
 useOnePt("/ATLAS_2011_S9126244/d24-x01-y01", "7000", "210" )
 useOnePt("/ATLAS_2011_S9126244/d25-x01-y01", "7000", "210" )
 mergeByPt("/ATLAS_2011_S9126244/d26-x01-y01", "7000")
 mergeByPt("/ATLAS_2011_S9126244/d26-x01-y02", "7000")
 mergeByPt("/ATLAS_2011_S9126244/d27-x01-y01", "7000")
 mergeByPt("/ATLAS_2011_S9126244/d27-x01-y02", "7000")
 mergeByPt("/ATLAS_2011_S9126244/d28-x01-y01", "7000")
 mergeByPt("/ATLAS_2011_S9126244/d28-x01-y02", "7000")
 mergeByPt("/ATLAS_2011_S9126244/d29-x01-y01", "7000")
 mergeByPt("/ATLAS_2011_S9126244/d29-x01-y02", "7000")
 useOnePt("/ATLAS_2011_S9126244/d30-x01-y01", "7000", "40" )
 useOnePt("/ATLAS_2011_S9126244/d31-x01-y01", "7000", "80" )
 useOnePt("/ATLAS_2011_S9126244/d32-x01-y01", "7000", "110" )
 useOnePt("/ATLAS_2011_S9126244/d33-x01-y01", "7000", "110" )
 useOnePt("/ATLAS_2011_S9126244/d34-x01-y01", "7000", "110" )
 useOnePt("/ATLAS_2011_S9126244/d35-x01-y01", "7000", "210" )
 useOnePt("/ATLAS_2011_S9126244/d36-x01-y01", "7000", "210" )
 useOnePt("/ATLAS_2011_S9126244/d37-x01-y01", "7000", "40" )
 useOnePt("/ATLAS_2011_S9126244/d37-x01-y02", "7000", "40" )
 useOnePt("/ATLAS_2011_S9126244/d38-x01-y01", "7000", "80" )
 useOnePt("/ATLAS_2011_S9126244/d38-x01-y02", "7000", "80" )
 useOnePt("/ATLAS_2011_S9126244/d39-x01-y01", "7000", "110" )
 useOnePt("/ATLAS_2011_S9126244/d39-x01-y02", "7000", "110" )
 useOnePt("/ATLAS_2011_S9126244/d40-x01-y01", "7000", "110" )
 useOnePt("/ATLAS_2011_S9126244/d40-x01-y02", "7000", "110" )
 useOnePt("/ATLAS_2011_S9126244/d41-x01-y01", "7000", "110" )
 useOnePt("/ATLAS_2011_S9126244/d41-x01-y02", "7000", "110" )
 useOnePt("/ATLAS_2011_S9126244/d42-x01-y01", "7000", "210" )
 useOnePt("/ATLAS_2011_S9126244/d42-x01-y02", "7000", "210" )
 useOnePt("/ATLAS_2011_S9126244/d43-x01-y01", "7000", "210" )
 useOnePt("/ATLAS_2011_S9126244/d43-x01-y02", "7000", "210" )
 
 # CMS_2011_S9120041 UE analysis
 logging.info("Processing CMS_2011_S9120041")
 mergeByPt("/CMS_2011_S9120041/d01-x01-y01", "7000")
 mergeByPt("/CMS_2011_S9120041/d02-x01-y01", "7000")
 if(opts.ue) :
     useOnePt("/CMS_2011_S9120041/d03-x01-y01",  "900", "0" )
     useOnePt("/CMS_2011_S9120041/d04-x01-y01",  "900", "0" )
     useOnePt("/CMS_2011_S9120041/d05-x01-y01", "7000", "0" )
     useOnePt("/CMS_2011_S9120041/d06-x01-y01", "7000", "0" )
     useOnePt("/CMS_2011_S9120041/d07-x01-y01", "7000", "0" )
     useOnePt("/CMS_2011_S9120041/d11-x01-y01",  "900", "0" )
     useOnePt("/CMS_2011_S9120041/d12-x01-y01",  "900", "0" )
     useOnePt("/CMS_2011_S9120041/d13-x01-y01",  "900", "0" )
     useOnePt("/CMS_2011_S9120041/d08-x01-y01", "7000", "20" )
     useOnePt("/CMS_2011_S9120041/d09-x01-y01", "7000", "20" )
     useOnePt("/CMS_2011_S9120041/d10-x01-y01", "7000", "20" )
 else :
     useOnePt("/CMS_2011_S9120041/d08-x01-y01", "7000", "10" )
     useOnePt("/CMS_2011_S9120041/d09-x01-y01", "7000", "10" )
     useOnePt("/CMS_2011_S9120041/d10-x01-y01", "7000", "10" )
 
 # CMS dijet decorrelation
 logging.info("Processing CMS_2011_S8950903")
 useOnePt("/CMS_2011_S8950903/d01-x01-y01", "7000", "80" )
 useOnePt("/CMS_2011_S8950903/d02-x01-y01", "7000", "110" )
 useOnePt("/CMS_2011_S8950903/d03-x01-y01", "7000", "110" )
 useOnePt("/CMS_2011_S8950903/d04-x01-y01", "7000", "210" )
 useOnePt("/CMS_2011_S8950903/d05-x01-y01", "7000", "260" )
 
 # CMS jet cross section
 logging.info("Processing CMS_2011_S9086218")
 mergeByPt("/CMS_2011_S9086218/d01-x01-y01", "7000")
 mergeByPt("/CMS_2011_S9086218/d02-x01-y01", "7000")
 mergeByPt("/CMS_2011_S9086218/d03-x01-y01", "7000")
 mergeByPt("/CMS_2011_S9086218/d04-x01-y01", "7000")
 mergeByPt("/CMS_2011_S9086218/d05-x01-y01", "7000")
 mergeByPt("/CMS_2011_S9086218/d06-x01-y01", "7000")
 
 # CMS 2/3 jet cross section ratio
 logging.info("Processing CMS_2011_S9086218")
 mergeByPt("/CMS_2011_S9088458/d01-x01-y01", "7000",500.)
 
 # ATLAS track jet
 logging.info("Processing ATLAS_2011_I919017")
 for d in range(1,3) :
     for y in range(1,5) :
         mergeByPt("/ATLAS_2011_I919017/d0%s-x01-y0%s" % (d,y), "7000")
         if( opts.ue) :
             for x in range(2,6) :
                 for y in ["01","02","06","07","11","12","16","17","21","22"] :
                     useOnePt("/ATLAS_2011_I919017/d0%s-x0%s-y%s" % (d,x,y),  "7000",  "0" )
                 for y in ["03","04","08","09","13","14","18","19","23","24"] :
                     useOnePt("/ATLAS_2011_I919017/d0%s-x0%s-y%s" % (d,x,y),  "7000",  "4" )
                 for y in range(5,30,5) :
                     useOnePt("/ATLAS_2011_I919017/d0%s-x%02d-y%02d" % (d,x,y) ,  "7000", "20" )
         else :
             for x in range(2,6) :
                 for y in range(5,30,5) :
                     useOnePt("/ATLAS_2011_I919017/d0%s-x%02d-y%02d" % (d,x,y) ,  "7000", "10" )
 
 logging.info("Processing ATLAS_2011_I926145")
 mergeByPt("/ATLAS_2011_I926145/d01-x01-y01", "7000",1.5)
 mergeByPt("/ATLAS_2011_I926145/d02-x01-y01", "7000",1.5)
 mergeByPt("/ATLAS_2011_I926145/d03-x01-y01", "7000",1.5)
 
 logging.info("Processing CMS_2011_S8941262")
 useOnePt("/CMS_2011_S8941262/d01-x01-y01",  "7000", "10" )
 useOnePt("/CMS_2011_S8941262/d03-x01-y01",  "7000", "10" )
 mergeByPt("/CMS_2011_S8941262/d02-x01-y01", "7000",1.5)
 
 logging.info("Processing CMS_2011_S8973270")
 useOnePt("/CMS_2011_S8973270/d01-x01-y01",  "7000", "70" )
 useOnePt("/CMS_2011_S8973270/d02-x01-y01",  "7000", "100" )
 useOnePt("/CMS_2011_S8973270/d03-x01-y01",  "7000", "130" )
 useOnePt("/CMS_2011_S8973270/d04-x01-y01",  "7000", "70" )
 useOnePt("/CMS_2011_S8973270/d05-x01-y01",  "7000", "100" )
 useOnePt("/CMS_2011_S8973270/d06-x01-y01",  "7000", "130" )
 
 logging.info("Processing ATLAS_2012_I1082009")
 useOnePt("/ATLAS_2012_I1082009/d08-x01-y01", "7000", "40" )
 useOnePt("/ATLAS_2012_I1082009/d09-x01-y01", "7000", "40" )
 useOnePt("/ATLAS_2012_I1082009/d10-x01-y01", "7000", "40" )
 useOnePt("/ATLAS_2012_I1082009/d11-x01-y01", "7000", "80" )
 useOnePt("/ATLAS_2012_I1082009/d12-x01-y01", "7000", "80" )
 useOnePt("/ATLAS_2012_I1082009/d13-x01-y01", "7000", "40" )
 
 logging.info("Processing ATLAS_2012_I1118269")
 mergeByPt("/ATLAS_2012_I1118269/d01-x01-y01", "7000")
 useOnePt("/ATLAS_2012_I1118269/d02-x01-y01", "7000", "10" )
 
 logging.info("Processing ATLAS_2012_I1188891")
 mergeByPt("/ATLAS_2012_I1188891/d01-x01-y01", "7000")
 mergeByPt("/ATLAS_2012_I1188891/d02-x01-y01", "7000")
 mergeByPt("/ATLAS_2012_I1188891/d03-x01-y01", "7000")
 mergeByPt("/ATLAS_2012_I1188891/d04-x01-y01", "7000")
 mergeByPt("/ATLAS_2012_I1188891/d05-x01-y01", "7000")
 mergeByPt("/ATLAS_2012_I1188891/d06-x01-y01", "7000")
 
 logging.info("Processing CMS_2012_I1087342")
 mergeByPt("/CMS_2012_I1087342/d01-x01-y01", "7000")
 mergeByPt("/CMS_2012_I1087342/d02-x01-y01", "7000")
 mergeByPt("/CMS_2012_I1087342/d03-x01-y01", "7000")
 logging.info("Processing CMS_2012_PAS_QCD_11_010")
 mergeByPt("/CMS_2012_PAS_QCD_11_010/d01-x01-y01", "7000")
 mergeByPt("/CMS_2012_PAS_QCD_11_010/d02-x01-y01", "7000")
 mergeByPt("/CMS_2012_PAS_QCD_11_010/d03-x01-y01", "7000")
 mergeByPt("/CMS_2012_PAS_QCD_11_010/d04-x01-y01", "7000")
 
 logging.info("Processing ATLAS_2011_S9035664")
 mergeByPt("/ATLAS_2011_S9035664/d11-x01-y01", "7000")
 mergeByPt("/ATLAS_2011_S9035664/d12-x01-y01", "7000")
 mergeByPt("/ATLAS_2011_S9035664/d13-x01-y01", "7000")
 mergeByPt("/ATLAS_2011_S9035664/d14-x01-y01", "7000")
 mergeByPt("/ATLAS_2011_S9035664/d15-x01-y01", "7000")
 mergeByPt("/ATLAS_2011_S9035664/d16-x01-y01", "7000")
 mergeByPt("/ATLAS_2011_S9035664/d17-x01-y01", "7000")
 mergeByPt("/ATLAS_2011_S9035664/d18-x01-y01", "7000")
 mergeByPt("/ATLAS_2011_S9035664/d20-x01-y01", "7000")
 mergeByPt("/ATLAS_2011_S9035664/d21-x01-y01", "7000")
 mergeByPt("/ATLAS_2011_S9035664/d22-x01-y01", "7000")
 mergeByPt("/ATLAS_2011_S9035664/d23-x01-y01", "7000")
 
 logging.info("Processing ATLAS_2012_I1125575")
 mergeByPt("/ATLAS_2012_I1125575/d01-x01-y01", "7000")
 mergeByPt("/ATLAS_2012_I1125575/d01-x01-y02", "7000")
 mergeByPt("/ATLAS_2012_I1125575/d01-x02-y01", "7000")
 mergeByPt("/ATLAS_2012_I1125575/d01-x02-y02", "7000")
 mergeByPt("/ATLAS_2012_I1125575/d01-x03-y01", "7000")
 mergeByPt("/ATLAS_2012_I1125575/d01-x03-y02", "7000")
 mergeByPt("/ATLAS_2012_I1125575/d01-x04-y01", "7000")
 mergeByPt("/ATLAS_2012_I1125575/d01-x04-y02", "7000")
 mergeByPt("/ATLAS_2012_I1125575/d01-x05-y01", "7000")
 mergeByPt("/ATLAS_2012_I1125575/d01-x05-y02", "7000")
 mergeByPt("/ATLAS_2012_I1125575/d02-x01-y01", "7000")
 mergeByPt("/ATLAS_2012_I1125575/d02-x01-y02", "7000")
 mergeByPt("/ATLAS_2012_I1125575/d02-x02-y01", "7000")
 mergeByPt("/ATLAS_2012_I1125575/d02-x02-y02", "7000")
 mergeByPt("/ATLAS_2012_I1125575/d02-x03-y01", "7000")
 mergeByPt("/ATLAS_2012_I1125575/d02-x03-y02", "7000")
 mergeByPt("/ATLAS_2012_I1125575/d02-x04-y01", "7000")
 mergeByPt("/ATLAS_2012_I1125575/d02-x04-y02", "7000")
 mergeByPt("/ATLAS_2012_I1125575/d02-x05-y01", "7000")
 mergeByPt("/ATLAS_2012_I1125575/d02-x05-y02", "7000")
 mergeByPt("/ATLAS_2012_I1125575/d03-x01-y01", "7000")
 mergeByPt("/ATLAS_2012_I1125575/d03-x01-y02", "7000")
 mergeByPt("/ATLAS_2012_I1125575/d03-x02-y01", "7000")
 mergeByPt("/ATLAS_2012_I1125575/d03-x02-y02", "7000")
 mergeByPt("/ATLAS_2012_I1125575/d03-x03-y01", "7000")
 mergeByPt("/ATLAS_2012_I1125575/d03-x03-y02", "7000")
 mergeByPt("/ATLAS_2012_I1125575/d03-x04-y01", "7000")
 mergeByPt("/ATLAS_2012_I1125575/d03-x04-y02", "7000")
 mergeByPt("/ATLAS_2012_I1125575/d03-x05-y01", "7000")
 mergeByPt("/ATLAS_2012_I1125575/d03-x05-y02", "7000")
 for d in range(4,7) :
     for x in range(1,6) :
         if(opts.ue) :
             for y in range(1,9) :
                 useOnePt("/ATLAS_2012_I1125575/d0%s-x0%s-y0%s" % (d,x,y),  "7000", "0" )
             for y in ["09","10","11","12","13","14","15","16"] :
                 useOnePt("/ATLAS_2012_I1125575/d0%s-x0%s-y%s" % (d,x,y),  "7000", "0" )
             for y in range(17,19) :
                 useOnePt("/ATLAS_2012_I1125575/d0%s-x0%s-y%s" % (d,x,y),  "7000", "20" )
         else :
             for y in range(17,19) :
                 useOnePt("/ATLAS_2012_I1125575/d0%s-x0%s-y%s" % (d,x,y),  "7000", "10" )
         for y in range(19,21) :
             useOnePt("/ATLAS_2012_I1125575/d0%s-x0%s-y%s" % (d,x,y),  "7000", "40" )
 
 # ATLAS_2012_I1094564
 useOnePt("/ATLAS_2012_I1094564/d01-x01-y01",  "7000", "210" )
 useOnePt("/ATLAS_2012_I1094564/d02-x01-y01",  "7000", "260" )
 useOnePt("/ATLAS_2012_I1094564/d03-x01-y01",  "7000", "400" )
 useOnePt("/ATLAS_2012_I1094564/d04-x01-y01",  "7000", "400" )
 useOnePt("/ATLAS_2012_I1094564/d05-x01-y01",  "7000", "210" )
 useOnePt("/ATLAS_2012_I1094564/d06-x01-y01",  "7000", "260" )
 useOnePt("/ATLAS_2012_I1094564/d07-x01-y01",  "7000", "400" )
 useOnePt("/ATLAS_2012_I1094564/d08-x01-y01",  "7000", "400" )
 useOnePt("/ATLAS_2012_I1094564/d09-x01-y01",  "7000", "210" )
 useOnePt("/ATLAS_2012_I1094564/d10-x01-y01",  "7000", "260" )
 useOnePt("/ATLAS_2012_I1094564/d11-x01-y01",  "7000", "400" )
 useOnePt("/ATLAS_2012_I1094564/d12-x01-y01",  "7000", "400" )
 useOnePt("/ATLAS_2012_I1094564/d13-x01-y01",  "7000", "210" )
 useOnePt("/ATLAS_2012_I1094564/d14-x01-y01",  "7000", "260" )
 useOnePt("/ATLAS_2012_I1094564/d15-x01-y01",  "7000", "400" )
 useOnePt("/ATLAS_2012_I1094564/d16-x01-y01",  "7000", "400" )
 useOnePt("/ATLAS_2012_I1094564/d17-x01-y01",  "7000", "210" )
 useOnePt("/ATLAS_2012_I1094564/d18-x01-y01",  "7000", "260" )
 useOnePt("/ATLAS_2012_I1094564/d19-x01-y01",  "7000", "400" )
 useOnePt("/ATLAS_2012_I1094564/d20-x01-y01",  "7000", "400" )
 useOnePt("/ATLAS_2012_I1094564/d21-x01-y01",  "7000", "210" )
 useOnePt("/ATLAS_2012_I1094564/d22-x01-y01",  "7000", "260" )
 useOnePt("/ATLAS_2012_I1094564/d23-x01-y01",  "7000", "400" )
 useOnePt("/ATLAS_2012_I1094564/d24-x01-y01",  "7000", "400" )
 useOnePt("/ATLAS_2012_I1094564/d25-x01-y01",  "7000", "210" )
 useOnePt("/ATLAS_2012_I1094564/d26-x01-y01",  "7000", "260" )
 useOnePt("/ATLAS_2012_I1094564/d27-x01-y01",  "7000", "400" )
 useOnePt("/ATLAS_2012_I1094564/d28-x01-y01",  "7000", "400" )
 useOnePt("/ATLAS_2012_I1094564/d29-x01-y01",  "7000", "210" )
 useOnePt("/ATLAS_2012_I1094564/d30-x01-y01",  "7000", "260" )
 useOnePt("/ATLAS_2012_I1094564/d31-x01-y01",  "7000", "400" )
 useOnePt("/ATLAS_2012_I1094564/d32-x01-y01",  "7000", "400" )
 useOnePt("/ATLAS_2012_I1094564/d33-x01-y01",  "7000", "210" )
 useOnePt("/ATLAS_2012_I1094564/d34-x01-y01",  "7000", "260" )
 useOnePt("/ATLAS_2012_I1094564/d35-x01-y01",  "7000", "400" )
 useOnePt("/ATLAS_2012_I1094564/d36-x01-y01",  "7000", "400" )
 
 logging.info("Processing CMS_2013_I1224539_DIJET")
 useOnePt("/CMS_2013_I1224539_DIJET/d01-x01-y01",  "7000", "210" )
 useOnePt("/CMS_2013_I1224539_DIJET/d02-x01-y01",  "7000", "260" )
 useOnePt("/CMS_2013_I1224539_DIJET/d03-x01-y01",  "7000", "400" )
 useOnePt("/CMS_2013_I1224539_DIJET/d04-x01-y01",  "7000", "400" )
 useOnePt("/CMS_2013_I1224539_DIJET/d05-x01-y01",  "7000", "600" )
 useOnePt("/CMS_2013_I1224539_DIJET/d06-x01-y01",  "7000", "600" )
 useOnePt("/CMS_2013_I1224539_DIJET/d07-x01-y01",  "7000", "600" )
 useOnePt("/CMS_2013_I1224539_DIJET/d08-x01-y01",  "7000", "210" )
 useOnePt("/CMS_2013_I1224539_DIJET/d09-x01-y01",  "7000", "260" )
 useOnePt("/CMS_2013_I1224539_DIJET/d10-x01-y01",  "7000", "400" )
 useOnePt("/CMS_2013_I1224539_DIJET/d11-x01-y01",  "7000", "400" )
 useOnePt("/CMS_2013_I1224539_DIJET/d12-x01-y01",  "7000", "600" )
 useOnePt("/CMS_2013_I1224539_DIJET/d13-x01-y01",  "7000", "600" )
 useOnePt("/CMS_2013_I1224539_DIJET/d14-x01-y01",  "7000", "600" )
 useOnePt("/CMS_2013_I1224539_DIJET/d15-x01-y01",  "7000", "210" )
 useOnePt("/CMS_2013_I1224539_DIJET/d16-x01-y01",  "7000", "260" )
 useOnePt("/CMS_2013_I1224539_DIJET/d17-x01-y01",  "7000", "400" )
 useOnePt("/CMS_2013_I1224539_DIJET/d18-x01-y01",  "7000", "400" )
 useOnePt("/CMS_2013_I1224539_DIJET/d19-x01-y01",  "7000", "600" )
 useOnePt("/CMS_2013_I1224539_DIJET/d20-x01-y01",  "7000", "600" )
 useOnePt("/CMS_2013_I1224539_DIJET/d21-x01-y01",  "7000", "600" )
 useOnePt("/CMS_2013_I1224539_DIJET/d22-x01-y01",  "7000", "210" )
 useOnePt("/CMS_2013_I1224539_DIJET/d23-x01-y01",  "7000", "260" )
 useOnePt("/CMS_2013_I1224539_DIJET/d24-x01-y01",  "7000", "400" )
 useOnePt("/CMS_2013_I1224539_DIJET/d25-x01-y01",  "7000", "600" )
 useOnePt("/CMS_2013_I1224539_DIJET/d26-x01-y01",  "7000", "600" )
 useOnePt("/CMS_2013_I1224539_DIJET/d27-x01-y01",  "7000", "600" )
 useOnePt("/CMS_2013_I1224539_DIJET/d28-x01-y01",  "7000", "600" )
 
 useOnePt("/CMS_2013_I1273574/d01-x01-y01",  "7000", "80" )
 mergeByPt("/CMS_2013_I1273574/d02-x01-y01", "7000",1.)
 useOnePt("/CMS_2013_I1273574/d03-x01-y01",  "7000", "80" )
 useOnePt("/CMS_2013_I1273574/d04-x01-y01",  "7000", "80" )
 useOnePt("/CMS_2013_I1273574/d05-x01-y01",  "7000", "80" )
 useOnePt("/CMS_2013_I1273574/d06-x01-y01",  "7000", "80" )
 mergeByPt("/CMS_2013_I1273574/d07-x01-y01", "7000",1.)
 useOnePt("/CMS_2013_I1273574/d08-x01-y01",  "7000", "80" )
 mergeByPt("/CMS_2013_I1273574/d09-x01-y01", "7000",1.)
 useOnePt("/CMS_2013_I1273574/d10-x01-y01",  "7000", "80" )
 mergeByPt("/CMS_2013_I1273574/d11-x01-y01", "7000",1.)
 
 useOnePt("/CMS_2013_I1261026/d01-x01-y01",  "7000", "0" )
 useOnePt("/CMS_2013_I1261026/d02-x01-y01",  "7000", "0" )
 useOnePt("/CMS_2013_I1261026/d03-x01-y01",  "7000", "0" )
 useOnePt("/CMS_2013_I1261026/d04-x01-y01",  "7000", "0" )
 useOnePt("/CMS_2013_I1261026/d05-x01-y01",  "7000", "0" )
 useOnePt("/CMS_2013_I1261026/d06-x01-y01",  "7000", "0" )
 useOnePt("/CMS_2013_I1261026/d07-x01-y01",  "7000", "0" )
 useOnePt("/CMS_2013_I1261026/d08-x01-y01",  "7000", "0" )
 useOnePt("/CMS_2013_I1261026/d09-x01-y01",  "7000", "0" )
 useOnePt("/CMS_2013_I1261026/d10-x01-y01",  "7000", "0" )
 useOnePt("/CMS_2013_I1261026/d11-x01-y01",  "7000", "0" )
 useOnePt("/CMS_2013_I1261026/d12-x01-y01",  "7000", "0" )
 useOnePt("/CMS_2013_I1261026/d13-x01-y01",  "7000", "0" )
 useOnePt("/CMS_2013_I1261026/d14-x01-y01",  "7000", "0" )
 useOnePt("/CMS_2013_I1261026/d15-x01-y01",  "7000", "0" )
 useOnePt("/CMS_2013_I1261026/d16-x01-y01",  "7000", "0" )
 useOnePt("/CMS_2013_I1261026/d17-x01-y01",  "7000", "0" )
 
 
 logging.info("Processing CMS_2012_I1090423")
 useOneMass("/CMS_2012_I1090423/d01-x01-y01", "7000", "2900" )
 useOneMass("/CMS_2012_I1090423/d02-x01-y01", "7000", "2300" )
 useOneMass("/CMS_2012_I1090423/d03-x01-y01", "7000", "1700" )
 useOneMass("/CMS_2012_I1090423/d04-x01-y01", "7000", "1100" )
 useOneMass("/CMS_2012_I1090423/d05-x01-y01", "7000", "1100" )
 useOneMass("/CMS_2012_I1090423/d06-x01-y01", "7000", "650" )
 useOneMass("/CMS_2012_I1090423/d07-x01-y01", "7000", "650" )
 useOneMass("/CMS_2012_I1090423/d08-x01-y01", "7000", "250" )
 useOneMass("/CMS_2012_I1090423/d09-x01-y01", "7000", "250" )
 
 
 logging.info("Processing ATLAS_2014_I1298811")
 mergeByPt("/ATLAS_2014_I1298811/d01-x01-y01", "7000")
 mergeByPt("/ATLAS_2014_I1298811/d01-x01-y02", "7000")
 mergeByPt("/ATLAS_2014_I1298811/d02-x01-y01", "7000")
 mergeByPt("/ATLAS_2014_I1298811/d02-x01-y02", "7000")
 mergeByPt("/ATLAS_2014_I1298811/d03-x01-y01", "7000")
 mergeByPt("/ATLAS_2014_I1298811/d03-x01-y02", "7000")
 mergeByPt("/ATLAS_2014_I1298811/d04-x01-y01", "7000")
 mergeByPt("/ATLAS_2014_I1298811/d04-x01-y02", "7000")
 mergeByPt("/ATLAS_2014_I1298811/d05-x01-y01", "7000")
 mergeByPt("/ATLAS_2014_I1298811/d05-x01-y02", "7000")
 mergeByPt("/ATLAS_2014_I1298811/d06-x01-y01", "7000")
 mergeByPt("/ATLAS_2014_I1298811/d06-x01-y02", "7000")
 mergeByPt("/ATLAS_2014_I1298811/d07-x01-y01", "7000")
 mergeByPt("/ATLAS_2014_I1298811/d07-x01-y02", "7000")
 mergeByPt("/ATLAS_2014_I1298811/d08-x01-y01", "7000")
 mergeByPt("/ATLAS_2014_I1298811/d08-x01-y02", "7000")
 mergeByPt("/ATLAS_2014_I1298811/d09-x01-y01", "7000")
 mergeByPt("/ATLAS_2014_I1298811/d09-x01-y02", "7000")
 mergeByPt("/ATLAS_2014_I1298811/d10-x01-y01", "7000")
 mergeByPt("/ATLAS_2014_I1298811/d10-x01-y02", "7000")
 useOnePt("/ATLAS_2014_I1298811/d11-x01-y01",  "7000", "0" )
 useOnePt("/ATLAS_2014_I1298811/d12-x01-y01",  "7000", "0" )
 
 useOnePt("/ATLAS_2014_I1298811/d13-x01-y01",  "7000", "4" )
 useOnePt("/ATLAS_2014_I1298811/d13-x01-y02",  "7000", "4" )
 useOnePt("/ATLAS_2014_I1298811/d14-x01-y01",  "7000", "4" )
 useOnePt("/ATLAS_2014_I1298811/d14-x01-y02",  "7000", "4" )
 useOnePt("/ATLAS_2014_I1298811/d15-x01-y01",  "7000", "4" )
 useOnePt("/ATLAS_2014_I1298811/d15-x01-y02",  "7000", "4" )
 useOnePt("/ATLAS_2014_I1298811/d25-x01-y01",  "7000", "4" )
 useOnePt("/ATLAS_2014_I1298811/d25-x01-y02",  "7000", "4" )
 useOnePt("/ATLAS_2014_I1298811/d26-x01-y01",  "7000", "4" )
 useOnePt("/ATLAS_2014_I1298811/d26-x01-y02",  "7000", "4" )
 useOnePt("/ATLAS_2014_I1298811/d27-x01-y01",  "7000", "4" )
 useOnePt("/ATLAS_2014_I1298811/d27-x01-y02",  "7000", "4" )
 
 useOnePt("/ATLAS_2014_I1298811/d16-x01-y01",  "7000", "4" )
 useOnePt("/ATLAS_2014_I1298811/d16-x01-y02",  "7000", "4" )
 useOnePt("/ATLAS_2014_I1298811/d17-x01-y01",  "7000", "4" )
 useOnePt("/ATLAS_2014_I1298811/d17-x01-y02",  "7000", "4" )
 useOnePt("/ATLAS_2014_I1298811/d18-x01-y01",  "7000", "4" )
 useOnePt("/ATLAS_2014_I1298811/d18-x01-y02",  "7000", "4" )
 useOnePt("/ATLAS_2014_I1298811/d28-x01-y01",  "7000", "4" )
 useOnePt("/ATLAS_2014_I1298811/d28-x01-y02",  "7000", "4" )
 useOnePt("/ATLAS_2014_I1298811/d29-x01-y01",  "7000", "4" )
 useOnePt("/ATLAS_2014_I1298811/d29-x01-y02",  "7000", "4" )
 useOnePt("/ATLAS_2014_I1298811/d30-x01-y01",  "7000", "4" )
 useOnePt("/ATLAS_2014_I1298811/d30-x01-y02",  "7000", "4" )
 
 useOnePt("/ATLAS_2014_I1298811/d19-x01-y01",  "7000", "40" )
 useOnePt("/ATLAS_2014_I1298811/d19-x01-y02",  "7000", "40" )
 useOnePt("/ATLAS_2014_I1298811/d20-x01-y01",  "7000", "40" )
 useOnePt("/ATLAS_2014_I1298811/d20-x01-y02",  "7000", "40" )
 useOnePt("/ATLAS_2014_I1298811/d21-x01-y01",  "7000", "40" )
 useOnePt("/ATLAS_2014_I1298811/d21-x01-y02",  "7000", "40" )
 useOnePt("/ATLAS_2014_I1298811/d31-x01-y01",  "7000", "40" )
 useOnePt("/ATLAS_2014_I1298811/d31-x01-y02",  "7000", "40" )
 useOnePt("/ATLAS_2014_I1298811/d32-x01-y01",  "7000", "40" )
 useOnePt("/ATLAS_2014_I1298811/d32-x01-y02",  "7000", "40" )
 useOnePt("/ATLAS_2014_I1298811/d33-x01-y01",  "7000", "40" )
 useOnePt("/ATLAS_2014_I1298811/d33-x01-y02",  "7000", "40" )
 
 useOnePt("/ATLAS_2014_I1298811/d22-x01-y01",  "7000", "210" )
 useOnePt("/ATLAS_2014_I1298811/d22-x01-y02",  "7000", "210" )
 useOnePt("/ATLAS_2014_I1298811/d23-x01-y01",  "7000", "210" )
 useOnePt("/ATLAS_2014_I1298811/d23-x01-y02",  "7000", "210" )
 useOnePt("/ATLAS_2014_I1298811/d24-x01-y01",  "7000", "210" )
 useOnePt("/ATLAS_2014_I1298811/d24-x01-y02",  "7000", "210" )
 useOnePt("/ATLAS_2014_I1298811/d34-x01-y01",  "7000", "210" )
 useOnePt("/ATLAS_2014_I1298811/d34-x01-y02",  "7000", "210" )
 useOnePt("/ATLAS_2014_I1298811/d35-x01-y01",  "7000", "210" )
 useOnePt("/ATLAS_2014_I1298811/d35-x01-y02",  "7000", "210" )
 useOnePt("/ATLAS_2014_I1298811/d36-x01-y01",  "7000", "210" )
 useOnePt("/ATLAS_2014_I1298811/d36-x01-y02",  "7000", "210" )
 
 
 logging.info("Processing ATLAS_2014_I1268975")
 mergeByMass("/ATLAS_2014_I1268975/d01-x01-y01", "7000", 1000.)
 mergeByMass("/ATLAS_2014_I1268975/d01-x01-y02", "7000", 1000.)
 mergeByMass("/ATLAS_2014_I1268975/d01-x01-y03", "7000", 1000.)
 mergeByMass("/ATLAS_2014_I1268975/d01-x01-y04", "7000", 1000.)
 mergeByMass("/ATLAS_2014_I1268975/d01-x01-y05", "7000", 1000.)
 mergeByMass("/ATLAS_2014_I1268975/d01-x01-y06", "7000", 1000.)
 
 mergeByMass("/ATLAS_2014_I1268975/d02-x01-y01", "7000", 1000.)
 mergeByMass("/ATLAS_2014_I1268975/d02-x01-y02", "7000", 1000.)
 mergeByMass("/ATLAS_2014_I1268975/d02-x01-y03", "7000", 1000.)
 mergeByMass("/ATLAS_2014_I1268975/d02-x01-y04", "7000", 1000.)
 mergeByMass("/ATLAS_2014_I1268975/d02-x01-y05", "7000", 1000.)
 mergeByMass("/ATLAS_2014_I1268975/d02-x01-y06", "7000", 1000.)
 
 logging.info("Processing ATLAS_2014_I1307243")
 useOnePt( "/ATLAS_2014_I1307243/d01-x01-y01",  "7000", "80" )
 mergeByPt("/ATLAS_2014_I1307243/d02-x01-y01", "7000")
 useOnePt( "/ATLAS_2014_I1307243/d03-x01-y01",  "7000", "80" )
 mergeByPt("/ATLAS_2014_I1307243/d04-x01-y01", "7000")
 useOnePt( "/ATLAS_2014_I1307243/d05-x01-y01",  "7000", "80" )
 mergeByPt("/ATLAS_2014_I1307243/d06-x01-y01", "7000")
 useOnePt( "/ATLAS_2014_I1307243/d07-x01-y01",  "7000", "80" )
 mergeByPt("/ATLAS_2014_I1307243/d08-x01-y01", "7000")
 useOnePt( "/ATLAS_2014_I1307243/d09-x01-y01",  "7000", "80" )
 mergeByPt("/ATLAS_2014_I1307243/d10-x01-y01", "7000")
 useOnePt( "/ATLAS_2014_I1307243/d11-x01-y01",  "7000", "80" )
 mergeByPt("/ATLAS_2014_I1307243/d12-x01-y01", "7000")
 useOnePt( "/ATLAS_2014_I1307243/d13-x01-y01",  "7000", "80" )
 useOnePt( "/ATLAS_2014_I1307243/d14-x01-y01",  "7000", "80" )
 useOnePt( "/ATLAS_2014_I1307243/d15-x01-y01",  "7000", "80" )
 useOnePt( "/ATLAS_2014_I1307243/d16-x01-y01",  "7000", "80" )
 useOnePt( "/ATLAS_2014_I1307243/d17-x01-y01",  "7000", "80" )
 useOnePt( "/ATLAS_2014_I1307243/d18-x01-y01",  "7000", "80" )
 useOnePt( "/ATLAS_2014_I1307243/d19-x01-y01",  "7000", "80" )
 useOnePt( "/ATLAS_2014_I1307243/d20-x01-y01",  "7000", "80" )
 useOnePt( "/ATLAS_2014_I1307243/d21-x01-y01",  "7000", "80" )
 useOnePt( "/ATLAS_2014_I1307243/d22-x01-y01",  "7000", "80" )
 useOnePt( "/ATLAS_2014_I1307243/d23-x01-y01",  "7000", "80" )
 useOnePt( "/ATLAS_2014_I1307243/d24-x01-y01",  "7000", "80" )
 useOnePt( "/ATLAS_2014_I1307243/d25-x01-y01",  "7000", "80" )
 useOnePt( "/ATLAS_2014_I1307243/d26-x01-y01",  "7000", "80" )
 useOnePt( "/ATLAS_2014_I1307243/d27-x01-y01",  "7000", "80" )
 useOnePt( "/ATLAS_2014_I1307243/d28-x01-y01",  "7000", "80" )
 useOnePt( "/ATLAS_2014_I1307243/d29-x01-y01",  "7000", "80" )
 useOnePt( "/ATLAS_2014_I1307243/d30-x01-y01",  "7000", "80" )
 useOnePt( "/ATLAS_2014_I1307243/d31-x01-y01",  "7000", "80" )
 useOnePt( "/ATLAS_2014_I1307243/d32-x01-y01",  "7000", "80" )
 useOnePt( "/ATLAS_2014_I1307243/d33-x01-y01",  "7000", "80" )
 useOnePt( "/ATLAS_2014_I1307243/d34-x01-y01",  "7000", "80" )
 useOnePt( "/ATLAS_2014_I1307243/d35-x01-y01",  "7000", "80" )
 useOnePt( "/ATLAS_2014_I1307243/d36-x01-y01",  "7000", "80" )
 useOnePt( "/ATLAS_2014_I1307243/d37-x01-y01",  "7000", "80" )
 mergeByPt("/ATLAS_2014_I1307243/d38-x01-y01", "7000")
 useOnePt( "/ATLAS_2014_I1307243/d39-x01-y01",  "7000", "80" )
 mergeByPt("/ATLAS_2014_I1307243/d40-x01-y01", "7000")
 
 
 logging.info("Processing ATLAS_2014_I1325553")
 mergeByPt("/ATLAS_2014_I1325553/d01-x01-y01", "7000")
-mergeByPt("/ATLAS_2014_I1325553/d01-x01-y02", "7000")
-mergeByPt("/ATLAS_2014_I1325553/d01-x01-y03", "7000")
-mergeByPt("/ATLAS_2014_I1325553/d01-x01-y04", "7000")
-mergeByPt("/ATLAS_2014_I1325553/d01-x01-y05", "7000")
-mergeByPt("/ATLAS_2014_I1325553/d01-x01-y06", "7000")
 mergeByPt("/ATLAS_2014_I1325553/d02-x01-y01", "7000")
-mergeByPt("/ATLAS_2014_I1325553/d02-x01-y02", "7000")
-mergeByPt("/ATLAS_2014_I1325553/d02-x01-y03", "7000")
-mergeByPt("/ATLAS_2014_I1325553/d02-x01-y04", "7000")
-mergeByPt("/ATLAS_2014_I1325553/d02-x01-y05", "7000")
-mergeByPt("/ATLAS_2014_I1325553/d02-x01-y06", "7000")
+mergeByPt("/ATLAS_2014_I1325553/d03-x01-y01", "7000")
+mergeByPt("/ATLAS_2014_I1325553/d04-x01-y01", "7000")
+mergeByPt("/ATLAS_2014_I1325553/d05-x01-y01", "7000")
+mergeByPt("/ATLAS_2014_I1325553/d06-x01-y01", "7000")
+mergeByPt("/ATLAS_2014_I1325553/d07-x01-y01", "7000")
+mergeByPt("/ATLAS_2014_I1325553/d08-x01-y01", "7000")
+mergeByPt("/ATLAS_2014_I1325553/d09-x01-y01", "7000")
+mergeByPt("/ATLAS_2014_I1325553/d10-x01-y01", "7000")
+mergeByPt("/ATLAS_2014_I1325553/d11-x01-y01", "7000")
+mergeByPt("/ATLAS_2014_I1325553/d12-x01-y01", "7000")
 
 logging.info("Processing ATLAS_2016_I1419070")
 for i in range(1,13) :
     if(i<10) :
         mergeByPt("/ATLAS_2016_I1419070/d0%s-x01-y01" % i, "8000")
     else :
         mergeByPt("/ATLAS_2016_I1419070/d%s-x01-y01"  % i, "8000")
 
 # remake differences and sums
 for ihist in range(1,4) :
     if not ("/ATLAS_2016_I1419070/d0%s-x01-y01" % ihist) in outhistos :
         continue
     h1 = outhistos["/ATLAS_2016_I1419070/d0%s-x01-y01" % ihist  ]
     h2 = outhistos["/ATLAS_2016_I1419070/d0%s-x01-y01" % (ihist+3)]
     sstring = "/ATLAS_2016_I1419070/d%s-x01-y01"  % (9+ihist)
     dstring = "/ATLAS_2016_I1419070/d0%s-x01-y01" % (6+ihist)
     hdiff = yoda.Scatter2D(dstring,dstring)
     hsum  = yoda.Scatter2D(sstring,sstring)
     outhistos[dstring]= hdiff
     outhistos[sstring]= hsum
     for nbin in range(0,h2.numBins) :
         bsum  = h1.bins[nbin]+h2.bins[nbin]
         try:
           ydiff = h2.bins[nbin].mean-h1.bins[nbin].mean
         except:
           ydiff = 0
         try:
           ysum  = bsum.mean
           bstderr = bsum.stdErr
         except:
           ysum  = 0
           bstderr = 0
         try:
           yerr  = math.sqrt(h1.bins[nbin].stdErr**2+h2.bins[nbin].stdErr**2)
         except:
           yerr  = 0
         x    = h1.bins[nbin].xMid
         xerr = 0.5*h1.bins[nbin].xWidth
         hdiff.addPoint(x,ydiff,xerr,yerr)
         hsum.addPoint(x,ysum ,xerr,bstderr)
 
 logging.info("ATLAS_2015_I1394679")
 for i in range(1,5) :
     mergeByPt("/ATLAS_2015_I1394679/d0%s-x01-y01" % i, "8000")
 for i in range(5,11) :
     if(i<10) :
         useOnePt( "/ATLAS_2015_I1394679/d0%s-x01-y01" % i,  "8000", "110" )
     else :
         useOnePt( "/ATLAS_2015_I1394679/d%s-x01-y01" % i,  "8000", "110" )
 
 for i in range(0,4) :
     useOnePt( "/ATLAS_2015_I1394679/d%s-x01-y01" % (11+4*i),  "8000", "110" )
     useOnePt( "/ATLAS_2015_I1394679/d%s-x01-y01" % (12+4*i),  "8000", "260" )
     useOnePt( "/ATLAS_2015_I1394679/d%s-x01-y01" % (13+4*i),  "8000", "600" )
     useOnePt( "/ATLAS_2015_I1394679/d%s-x01-y01" % (14+4*i),  "8000", "900" )
 
 for i in range(0,5) :
     useOnePt( "/ATLAS_2015_I1394679/d%s-x01-y01" % (27+4*i),  "8000", "110" )
     useOnePt( "/ATLAS_2015_I1394679/d%s-x01-y01" % (28+4*i),  "8000", "260" )
     useOnePt( "/ATLAS_2015_I1394679/d%s-x01-y01" % (29+4*i),  "8000", "400" )
     useOnePt( "/ATLAS_2015_I1394679/d%s-x01-y01" % (30+4*i),  "8000", "400" )
 
 logging.info("Processing CMS_2013_I1208923")
 for i in range(1,6) :
     mergeByPt  ("/CMS_2013_I1208923/d01-x01-y0%s" % i, "7000")
     mergeByMass("/CMS_2013_I1208923/d02-x01-y0%s" % i, "7000", 1.)
 
 logging.info("Processing CMS_2014_I1298810")
 for i in range(1,19) :
     if(i<10) :
         mergeByPt("/CMS_2014_I1298810/d0"+str(i)+"-x01-y01", "7000")
     else :
         mergeByPt("/CMS_2014_I1298810/d"+str(i)+"-x01-y01", "7000")
 
 logging.info("Processing CMS_2014_I1305624")
 for x in range(1,6) :
     useOnePt( "/CMS_2014_I1305624/d01-x%02d-y01" % x,  "7000", "110" )
     useOnePt( "/CMS_2014_I1305624/d01-x%02d-y02" % x,  "7000", "110" )
     useOnePt( "/CMS_2014_I1305624/d01-x%02d-y03" % x,  "7000", "260" )
     useOnePt( "/CMS_2014_I1305624/d01-x%02d-y04" % x,  "7000", "260" )
     useOnePt( "/CMS_2014_I1305624/d01-x%02d-y05" % x,  "7000", "400" )
 
 logging.info("Processing ATLAS_2011_I929691")
 
 for x in range(0,3) :
     useOnePt( "/ATLAS_2011_I929691/d%02d-x01-y01" % (10*x+ 1),  "7000", "20" )
     useOnePt( "/ATLAS_2011_I929691/d%02d-x01-y01" % (10*x+ 2),  "7000", "40" )
     useOnePt( "/ATLAS_2011_I929691/d%02d-x01-y01" % (10*x+ 3),  "7000", "40" )
     useOnePt( "/ATLAS_2011_I929691/d%02d-x01-y01" % (10*x+ 4),  "7000", "80" )
     useOnePt( "/ATLAS_2011_I929691/d%02d-x01-y01" % (10*x+ 5),  "7000", "110" )
     useOnePt( "/ATLAS_2011_I929691/d%02d-x01-y01" % (10*x+ 6),  "7000", "110" )
     useOnePt( "/ATLAS_2011_I929691/d%02d-x01-y01" % (10*x+ 7),  "7000", "210" )
     useOnePt( "/ATLAS_2011_I929691/d%02d-x01-y01" % (10*x+ 8),  "7000", "260" )
     useOnePt( "/ATLAS_2011_I929691/d%02d-x01-y01" % (10*x+ 9),  "7000", "260" )
     useOnePt( "/ATLAS_2011_I929691/d%02d-x01-y01" % (10*x+10),  "7000", "400" )
 
 logging.info("Processing ATLAS_2015_I1393758")
 for i in range(1,13) :
     mergeByPt("/ATLAS_2015_I1393758/d%02d-x01-y01" % i, "8000")
 
 logging.info("Processing CMS_2016_I1459051")
 for i in range(1,15) :
     mergeByPt("/CMS_2016_I1459051/d%02d-x01-y01" % i, "13000")
     
 logging.info("Processing ATLAS_2016_CONF_2016_092")
 for i in range(1,7) :
     mergeByPt("/ATLAS_2016_CONF_2016_092/d%02d-x01-y01" % i, "13000")
     
 logging.info("Processing ATLAS_2017_I1609253")
 useOnePt( "/ATLAS_2017_I1609253/d01-x01-y01",  "8000", "260" )
 useOnePt( "/ATLAS_2017_I1609253/d02-x01-y01",  "8000", "260" )
 useOnePt( "/ATLAS_2017_I1609253/d03-x01-y01",  "8000", "260" )
 useOnePt( "/ATLAS_2017_I1609253/d04-x01-y01",  "8000", "260" )
 useOnePt( "/ATLAS_2017_I1609253/d05-x01-y01",  "8000", "400" )
 useOnePt( "/ATLAS_2017_I1609253/d06-x01-y01",  "8000", "400" )
 useOnePt( "/ATLAS_2017_I1609253/d07-x01-y01",  "8000", "400" )
 useOnePt( "/ATLAS_2017_I1609253/d08-x01-y01",  "8000", "400" )
 useOnePt( "/ATLAS_2017_I1609253/d09-x01-y01",  "8000", "400" )
 useOnePt( "/ATLAS_2017_I1609253/d10-x01-y01",  "8000", "400" )
 useOnePt( "/ATLAS_2017_I1609253/d11-x01-y01",  "8000", "600" )
 useOnePt( "/ATLAS_2017_I1609253/d12-x01-y01",  "8000", "600" )
 
 logging.info("Processing CMS_2016_I1487277")
 mergeByPt("/CMS_2016_I1487277/d01-x01-y01", "8000")
 mergeByPt("/CMS_2016_I1487277/d02-x01-y01", "8000")
 mergeByPt("/CMS_2016_I1487277/d03-x01-y01", "8000")
 mergeByPt("/CMS_2016_I1487277/d04-x01-y01", "8000")
 mergeByPt("/CMS_2016_I1487277/d05-x01-y01", "8000")
 mergeByPt("/CMS_2016_I1487277/d06-x01-y01", "8000")
 mergeByPt("/CMS_2016_I1487277/d07-x01-y01", "8000")
 
 logging.info("Processing CMS_2016_I1421646")
 useOnePt( "/CMS_2016_I1421646/d01-x01-y01",  "8000", "210" )
 useOnePt( "/CMS_2016_I1421646/d02-x01-y01",  "8000", "260" )
 useOnePt( "/CMS_2016_I1421646/d03-x01-y01",  "8000", "400" )
 useOnePt( "/CMS_2016_I1421646/d04-x01-y01",  "8000", "400" )
 useOnePt( "/CMS_2016_I1421646/d05-x01-y01",  "8000", "600" )
 useOnePt( "/CMS_2016_I1421646/d06-x01-y01",  "8000", "900" )
 useOnePt( "/CMS_2016_I1421646/d07-x01-y01",  "8000", "900" )
 
 
 logging.info("Processing CMS_2017_I1605749")
 for i in [1,2,3,4,5,6,7,8,9,10,13,16] :
     useOnePt("/CMS_2017_I1605749/d%02d-x01-y01" % i, "8000", "400" )
 for i in [11,14,17]:
     useOnePt("/CMS_2017_I1605749/d%02d-x01-y01" % i, "8000", "600" )
 for i in [12,15,18]:
     useOnePt("/CMS_2017_I1605749/d%02d-x01-y01" % i, "8000", "900" )
 
 def CMS_2012_I1111014_name(i,j) :
     if(i+j<100) :
         return "/CMS_2012_I1111014/d%02d-x01-y01" % (i+j)
     else :
         return "/CMS_2012_I1111014/d%03d-x01-y01" % (i+j)
 
 logging.info("Processing CMS_2012_I1111014")
 for j in [0,22,44,66,87,106]:
     for i in [1,2,3] :
         useOnePt(CMS_2012_I1111014_name(i,j), "7000", "20" )
     for i in [4,5,6,7]:
         useOnePt(CMS_2012_I1111014_name(i,j), "7000", "40" )
     for i in [8,9,10]:
         useOnePt(CMS_2012_I1111014_name(i,j), "7000", "80" )
     for i in [11,12,13,14,15,16]:
         useOnePt(CMS_2012_I1111014_name(i,j), "7000", "110" )
     for i in [17,18]:
         useOnePt(CMS_2012_I1111014_name(i,j), "7000", "210" )
     useOnePt(CMS_2012_I1111014_name(19,j), "7000", "260" )
     if(j<87) :
         for i in [20,21]:
             useOnePt(CMS_2012_I1111014_name(i,j), "7000", "400" )
     if(j<66) :
         useOnePt(CMS_2012_I1111014_name(22,j), "7000", "600" )
 
 for i in [126,127,128] :
     for j in [1,2] :
         mergeByPt("/CMS_2012_I1111014/d%03d-x01-y%02d" % (i,j), "7000")
         
 logging.info("Processing CMS_2018_I1682495")
 for i in [0,1,2,3] :
     useOnePt("/CMS_2018_I1682495/d%02d-x01-y01" % (12*i+ 1), "13000", "110" )
     useOnePt("/CMS_2018_I1682495/d%02d-x01-y01" % (12*i+ 2), "13000", "260" )
     useOnePt("/CMS_2018_I1682495/d%02d-x01-y01" % (12*i+ 3), "13000", "260" )
     useOnePt("/CMS_2018_I1682495/d%02d-x01-y01" % (12*i+ 4), "13000", "400" )
     useOnePt("/CMS_2018_I1682495/d%02d-x01-y01" % (12*i+ 5), "13000", "400" )
     useOnePt("/CMS_2018_I1682495/d%02d-x01-y01" % (12*i+ 6), "13000", "600" )
     useOnePt("/CMS_2018_I1682495/d%02d-x01-y01" % (12*i+ 7), "13000", "600" )
     useOnePt("/CMS_2018_I1682495/d%02d-x01-y01" % (12*i+ 8), "13000", "900" )
     useOnePt("/CMS_2018_I1682495/d%02d-x01-y01" % (12*i+ 9), "13000", "900" )
     useOnePt("/CMS_2018_I1682495/d%02d-x01-y01" % (12*i+10), "13000", "900" )
     useOnePt("/CMS_2018_I1682495/d%02d-x01-y01" % (12*i+11), "13000", "900" )
     useOnePt("/CMS_2018_I1682495/d%02d-x01-y01" % (12*i+12), "13000", "900" )
-        
+    
+logging.info("Processing CMS_2015_I1385107")
+for i in range(1,9) :
+    mergeByPt("/CMS_2015_I1385107/d%02d-x01-y01" % i, "2760")
+
+# rescaling for semi-leptonic top decays (we only simulate 1 charge combination)
+for i in range(96,116,2) :
+    rescale("/ATLAS_2018_I1656578/d%s-x01-y01" % i,2.)
+for i in range(15,29,2) :
+    rescale("/ATLAS_2017_I1614149/d%s-x01-y01" % i,2.)
+for i in range(1,23,2) :
+    rescale("/ATLAS_2015_I1404878/d%02d-x01-y01" % i,2.)
+rescale("/ATLAS_2015_I1397637/d01-x01-y01",2.)
+for i in range(1,22,1) :
+    rescale("/ATLAS_2015_I1345452/d%02d-x01-y01" % i,2.)
+for i in range(1,10,1) :
+    rescale("/ATLAS_2014_I1304688/d%02d-x01-y01" % i,2.)
+for i in range(1,82) :
+    rescale("/CMS_2018_I1663958/d%02d-x01-y01" % i,2.)
+for i in range(169,173,1) :
+    rescale("/CMS_2018_I1663958/d%02d-x01-y01" % i,2.)
+for i in range(8,15) :
+    rescale("/CMS_2018_I1662081/d%02d-x01-y01" % i,2.)
+for i in range(1,41) :
+    rescale("/CMS_2016_I1491950/d%02d-x02-y01" % i,2.)
+for i in range(1,13) :
+    rescale("/CMS_2016_I1454211/d%02d-x01-y01" % i,2.)
+rescale("/CMS_2017_I1518399/d01-x01-y01",2.)
 # Choose output file
 name = args[0]+"-Jets.yoda"
 yoda.writeYODA(outhistos,name)
 sys.exit(0)
diff --git a/Tests/python/merge-LHC-Photon b/Tests/python/merge-LHC-Photon
--- a/Tests/python/merge-LHC-Photon
+++ b/Tests/python/merge-LHC-Photon
@@ -1,288 +1,298 @@
 #! /usr/bin/env python
 import logging
 import sys
 import os, yoda
 
 """%prog
 
 Script for merging aida files
 
 """
 
 def fillAbove(scale,desthisto, sourcehistosbyptmin):
     pthigh= 1e100
     ptlow =-1e100
     for pt, h in sorted(sourcehistosbyptmin.iteritems(),reverse=True):
         ptlow=pt
         if(type(desthisto)==yoda.core.Scatter2D) :
             for i in range(0,h.numPoints) :
                 xMin = h.points[i].x-h.points[i].xErrs.minus
                 if( xMin*scale >= ptlow and 
                     xMin*scale <  pthigh ) :
                     desthisto.addPoint(h.points[i])
         elif(type(desthisto)==yoda.core.Profile1D) :
             for i in range(0,h.numBins) :
                 if(h.bins[i].xMin*scale  >= ptlow and 
                    h.bins[i].xMin*scale  <  pthigh ) :
                     desthisto.bins[i] += h.bins[i]
         elif(type(desthisto)==yoda.core.Histo1D) :
             for i in range(0,h.numBins) :
                 if(h.bins[i].xMin*scale  >= ptlow and 
                    h.bins[i].xMin*scale  <  pthigh ) :
                     desthisto.bins[i] += h.bins[i]
         else :
             logging.error("Can't merge %s, unknown type" % desthisto.path)
             sys.exit(1)
         pthigh=pt
 
 def mergeByPt(hpath, scale=1.):
     global inhistos
     global outhistos
     try:
         fillAbove(scale,outhistos[hpath], inhistos[hpath])
     except:
         pass
 
 def useOnePt(hpath, ptmin):
     global inhistos
     global outhistos
     try:
        ## Find best pT_min match
         ptmins = inhistos[hpath].keys()
         closest_ptmin = None
         for ptm in ptmins:
             if closest_ptmin is None or \
                     abs(ptm-float(ptmin)) < abs(closest_ptmin-float(ptmin)):
                 closest_ptmin = ptm
         if closest_ptmin != float(ptmin):
             logging.warning("Inexact match for requested pTmin=%s: " % ptmin + \
                                 "using pTmin=%e instead" % closest_ptmin)
         outhistos[hpath] =  inhistos[hpath][closest_ptmin]
     except:
         pass
 
 if sys.version_info[:3] < (2,4,0):
     print "rivet scripts require Python version >= 2.4.0... exiting"
     sys.exit(1)
 
 if __name__ == "__main__":
     import logging
     from optparse import OptionParser, OptionGroup
     parser = OptionParser(usage="%prog base")
     verbgroup = OptionGroup(parser, "Verbosity control")
     verbgroup.add_option("-v", "--verbose", action="store_const", const=logging.DEBUG, dest="LOGLEVEL",
                          default=logging.INFO, help="print debug (very verbose) messages")
     verbgroup.add_option("-q", "--quiet", action="store_const", const=logging.WARNING, dest="LOGLEVEL",
                          default=logging.INFO, help="be very quiet")
     parser.add_option_group(verbgroup)
     (opts, args) = parser.parse_args()
     logging.basicConfig(level=opts.LOGLEVEL, format="%(message)s")
 
     ## Check args
     if len(args) < 1:
         logging.error("Must specify at least the name of the files")
         sys.exit(1)
 
-files=["-7-PromptPhoton-1.yoda","-7-PromptPhoton-2.yoda",
-       "-7-PromptPhoton-3.yoda","-7-PromptPhoton-4.yoda",
-       "-8-PromptPhoton-1.yoda","-8-PromptPhoton-2.yoda",
-       "-8-PromptPhoton-3.yoda","-8-PromptPhoton-4.yoda",
-       "-7-DiPhoton-GammaGamma.yoda","-7-DiPhoton-GammaJet.yoda","-GammaGamma-7.yoda",
+files=["-7-DiPhoton-GammaGamma.yoda","-7-DiPhoton-GammaJet.yoda","-GammaGamma-7.yoda",
        "-8-DiPhoton-GammaGamma.yoda","-8-DiPhoton-GammaJet.yoda","-GammaGamma-8.yoda"]
 
+for i in [7,8,13] :
+    for j in range(1,5) :
+        files.append("-%s-PromptPhoton-%s.yoda" % (i,j))
+
 ## Get histos
 inhistos = {}
 outhistos={}
 for f in files:
     file='Rivet-'+args[0]+f
     if not os.access(file, os.R_OK):
         logging.error("%s can not be read" % file)
         continue
     try:
         aos = yoda.read(file)
     except:
         logging.error("%s can not be parsed as XML" % file)
         break
     if(file.find("PromptPhoton")>=0) :
         if(file.find("PromptPhoton-1")>0) :
             ptmin=0.
         elif(file.find("PromptPhoton-2")>0) :
             ptmin=35.
         elif(file.find("PromptPhoton-3")>0) :
             ptmin=90.
         elif(file.find("PromptPhoton-4")>0) :
             ptmin=170.
         ## Get histos from this YODA file
         for aopath, ao in aos.iteritems() :
+            if("RAW" in aopath) :continue
             if not inhistos.has_key(aopath):
                 inhistos[aopath] = {}
             if (aopath.find("CMS_2013_I1258128")>0) :
                 if(aopath.find("d05")>0 or aopath.find("d06")>0 or
                    aopath.find("d07")>0 or aopath.find("d08")>0) :
                     inhistos[aopath][ptmin] = ao
             else :
                 inhistos[aopath][ptmin] = ao
     else : 
         ## Get histos from this YODA file
         for aopath, ao in aos.iteritems() :
+            if("RAW" in aopath) :continue
             if(aopath.find("XSEC")>=0 or aopath.find("EVTCOUNT")>=0) : continue
             if ( aopath in outhistos ) :
                 aotype = type(ao)
                 if aotype in (yoda.Counter, yoda.Histo1D, yoda.Histo2D, yoda.Profile1D, yoda.Profile2D):
                     outhistos[aopath] += ao
                 else :
                     quit()
             else:
                 outhistos[aopath] = ao
 
 for hpath,hsets in inhistos.iteritems():
     if( hpath.find("1263495")>0 or hpath.find("1093738")>0 or 
         hpath.find("921594" )>0 or hpath.find("8914702")>0 or 
         hpath.find("1244522")>0 or hpath.find("1457605")>0 or
-        hpath.find("1632756")>0 or hpath.find("1266056")>0 ) :
+        hpath.find("1632756")>0 or hpath.find("1266056")>0 or
+        hpath.find("1645627")>0) :
         if(type(hsets.values()[0])==yoda.core.Scatter2D) :
             outhistos[hpath] = yoda.core.Scatter2D(hsets.values()[0].path,
                                                    hsets.values()[0].title)
         elif(type(hsets.values()[0])==yoda.core.Profile1D) :
             outhistos[hpath] = yoda.core.Profile1D(hsets.values()[0].path,
                                                    hsets.values()[0].title)
             for i in range(0,hsets.values()[0].numBins) :
                 outhistos[hpath].addBin(hsets.values()[0].bins[i].xMin,
                                         hsets.values()[0].bins[i].xMax)
         elif(type(hsets.values()[0])==yoda.core.Histo1D) :
             outhistos[hpath] = yoda.core.Histo1D(hsets.values()[0].path,
                                                 hsets.values()[0].title)
             for i in range(0,hsets.values()[0].numBins) :
                 outhistos[hpath].addBin(hsets.values()[0].bins[i].xMin,
                                         hsets.values()[0].bins[i].xMax)
         else :
             logging.error("Histogram %s is of unknown type" % hpath)
             print hpath,type(hsets.values()[0])
             sys.exit(1)
 
 
 
 logging.info("Processing ATLAS_2013_I1263495")
 mergeByPt("/ATLAS_2013_I1263495/d01-x01-y01")
-mergeByPt("/ATLAS_2013_I1263495/d01-x01-y03")
-useOnePt("/ATLAS_2013_I1263495/d01-x02-y01", "90" )
+mergeByPt("/ATLAS_2013_I1263495/d02-x01-y01")
+useOnePt("/ATLAS_2013_I1263495/d03-x01-y01", "90" )
 
 logging.info("Processing ATLAS_2012_I1093738")
 mergeByPt("/ATLAS_2012_I1093738/d01-x01-y01")
 mergeByPt("/ATLAS_2012_I1093738/d02-x01-y01")
 mergeByPt("/ATLAS_2012_I1093738/d03-x01-y01")
 mergeByPt("/ATLAS_2012_I1093738/d04-x01-y01")
 mergeByPt("/ATLAS_2012_I1093738/d05-x01-y01")
 mergeByPt("/ATLAS_2012_I1093738/d06-x01-y01")
 
 
 logging.info("Processing ATLAS_2011_I921594")
 mergeByPt("/ATLAS_2011_I921594/d01-x01-y01")
 mergeByPt("/ATLAS_2011_I921594/d01-x01-y02")
 mergeByPt("/ATLAS_2011_I921594/d01-x01-y04")
 mergeByPt("/ATLAS_2011_I921594/d01-x01-y05")
 
 logging.info("Processing ATLAS_2010_S8914702")
 mergeByPt("/ATLAS_2010_S8914702/d01-x01-y01")
 mergeByPt("/ATLAS_2010_S8914702/d01-x01-y02")
 mergeByPt("/ATLAS_2010_S8914702/d01-x01-y03")
 
 logging.info("Processing CMS_2013_I1258128")
 useOnePt("/CMS_2013_I1258128/d05-x01-y01", "35" )
 useOnePt("/CMS_2013_I1258128/d06-x01-y01", "35" )
 useOnePt("/CMS_2013_I1258128/d07-x01-y01", "35" )
 useOnePt("/CMS_2013_I1258128/d08-x01-y01", "35" )
 
 logging.info("Processing ATLAS_2013_I1244522")
 mergeByPt("/ATLAS_2013_I1244522/d01-x01-y01")
 mergeByPt("/ATLAS_2013_I1244522/d02-x01-y01")
 useOnePt("/ATLAS_2013_I1244522/d03-x01-y01", "35" )
 useOnePt("/ATLAS_2013_I1244522/d04-x01-y01", "35" )
 useOnePt("/ATLAS_2013_I1244522/d05-x01-y01", "35" )
 useOnePt("/ATLAS_2013_I1244522/d06-x01-y01", "35" )
 useOnePt("/ATLAS_2013_I1244522/d07-x01-y01", "35" )
 
 logging.info("Processing ATLAS_2016_I1457605")
 mergeByPt("/ATLAS_2016_I1457605/d01-x01-y01")
 mergeByPt("/ATLAS_2016_I1457605/d02-x01-y01")
 mergeByPt("/ATLAS_2016_I1457605/d03-x01-y01")
 mergeByPt("/ATLAS_2016_I1457605/d04-x01-y01")
 
 logging.info("Processing ATLAS_2017_I1632756")
 mergeByPt("/ATLAS_2017_I1632756/d02-x01-y01")
 mergeByPt("/ATLAS_2017_I1632756/d03-x01-y01")
 mergeByPt("/ATLAS_2017_I1632756/d04-x01-y01")
 mergeByPt("/ATLAS_2017_I1632756/d05-x01-y01")
 
 logging.info("Processing CMS_2014_I1266056")
 mergeByPt("/CMS_2014_I1266056/d01-x01-y01")
 mergeByPt("/CMS_2014_I1266056/d01-x01-y02")
 mergeByPt("/CMS_2014_I1266056/d02-x01-y01")
 mergeByPt("/CMS_2014_I1266056/d02-x01-y02")
 mergeByPt("/CMS_2014_I1266056/d03-x01-y01")
 mergeByPt("/CMS_2014_I1266056/d03-x01-y02")
 mergeByPt("/CMS_2014_I1266056/d04-x01-y01")
 mergeByPt("/CMS_2014_I1266056/d04-x01-y02")
 
+logging.info("Processing ATLAS_2017_I1645627")
+mergeByPt("/ATLAS_2017_I1645627/d01-x01-y01")
+mergeByPt("/ATLAS_2017_I1645627/d02-x01-y01")
+useOnePt("/ATLAS_2017_I1645627/d03-x01-y01","90")
+useOnePt("/ATLAS_2017_I1645627/d04-x01-y01","90")
+useOnePt("/ATLAS_2017_I1645627/d05-x01-y01","90")
+
 logging.info("Processing /MC_PHOTONJETS")
 useOnePt("/MC_PHOTONJETS/jet_HT","0")
 useOnePt("/MC_PHOTONJETS/jet_eta_1","0")
 useOnePt("/MC_PHOTONJETS/jet_eta_2","0")
 useOnePt("/MC_PHOTONJETS/jet_eta_3","0")
 useOnePt("/MC_PHOTONJETS/jet_eta_4","0")
 useOnePt("/MC_PHOTONJETS/jet_eta_pmratio_1","0")
 useOnePt("/MC_PHOTONJETS/jet_eta_pmratio_2","0")
 useOnePt("/MC_PHOTONJETS/jet_eta_pmratio_3","0")
 useOnePt("/MC_PHOTONJETS/jet_eta_pmratio_4","0")
 useOnePt("/MC_PHOTONJETS/jet_mass_1","0")
 useOnePt("/MC_PHOTONJETS/jet_mass_2","0")
 useOnePt("/MC_PHOTONJETS/jet_mass_3","0")
 useOnePt("/MC_PHOTONJETS/jet_mass_4","0")
 useOnePt("/MC_PHOTONJETS/jet_multi_exclusive","0")
 useOnePt("/MC_PHOTONJETS/jet_multi_inclusive","0")
 useOnePt("/MC_PHOTONJETS/jet_multi_ratio","0")
 useOnePt("/MC_PHOTONJETS/jet_pT_1","0")
 useOnePt("/MC_PHOTONJETS/jet_pT_2","0")
 useOnePt("/MC_PHOTONJETS/jet_pT_3","0")
 useOnePt("/MC_PHOTONJETS/jet_pT_4","0")
 useOnePt("/MC_PHOTONJETS/jet_y_1","0")
 useOnePt("/MC_PHOTONJETS/jet_y_2","0")
 useOnePt("/MC_PHOTONJETS/jet_y_3","0")
 useOnePt("/MC_PHOTONJETS/jet_y_4","0")
 useOnePt("/MC_PHOTONJETS/jet_y_pmratio_1","0")
 useOnePt("/MC_PHOTONJETS/jet_y_pmratio_2","0")
 useOnePt("/MC_PHOTONJETS/jet_y_pmratio_3","0")
 useOnePt("/MC_PHOTONJETS/jet_y_pmratio_4","0")
 useOnePt("/MC_PHOTONJETS/jets_dR_12","0")
 useOnePt("/MC_PHOTONJETS/jets_dR_13","0")
 useOnePt("/MC_PHOTONJETS/jets_dR_23","0")
 useOnePt("/MC_PHOTONJETS/jets_deta_12","0")
 useOnePt("/MC_PHOTONJETS/jets_deta_13","0")
 useOnePt("/MC_PHOTONJETS/jets_deta_23","0")
 useOnePt("/MC_PHOTONJETS/jets_dphi_12","0")
 useOnePt("/MC_PHOTONJETS/jets_dphi_13","0")
 useOnePt("/MC_PHOTONJETS/jets_dphi_23","0")
 useOnePt("/MC_PHOTONJETS/photon_jet1_dR","0")
 useOnePt("/MC_PHOTONJETS/photon_jet1_deta","0")
 useOnePt("/MC_PHOTONJETS/photon_jet1_dphi","0")
 useOnePt("/MC_PHOTONJETUE/gammajet-dR","0")
 useOnePt("/MC_PHOTONJETUE/gammajet-dphi","0")
 useOnePt("/MC_PHOTONJETUE/trans-maxnchg-gamma","0")
 useOnePt("/MC_PHOTONJETUE/trans-maxnchg-jet","0")
 useOnePt("/MC_PHOTONJETUE/trans-maxptsum-gamma","0")
 useOnePt("/MC_PHOTONJETUE/trans-maxptsum-jet","0")
 useOnePt("/MC_PHOTONJETUE/trans-minnchg-gamma","0")
 useOnePt("/MC_PHOTONJETUE/trans-minnchg-jet","0")
 useOnePt("/MC_PHOTONJETUE/trans-minptsum-gamma","0")
 useOnePt("/MC_PHOTONJETUE/trans-minptsum-jet","0")
 useOnePt("/MC_PHOTONJETUE/trans-nchg-gamma","0")
 useOnePt("/MC_PHOTONJETUE/trans-nchg-jet","0")
 useOnePt("/MC_PHOTONJETUE/trans-ptavg-gamma","0")
 useOnePt("/MC_PHOTONJETUE/trans-ptavg-jet","0")
 useOnePt("/MC_PHOTONJETUE/trans-ptsum-gamma","0")
 useOnePt("/MC_PHOTONJETUE/trans-ptsum-jet","0")
 
 # Choose output file
 name = args[0]+"-Photon.yoda"
 yoda.writeYODA(outhistos,name)
 sys.exit(0)
diff --git a/Tests/python/merge-SppS b/Tests/python/merge-SppS
--- a/Tests/python/merge-SppS
+++ b/Tests/python/merge-SppS
@@ -1,164 +1,165 @@
 #! /usr/bin/env python
 # import lighthisto
 import logging
 import sys
 
 if sys.version_info[:3] < (2,4,0):
     print "rivet scripts require Python version >= 2.4.0... exiting"
     sys.exit(1)
 
 import os, yoda, copy
 
 # # #############################################
 
 def useOne(hpath, sqrts):
     global inhistos
     global outhistos
     try:
         outhistos[hpath] =  inhistos[hpath][float(sqrts)]
     except:
         pass
 
 if __name__ == "__main__":
     import logging
     from optparse import OptionParser, OptionGroup
     parser = OptionParser(usage="%prog name")
     verbgroup = OptionGroup(parser, "Verbosity control")
     verbgroup.add_option("-v", "--verbose", action="store_const", const=logging.DEBUG, dest="LOGLEVEL",
                          default=logging.INFO, help="print debug (very verbose) messages")
     verbgroup.add_option("-q", "--quiet", action="store_const", const=logging.WARNING, dest="LOGLEVEL",
                          default=logging.INFO, help="be very quiet")
     parser.add_option_group(verbgroup)
     (opts, args) = parser.parse_args()
     logging.basicConfig(level=opts.LOGLEVEL, format="%(message)s")
 
     ## Check args
     if len(args) < 1:
         logging.error("Must specify at least the name of the files")
         sys.exit(1)
 
 #######################################
 
 yodafiles=["ISR-44-UE.yoda","ISR-62-UE.yoda",args[0]+"-63-UE.yoda","ISR-30-UE.yoda", \
            "ISR-53-UE.yoda",args[0]+"-200-UE.yoda",args[0]+"-500-UE.yoda",args[0]+"-900-UE.yoda", \
            args[0]+"-546-UE.yoda",args[0]+"-53-UE.yoda"]
            
 ## Get histos
 inhistos = {}
 outhistos={}
 for file in yodafiles:
     file = 'Rivet-'+file
     if(file.find("44")>0) :
         sqrts=44
     elif(file.find("63")>0) :
         sqrts=63
     elif(file.find("30")>0) :
         sqrts=30
     elif(file.find("53")>0) :
         sqrts=53
     elif(file.find("200")>0) :
         sqrts=200
     elif(file.find("500")>0) :
         sqrts=500
     elif(file.find("900")>0) :
         sqrts=900
     elif(file.find("546")>0) :
         sqrts=546
     elif(file.find("53")>0) :
         sqrts=53
 
     if not os.access(file, os.R_OK):
         logging.error("%s can not be read" % file)
         continue
     try:
         aos = yoda.read(file)
     except:
         logging.error("%s can not be parsed as yoda" % file)
         break
     ## Get histos from this YODA file
     for aopath, ao in aos.iteritems() :
+        if("RAW" in aopath) :continue
         if(aopath.find("1926373")>0 or aopath.find("1867512")>0 or
            aopath.find("1583476")>0 or aopath.find("2044935")>0 or
            aopath.find("1178091")>0 ) :
             if not inhistos.has_key(aopath):
                 inhistos[aopath] = {}
             if not inhistos[aopath].has_key(sqrts):
                 inhistos[aopath][sqrts] = ao
             else:
                 raise Exception("A set with sqrts = %s already exists" % ( sqrts))
         else :
             outhistos[aopath] = ao
 
 # UA5_1989_S1926373
 useOne("/UA5_1989_S1926373/d01-x01-y01","200")
 useOne("/UA5_1989_S1926373/d02-x01-y01","900")
 useOne("/UA5_1989_S1926373/d03-x01-y01","200")
 useOne("/UA5_1989_S1926373/d04-x01-y01","200")
 useOne("/UA5_1989_S1926373/d05-x01-y01","200")
 useOne("/UA5_1989_S1926373/d06-x01-y01","200")
 useOne("/UA5_1989_S1926373/d07-x01-y01","900")
 useOne("/UA5_1989_S1926373/d08-x01-y01","900")
 useOne("/UA5_1989_S1926373/d09-x01-y01","900")
 useOne("/UA5_1989_S1926373/d10-x01-y01","900")
 useOne("/UA5_1989_S1926373/d11-x01-y01","200")
 useOne("/UA5_1989_S1926373/d12-x01-y01","900")
 # UA5_1988_S1867512
 useOne("/UA5_1988_S1867512/d02-x01-y01","200")
 useOne("/UA5_1988_S1867512/d02-x01-y02","546")
 useOne("/UA5_1988_S1867512/d02-x01-y03","900")
 useOne("/UA5_1988_S1867512/d03-x01-y01","200")
 useOne("/UA5_1988_S1867512/d03-x01-y02","546")
 useOne("/UA5_1988_S1867512/d03-x01-y03","900")
 # UA5_1986_S1583476
 useOne("/UA5_1986_S1583476/d01-x01-y01","200")
 useOne("/UA5_1986_S1583476/d01-x01-y02","200")
 useOne("/UA5_1986_S1583476/d01-x01-y03","900")
 useOne("/UA5_1986_S1583476/d01-x01-y04","900")
 useOne("/UA5_1986_S1583476/d02-x01-y01","200")
 useOne("/UA5_1986_S1583476/d02-x01-y02","200")
 useOne("/UA5_1986_S1583476/d02-x01-y03","200")
 useOne("/UA5_1986_S1583476/d02-x01-y04","200")
 useOne("/UA5_1986_S1583476/d02-x01-y05","200")
 useOne("/UA5_1986_S1583476/d02-x01-y06","200")
 useOne("/UA5_1986_S1583476/d03-x01-y01","900")
 useOne("/UA5_1986_S1583476/d03-x01-y02","900")
 useOne("/UA5_1986_S1583476/d03-x01-y03","900")
 useOne("/UA5_1986_S1583476/d03-x01-y04","900")
 useOne("/UA5_1986_S1583476/d03-x01-y05","900")
 useOne("/UA5_1986_S1583476/d03-x01-y06","900")
 useOne("/UA5_1986_S1583476/d03-x01-y07","900")
 useOne("/UA5_1986_S1583476/d03-x01-y08","900")
 useOne("/UA5_1986_S1583476/d03-x01-y09","900")
 # UA1_1990_S2044935
 useOne("/UA1_1990_S2044935/d01-x01-y01","200")
 useOne("/UA1_1990_S2044935/d01-x01-y02","500")
 useOne("/UA1_1990_S2044935/d01-x01-y03","900")
 useOne("/UA1_1990_S2044935/d02-x01-y01","200")
 useOne("/UA1_1990_S2044935/d02-x01-y02","500")
 useOne("/UA1_1990_S2044935/d02-x01-y03","900")
 useOne("/UA1_1990_S2044935/d03-x01-y01","900")
 useOne("/UA1_1990_S2044935/d04-x01-y01","900")
 useOne("/UA1_1990_S2044935/d05-x01-y01","900")
 useOne("/UA1_1990_S2044935/d06-x01-y01","200")
 useOne("/UA1_1990_S2044935/d07-x01-y01","900")
 useOne("/UA1_1990_S2044935/d08-x01-y01","63")
 useOne("/UA1_1990_S2044935/d09-x01-y01","200")
 useOne("/UA1_1990_S2044935/d10-x01-y01","500")
 useOne("/UA1_1990_S2044935/d11-x01-y01","900")
 useOne("/UA1_1990_S2044935/d12-x01-y01","200")
 useOne("/UA1_1990_S2044935/d12-x01-y02","500")
 useOne("/UA1_1990_S2044935/d12-x01-y03","900")
 # SFM_1984_S1178091
 useOne("/SFM_1984_S1178091/d01-x01-y01","30")
 useOne("/SFM_1984_S1178091/d01-x01-y02","44")
 useOne("/SFM_1984_S1178091/d01-x01-y03","53")
 useOne("/SFM_1984_S1178091/d01-x01-y04","63")
 useOne("/SFM_1984_S1178091/d02-x01-y01","30")
 useOne("/SFM_1984_S1178091/d02-x01-y02","44")
 useOne("/SFM_1984_S1178091/d02-x01-y03","53")
 useOne("/SFM_1984_S1178091/d02-x01-y04","63")
 # Choose output file
 name = args[0]+".yoda"
 # output the yoda file
 yoda.writeYODA(outhistos,name)
 sys.exit(0)
diff --git a/Tests/python/merge-Star b/Tests/python/merge-Star
--- a/Tests/python/merge-Star
+++ b/Tests/python/merge-Star
@@ -1,167 +1,168 @@
 #! /usr/bin/env python
 import logging
 import sys
 
 if sys.version_info[:3] < (2,4,0):
     print "rivet scripts require Python version >= 2.4.0... exiting"
     sys.exit(1)
 
 import os, yoda
 
 # #############################################
 
 def fillAbove(desthisto, sourcehistosbyptmin):
     pthigh= 1e100
     ptlow =-1e100
     for pt, h in sorted(sourcehistosbyptmin.iteritems(),reverse=True):
         ptlow=pt
         if(type(desthisto)==yoda.core.Scatter2D) :
             for i in range(0,h.numPoints) :
                 xMin = h.points[i].x-h.points[i].xErrs.minus
                 if( xMin >= ptlow and 
                     xMin <  pthigh ) :
                     desthisto.addPoint(h.points[i])
         elif(type(desthisto)==yoda.core.Profile1D) :
             for i in range(0,h.numBins) :
                 if(h.bins[i].xMin  >= ptlow and 
                    h.bins[i].xMin  <  pthigh ) :
                     desthisto.bins[i] += h.bins[i]
         elif(type(desthisto)==yoda.core.Histo1D) :
             for i in range(0,h.numBins) :
                 if(h.bins[i].xMin  >= ptlow and 
                    h.bins[i].xMin  <  pthigh ) :
                     desthisto.bins[i] += h.bins[i]
         else :
             logging.error("Can't merge %s, unknown type" % desthisto.path)
             sys.exit(1)
         pthigh=pt
 
 def mergeByPt(hpath, sqrts):
     global inhistos
     global outhistos
     try:
         fillAbove(outhistos[hpath], inhistos[hpath][float(sqrts)])
     except:
         pass
 
 def useOnePt(hpath, sqrts, ptmin):
     global inhistos
     global outhistos
     try:
        ## Find best pT_min match
         ptmins = inhistos[hpath][float(sqrts)].keys()
         closest_ptmin = None
         for ptm in ptmins:
             if closest_ptmin is None or \
                     abs(ptm-float(ptmin)) < abs(closest_ptmin-float(ptmin)):
                 closest_ptmin = ptm
         if closest_ptmin != float(ptmin):
             logging.warning("Inexact match for requested pTmin=%s: " % ptmin + \
                                 "using pTmin=%e instead" % closest_ptmin)
         outhistos[hpath] =  inhistos[hpath][float(sqrts)][closest_ptmin]
     except:
         pass
 
 # #######################################
 
 if __name__ == "__main__":
     import logging
     from optparse import OptionParser, OptionGroup
     parser = OptionParser(usage="%prog name")
     verbgroup = OptionGroup(parser, "Verbosity control")
     verbgroup.add_option("-v", "--verbose", action="store_const", const=logging.DEBUG, dest="LOGLEVEL",
                          default=logging.INFO, help="print debug (very verbose) messages")
     verbgroup.add_option("-q", "--quiet", action="store_const", const=logging.WARNING, dest="LOGLEVEL",
                          default=logging.INFO, help="be very quiet")
     parser.add_option_group(verbgroup)
     (opts, args) = parser.parse_args()
     logging.basicConfig(level=opts.LOGLEVEL, format="%(message)s")
 
     ## Check args
     if len(args) < 1:
         logging.error("Must specify at least the name of the files")
         sys.exit(1)
 
 yodafiles=["-UE.yoda","-Jets-1.yoda","-Jets-2.yoda","-Jets-3.yoda","-Jets-4.yoda"]
 
 ## Get histos
 inhistos = {}
 outhistos={}
 weights = {}
 for f in yodafiles:
     file='Rivet-'+args[0]+f
     if(file.find("-UE")>0) :
         sqrts=200
         ptmin=0.
     elif(file.find("-Jets-1")>0) :
         sqrts=200
         ptmin=2.
     elif(file.find("-Jets-2")>0) :
         sqrts=200
         ptmin=5.
     elif(file.find("-Jets-3")>0) :
         sqrts=200
         ptmin=26.
     elif(file.find("-Jets-4")>0) :
         sqrts=200
         ptmin=15.
 
     if not os.access(file, os.R_OK):
         logging.error("%s can not be read" % file)
         break
     try:
         aos = yoda.read(file)
     except:
         logging.error("%s can not be parsed as YODA" % file)
         break
     ## Get histos from this YODA file
     for aopath, ao in aos.iteritems() :
+        if("RAW" in aopath) :continue
         if(aopath.find("6870392")>0 or aopath.find("HELEN")>0) :
             if not inhistos.has_key(aopath):
                 inhistos[aopath] = {}
             tmpE = inhistos[aopath]
             if not tmpE.has_key(sqrts):
                 tmpE[sqrts] = {}
             tmpP = tmpE[sqrts]
             if not tmpP.has_key(ptmin):
                 tmpP[ptmin] = ao
             else:
                 raise Exception("A set with ptmin = %s already exists" % ( ptmin))
         else :
             outhistos[aopath] = ao
 
 ## Make empty output histos if needed
 for hpath,hsets in inhistos.iteritems():
     if( (hpath.find("6870392")>0 and hpath.find("d02-x01-y01" )>0 ) or
         hpath.find("HELEN")>0 ) :
         if(type(hsets.values()[0].values()[0])==yoda.core.Scatter2D) :
             outhistos[hpath] = yoda.core.Scatter2D(hsets.values()[0].values()[0].path,
                                                    hsets.values()[0].values()[0].title)
         elif(type(hsets.values()[0].values()[0])==yoda.core.Profile1D) :
             outhistos[hpath] = yoda.core.Profile1D(hsets.values()[0].values()[0].path,
                                                    hsets.values()[0].values()[0].title)
             for i in range(0,hsets.values()[0].values()[0].numBins) :
                 outhistos[hpath].addBin(hsets.values()[0].values()[0].bins[i].xMin,
                                         hsets.values()[0].values()[0].bins[i].xMax)
         elif(type(hsets.values()[0].values()[0])==yoda.core.Histo1D) :
             outhistos[hpath] = yoda.core.Histo1D(hsets.values()[0].values()[0].path,
                                                 hsets.values()[0].values()[0].title)
             for i in range(0,hsets.values()[0].values()[0].numBins) :
                 outhistos[hpath].addBin(hsets.values()[0].values()[0].bins[i].xMin,
                                         hsets.values()[0].values()[0].bins[i].xMax)
         else :
             logging.error("Histogram %s is of unknown type" % hpath)
             print hpath,type(hsets.values()[0].values()[0])
             sys.exit(1)
 
 useOnePt("/STAR_2006_S6870392/d01-x01-y01","200","2")
 mergeByPt("/STAR_2006_S6870392/d02-x01-y01","200")
 mergeByPt("/STAR_2009_UE_HELEN/d01-x01-y01","200")
 mergeByPt("/STAR_2009_UE_HELEN/d02-x01-y01","200")
 mergeByPt("/STAR_2009_UE_HELEN/d03-x01-y01","200")
 
 # Choose output file
 name = args[0]+".yoda"
 print "write to ",name
 yoda.writeYODA(outhistos,name)
 sys.exit(0)
diff --git a/Tests/python/merge-TVT-EW b/Tests/python/merge-TVT-EW
--- a/Tests/python/merge-TVT-EW
+++ b/Tests/python/merge-TVT-EW
@@ -1,73 +1,74 @@
 #! /usr/bin/env python
 import logging
 import sys
 import os, yoda
 
 """%prog
 
 Script for merging yoda files
 
 """
 
 import sys
 if sys.version_info[:3] < (2,4,0):
     print "rivet scripts require Python version >= 2.4.0... exiting"
     sys.exit(1)
 
 if __name__ == "__main__":
     import logging
     from optparse import OptionParser, OptionGroup
     parser = OptionParser(usage="%prog base")
     verbgroup = OptionGroup(parser, "Verbosity control")
     verbgroup.add_option("-v", "--verbose", action="store_const", const=logging.DEBUG, dest="LOGLEVEL",
                          default=logging.INFO, help="print debug (very verbose) messages")
     verbgroup.add_option("-q", "--quiet", action="store_const", const=logging.WARNING, dest="LOGLEVEL",
                          default=logging.INFO, help="be very quiet")
     parser.add_option_group(verbgroup)
     (opts, args) = parser.parse_args()
     logging.basicConfig(level=opts.LOGLEVEL, format="%(message)s")
 
     ## Check args
     if len(args) < 1:
         logging.error("Must specify at least the name of the files")
         sys.exit(1)
 
 
     yodafiles=["-Run-II-Z-e","-Run-II-Z-mu","-Run-II-Z-LowMass-mu","-Run-II-Z-HighMass-mu","-Run-I-W","-Run-I-Z","-Run-I-WZ"]
 
     ## Get histos
     outhistos={}
     for f in yodafiles:
         file='Rivet-'+args[0]+f+".yoda"
         if not os.access(file, os.R_OK):
             logging.error("%s can not be read" % file)
-            break
+            continue
         try:
             aos = yoda.read(file)
         except:
             logging.error("%s can not be parsed as yoda" % file)
-            break
+            continue
         ## Get histos from this YODA file
         for aopath, ao in aos.iteritems() :
+            if("RAW" in aopath) :continue
             if(aopath.find("D0_2010_S8821313")>0) :
                 if(aopath.find("d01")>0 and file.find("-e")>0) : 
                     outhistos[aopath] = ao
                 elif(aopath.find("d02")>0 and file.find("-mu")>0) : 
                     outhistos[aopath] = ao
             elif(aopath.find("D0_2015_I1324946")>0) :
                 if(file.find("LowMass")>0) : 
                     if(aopath.find("d02")>0) :
                         outhistos[aopath] = ao
                 elif(file.find("HighMass")>0) : 
                     if(aopath.find("d03")>0 or aopath.find("d04")>0) :
                         outhistos[aopath] = ao
                 else:
                     if(aopath.find("d01")>0) :
                         outhistos[aopath] = ao
             else :
                 outhistos[aopath] = ao
 
     # output the yoda file
     name = args[0]+"-EW.yoda"
     yoda.writeYODA(outhistos,name)
     sys.exit(0)
diff --git a/Tests/python/merge-TVT-Energy b/Tests/python/merge-TVT-Energy
deleted file mode 100755
--- a/Tests/python/merge-TVT-Energy
+++ /dev/null
@@ -1,144 +0,0 @@
-#! /usr/bin/env python
-import logging
-import sys
-
-if sys.version_info[:3] < (2,4,0):
-    print "rivet scripts require Python version >= 2.4.0... exiting"
-    sys.exit(1)
-
-import os, yoda
-
-# #############################################
-
-def fillAbove(desthisto, sourcehistosbyptmin):
-    pthigh= 1e100
-    ptlow =-1e100
-    for pt, h in sorted(sourcehistosbyptmin.iteritems(),reverse=True):
-        ptlow=pt
-        for i in range(0,h.numBins) :
-            if(h.bins[i].xMin  >= ptlow and 
-               h.bins[i].xMin  <  pthigh ) :
-                desthisto.bins[i] += h.bins[i]
-        pthigh=pt
-
-def mergeByPt(hpath, sqrts):
-    global inhistos
-    global outhistos
-    try:
-        fillAbove(outhistos[hpath], inhistos[hpath][float(sqrts)])
-    except:
-        pass
-
-# #######################################
-
-if __name__ == "__main__":
-    import logging
-    from optparse import OptionParser, OptionGroup
-    parser = OptionParser(usage="%prog name")
-    verbgroup = OptionGroup(parser, "Verbosity control")
-    verbgroup.add_option("-v", "--verbose", action="store_const", const=logging.DEBUG, dest="LOGLEVEL",
-                         default=logging.INFO, help="print debug (very verbose) messages")
-    verbgroup.add_option("-q", "--quiet", action="store_const", const=logging.WARNING, dest="LOGLEVEL",
-                         default=logging.INFO, help="be very quiet")
-    parser.add_option_group(verbgroup)
-    (opts, args) = parser.parse_args()
-    logging.basicConfig(level=opts.LOGLEVEL, format="%(message)s")
-
-    ## Check args
-    if len(args) < 1:
-        logging.error("Must specify at least the name of the files")
-        sys.exit(1)
-
-yodafiles=["-Run-II-UE.yoda","-Run-II-Jets-0.yoda",
-           "-300-UE.yoda"   ,"-300-Jets-1.yoda"  ,
-           "-900-UE.yoda"   ,"-900-Jets-1.yoda"  ]
-
-## Get histos
-inhistos = {}
-outhistos={}
-weights = {}
-for f in yodafiles:
-    file='Rivet-'+args[0]+f
-    if(file.find("Run-II-UE")>0) :
-        sqrts=1960
-        ptmin=0.
-    elif(file.find("Run-II-Jets-0")>0) :
-        sqrts=1960
-        ptmin=15
-    elif(file.find("300-UE")>0) :
-        sqrts=300
-        ptmin=0.
-    elif(file.find("300-Jets-1")>0) :
-        sqrts=300
-        ptmin=6.
-    elif(file.find("900-UE")>0) :
-        sqrts=900
-        ptmin=0.
-    elif(file.find("900-Jets-1")>0) :
-        sqrts=900
-        ptmin=10.
-    if not os.access(file, os.R_OK):
-        logging.error("%s can not be read" % file)
-        break
-    try:
-        aos = yoda.read(file)
-    except:
-        logging.error("%s can not be parsed as YODA" % file)
-        break
-    ## Get histos from this YODA file
-    for aopath, ao in aos.iteritems() :
-        if(aopath.find("NOTE10874")<0) : continue
-        if not inhistos.has_key(aopath):
-            inhistos[aopath] = {}
-        tmpE = inhistos[aopath]
-        if not tmpE.has_key(sqrts):
-            tmpE[sqrts] = {}
-        tmpP = tmpE[sqrts]
-        if not tmpP.has_key(ptmin):
-            tmpP[ptmin] = ao
-        else:
-            raise Exception("A set with ptmin = %s already exists" % ( ptmin))
-
-## Make empty output histos if needed
-for hpath,hsets in inhistos.iteritems():
-    if(type(hsets.values()[0].values()[0])==yoda.core.Scatter2D) :
-        outhistos[hpath] = yoda.core.Scatter2D(hsets.values()[0].values()[0].path,
-                                               hsets.values()[0].values()[0].title)
-    elif(type(hsets.values()[0].values()[0])==yoda.core.Profile1D) :
-        outhistos[hpath] = yoda.core.Profile1D(hsets.values()[0].values()[0].path,
-                                               hsets.values()[0].values()[0].title)
-        for i in range(0,hsets.values()[0].values()[0].numBins) :
-            outhistos[hpath].addBin(hsets.values()[0].values()[0].bins[i].xMin,
-                                    hsets.values()[0].values()[0].bins[i].xMax)
-    else :
-        logging.error("Histogram %s is of unknown type" % hpath)
-        sys.exit(1)
-
-## Field analysis
-logging.info("Processing CDF_2012_NOTE10874")
-## Angular distributions in different pT bins
-mergeByPt("/CDF_2012_NOTE10874/d01-x01-y01", "300")
-mergeByPt("/CDF_2012_NOTE10874/d01-x01-y02", "900")
-mergeByPt("/CDF_2012_NOTE10874/d01-x01-y03","1960")
-mergeByPt("/CDF_2012_NOTE10874/d02-x01-y01", "300")
-mergeByPt("/CDF_2012_NOTE10874/d02-x01-y02", "900")
-mergeByPt("/CDF_2012_NOTE10874/d02-x01-y03","1960")
-mergeByPt("/CDF_2012_NOTE10874/d03-x01-y01", "300")
-mergeByPt("/CDF_2012_NOTE10874/d03-x01-y02", "900")
-mergeByPt("/CDF_2012_NOTE10874/d03-x01-y03","1960")
-
-# Choose output file
-for i in range(1,4) :
-    if(i==1) : 
-        name = args[0]+"-300-Energy.yoda"
-    elif(i==2) :
-        name = args[0]+"-900-Energy.yoda"
-    elif(i==3) :
-        name = args[0]+"-1960-Energy.yoda"
-    temphistos={}
-    for hpath, h in sorted(outhistos.iteritems()):
-        if(hpath.find("y0"+str(i))>0) :
-            temphistos[hpath] = h
-    yoda.writeYODA(temphistos,name)
-
-sys.exit(0)
diff --git a/Tests/python/merge-TVT-Jets b/Tests/python/merge-TVT-Jets
--- a/Tests/python/merge-TVT-Jets
+++ b/Tests/python/merge-TVT-Jets
@@ -1,557 +1,634 @@
 #! /usr/bin/env python
 import logging
 import sys
+import math
 
 if sys.version_info[:3] < (2,4,0):
     print "rivet scripts require Python version >= 2.4.0... exiting"
     sys.exit(1)
 
 import os, yoda
 
-# #############################################
+# Divide two profile histograms with different nos of bins
+def divide(name,numer,denom) :
+    output = yoda.Scatter2D(name,name)
+    size = min(numer.numBins,denom.numBins)
+    for i in range(0,size) :
+        b1 = numer.bin(i)
+        b2 = denom.bin(i)
+        # Assemble the x value and error
+        x = b1.xMid
+        exminus = x - b1.xMin
+        explus  = b1.xMax - x
+        # Assemble the y value and error
+        # numerator
+        yupp=0.
+        relerr_1=0.
+        try :
+            yupp = b1.mean
+            try :
+                if b1.stdErr() != 0 :
+                    relerr_1 =  b1.stdErr()/b1.mean()
+            except:
+                relerr_1=0.
+        except :
+            yupp = 0.
+            relerr_1 =0.
+        # denominator
+        ylow=0.
+        relerr_2 = 0.
+        try :
+            ylow = b2.mean
+            try :
+                if b2.stdErr() != 0 :
+                    relerr_2 =  b2.stdErr()/b2.mean()
+            except:
+                relerr_2=0.
+        except :
+            ylow = 0.
+            relerr_2 = 0.
+        if yupp==0. or ylow== 0. :
+            y=0.
+        else :
+            y = yupp / ylow
+            ey = y * math.sqrt(relerr_1**2 + relerr_2**2)
+        output.addPoint(x, y, (exminus,explus), (ey,ey))
+    return output
 
 def fillAbove(desthisto, sourcehistosbyptmin):
     pthigh= 1e100
     ptlow =-1e100
     for pt, h in sorted(sourcehistosbyptmin.iteritems(),reverse=True):
         ptlow=pt
         if(type(desthisto)==yoda.core.Scatter2D) :
             for i in range(0,h.numPoints) :
                 xMin = h.points[i].x-h.points[i].xErrs.minus
                 if( xMin >= ptlow and 
                     xMin <  pthigh ) :
                     desthisto.addPoint(h.points[i])
         elif(type(desthisto)==yoda.core.Profile1D) :
             for i in range(0,h.numBins) :
                 if(h.bins[i].xMin  >= ptlow and 
                    h.bins[i].xMin  <  pthigh ) :
                     desthisto.bins[i] += h.bins[i]
         elif(type(desthisto)==yoda.core.Histo1D) :
             for i in range(0,h.numBins) :
                 if(h.bins[i].xMin  >= ptlow and 
                    h.bins[i].xMin  <  pthigh ) :
                     desthisto.bins[i] += h.bins[i]
         elif(type(desthisto)==yoda.core.Counter) :
                     desthisto += h
         else :
             logging.error("Can't merge %s, unknown type" % desthisto.path)
             sys.exit(1)
         pthigh=pt
 
 def mergeByPt(hpath, sqrts):
     global inhistos
     global outhistos
     try:
         fillAbove(outhistos[hpath], inhistos[hpath][float(sqrts)])
     except:
         pass
 
 def useOnePt(hpath, sqrts, ptmin):
     global inhistos
     global outhistos
     try:
        ## Find best pT_min match
         ptmins = inhistos[hpath][float(sqrts)].keys()
         closest_ptmin = None
         for ptm in ptmins:
             if closest_ptmin is None or \
                     abs(ptm-float(ptmin)) < abs(closest_ptmin-float(ptmin)):
                 closest_ptmin = ptm
         if closest_ptmin != float(ptmin):
             logging.warning("Inexact match for requested pTmin=%s: " % ptmin + \
                                 "using pTmin=%e instead" % closest_ptmin)
         outhistos[hpath] =  inhistos[hpath][float(sqrts)][closest_ptmin]
     except:
         pass
 
 # #######################################
 
 if __name__ == "__main__":
     import logging
     from optparse import OptionParser, OptionGroup
     parser = OptionParser(usage="%progbase")
     verbgroup = OptionGroup(parser, "Verbosity control")
     verbgroup.add_option("-v", "--verbose", action="store_const", const=logging.DEBUG, dest="LOGLEVEL",
                          default=logging.INFO, help="print debug (very verbose) messages")
     verbgroup.add_option("-q", "--quiet", action="store_const", const=logging.WARNING, dest="LOGLEVEL",
                          default=logging.INFO, help="be very quiet")
     parser.add_option("--with-ue",
                       action='store_true' ,
                       dest="ue",
                       default=True,
                       help="Include UE analyses")
     parser.add_option("--without-ue",
                       action='store_false',
                       dest="ue",
                       default=True,
                       help="Don\'t include UE analyses")
     parser.add_option_group(verbgroup)
     (opts, args) = parser.parse_args()
     logging.basicConfig(level=opts.LOGLEVEL, format="%(message)s")
 
     ## Check args
     if len(args) < 1:
         logging.error("Must specify at least the name of the files")
         sys.exit(1)
 
 yodafiles=["-Run-II-Jets-0.yoda","-Run-II-Jets-1.yoda",\
            "-Run-II-Jets-2.yoda",\
            "-Run-II-Jets-3.yoda","-Run-II-Jets-4.yoda","-Run-II-Jets-5.yoda",\
            "-Run-II-Jets-6.yoda","-Run-II-Jets-7.yoda",\
            "-Run-I-Jets-1.yoda","-Run-I-Jets-2.yoda",\
            "-Run-I-Jets-3.yoda","-Run-I-Jets-4.yoda","-Run-I-Jets-5.yoda",\
            "-630-Jets-1.yoda"  ,"-630-Jets-2.yoda"  ,\
-           "-630-Jets-3.yoda", "-300-UE.yoda", "-900-UE.yoda"
-#           "-RatioPlots.yoda"
-           ]
+           "-630-Jets-3.yoda", "-300-UE.yoda", "-900-UE.yoda"]
 if(opts.ue) :
-    yodafiles += ["-Run-II-UE.yoda"    ,"-Run-I-UE.yoda"    ,"-630-UE.yoda"      ,]
+    yodafiles += ["-Run-II-UE.yoda"    ,"-Run-I-UE.yoda"    ,"-630-UE.yoda"      ,\
+                  "-300-Jets-1.yoda", "-900-Jets-1.yoda"]
 
 ## Get histos
 inhistos = {}
 outhistos={}
 for f in yodafiles:
     file='Rivet-'+args[0]+f
     if(file.find("Run-II-UE")>0) :
         sqrts=1960
         ptmin=0.
     elif(file.find("Run-II-Jets-0")>0) :
         sqrts=1960
         ptmin=20.
     elif(file.find("Run-II-Jets-1")>0) :
         sqrts=1960
         ptmin=36.
     elif(file.find("Run-II-Jets-2")>0) :
         sqrts=1960
         ptmin=55.
     elif(file.find("Run-II-Jets-3")>0) :
         sqrts=1960
         ptmin=75.
     elif(file.find("Run-II-Jets-4")>0) :
         sqrts=1960
         ptmin=100.
     elif(file.find("Run-II-Jets-5")>0) :
         sqrts=1960
         ptmin=125.
     elif(file.find("Run-II-Jets-6")>0) :
         ptmin=175.
         sqrts=1960
     elif(file.find("Run-II-Jets-7")>0) :
         sqrts=1960
         ptmin=265.
     elif(file.find("300-UE")>0) :
         sqrts=300
         ptmin=0.
+    elif(file.find("300-Jets-1")>0) :
+        sqrts=300
+        ptmin=6.
     elif(file.find("900-UE")>0) :
         sqrts=900
         ptmin=0.
+    elif(file.find("900-Jets-1")>0) :
+        sqrts=900
+        ptmin=10.
     elif(file.find("630-UE")>0) :
         sqrts=630
         ptmin=0.
     elif(file.find("630-Jets-1")>0) :
         sqrts=630
         ptmin=30.
     elif(file.find("630-Jets-2")>0) :
         sqrts=630
         ptmin=55.
     elif(file.find("630-Jets-3")>0) :
         sqrts=630
         ptmin=90.
     elif(file.find("Run-I-UE")>0) :
         sqrts=1800
         ptmin=0.
     elif(file.find("Run-I-Jets-1")>0) :
         sqrts=1800
         ptmin=30.
     elif(file.find("Run-I-Jets-2")>0) :
         sqrts=1800
         ptmin=55.
     elif(file.find("Run-I-Jets-3")>0) :
         sqrts=1800
         ptmin=80.
     elif(file.find("Run-I-Jets-4")>0) :
         sqrts=1800
         ptmin=105.
     elif(file.find("Run-I-Jets-5")>0) :
         sqrts=1800
         ptmin=175.
     if not os.access(file, os.R_OK):
         logging.error("%s can not be read" % file)
         continue
     try:
         aos = yoda.read(file)
     except:
         logging.error("%s can not be parsed as YODA" % file)
         continue
     ## Get histos from this YODA file
     for aopath, ao in aos.iteritems() :
+        if("RAW" in aopath) :continue
         # di-jet decorrelations
         # jet shapes
         if(aopath.find("5992206")>0 or aopath.find("6217184")>0 or
            aopath.find("LEADINGJETS")>0 or aopath.find("7662670")>0 or
            aopath.find("7057202")>0 or aopath.find("6450792")>0 or
            aopath.find("7828950")>0 or aopath.find("4751469")>0 or
            aopath.find("5839831")>0 or aopath.find("4563131")>0 or
            aopath.find("4517016")>0 or aopath.find("3618439")>0 or
            aopath.find("8591881")>0 or aopath.find("1388868")>0 or
-           aopath.find("398175")>0) :
+           aopath.find("NOTE10874")>0 or aopath.find("398175")>0) :
            if not inhistos.has_key(aopath):
                inhistos[aopath] = {}
            tmpE = inhistos[aopath]
            if not tmpE.has_key(sqrts):
                tmpE[sqrts] = {}
            tmpP = tmpE[sqrts]
            if not tmpP.has_key(ptmin):
                tmpP[ptmin] = ao
            else:
                 raise Exception("A set with ptmin = %s already exists" % ( ptmin))
         elif(aopath.find("8233977")>0 or aopath.find("NOTE_9936")>0 or
              aopath.find("3905616")>0 or aopath.find("3324664")>0 or
              aopath.find("4796047")>0 or aopath.find("1865951")>0 or
              aopath.find("2089246")>0 or aopath.find("3108457")>0 or
              aopath.find("3349578")>0 or aopath.find("3541940")>0 or
              aopath.find("3214044")>0 or aopath.find("2952106")>0 or
-             aopath.find("NOTE10874")>0 or aopath.find("895662")>0 ) :
-            if( opts.ue ) :
-                outhistos[aopath] = ao
-            elif (aopath.find("NOTE10874")<0) :
-                outhistos[aopath] = ao
+             aopath.find("895662")>0 ) :
+            outhistos[aopath] = ao
         else :
             if(aopath.find("/_EVTCOUNT")>=0 or 
                aopath.find("/_XSEC"    )>=0 ) : continue
             print aopath
             quit()
 yodafiles=["-Run-II-Jets-8.yoda","-Run-II-Jets-9.yoda","-Run-II-Jets-10.yoda","-Run-II-Jets-11.yoda",\
            "-Run-I-Jets-6.yoda","-Run-I-Jets-7.yoda","-Run-I-Jets-8.yoda"]
 
 for f in yodafiles:
     file='Rivet-'+args[0]+f
     if(file.find("Run-II-Jets-8")>0) :
         sqrts=1960
         ptmin=0.150
     elif(file.find("Run-II-Jets-9")>0) :
         sqrts=1960
         ptmin=0.400
     elif(file.find("Run-II-Jets-10")>0) :
         sqrts=1960
         ptmin=0.600
     elif(file.find("Run-II-Jets-11")>0) :
         sqrts=1960
         ptmin=1.000
     elif(file.find("Run-I-Jets-6")>0) :
         sqrts=1800
         ptmin=0.150
     elif(file.find("Run-I-Jets-7")>0) :
         sqrts=1800
         ptmin=0.5
     elif(file.find("Run-I-Jets-8")>0) :
         sqrts=1800
         ptmin=0.8
     if not os.access(file, os.R_OK):
         logging.error("%s can not be read" % file)
         continue
     try:
         aos = yoda.read(file)
     except:
         logging.error("%s can not be parsed as YODA" % file)
         continue
-    ## Get histos from this AIDA file
+    ## Get histos from this yoda file
     for aopath, ao in aos.iteritems() :
+        if("RAW" in aopath) :continue
         if(aopath.find("8566488")>0 or aopath.find("8320160")>0) :
            if not inhistos.has_key(aopath):
                inhistos[aopath] = {}
            tmpE = inhistos[aopath]
            if not tmpE.has_key(sqrts):
                tmpE[sqrts] = {}
            tmpP = tmpE[sqrts]
            if not tmpP.has_key(ptmin):
                tmpP[ptmin] = ao
            else:
                 raise Exception("A set with ptmin = %s already exists" % ( ptmin))
         elif(aopath.find("8093652")>0 or aopath.find("3418421")>0 or 
              aopath.find("4266730")>0) :
            if not inhistos.has_key(aopath):
                inhistos[aopath] = {}
            tmpE = inhistos[aopath]
            if not tmpE.has_key(sqrts):
                tmpE[sqrts] = {}
            tmpP = tmpE[sqrts]
            if not tmpP.has_key(1000.*ptmin):
                tmpP[1000.*ptmin] = ao
            else:
                 raise Exception("A set with ptmin = %s already exists" % ( 1000.*ptmin))
 
 ## Make empty output histos if needed
 for hpath,hsets in inhistos.iteritems():
     if( (hpath.find("6217184")>0 and hpath.find("d13-x01-y01")>0 ) or
         hpath.find("LEADINGJETS")>0 or hpath.find("7662670")>0 or
         hpath.find("7057202")>0 or hpath.find("6450792")>0 or
         hpath.find("7828950")>0 or hpath.find("8566488")>0 or
         hpath.find("8320160")>0 or hpath.find("8093652")>0 or
         hpath.find("4751469")>0 or hpath.find("5839831")>0 or
         hpath.find("4563131")>0 or hpath.find("4517016")>0 or
         hpath.find("3618439")>0 or hpath.find("4266730")>0 or
         hpath.find("3418421")>0 or hpath.find("8591881")>0 or
-        hpath.find("1388868")>0) :
+        hpath.find("1388868")>0 or hpath.find("NOTE10874")>0) :
         if(type(hsets.values()[0].values()[0])==yoda.core.Counter) :
             outhistos[hpath] = yoda.core.Counter(hsets.values()[0].values()[0].path,
                                                  hsets.values()[0].values()[0].title)
         elif(type(hsets.values()[0].values()[0])==yoda.core.Scatter2D) :
             outhistos[hpath] = yoda.core.Scatter2D(hsets.values()[0].values()[0].path,
                                                    hsets.values()[0].values()[0].title)
         elif(type(hsets.values()[0].values()[0])==yoda.core.Profile1D) :
             outhistos[hpath] = yoda.core.Profile1D(hsets.values()[0].values()[0].path,
                                                    hsets.values()[0].values()[0].title)
             for i in range(0,hsets.values()[0].values()[0].numBins) :
                 outhistos[hpath].addBin(hsets.values()[0].values()[0].bins[i].xMin,
                                         hsets.values()[0].values()[0].bins[i].xMax)
         elif(type(hsets.values()[0].values()[0])==yoda.core.Histo1D) :
             outhistos[hpath] = yoda.core.Histo1D(hsets.values()[0].values()[0].path,
                                                 hsets.values()[0].values()[0].title)
             for i in range(0,hsets.values()[0].values()[0].numBins) :
                 outhistos[hpath].addBin(hsets.values()[0].values()[0].bins[i].xMin,
                                         hsets.values()[0].values()[0].bins[i].xMax)
         else :
             logging.error("Histogram %s is of unknown type" % hpath)
             print hpath,type(hsets.values()[0].values()[0])
             sys.exit(1)
 
 ## Field analysis
 logging.info("Processing CDF_2001_S4751469")
 ## Angular distributions in different pT bins
 if(opts.ue) :
     useOnePt("/CDF_2001_S4751469/d01-x01-y01", "1800", "0")
     useOnePt("/CDF_2001_S4751469/d01-x01-y02", "1800", "0")
     useOnePt("/CDF_2001_S4751469/d02-x01-y01", "1800", "0")
     useOnePt("/CDF_2001_S4751469/d02-x01-y02", "1800", "0")
 useOnePt("/CDF_2001_S4751469/d01-x01-y03", "1800", "30")
 useOnePt("/CDF_2001_S4751469/d02-x01-y03", "1800", "30")
 ## Number, profile in pT_lead (True?)
 if(opts.ue) :
     useOnePt("/CDF_2001_S4751469/d03-x01-y01", "1800", "0")
     useOnePt("/CDF_2001_S4751469/d03-x01-y02", "1800", "0")
     useOnePt("/CDF_2001_S4751469/d03-x01-y03", "1800", "0")
 useOnePt("/CDF_2001_S4751469/d04-x01-y01", "1800", "30")
 useOnePt("/CDF_2001_S4751469/d04-x01-y02", "1800", "30")
 useOnePt("/CDF_2001_S4751469/d04-x01-y03", "1800", "30")
 ## pT sums, profile in pT_lead (True?)
 if(opts.ue) :
     useOnePt("/CDF_2001_S4751469/d05-x01-y01", "1800",  "0")
     useOnePt("/CDF_2001_S4751469/d05-x01-y02", "1800",  "0")
     useOnePt("/CDF_2001_S4751469/d05-x01-y03", "1800",  "0")
 useOnePt("/CDF_2001_S4751469/d06-x01-y01", "1800", "30")
 useOnePt("/CDF_2001_S4751469/d06-x01-y02", "1800", "30")
 useOnePt("/CDF_2001_S4751469/d06-x01-y03", "1800", "30")
 ## pT distributions (use a specific pT cut run)
 if(opts.ue) :
     useOnePt("/CDF_2001_S4751469/d07-x01-y01", "1800", "0")
     useOnePt("/CDF_2001_S4751469/d07-x01-y02", "1800", "0")
 useOnePt("/CDF_2001_S4751469/d07-x01-y03", "1800", "30")
 
 ## Acosta analysis
 logging.info("Processing CDF_2004_S5839831")
 ## Mean pT, profile in ET_lead
 mergeByPt("/CDF_2004_S5839831/d01-x01-y01", "1800")
 mergeByPt("/CDF_2004_S5839831/d01-x01-y02", "1800")
 ## pT_max,min, profiles in ET_lead
 mergeByPt("/CDF_2004_S5839831/d02-x01-y01", "1800")
 mergeByPt("/CDF_2004_S5839831/d02-x01-y02", "1800")
 mergeByPt("/CDF_2004_S5839831/d02-x01-y03", "1800")
 ## pT distributions (want to use a specific pT cut run)
 useOnePt("/CDF_2004_S5839831/d03-x01-y01", "1800", "30")
 useOnePt("/CDF_2004_S5839831/d03-x01-y02", "1800", "80")
 useOnePt("/CDF_2004_S5839831/d03-x01-y03", "1800", "105")
 useOnePt("/CDF_2004_S5839831/d03-x01-y04", "1800", "105")
 useOnePt("/CDF_2004_S5839831/d03-x01-y05", "1800", "175")
 ## N_max,min, profiles in ET_lead
 mergeByPt("/CDF_2004_S5839831/d04-x01-y01", "1800")
 mergeByPt("/CDF_2004_S5839831/d04-x01-y02", "1800")
 ## Min bias dbs (want to use min bias pT cut)
 if(opts.ue) :
     useOnePt("/CDF_2004_S5839831/d05-x01-y01", "1800", "0")
     useOnePt("/CDF_2004_S5839831/d06-x01-y01", "1800", "0")
 ## Swiss Cheese, profile in ET_lead
 mergeByPt("/CDF_2004_S5839831/d07-x01-y01", "1800")
 mergeByPt("/CDF_2004_S5839831/d07-x01-y02", "1800")
 ## pT_max,min, profiles in ET_lead
 mergeByPt("/CDF_2004_S5839831/d08-x01-y01", "630")
 mergeByPt("/CDF_2004_S5839831/d08-x01-y02", "630")
 mergeByPt("/CDF_2004_S5839831/d08-x01-y03", "630")
 ## Swiss Cheese, profile in ET_lead
 mergeByPt("/CDF_2004_S5839831/d09-x01-y01", "630")
 mergeByPt("/CDF_2004_S5839831/d09-x01-y02", "630")
 ## Min bias dbs (want to use min bias pT cut)
 if(opts.ue) :
     useOnePt("/CDF_2004_S5839831/d10-x01-y01", "630", "0")
     useOnePt("/CDF_2004_S5839831/d11-x01-y01", "630", "0")
 
 ## CDF jet shape analysis
 logging.info("Processing CDF_2005_S6217184")
 useOnePt("/CDF_2005_S6217184/d01-x01-y01", "1960", "36" )
 useOnePt("/CDF_2005_S6217184/d01-x01-y02", "1960", "36" )
 useOnePt("/CDF_2005_S6217184/d01-x01-y03", "1960", "55" )
 useOnePt("/CDF_2005_S6217184/d02-x01-y01", "1960", "55" )
 useOnePt("/CDF_2005_S6217184/d02-x01-y02", "1960", "55" )
 useOnePt("/CDF_2005_S6217184/d02-x01-y03", "1960", "75" )
 useOnePt("/CDF_2005_S6217184/d03-x01-y01", "1960", "75" )
 useOnePt("/CDF_2005_S6217184/d03-x01-y02", "1960", "100")
 useOnePt("/CDF_2005_S6217184/d03-x01-y03", "1960", "100")
 useOnePt("/CDF_2005_S6217184/d04-x01-y01", "1960", "125")
 useOnePt("/CDF_2005_S6217184/d04-x01-y02", "1960", "125")
 useOnePt("/CDF_2005_S6217184/d04-x01-y03", "1960", "175")
 useOnePt("/CDF_2005_S6217184/d05-x01-y01", "1960", "175")
 useOnePt("/CDF_2005_S6217184/d05-x01-y02", "1960", "175")
 useOnePt("/CDF_2005_S6217184/d05-x01-y03", "1960", "175")
 useOnePt("/CDF_2005_S6217184/d06-x01-y01", "1960", "265")
 useOnePt("/CDF_2005_S6217184/d06-x01-y02", "1960", "265")
 useOnePt("/CDF_2005_S6217184/d06-x01-y03", "1960", "265")
 useOnePt("/CDF_2005_S6217184/d07-x01-y01", "1960", "36" )
 useOnePt("/CDF_2005_S6217184/d07-x01-y02", "1960", "36" )
 useOnePt("/CDF_2005_S6217184/d07-x01-y03", "1960", "55" )
 useOnePt("/CDF_2005_S6217184/d08-x01-y01", "1960", "55" )
 useOnePt("/CDF_2005_S6217184/d08-x01-y02", "1960", "55" )
 useOnePt("/CDF_2005_S6217184/d08-x01-y03", "1960", "75" )
 useOnePt("/CDF_2005_S6217184/d09-x01-y01", "1960", "75" )
 useOnePt("/CDF_2005_S6217184/d09-x01-y02", "1960", "100")
 useOnePt("/CDF_2005_S6217184/d09-x01-y03", "1960", "100")
 useOnePt("/CDF_2005_S6217184/d10-x01-y01", "1960", "125")
 useOnePt("/CDF_2005_S6217184/d10-x01-y02", "1960", "125")
 useOnePt("/CDF_2005_S6217184/d10-x01-y03", "1960", "175")
 useOnePt("/CDF_2005_S6217184/d11-x01-y01", "1960", "175")
 useOnePt("/CDF_2005_S6217184/d11-x01-y02", "1960", "175")
 useOnePt("/CDF_2005_S6217184/d11-x01-y03", "1960", "175")
 useOnePt("/CDF_2005_S6217184/d12-x01-y01", "1960", "265")
 useOnePt("/CDF_2005_S6217184/d12-x01-y02", "1960", "265")
 useOnePt("/CDF_2005_S6217184/d12-x01-y03", "1960", "265")
 mergeByPt("/CDF_2005_S6217184/d13-x01-y01", "1960")
 
-#     ## CDF dijet mass spectrum
+# CDF dijet mass spectrum
 mergeByPt("/CDF_2008_S8093652/d01-x01-y01", "1960")
 
 # ## Rick Field Run-II Leading Jets analysis
 # logging.info("Processing CDF_2008_LEADINGJETS")
 # ## charged particle density
 # mergeByPt("/CDF_2008_LEADINGJETS/d01-x01-y01", "1960")
 # mergeByPt("/CDF_2008_LEADINGJETS/d02-x01-y01", "1960")
 # mergeByPt("/CDF_2008_LEADINGJETS/d03-x01-y01", "1960")
 # mergeByPt("/CDF_2008_LEADINGJETS/d04-x01-y01", "1960")
 # ## pT sum density
 # mergeByPt("/CDF_2008_LEADINGJETS/d05-x01-y01", "1960")
 # mergeByPt("/CDF_2008_LEADINGJETS/d06-x01-y01", "1960")
 # mergeByPt("/CDF_2008_LEADINGJETS/d07-x01-y01", "1960")
 # mergeByPt("/CDF_2008_LEADINGJETS/d08-x01-y01", "1960")
 # ## mean pT
 # mergeByPt("/CDF_2008_LEADINGJETS/d09-x01-y01", "1960")
 
 ## newer version
 logging.info("Processing CDF_2010_S8591881_QCD")
 mergeByPt("/CDF_2010_S8591881_QCD/d10-x01-y01", "1960")
 mergeByPt("/CDF_2010_S8591881_QCD/d10-x01-y02", "1960")
 mergeByPt("/CDF_2010_S8591881_QCD/d10-x01-y03", "1960")
 mergeByPt("/CDF_2010_S8591881_QCD/d11-x01-y01", "1960")
 mergeByPt("/CDF_2010_S8591881_QCD/d11-x01-y02", "1960")
 mergeByPt("/CDF_2010_S8591881_QCD/d11-x01-y03", "1960")
 mergeByPt("/CDF_2010_S8591881_QCD/d12-x01-y01", "1960")
 mergeByPt("/CDF_2010_S8591881_QCD/d12-x01-y02", "1960")
 mergeByPt("/CDF_2010_S8591881_QCD/d12-x01-y03", "1960")
 mergeByPt("/CDF_2010_S8591881_QCD/d13-x01-y01", "1960")
 mergeByPt("/CDF_2010_S8591881_QCD/d13-x01-y02", "1960")
 mergeByPt("/CDF_2010_S8591881_QCD/d13-x01-y03", "1960")
 mergeByPt("/CDF_2010_S8591881_QCD/d14-x01-y01", "1960")
 mergeByPt("/CDF_2010_S8591881_QCD/d15-x01-y01", "1960")
 
 ## D0 dijet correlation analysis
 logging.info("Processing D0_2004_S5992206")
 useOnePt("/D0_2004_S5992206/d01-x02-y01", "1960", "75")
 useOnePt("/D0_2004_S5992206/d02-x02-y01", "1960", "100")
 useOnePt("/D0_2004_S5992206/d03-x02-y01", "1960", "125")
 useOnePt("/D0_2004_S5992206/d04-x02-y01", "1960", "175")
 
 ## D0 incl jet cross-section analysis
 logging.info("Processing D0_2008_S7662670")
 mergeByPt("/D0_2008_S7662670/d01-x01-y01", "1960")
 mergeByPt("/D0_2008_S7662670/d02-x01-y01", "1960")
 mergeByPt("/D0_2008_S7662670/d03-x01-y01", "1960")
 mergeByPt("/D0_2008_S7662670/d04-x01-y01", "1960")
 mergeByPt("/D0_2008_S7662670/d05-x01-y01", "1960")
 mergeByPt("/D0_2008_S7662670/d06-x01-y01", "1960")
 
 mergeByPt("/D0_2010_S8566488/d01-x01-y01", "1960")
 mergeByPt("/D0_2010_S8566488/d02-x01-y01", "1960")
 mergeByPt("/D0_2010_S8566488/d03-x01-y01", "1960")
 mergeByPt("/D0_2010_S8566488/d04-x01-y01", "1960")
 mergeByPt("/D0_2010_S8566488/d05-x01-y01", "1960")
 mergeByPt("/D0_2010_S8566488/d06-x01-y01", "1960")
 
 # CDF jet cross section
 
 mergeByPt("/CDF_2001_S4563131/d01-x01-y01", "1800")
 
 mergeByPt("/CDF_2001_S4517016/d01-x01-y01", "1800")
 mergeByPt("/CDF_2001_S4517016/d02-x01-y01", "1800")
 mergeByPt("/CDF_2001_S4517016/d03-x01-y01", "1800")
 mergeByPt("/CDF_2001_S4517016/d04-x01-y01", "1800")
 
 useOnePt("/CDF_1998_S3618439/d01-x01-y01", "1800","105")
 useOnePt("/CDF_1998_S3618439/d01-x01-y02", "1800","105")
 
 mergeByPt("/CDF_2008_S7828950/d01-x01-y01", "1960")
 mergeByPt("/CDF_2008_S7828950/d02-x01-y01", "1960")
 mergeByPt("/CDF_2008_S7828950/d03-x01-y01", "1960")
 mergeByPt("/CDF_2008_S7828950/d04-x01-y01", "1960")
 mergeByPt("/CDF_2008_S7828950/d05-x01-y01", "1960")
 
 mergeByPt("/CDF_2007_S7057202/d01-x01-y01", "1960")
 mergeByPt("/CDF_2007_S7057202/d02-x01-y01", "1960")
 mergeByPt("/CDF_2007_S7057202/d03-x01-y01", "1960")
 mergeByPt("/CDF_2007_S7057202/d04-x01-y01", "1960")
 mergeByPt("/CDF_2007_S7057202/d05-x01-y01", "1960")
 mergeByPt("/CDF_2007_S7057202/d06-x01-y01", "1960")
 mergeByPt("/CDF_2007_S7057202/d07-x01-y01", "1960")
 
 mergeByPt("/CDF_2006_S6450792/d01-x01-y01", "1960")
 
 mergeByPt("/CDF_2000_S4266730/d01-x01-y01", "1800")
 
 useOnePt("/CDF_1996_S3418421/d01-x01-y01","1800","150")
 useOnePt("/CDF_1996_S3418421/d01-x01-y02","1800","150")
 useOnePt("/CDF_1996_S3418421/d01-x01-y03","1800","150")
 useOnePt("/CDF_1996_S3418421/d01-x01-y04","1800","500")
 useOnePt("/CDF_1996_S3418421/d01-x01-y05","1800","500")
 mergeByPt("/CDF_1996_S3418421/d02-x01-y01","1800")
 
 useOnePt("/D0_2009_S8320160/d01-x01-y01", "1960", "0.15" )
 useOnePt("/D0_2009_S8320160/d02-x01-y01", "1960", "0.15" )
 useOnePt("/D0_2009_S8320160/d03-x01-y01", "1960", "0.4" )
 useOnePt("/D0_2009_S8320160/d04-x01-y01", "1960", "0.4" )
 useOnePt("/D0_2009_S8320160/d05-x01-y01", "1960", "0.6" )
 useOnePt("/D0_2009_S8320160/d06-x01-y01", "1960", "0.6" )
 useOnePt("/D0_2009_S8320160/d07-x01-y01", "1960", "0.6" )
 useOnePt("/D0_2009_S8320160/d08-x01-y01", "1960", "0.6" )
 useOnePt("/D0_2009_S8320160/d09-x01-y01", "1960", "1.0" )
 useOnePt("/D0_2009_S8320160/d10-x01-y01", "1960", "1.0" )
 
 logging.info("Processing CDF_2015_I1388868")
 for d in range(1,4) :
     if d == 1 :
         energy="1960"
     elif d ==2 :
         energy = "900"
     elif d==3 :
         energy = "300"
     for y in [1,2,3,4,6,7,8,9]:
         useOnePt("/CDF_2015_I1388868/d0%s-x01-y0%s" % (d,y) , energy, "0" )
 
 # D0 jet shape
 logging.info("Processing D0_1995_I398175")
 useOnePt("/D0_1995_I398175/d01-x01-y01", "1800", "30" )
 useOnePt("/D0_1995_I398175/d02-x01-y01", "1800", "55" )
 useOnePt("/D0_1995_I398175/d03-x01-y01", "1800", "105" )
 useOnePt("/D0_1995_I398175/d04-x01-y01", "1800", "105" )
 useOnePt("/D0_1995_I398175/d05-x01-y01", "1800", "30" )
 useOnePt("/D0_1995_I398175/d06-x01-y01", "1800", "55" )
-        
+
+logging.info("CDF_2012_NOTE10874")
+mergeByPt("/CDF_2012_NOTE10874/d01-x01-y01", "300")
+mergeByPt("/CDF_2012_NOTE10874/d01-x01-y02", "900")
+mergeByPt("/CDF_2012_NOTE10874/d01-x01-y03","1960")
+mergeByPt("/CDF_2012_NOTE10874/d02-x01-y01", "300")
+mergeByPt("/CDF_2012_NOTE10874/d02-x01-y02", "900")
+mergeByPt("/CDF_2012_NOTE10874/d02-x01-y03","1960")
+mergeByPt("/CDF_2012_NOTE10874/d03-x01-y01", "300")
+mergeByPt("/CDF_2012_NOTE10874/d03-x01-y02", "900")
+mergeByPt("/CDF_2012_NOTE10874/d03-x01-y03","1960")
+
+for i in range(1,4) :
+    names = ["/CDF_2012_NOTE10874/d0%s-x01-y01" % i,
+             "/CDF_2012_NOTE10874/d0%s-x01-y02" % i,
+             "/CDF_2012_NOTE10874/d0%s-x01-y03" % i]
+    # ratio 1960/300
+    if names[0] in outhistos and names[2] in outhistos :
+        outhistos["/CDF_2012_NOTE10874/d0%s-x01-y04" % i] = \
+        divide("/CDF_2012_NOTE10874/d0%s-x01-y04" % i,outhistos[names[2]],outhistos[names[0]])
+    # ratio 900/300
+    if names[0] in outhistos and names[1] in outhistos :
+        outhistos["/CDF_2012_NOTE10874/d0%s-x01-y05" % i]= \
+        divide("/CDF_2012_NOTE10874/d0%s-x01-y05" % i,outhistos[names[1]],outhistos[names[0]])
+    # ratio 1960/900
+    if names[1] in outhistos and names[2] in outhistos :
+        outhistos["/CDF_2012_NOTE10874/d0%s-x01-y06" % i]= \
+        divide("/CDF_2012_NOTE10874/d0%s-x01-y06" %i,outhistos[names[2]],outhistos[names[1]])
+
 # Choose output file
 name = args[0]+"-Jets.yoda"
 yoda.writeYODA(outhistos,name)
 sys.exit(0)
diff --git a/Tests/python/merge-TVT-Photon b/Tests/python/merge-TVT-Photon
--- a/Tests/python/merge-TVT-Photon
+++ b/Tests/python/merge-TVT-Photon
@@ -1,65 +1,66 @@
 #! /usr/bin/env python
 import logging
 import sys
 import os, yoda
 
 """%prog
 
 Script for merging aida files
 
 """
 
 if sys.version_info[:3] < (2,4,0):
     print "rivet scripts require Python version >= 2.4.0... exiting"
     sys.exit(1)
 
 if __name__ == "__main__":
     import logging
     from optparse import OptionParser, OptionGroup
     parser = OptionParser(usage="%prog base")
     verbgroup = OptionGroup(parser, "Verbosity control")
     verbgroup.add_option("-v", "--verbose", action="store_const", const=logging.DEBUG, dest="LOGLEVEL",
                          default=logging.INFO, help="print debug (very verbose) messages")
     verbgroup.add_option("-q", "--quiet", action="store_const", const=logging.WARNING, dest="LOGLEVEL",
                          default=logging.INFO, help="be very quiet")
     parser.add_option_group(verbgroup)
     (opts, args) = parser.parse_args()
     logging.basicConfig(level=opts.LOGLEVEL, format="%(message)s")
 
     ## Check args
     if len(args) < 1:
         logging.error("Must specify at least the name of the files")
         sys.exit(1)
 
 files=["-Run-II-PromptPhoton.yoda",
        "-Run-II-DiPhoton-GammaGamma.yoda","-Run-II-DiPhoton-GammaJet.yoda"]
 
 ## Get histos
 inhistos = {}
 outhistos={}
 for f in files:
     file='Rivet-'+args[0]+f
     if not os.access(file, os.R_OK):
         logging.error("%s can not be read" % file)
         continue
     try:
         aos = yoda.read(file)
     except:
-        logging.error("%s can not be parsed as XML" % file)
-        break
+        logging.error("%s can not be parsed as yoda" % file)
+        continue
     ## Get histos from this YODA file
     for aopath, ao in aos.iteritems() :
+        if("RAW" in aopath) :continue
         if(aopath.find("XSEC")>=0 or aopath.find("EVTCOUNT")>=0) : continue
         if ( aopath in outhistos ) :
             aotype = type(ao)
             if aotype in (yoda.Counter, yoda.Histo1D, yoda.Histo2D, yoda.Profile1D, yoda.Profile2D):
                 outhistos[aopath] += ao
             else :
                 quit()
         else:
             outhistos[aopath] = ao
 
 # Choose output file
 name = args[0]+"-Photon.yoda"
 yoda.writeYODA(outhistos,name)
 sys.exit(0)
diff --git a/src/defaults/Hadronization.in b/src/defaults/Hadronization.in
--- a/src/defaults/Hadronization.in
+++ b/src/defaults/Hadronization.in
@@ -1,95 +1,95 @@
 # -*- ThePEG-repository -*-
 
 ############################################################
 # Setup of default hadronization 
 #
 # There are no user servicable parts inside.
 #
 # Anything that follows below should only be touched if you 
 # know what you're doing. 
 #############################################################
 
 cd /Herwig/Particles
 create ThePEG::ParticleData Cluster
 setup Cluster 81 Cluster 0.00990 0.0 0.0 0.0  0 0  0  1
 create ThePEG::ParticleData Remnant
 setup Remnant 82 Remnant 0.00990 0.0 0.0 0.0  0 0  0  1
 
 mkdir /Herwig/Hadronization
 cd /Herwig/Hadronization
 
 create Herwig::ClusterHadronizationHandler ClusterHadHandler
 create Herwig::PartonSplitter PartonSplitter
 create Herwig::ClusterFinder ClusterFinder
 create Herwig::ColourReconnector ColourReconnector
 create Herwig::ClusterFissioner ClusterFissioner
 create Herwig::LightClusterDecayer LightClusterDecayer
 create Herwig::ClusterDecayer ClusterDecayer
 create Herwig::HwppSelector HadronSelector
 
 newdef ClusterHadHandler:PartonSplitter PartonSplitter
 newdef ClusterHadHandler:ClusterFinder ClusterFinder
 newdef ClusterHadHandler:ColourReconnector ColourReconnector
 newdef ClusterHadHandler:ClusterFissioner ClusterFissioner
 newdef ClusterHadHandler:LightClusterDecayer LightClusterDecayer
 newdef ClusterHadHandler:ClusterDecayer ClusterDecayer
 newdef ClusterHadHandler:MinVirtuality2 0.1*GeV2
 newdef ClusterHadHandler:MaxDisplacement 1.0e-10*millimeter
 newdef ClusterHadHandler:UnderlyingEventHandler NULL
 
 newdef ClusterFissioner:HadronSelector HadronSelector 
 newdef LightClusterDecayer:HadronSelector HadronSelector
 newdef ClusterDecayer:HadronSelector HadronSelector
 
 newdef ColourReconnector:ColourReconnection Yes
 newdef ColourReconnector:ReconnectionProbability 0.652710
 newdef ColourReconnector:Algorithm Plain
 newdef ColourReconnector:InitialTemperature 0.01
 newdef ColourReconnector:AnnealingFactor 0.21
 newdef ColourReconnector:AnnealingSteps 10
 newdef ColourReconnector:TriesPerStepFactor 0.66
 newdef ColourReconnector:OctetTreatment All
 
 # Clustering parameters for light quarks
-newdef ClusterFissioner:ClMaxLight  3.002538
-newdef ClusterFissioner:ClPowLight  1.424265
-newdef ClusterFissioner:PSplitLight 0.847541
+newdef ClusterFissioner:ClMaxLight  3.649
+newdef ClusterFissioner:ClPowLight  2.780
+newdef ClusterFissioner:PSplitLight 0.899
 newdef ClusterDecayer:ClDirLight 1
 newdef ClusterDecayer:ClSmrLight 0.78
 
 # Clustering parameters for b-quarks
-newdef ClusterFissioner:ClMaxBottom  3.91100
-newdef ClusterFissioner:ClPowBottom  .63750
-newdef ClusterFissioner:PSplitBottom .5306
+newdef ClusterFissioner:ClMaxBottom  3.757
+newdef ClusterFissioner:ClPowBottom  0.547
+newdef ClusterFissioner:PSplitBottom 0.625
 newdef ClusterDecayer:ClDirBottom 1
-newdef ClusterDecayer:ClSmrBottom 0.0204
-newdef HadronSelector:SingleHadronLimitBottom 0.0
+newdef ClusterDecayer:ClSmrBottom 0.078
+newdef HadronSelector:SingleHadronLimitBottom 0.000
 
 # Clustering parameters for c-quarks
-newdef ClusterFissioner:ClMaxCharm  3.638218
-newdef ClusterFissioner:ClPowCharm  2.331856
-newdef ClusterFissioner:PSplitCharm 1.233994
+newdef ClusterFissioner:ClMaxCharm  3.950
+newdef ClusterFissioner:ClPowCharm  2.559
+newdef ClusterFissioner:PSplitCharm 0.994
 newdef ClusterDecayer:ClDirCharm 1
-newdef ClusterDecayer:ClSmrCharm 0.
-newdef HadronSelector:SingleHadronLimitCharm 0.000000
+newdef ClusterDecayer:ClSmrCharm  0.163
+newdef HadronSelector:SingleHadronLimitCharm 0.000
 
 # Clustering parameters for exotic quarks
 # (e.g. hadronizing Susy particles)
 newdef ClusterFissioner:ClMaxExotic  2.7*GeV
 newdef ClusterFissioner:ClPowExotic  1.46
 newdef ClusterFissioner:PSplitExotic 1.00
 newdef ClusterDecayer:ClDirExotic 1
 newdef ClusterDecayer:ClSmrExotic 0.
 newdef HadronSelector:SingleHadronLimitExotic 0.
 
 # 
 newdef HadronSelector:PwtDquark  1.0
 newdef HadronSelector:PwtUquark  1.0
-newdef HadronSelector:PwtSquark  0.665563
+newdef HadronSelector:PwtSquark 0.700
 newdef HadronSelector:PwtCquark  1.0
 newdef HadronSelector:PwtBquark  1.0
-newdef HadronSelector:PwtDIquark 0.439018
+newdef HadronSelector:PwtDIquark  0.298
 newdef HadronSelector:SngWt      0.74
 newdef HadronSelector:DecWt      0.62
 newdef HadronSelector:Mode 1
 newdef HadronSelector:BelowThreshold All
diff --git a/src/defaults/Shower.in b/src/defaults/Shower.in
--- a/src/defaults/Shower.in
+++ b/src/defaults/Shower.in
@@ -1,354 +1,364 @@
 # -*- ThePEG-repository -*-
 
 ############################################################
 # Setup of default parton shower
 #
 # Useful switches for users are marked near the top of 
 # this file.
 #
 # Don't edit this file directly, but reset the switches
 # in your own input files!
 ############################################################
 library HwMPI.so
 library HwShower.so
 library HwMatching.so
 
 mkdir /Herwig/Shower
 cd /Herwig/Shower
 
 create Herwig::QTildeShowerHandler ShowerHandler
 newdef ShowerHandler:MPIHandler /Herwig/UnderlyingEvent/MPIHandler
 newdef ShowerHandler:RemDecayer /Herwig/Partons/RemnantDecayer
 # use LO PDFs for Shower, can be changed later
 newdef ShowerHandler:PDFA /Herwig/Partons/ShowerLOPDF
 newdef ShowerHandler:PDFB /Herwig/Partons/ShowerLOPDF
 newdef ShowerHandler:PDFARemnant /Herwig/Partons/RemnantPDF
 newdef ShowerHandler:PDFBRemnant /Herwig/Partons/RemnantPDF
 
 #####################################
 # initial setup, don't change these!
 #####################################
 create Herwig::SplittingGenerator SplittingGenerator
 create Herwig::ShowerAlphaQCD AlphaQCD
 create Herwig::ShowerAlphaQED AlphaQED
 set AlphaQED:CouplingSource Thompson
 create Herwig::ShowerAlphaQED AlphaEW
 set AlphaEW:CouplingSource MZ
 create Herwig::PartnerFinder PartnerFinder
 newdef PartnerFinder:PartnerMethod 1
 newdef PartnerFinder:ScaleChoice 1
 create Herwig::KinematicsReconstructor KinematicsReconstructor
 newdef KinematicsReconstructor:ReconstructionOption Colour3
 newdef KinematicsReconstructor:InitialStateReconOption SofterFraction
 newdef KinematicsReconstructor:InitialInitialBoostOption LongTransBoost
+newdef KinematicsReconstructor:FinalFinalWeight Yes
 
 newdef /Herwig/Partons/RemnantDecayer:AlphaS  AlphaQCD
 newdef /Herwig/Partons/RemnantDecayer:AlphaEM AlphaQED
 
 newdef ShowerHandler:PartnerFinder PartnerFinder
 newdef ShowerHandler:KinematicsReconstructor KinematicsReconstructor
 newdef ShowerHandler:SplittingGenerator SplittingGenerator
 newdef ShowerHandler:Interactions QEDQCD
 newdef ShowerHandler:SpinCorrelations Yes
 newdef ShowerHandler:SoftCorrelations Singular
 
 ##################################################################
 # Intrinsic pT
 #
 # Recommended: 
 # 1.9 GeV for Tevatron W/Z production.
 # 2.1 GeV for LHC W/Z production at 10 TeV
 # 2.2 GeV for LHC W/Z production at 14 TeV
 #
 # Set all parameters to 0 to disable
 ##################################################################
 newdef ShowerHandler:IntrinsicPtGaussian 1.3*GeV
 newdef ShowerHandler:IntrinsicPtBeta  	0
 newdef ShowerHandler:IntrinsicPtGamma 	0*GeV
 newdef ShowerHandler:IntrinsicPtIptmax   0*GeV
 #############################################################
 # Set up truncated shower handler.
 #############################################################
 
 create Herwig::PowhegShowerHandler PowhegShowerHandler
 set PowhegShowerHandler:MPIHandler /Herwig/UnderlyingEvent/MPIHandler
 set PowhegShowerHandler:RemDecayer /Herwig/Partons/RemnantDecayer
 newdef PowhegShowerHandler:PDFA /Herwig/Partons/ShowerLOPDF
 newdef PowhegShowerHandler:PDFB /Herwig/Partons/ShowerLOPDF
 newdef PowhegShowerHandler:PDFARemnant /Herwig/Partons/RemnantPDF
 newdef PowhegShowerHandler:PDFBRemnant /Herwig/Partons/RemnantPDF
 newdef PowhegShowerHandler:MPIHandler /Herwig/UnderlyingEvent/MPIHandler
 newdef PowhegShowerHandler:RemDecayer /Herwig/Partons/RemnantDecayer
 newdef PowhegShowerHandler:PDFA /Herwig/Partons/ShowerLOPDF
 newdef PowhegShowerHandler:PDFB /Herwig/Partons/ShowerLOPDF
 newdef PowhegShowerHandler:PDFARemnant /Herwig/Partons/RemnantPDF
 newdef PowhegShowerHandler:PDFBRemnant /Herwig/Partons/RemnantPDF
 newdef PowhegShowerHandler:PartnerFinder PartnerFinder
 newdef PowhegShowerHandler:KinematicsReconstructor KinematicsReconstructor
 newdef PowhegShowerHandler:SplittingGenerator SplittingGenerator
 newdef PowhegShowerHandler:Interactions QEDQCD
 newdef PowhegShowerHandler:SpinCorrelations Yes
 newdef PowhegShowerHandler:SoftCorrelations Singular
 newdef PowhegShowerHandler:IntrinsicPtGaussian 1.3*GeV
 newdef PowhegShowerHandler:IntrinsicPtBeta  	0
 newdef PowhegShowerHandler:IntrinsicPtGamma 	0*GeV
 newdef PowhegShowerHandler:IntrinsicPtIptmax   0*GeV
-newdef PowhegShowerHandler:ReconstructionOption OffShell5
+newdef PowhegShowerHandler:EvolutionScheme DotProduct
 
 #############################################################
 # End of interesting user servicable section.
 #
 # Anything that follows below should only be touched if you 
 # know what you're doing. 
 #
 # Really.
 #############################################################
 #
 # a few default values
 newdef ShowerHandler:MECorrMode 1
-newdef ShowerHandler:ReconstructionOption OffShell5
+newdef ShowerHandler:EvolutionScheme DotProduct
 newdef AlphaQCD:ScaleFactor 1.0
 newdef AlphaQCD:NPAlphaS 2
 newdef AlphaQCD:Qmin 0.935
 newdef AlphaQCD:NumberOfLoops 2
-newdef AlphaQCD:AlphaIn 0.126234
+newdef AlphaQCD:AlphaIn 0.1186
 #
 #
 # Lets set up all the splittings
 create Herwig::HalfHalfOneSplitFn QtoQGammaSplitFn
 set QtoQGammaSplitFn:InteractionType QED
 set QtoQGammaSplitFn:ColourStructure ChargedChargedNeutral
 set QtoQGammaSplitFn:AngularOrdered Yes
+set QtoQGammaSplitFn:StrictAO Yes
 
 create Herwig::HalfHalfOneSplitFn QtoQGSplitFn
 newdef QtoQGSplitFn:InteractionType QCD
 newdef QtoQGSplitFn:ColourStructure TripletTripletOctet
 set QtoQGSplitFn:AngularOrdered Yes
+set QtoQGSplitFn:StrictAO Yes
 
 create Herwig::OneOneOneSplitFn GtoGGSplitFn
 newdef GtoGGSplitFn:InteractionType QCD
 newdef GtoGGSplitFn:ColourStructure OctetOctetOctet
 set GtoGGSplitFn:AngularOrdered Yes
+set GtoGGSplitFn:StrictAO Yes
 
 create Herwig::OneOneOneMassiveSplitFn WtoWGammaSplitFn
 newdef WtoWGammaSplitFn:InteractionType QED
 newdef WtoWGammaSplitFn:ColourStructure ChargedChargedNeutral
 set WtoWGammaSplitFn:AngularOrdered Yes
+set WtoWGammaSplitFn:StrictAO Yes
 
 create Herwig::OneHalfHalfSplitFn GtoQQbarSplitFn
 newdef GtoQQbarSplitFn:InteractionType QCD
 newdef GtoQQbarSplitFn:ColourStructure OctetTripletTriplet
 set GtoQQbarSplitFn:AngularOrdered Yes
+set GtoQQbarSplitFn:StrictAO Yes
 
 create Herwig::OneHalfHalfSplitFn GammatoQQbarSplitFn
 newdef GammatoQQbarSplitFn:InteractionType QED
 newdef GammatoQQbarSplitFn:ColourStructure NeutralChargedCharged
 set GammatoQQbarSplitFn:AngularOrdered Yes
+set GammatoQQbarSplitFn:StrictAO Yes
 
 create Herwig::HalfOneHalfSplitFn QtoGQSplitFn
 newdef QtoGQSplitFn:InteractionType QCD
 newdef QtoGQSplitFn:ColourStructure TripletOctetTriplet
 set QtoGQSplitFn:AngularOrdered Yes
+set QtoGQSplitFn:StrictAO Yes
 
 create Herwig::HalfOneHalfSplitFn QtoGammaQSplitFn
 newdef QtoGammaQSplitFn:InteractionType QED
 newdef QtoGammaQSplitFn:ColourStructure ChargedNeutralCharged
 set QtoGammaQSplitFn:AngularOrdered Yes
+set QtoGammaQSplitFn:StrictAO Yes
 
 create Herwig::HalfHalfOneEWSplitFn QtoQWZSplitFn
 newdef QtoQWZSplitFn:InteractionType EW
 newdef QtoQWZSplitFn:ColourStructure EW
+
 #
 # Now the Sudakovs
 create Herwig::PTCutOff PTCutOff
-newdef PTCutOff:pTmin 1.222798*GeV
+newdef PTCutOff:pTmin 0.958*GeV
 
 create Herwig::SudakovFormFactor SudakovCommon
 newdef SudakovCommon:Alpha AlphaQCD
 newdef SudakovCommon:Cutoff PTCutOff
 newdef SudakovCommon:PDFmax 1.0
 
 cp SudakovCommon QtoQGSudakov
 newdef QtoQGSudakov:SplittingFunction QtoQGSplitFn
 newdef QtoQGSudakov:PDFmax 1.9
 
 cp SudakovCommon QtoQGammaSudakov
 set QtoQGammaSudakov:SplittingFunction QtoQGammaSplitFn
 set QtoQGammaSudakov:Alpha AlphaQED
 set QtoQGammaSudakov:PDFmax 1.9
 
 cp QtoQGammaSudakov LtoLGammaSudakov
 cp PTCutOff LtoLGammaPTCutOff
 # Technical parameter to stop evolution.
 set LtoLGammaPTCutOff:pTmin 0.000001
 set LtoLGammaSudakov:Cutoff LtoLGammaPTCutOff
 
 cp SudakovCommon QtoQWZSudakov
 set QtoQWZSudakov:SplittingFunction QtoQWZSplitFn
 set QtoQWZSudakov:Alpha AlphaEW
 set QtoQWZSudakov:PDFmax 1.9
 
 cp QtoQWZSudakov LtoLWZSudakov
 
 cp SudakovCommon GtoGGSudakov
 newdef GtoGGSudakov:SplittingFunction GtoGGSplitFn
 newdef GtoGGSudakov:PDFmax 2.0
 
 cp SudakovCommon WtoWGammaSudakov
 newdef WtoWGammaSudakov:SplittingFunction WtoWGammaSplitFn
 set WtoWGammaSudakov:Alpha AlphaQED
 
 cp SudakovCommon GtoQQbarSudakov
 newdef GtoQQbarSudakov:SplittingFunction GtoQQbarSplitFn
 newdef GtoQQbarSudakov:PDFmax 120.0
 
 cp SudakovCommon GammatoQQbarSudakov
 newdef GammatoQQbarSudakov:SplittingFunction GammatoQQbarSplitFn
 set GammatoQQbarSudakov:Alpha AlphaQED
 newdef GammatoQQbarSudakov:PDFmax 120.0
 
 cp SudakovCommon GtobbbarSudakov
 newdef GtobbbarSudakov:SplittingFunction GtoQQbarSplitFn
 newdef GtobbbarSudakov:PDFmax 40000.0
 
 cp SudakovCommon GtoccbarSudakov
 newdef GtoccbarSudakov:SplittingFunction GtoQQbarSplitFn
 newdef GtoccbarSudakov:PDFmax 2000.0
 
 cp SudakovCommon QtoGQSudakov
 newdef QtoGQSudakov:SplittingFunction QtoGQSplitFn
 
 cp SudakovCommon QtoGammaQSudakov
 newdef QtoGammaQSudakov:SplittingFunction QtoGammaQSplitFn
 set QtoGammaQSudakov:Alpha AlphaQED
 
 cp SudakovCommon utoGuSudakov
 newdef utoGuSudakov:SplittingFunction QtoGQSplitFn
 newdef utoGuSudakov:PDFFactor OverOneMinusZ
 newdef utoGuSudakov:PDFmax 5.0
 
 cp SudakovCommon dtoGdSudakov
 newdef dtoGdSudakov:SplittingFunction QtoGQSplitFn
 newdef dtoGdSudakov:PDFFactor OverOneMinusZ
 
 
 #
 # Now add the final splittings
 #
 do SplittingGenerator:AddFinalSplitting u->u,g; QtoQGSudakov
 do SplittingGenerator:AddFinalSplitting d->d,g; QtoQGSudakov
 do SplittingGenerator:AddFinalSplitting s->s,g; QtoQGSudakov
 do SplittingGenerator:AddFinalSplitting c->c,g; QtoQGSudakov
 do SplittingGenerator:AddFinalSplitting b->b,g; QtoQGSudakov
 do SplittingGenerator:AddFinalSplitting t->t,g; QtoQGSudakov
 #
 do SplittingGenerator:AddFinalSplitting g->g,g; GtoGGSudakov
 #
 do SplittingGenerator:AddFinalSplitting g->u,ubar; GtoQQbarSudakov
 do SplittingGenerator:AddFinalSplitting g->d,dbar; GtoQQbarSudakov
 do SplittingGenerator:AddFinalSplitting g->s,sbar; GtoQQbarSudakov
 do SplittingGenerator:AddFinalSplitting g->c,cbar; GtoccbarSudakov
 do SplittingGenerator:AddFinalSplitting g->b,bbar; GtobbbarSudakov
 do SplittingGenerator:AddFinalSplitting g->t,tbar; GtoQQbarSudakov
 #
 do SplittingGenerator:AddFinalSplitting gamma->u,ubar; GammatoQQbarSudakov
 do SplittingGenerator:AddFinalSplitting gamma->d,dbar; GammatoQQbarSudakov
 do SplittingGenerator:AddFinalSplitting gamma->s,sbar; GammatoQQbarSudakov
 do SplittingGenerator:AddFinalSplitting gamma->c,cbar; GammatoQQbarSudakov
 do SplittingGenerator:AddFinalSplitting gamma->b,bbar; GammatoQQbarSudakov
 do SplittingGenerator:AddFinalSplitting gamma->t,tbar; GammatoQQbarSudakov
 do SplittingGenerator:AddFinalSplitting gamma->e-,e+; GammatoQQbarSudakov
 do SplittingGenerator:AddFinalSplitting gamma->mu-,mu+; GammatoQQbarSudakov
 do SplittingGenerator:AddFinalSplitting gamma->tau-,tau+; GammatoQQbarSudakov
 #
 do SplittingGenerator:AddFinalSplitting u->u,gamma; QtoQGammaSudakov
 do SplittingGenerator:AddFinalSplitting d->d,gamma; QtoQGammaSudakov
 do SplittingGenerator:AddFinalSplitting s->s,gamma; QtoQGammaSudakov
 do SplittingGenerator:AddFinalSplitting c->c,gamma; QtoQGammaSudakov
 do SplittingGenerator:AddFinalSplitting b->b,gamma; QtoQGammaSudakov
 do SplittingGenerator:AddFinalSplitting t->t,gamma; QtoQGammaSudakov
 
 do SplittingGenerator:AddFinalSplitting e-->e-,gamma; LtoLGammaSudakov
 do SplittingGenerator:AddFinalSplitting mu-->mu-,gamma; LtoLGammaSudakov
 do SplittingGenerator:AddFinalSplitting tau-->tau-,gamma; LtoLGammaSudakov
 
 do SplittingGenerator:AddFinalSplitting W+->W+,gamma; WtoWGammaSudakov
 #
 # Now lets add the initial splittings. Remember the form a->b,c; means
 # that the current particle b is given and we backward branch to new
 # particle a which is initial state and new particle c which is final state
 #
 do SplittingGenerator:AddInitialSplitting u->u,g; QtoQGSudakov
 do SplittingGenerator:AddInitialSplitting d->d,g; QtoQGSudakov
 do SplittingGenerator:AddInitialSplitting s->s,g; QtoQGSudakov
 do SplittingGenerator:AddInitialSplitting c->c,g; QtoQGSudakov
 do SplittingGenerator:AddInitialSplitting b->b,g; QtoQGSudakov
 do SplittingGenerator:AddInitialSplitting u->u,gamma; QtoQGammaSudakov
 do SplittingGenerator:AddInitialSplitting d->d,gamma; QtoQGammaSudakov
 do SplittingGenerator:AddInitialSplitting s->s,gamma; QtoQGammaSudakov
 do SplittingGenerator:AddInitialSplitting c->c,gamma; QtoQGammaSudakov
 do SplittingGenerator:AddInitialSplitting b->b,gamma; QtoQGammaSudakov
 do SplittingGenerator:AddInitialSplitting t->t,gamma; QtoQGammaSudakov
 
 do SplittingGenerator:AddInitialSplitting g->g,g; GtoGGSudakov
 #
 do SplittingGenerator:AddInitialSplitting g->d,dbar; GtoQQbarSudakov
 do SplittingGenerator:AddInitialSplitting g->u,ubar; GtoQQbarSudakov
 do SplittingGenerator:AddInitialSplitting g->s,sbar; GtoQQbarSudakov
 do SplittingGenerator:AddInitialSplitting g->c,cbar; GtoccbarSudakov
 do SplittingGenerator:AddInitialSplitting g->b,bbar; GtobbbarSudakov
 #
 do SplittingGenerator:AddInitialSplitting gamma->d,dbar; GammatoQQbarSudakov
 do SplittingGenerator:AddInitialSplitting gamma->u,ubar; GammatoQQbarSudakov
 do SplittingGenerator:AddInitialSplitting gamma->s,sbar; GammatoQQbarSudakov
 do SplittingGenerator:AddInitialSplitting gamma->c,cbar; GammatoQQbarSudakov
 do SplittingGenerator:AddInitialSplitting gamma->b,bbar; GammatoQQbarSudakov
 #
 do SplittingGenerator:AddInitialSplitting d->g,d; dtoGdSudakov
 do SplittingGenerator:AddInitialSplitting u->g,u; utoGuSudakov
 do SplittingGenerator:AddInitialSplitting s->g,s; QtoGQSudakov
 do SplittingGenerator:AddInitialSplitting c->g,c; QtoGQSudakov
 do SplittingGenerator:AddInitialSplitting b->g,b; QtoGQSudakov
 do SplittingGenerator:AddInitialSplitting dbar->g,dbar; dtoGdSudakov
 do SplittingGenerator:AddInitialSplitting ubar->g,ubar; utoGuSudakov
 do SplittingGenerator:AddInitialSplitting sbar->g,sbar; QtoGQSudakov
 do SplittingGenerator:AddInitialSplitting cbar->g,cbar; QtoGQSudakov
 do SplittingGenerator:AddInitialSplitting bbar->g,bbar; QtoGQSudakov
 #
 do SplittingGenerator:AddInitialSplitting d->gamma,d; QtoGammaQSudakov
 do SplittingGenerator:AddInitialSplitting u->gamma,u; QtoGammaQSudakov
 do SplittingGenerator:AddInitialSplitting s->gamma,s; QtoGammaQSudakov
 do SplittingGenerator:AddInitialSplitting c->gamma,c; QtoGammaQSudakov
 do SplittingGenerator:AddInitialSplitting b->gamma,b; QtoGammaQSudakov
 do SplittingGenerator:AddInitialSplitting dbar->gamma,dbar; QtoGammaQSudakov
 do SplittingGenerator:AddInitialSplitting ubar->gamma,ubar; QtoGammaQSudakov
 do SplittingGenerator:AddInitialSplitting sbar->gamma,sbar; QtoGammaQSudakov
 do SplittingGenerator:AddInitialSplitting cbar->gamma,cbar; QtoGammaQSudakov
 do SplittingGenerator:AddInitialSplitting bbar->gamma,bbar; QtoGammaQSudakov
 
 #
 #  Electroweak
 #
 do SplittingGenerator:AddFinalSplitting u->u,Z0; QtoQWZSudakov
 do SplittingGenerator:AddFinalSplitting d->d,Z0; QtoQWZSudakov
 do SplittingGenerator:AddFinalSplitting s->s,Z0; QtoQWZSudakov
 do SplittingGenerator:AddFinalSplitting c->c,Z0; QtoQWZSudakov
 do SplittingGenerator:AddFinalSplitting b->b,Z0; QtoQWZSudakov
 do SplittingGenerator:AddFinalSplitting t->t,Z0; QtoQWZSudakov
 do SplittingGenerator:AddInitialSplitting u->u,Z0; QtoQWZSudakov
 do SplittingGenerator:AddInitialSplitting d->d,Z0; QtoQWZSudakov
 do SplittingGenerator:AddInitialSplitting s->s,Z0; QtoQWZSudakov
 do SplittingGenerator:AddInitialSplitting c->c,Z0; QtoQWZSudakov
 do SplittingGenerator:AddInitialSplitting b->b,Z0; QtoQWZSudakov
 do SplittingGenerator:AddInitialSplitting t->t,Z0; QtoQWZSudakov
 
 do SplittingGenerator:AddFinalSplitting u->d,W+; QtoQWZSudakov
 do SplittingGenerator:AddFinalSplitting c->s,W+; QtoQWZSudakov
 do SplittingGenerator:AddFinalSplitting d->u,W-; QtoQWZSudakov
 do SplittingGenerator:AddFinalSplitting s->c,W-; QtoQWZSudakov
 do SplittingGenerator:AddInitialSplitting u->d,W+; QtoQWZSudakov
 do SplittingGenerator:AddInitialSplitting c->s,W+; QtoQWZSudakov
 do SplittingGenerator:AddInitialSplitting d->u,W-; QtoQWZSudakov
 do SplittingGenerator:AddInitialSplitting s->c,W-; QtoQWZSudakov
 
 
diff --git a/src/snippets/EvolutionScheme-DotProduct-Veto.in b/src/snippets/EvolutionScheme-DotProduct-Veto.in
new file mode 100644
--- /dev/null
+++ b/src/snippets/EvolutionScheme-DotProduct-Veto.in
@@ -0,0 +1,18 @@
+# -*- ThePEG-repository -*-
+#
+#  Settings for the dot product preserving tune with veto of arXiv:1904.11866
+#  http://inspirehep.net/record/1731587
+#
+# dot product scheme
+set /Herwig/Shower/PowhegShowerHandler:EvolutionScheme DotProduct
+set /Herwig/Shower/ShowerHandler:EvolutionScheme DotProduct
+set /Herwig/Shower/KinematicsReconstructor:FinalFinalWeight Yes
+# don't enforce strict angular ordering
+set /Herwig/Shower/QtoQGammaSplitFn:StrictAO Yes
+set /Herwig/Shower/QtoQGSplitFn:StrictAO Yes
+set /Herwig/Shower/GtoGGSplitFn:StrictAO Yes
+set /Herwig/Shower/WtoWGammaSplitFn:StrictAO Yes
+set /Herwig/Shower/GtoQQbarSplitFn:StrictAO Yes
+set /Herwig/Shower/GammatoQQbarSplitFn:StrictAO Yes
+set /Herwig/Shower/QtoGQSplitFn:StrictAO Yes
+set /Herwig/Shower/QtoGammaQSplitFn:StrictAO Yes
diff --git a/src/snippets/EvolutionScheme-DotProduct.in b/src/snippets/EvolutionScheme-DotProduct.in
new file mode 100644
--- /dev/null
+++ b/src/snippets/EvolutionScheme-DotProduct.in
@@ -0,0 +1,18 @@
+# -*- ThePEG-repository -*-
+#
+#  Settings for the dot-product preserving evolution scheme of arXiv:1904.11866
+#  http://inspirehep.net/record/1731587
+#
+# dot-product scheme
+set /Herwig/Shower/PowhegShowerHandler:EvolutionScheme DotProduct
+set /Herwig/Shower/ShowerHandler:EvolutionScheme DotProduct
+set /Herwig/Shower/KinematicsReconstructor:FinalFinalWeight No
+# don't enforce strict angular ordering
+set /Herwig/Shower/QtoQGammaSplitFn:StrictAO Yes
+set /Herwig/Shower/QtoQGSplitFn:StrictAO Yes
+set /Herwig/Shower/GtoGGSplitFn:StrictAO Yes
+set /Herwig/Shower/WtoWGammaSplitFn:StrictAO Yes
+set /Herwig/Shower/GtoQQbarSplitFn:StrictAO Yes
+set /Herwig/Shower/GammatoQQbarSplitFn:StrictAO Yes
+set /Herwig/Shower/QtoGQSplitFn:StrictAO Yes
+set /Herwig/Shower/QtoGammaQSplitFn:StrictAO Yes
diff --git a/src/snippets/EvolutionScheme-Q2.in b/src/snippets/EvolutionScheme-Q2.in
new file mode 100644
--- /dev/null
+++ b/src/snippets/EvolutionScheme-Q2.in
@@ -0,0 +1,18 @@
+# -*- ThePEG-repository -*-
+#
+#  Settings for the q^2 preserving tune of arXiv:1904.11866
+#  http://inspirehep.net/record/1731587
+#
+# q^2 scheme
+set /Herwig/Shower/PowhegShowerHandler:EvolutionScheme Q2
+set /Herwig/Shower/ShowerHandler:EvolutionScheme Q2
+set /Herwig/Shower/KinematicsReconstructor:FinalFinalWeight No
+# don't enforce strict angular ordering
+set /Herwig/Shower/QtoQGammaSplitFn:StrictAO No
+set /Herwig/Shower/QtoQGSplitFn:StrictAO No
+set /Herwig/Shower/GtoGGSplitFn:StrictAO No
+set /Herwig/Shower/WtoWGammaSplitFn:StrictAO No
+set /Herwig/Shower/GtoQQbarSplitFn:StrictAO No
+set /Herwig/Shower/GammatoQQbarSplitFn:StrictAO No
+set /Herwig/Shower/QtoGQSplitFn:StrictAO No
+set /Herwig/Shower/QtoGammaQSplitFn:StrictAO No
diff --git a/src/snippets/EvolutionScheme-pT.in b/src/snippets/EvolutionScheme-pT.in
new file mode 100644
--- /dev/null
+++ b/src/snippets/EvolutionScheme-pT.in
@@ -0,0 +1,18 @@
+# -*- ThePEG-repository -*-
+#
+#  Settings for the pT preserving tune of arXiv:1904.11866
+#  http://inspirehep.net/record/1731587
+#
+# pT scheme
+set /Herwig/Shower/PowhegShowerHandler:EvolutionScheme pT
+set /Herwig/Shower/ShowerHandler:EvolutionScheme pT
+set /Herwig/Shower/KinematicsReconstructor:FinalFinalWeight No
+# don't enforce strict angular ordering
+set /Herwig/Shower/QtoQGammaSplitFn:StrictAO No
+set /Herwig/Shower/QtoQGSplitFn:StrictAO No
+set /Herwig/Shower/GtoGGSplitFn:StrictAO No
+set /Herwig/Shower/WtoWGammaSplitFn:StrictAO No
+set /Herwig/Shower/GtoQQbarSplitFn:StrictAO No
+set /Herwig/Shower/GammatoQQbarSplitFn:StrictAO No
+set /Herwig/Shower/QtoGQSplitFn:StrictAO No
+set /Herwig/Shower/QtoGammaQSplitFn:StrictAO No
diff --git a/src/snippets/Makefile.am b/src/snippets/Makefile.am
--- a/src/snippets/Makefile.am
+++ b/src/snippets/Makefile.am
@@ -1,41 +1,49 @@
 BUILT_SOURCES = done-all-links
 
 snippetsdir = ${pkgdatadir}/snippets
 
 INPUTFILES = \
 CellGridSampler.in \
 Diffraction.in \
 DipoleMerging.in \
 DipoleShowerFiveFlavours.in \
 DipoleShowerFourFlavours.in \
 EECollider.in \
 EPCollider.in \
 HepMCFixedOrder.in \
 HepMC.in \
 Matchbox.in \
 MB-DipoleShower.in \
 MB.in \
 MonacoSampler.in \
 Particles-SetLonglivedParticlesStable.in \
 PDF-CT10.in \
 PDF-NNPDF30NLO.in \
 PPCollider.in \
 RivetFixedOrder.in \
 Rivet.in \
 SoftModel.in \
 SoftTune.in \
 YFS.in \
 BaryonicReconnection.in \
 CMWinQtiledShower.in \
-Dipole_AutoTune_prel.in
+Dipole_AutoTune_prel.in \
+Tune-DotProduct.in  \
+Tune-DotProduct-Veto.in  \
+Tune-pT.in  \
+Tune-Q2.in \
+EvolutionScheme-DotProduct.in  \
+EvolutionScheme-DotProduct-Veto.in  \
+EvolutionScheme-pT.in  \
+EvolutionScheme-Q2.in
 
 dist_snippets_DATA = $(INPUTFILES)
 
 CLEANFILES = done-all-links
 
 done-all-links: $(INPUTFILES)
 	@echo "Linking input files"
 	@for i in $(INPUTFILES); do \
 	if test -f $(srcdir)/$$i -a ! -e $$i; then \
 	$(LN_S) -f $(srcdir)/$$i; fi; done
 	@touch done-all-links
diff --git a/src/snippets/Tune-DotProduct-Veto.in b/src/snippets/Tune-DotProduct-Veto.in
new file mode 100644
--- /dev/null
+++ b/src/snippets/Tune-DotProduct-Veto.in
@@ -0,0 +1,25 @@
+# -*- ThePEG-repository -*-
+#
+#  Settings for the dot product preserving tune with veto of arXiv:1904.11866
+#  http://inspirehep.net/record/1731587
+#
+# dot-product scheme
+read snippets/EvolutionScheme-DotProduct-Veto.in
+# parameters of the tune
+set /Herwig/Shower/AlphaQCD:AlphaIn                                0.1186
+set /Herwig/Shower/PTCutOff:pTmin                                  0.958
+set /Herwig/Hadronization/ClusterFissioner:ClMaxLight              3.649
+set /Herwig/Hadronization/ClusterFissioner:ClPowLight              2.780
+set /Herwig/Hadronization/ClusterFissioner:PSplitLight 		   0.899
+set /Herwig/Hadronization/HadronSelector:PwtSquark     		   0.700
+set /Herwig/Hadronization/HadronSelector:PwtDIquark    		   0.298
+set /Herwig/Hadronization/ClusterFissioner:ClMaxCharm              3.950
+set /Herwig/Hadronization/ClusterFissioner:ClPowCharm 		   2.559
+set /Herwig/Hadronization/ClusterFissioner:PSplitCharm		   0.994
+set /Herwig/Hadronization/ClusterDecayer:ClSmrCharm  		   0.163
+set /Herwig/Hadronization/HadronSelector:SingleHadronLimitCharm	   0.000
+set /Herwig/Hadronization/ClusterFissioner:ClMaxBottom             3.757
+set /Herwig/Hadronization/ClusterFissioner:ClPowBottom 		   0.547
+set /Herwig/Hadronization/ClusterFissioner:PSplitBottom		   0.625
+set /Herwig/Hadronization/ClusterDecayer:ClSmrBottom  		   0.078
+set /Herwig/Hadronization/HadronSelector:SingleHadronLimitBottom   0.000
diff --git a/src/snippets/Tune-DotProduct.in b/src/snippets/Tune-DotProduct.in
new file mode 100644
--- /dev/null
+++ b/src/snippets/Tune-DotProduct.in
@@ -0,0 +1,25 @@
+# -*- ThePEG-repository -*-
+#
+#  Settings for the dot-product preserving tune of arXiv:1904.11866
+#  http://inspirehep.net/record/1731587
+#
+# dot-product scheme
+read snippets/EvolutionScheme-DotProduct.in
+# parameters of the tune
+set /Herwig/Shower/AlphaQCD:AlphaIn                                0.1136
+set /Herwig/Shower/PTCutOff:pTmin                                  0.924
+set /Herwig/Hadronization/ClusterFissioner:ClMaxLight              3.653
+set /Herwig/Hadronization/ClusterFissioner:ClPowLight              2.000
+set /Herwig/Hadronization/ClusterFissioner:PSplitLight 		   0.935
+set /Herwig/Hadronization/HadronSelector:PwtSquark     		   0.650
+set /Herwig/Hadronization/HadronSelector:PwtDIquark    		   0.306
+set /Herwig/Hadronization/ClusterFissioner:ClMaxCharm              3.796
+set /Herwig/Hadronization/ClusterFissioner:ClPowCharm 		   2.235
+set /Herwig/Hadronization/ClusterFissioner:PSplitCharm		   0.990
+set /Herwig/Hadronization/ClusterDecayer:ClSmrCharm  		   0.139
+set /Herwig/Hadronization/HadronSelector:SingleHadronLimitCharm	   0.000
+set /Herwig/Hadronization/ClusterFissioner:ClMaxBottom             6.000
+set /Herwig/Hadronization/ClusterFissioner:ClPowBottom 		   0.680
+set /Herwig/Hadronization/ClusterFissioner:PSplitBottom		   0.550
+set /Herwig/Hadronization/ClusterDecayer:ClSmrBottom  		   0.105
+set /Herwig/Hadronization/HadronSelector:SingleHadronLimitBottom   0.000
diff --git a/src/snippets/Tune-Q2.in b/src/snippets/Tune-Q2.in
new file mode 100644
--- /dev/null
+++ b/src/snippets/Tune-Q2.in
@@ -0,0 +1,25 @@
+# -*- ThePEG-repository -*-
+#
+#  Settings for the q^2 preserving tune of arXiv:1904.11866
+#  http://inspirehep.net/record/1731587
+#
+# q^2 scheme
+read snippets/EvolutionScheme-Q2.in
+# parameters of the tune
+set /Herwig/Shower/AlphaQCD:AlphaIn                                0.1244
+set /Herwig/Shower/PTCutOff:pTmin                                  1.136
+set /Herwig/Hadronization/ClusterFissioner:ClMaxLight              3.141
+set /Herwig/Hadronization/ClusterFissioner:ClPowLight              1.353
+set /Herwig/Hadronization/ClusterFissioner:PSplitLight 		   0.831
+set /Herwig/Hadronization/HadronSelector:PwtSquark     		   0.737
+set /Herwig/Hadronization/HadronSelector:PwtDIquark    		   0.383
+set /Herwig/Hadronization/ClusterFissioner:ClMaxCharm              3.564
+set /Herwig/Hadronization/ClusterFissioner:ClPowCharm 		   2.089
+set /Herwig/Hadronization/ClusterFissioner:PSplitCharm		   0.928
+set /Herwig/Hadronization/ClusterDecayer:ClSmrCharm  		   0.141
+set /Herwig/Hadronization/HadronSelector:SingleHadronLimitCharm	   0.011
+set /Herwig/Hadronization/ClusterFissioner:ClMaxBottom             2.900
+set /Herwig/Hadronization/ClusterFissioner:ClPowBottom 		   0.518
+set /Herwig/Hadronization/ClusterFissioner:PSplitBottom		   0.365
+set /Herwig/Hadronization/ClusterDecayer:ClSmrBottom  		   0.070
+set /Herwig/Hadronization/HadronSelector:SingleHadronLimitBottom   0.000
diff --git a/src/snippets/Tune-pT.in b/src/snippets/Tune-pT.in
new file mode 100644
--- /dev/null
+++ b/src/snippets/Tune-pT.in
@@ -0,0 +1,25 @@
+# -*- ThePEG-repository -*-
+#
+#  Settings for the pT preserving tune of arXiv:1904.11866
+#  http://inspirehep.net/record/1731587
+#
+# pT scheme
+read snippets/EvolutionScheme-pT.in
+# parameters of the tune
+set /Herwig/Shower/AlphaQCD:AlphaIn                                0.1074
+set /Herwig/Shower/PTCutOff:pTmin                                  0.900
+set /Herwig/Hadronization/ClusterFissioner:ClMaxLight              4.204
+set /Herwig/Hadronization/ClusterFissioner:ClPowLight              3.000
+set /Herwig/Hadronization/ClusterFissioner:PSplitLight 		   0.914
+set /Herwig/Hadronization/HadronSelector:PwtSquark     		   0.647
+set /Herwig/Hadronization/HadronSelector:PwtDIquark    		   0.236
+set /Herwig/Hadronization/ClusterFissioner:ClMaxCharm              4.204
+set /Herwig/Hadronization/ClusterFissioner:ClPowCharm 		   3.000
+set /Herwig/Hadronization/ClusterFissioner:PSplitCharm		   1.060
+set /Herwig/Hadronization/ClusterDecayer:ClSmrCharm  		   0.098
+set /Herwig/Hadronization/HadronSelector:SingleHadronLimitCharm	   0.000
+set /Herwig/Hadronization/ClusterFissioner:ClMaxBottom             5.757
+set /Herwig/Hadronization/ClusterFissioner:ClPowBottom 		   0.672
+set /Herwig/Hadronization/ClusterFissioner:PSplitBottom		   0.557
+set /Herwig/Hadronization/ClusterDecayer:ClSmrBottom  		   0.117
+set /Herwig/Hadronization/HadronSelector:SingleHadronLimitBottom   0.000