diff --git a/.hgtags b/.hgtags
--- a/.hgtags
+++ b/.hgtags
@@ -1,23 +1,24 @@
 168ae2110e964d62fbc1331a1c2e095952a67748 release-2-5-2
 3abb4fa42e20e332796c2572334c2d77204cd0e0 release-2-4-2
 4796ca080aafd5daa3b7349b015cb1df944428a2 release-2-5-0
 76da042f056eb153981b4d005d5474ffb90a5e88 release-2-4-1
 81a684a558413c69df314365eabf09893ffd43d8 release-2-6-0
 bd75cd00d99f4bdbaed992daf98f0a73c0f91e9b release-2-4-0
 ff6ecc8d49ce10299303b050394bd5cb5837f1c3 release-2-5-1
 d0389f5453b2c210923e1adc7b872b18269de668 release-2-6-1
 f8998033021185942533b824607285feb3fbd2dc release-2-6-1a
 cead23e428b9aacaf2d709e722624e54f844498b release-2-6-1b
 191db4655439045f912cb21bd905e729d59ec7bc release-2-6-2
 edb538156e9c3d64bb842934b4cebf0126aeb9ea release-2-6-3
 eb4a104591859ecac18746b1ad54d6aa0c2a5d1a release-2-7-0
 568971ac5b3c1d044c9259f2280a8304fc5a62e9 trunk-before-QED
 6e3edb6cfeb4ee48687eb4eb3d016026fc59d602 trunk-after-QED
 633abb80b571aa23088957df60e9b0000bbb8a22 release-2-7-1
 1bdde095d2346c15ee548e5406a96f0fc6d6e0f1 beforeHQ
 a0f9fb821396092bdbeee532bcb0bd624f58335b before_MB_merge
 270c1e6b34aa7f758f1d9868c4d3e1ec4bf4e709 herwig-7-0-0
 6e0f198c1c2603ecd1a0b6cfe40105cda4bd58c5 herwig-7-0-1
 566c1de845a8070559cda45b1bdb40afa18cb2cc herwig-7-0-2
 f5c4aa956880f2def763ebd57de7b5bfa55cb1db herwig-7-0-3
 65282dedfc2e4bec184e68678dbf4c553c968f38 herwig-7-0-4
+541e7790b65ed423c86780bf66ec30e6b99b5a18 herwig-7-1-0
diff --git a/API/Makefile.am b/API/Makefile.am
--- a/API/Makefile.am
+++ b/API/Makefile.am
@@ -1,12 +1,12 @@
 pkglib_LTLIBRARIES = libHerwigAPI.la
 
 
 libHerwigAPI_la_SOURCES = \
 RunDirectories.h RunDirectories.cc HerwigAPI.h HerwigAPI.cc \
 HerwigUI.h
 
-libHerwigAPI_la_LDFLAGS = $(AM_LDFLAGS) -version-info 1:0:0
+libHerwigAPI_la_LDFLAGS = $(AM_LDFLAGS) -version-info 2:0:0
 libHerwigAPI_la_CPPFLAGS = $(AM_CPPFLAGS) \
 -DHERWIG_PKGDATADIR="\"$(pkgdatadir)\"" \
 -DHERWIG_PKGLIBDIR="\"$(pkglibdir)\"" \
 -DTHEPEG_PKGLIBDIR="\"$(THEPEGLIBPATH)\""
diff --git a/AUTHORS b/AUTHORS
--- a/AUTHORS
+++ b/AUTHORS
@@ -1,57 +1,56 @@
 ================================================================================
-Herwig 7.0.4
+Herwig 7.1.0
 ================================================================================
 
 Please contact <herwig@projects.hepforge.org> for any queries.
 
 --------------------------------------------------------------------------------
 Herwig is actively developed by:
 --------------------------------------------------------------------------------
 
 Johannes Bellm
 Stefan Gieseke
 David Grellscheid
+Patrick Kirchgaeßer
+Frashër Loshaj
+Graeme Nail
+Andreas Papaefstathiou
 Simon Plätzer
+Radek Podskubka
 Michael Rauch
 Christian Reuschle
 Peter Richardson
 Peter Schichtel
 Mike Seymour
 Andrzej Siödmok
 Stephen Webster
-Alix Wilcock
 
---------------------------------------------------------------------------------
-With contributions by:
---------------------------------------------------------------------------------
-
-Nadine Fischer
-Marco A. Harrendorf
-Graeme Nail
-Andreas Papaefstathiou
-Daniel Rauch
 
 --------------------------------------------------------------------------------
 Former authors are:
 --------------------------------------------------------------------------------
 
 Ken Arnold
 Manuel Bähr
 Luca d'Errico
 Martyn Gigg
+Nadine Fischer
 Keith Hamilton
+Marco A. Harrendorf
 Seyi Latunde-Dada
+Daniel Rauch
 Alberto Ribon
 Christian Röhr
 Pavel Růžička
 Alex Schofield
 Thomas Schuh
 Alexander Sherstnev
 Philip Stephens
 Martin Stoll
 Louise Suter
 Jon Tully
 Bryan Webber
+Alix Wilcock
 David Winn
 Benedikt Zimmermann
 
diff --git a/Analysis/BELLECharmAnalysis.cc b/Analysis/BELLECharmAnalysis.cc
deleted file mode 100644
--- a/Analysis/BELLECharmAnalysis.cc
+++ /dev/null
@@ -1,864 +0,0 @@
-// -*- C++ -*-
-//
-// BELLECharmAnalysis.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 BELLECharmAnalysis class.
-//
-
-#include "BELLECharmAnalysis.h"
-#include "ThePEG/PDT/EnumParticles.h"
-#include "ThePEG/Interface/Switch.h"
-#include "ThePEG/Interface/ClassDocumentation.h"
-#include "ThePEG/Persistency/PersistentOStream.h"
-#include "ThePEG/Persistency/PersistentIStream.h"
-#include "ThePEG/EventRecord/Event.h"
-#include "ThePEG/Repository/CurrentGenerator.h"
-
-using namespace Herwig;
-
-void BELLECharmAnalysis::analyze(tEventPtr event, long, int, int) {
-  _weight = event->weight();
-  _s = (event->incoming().first ->momentum()+
-	event->incoming().second->momentum()).m2();  
-  set<tPPtr> particles;
-  StepVector steps = event->primaryCollision()->steps();
-  for ( StepVector::const_iterator it = steps.begin()+2;
-	it != steps.end(); ++it ) {
-    (**it).select(inserter(particles), ThePEG::AllSelector());
-  }
-  tPVector output;
-  for(set<tPPtr>::const_iterator it = particles.begin(); 
-      it != particles.end(); ++it) {
-    long id = abs((*it)->id());
-    if(id==ParticleID::Dplus   || id==ParticleID::Dstarplus    ||
-       id==ParticleID::D0      || id==ParticleID::Dstar0       || 
-       id==ParticleID::D_splus || id==ParticleID::Lambda_cplus )
-      output.push_back(*it);
-  }
-  analyze(output);
-}
-
-void BELLECharmAnalysis::analyze(const tPVector & particles) {
-  for(unsigned int ix=0;ix<particles.size();++ix) analyze(particles[ix]);
-}
-
-void BELLECharmAnalysis::analyze(tPPtr particle) {
-  double xp = particle->momentum().vect().mag()/
-    sqrt(0.25*_s-sqr(particle->mass()));
-  int id = abs(particle->id());
-  if(id==ParticleID::Dstarplus) {
-    _histDstarplus  ->addWeighted( xp,_weight);
-    _statDstar      += _weight;
-  }
-  else if(id==ParticleID::Dstar0) {
-    _histDstar0     ->addWeighted( xp,_weight);
-    _statDstar      += _weight;
-  }
-  else if(id==ParticleID::D0) {
-    _histD0         ->addWeighted( xp,_weight);
-    _statD          += _weight;
-  }
-  else if(id==ParticleID::Dplus) {
-    _histDplus      ->addWeighted( xp,_weight);
-    _statD          += _weight;
-  }
-  else if(id==ParticleID::D_splus) {
-    _histDs         ->addWeighted( xp,_weight);
-    _statDs         += _weight;
-  }
-  else if(id==ParticleID::Lambda_cplus) {
-    _histLambda     ->addWeighted( xp,_weight);
-    _statLambda     += _weight;
-  }
-}
-
-void BELLECharmAnalysis::persistentOutput(PersistentOStream & os) const {
-  os << _onshell;
-}
-
-void BELLECharmAnalysis::persistentInput(PersistentIStream & is, int) {
-  is >> _onshell;
-}
-
-ClassDescription<BELLECharmAnalysis> BELLECharmAnalysis::initBELLECharmAnalysis;
-// Definition of the static class description member.
-
-void BELLECharmAnalysis::Init() {
-
-  static ClassDocumentation<BELLECharmAnalysis> documentation
-    ("The BELLECharmAnalysis class implements the analysis of hep-ex/0506068",
-     "The results of Herwig were compared with the data of the Belle collaboration"
-     "\\cite{Seuster:2005tr} on charm fragmentation functions.",
-     "\\bibitem{Seuster:2005tr} R.~Seuster {\\it et al.}  [Belle Collaboration],"
-     "Phys.\\ Rev.\\  D {\\bf 73} (2006) 032002 [arXiv:hep-ex/0506068].\n"
-     "%%CITATION = PHRVA,D73,032002;%%\n");
-
-  static Switch<BELLECharmAnalysis,bool> interfaceResonance
-    ("Resonance",
-     "Whether we are doing Upsilon(4S)->B,B or continuum production",
-     &BELLECharmAnalysis::_onshell, false, false, false);
-  static SwitchOption interfaceResonanceContinuum
-    (interfaceResonance,
-     "Continuum",
-     "Continuum production",
-     false);
-  static SwitchOption interfaceResonanceUpsilon4S
-    (interfaceResonance,
-     "Upsilon4S",
-     "At Upsilon(4S) resonance",
-     true);
-}
-
-void BELLECharmAnalysis::dofinish() {
-  useMe();
-  AnalysisHandler::dofinish();
-  string fname = generator()->filename() + 
-    string("-") + name() + string(".top");
-  ofstream output(fname.c_str());
-  using namespace HistogramOptions;
-  double chisq=0.,minfrac=0.05;
-  unsigned int ndegrees;
-  _histDstarplus->chiSquared(chisq,ndegrees,minfrac);
-  generator()->log() << "Chi Square = " << chisq << " for " << ndegrees 
-			  << " degrees of freedom for BELLE D*+ distribution\n";
-  _histDstar0   ->chiSquared(chisq,ndegrees,minfrac);
-  generator()->log() << "Chi Square = " << chisq << " for " << ndegrees 
-			  << " degrees of freedom for BELLE D*0 distribution\n";
-  _histD0       ->chiSquared(chisq,ndegrees,minfrac);
-  generator()->log() << "Chi Square = " << chisq << " for " << ndegrees 
-			  << " degrees of freedom for BELLE D0 distribution\n";
-  _histDplus    ->chiSquared(chisq,ndegrees,minfrac);
-  generator()->log() << "Chi Square = " << chisq << " for " << ndegrees 
-			  << " degrees of freedom for BELLE D+ distribution\n";
-  _histDs       ->chiSquared(chisq,ndegrees,minfrac);
-  generator()->log() << "Chi Square = " << chisq << " for " << ndegrees 
-			  << " degrees of freedom for BELLE D_s+ distribution\n";
-  _histLambda   ->chiSquared(chisq,ndegrees,minfrac);
-  generator()->log() << "Chi Square = " << chisq << " for " << ndegrees 
-			  << " degrees of freedom for BELLE Lambda_c+ distribution\n";
-  _histDstarplus->topdrawOutput(output,Frame|Errorbars,
-				"RED",
-				"D2*+3",
-				" X  X",
-				"1/SdS/dx0p1",
-				"  G G   X X",
-				"x0p1",
-				" X X");
-  _histDstar0->topdrawOutput(output,Frame|Errorbars,
-			     "RED",
-			     "D2*03",
-			     " X  X",
-			     "1/SdS/dx0p1",
-			     "  G G   X X",
-			     "x0p1",
-			     " X X");
-  _histD0->topdrawOutput(output,Frame|Errorbars,
-			 "RED",
-			 "D203",
-			 " X X",
-			 "1/SdS/dx0p1",
-			 "  G G   X X",
-			 "x0p1",
-			 " X X");
-  _histDplus->topdrawOutput(output,Frame|Errorbars,
-			    "RED",
-			    "D2+3",
-			    " X X",
-			    "1/SdS/dx0p1",
-			    "  G G   X X",
-			    "x0p1",
-			    " X X");
-  _histDs->topdrawOutput(output,Frame|Errorbars,
-			 "RED",
-			 "D0s12+3",
-			 " X XX X",
-			 "1/SdS/dx0p1",
-			 "  G G   X X",
-			 "x0p1",
-			 " X X");
-  _histLambda->topdrawOutput(output,Frame|Errorbars,
-			     "RED",
-			     "L0c12+3",
-			     "FX XX X",
-			     "1/SdS/dx0p1",
-			     "  G G   X X",
-			     "x0p1",
-			     " X X");
-  // and the ratios
-  double denom1 = _statD.total();
-  double denom2 = denom1+_statDs.total();
-  double data[3] ={_statDstar .total()/denom1,
-		   _statDs    .total()/denom2,
-		   _statLambda.total()/denom2};
-  double derror[3] = {data[0]*sqrt(1./denom1+1./_statDstar .total()),
-		      data[1]*sqrt(1./denom2+1./_statDs    .total()),
-		      data[2]*sqrt(1./denom2+1./_statLambda.total())};
-  double ratio[3]={0.527,0.099,0.081};
-  double error[3]={0.027,0.004,0.004};
-  for(unsigned int ix=0;ix<3;++ix) {
-    double chisq = sqr(data[ix]-ratio[ix])/(sqr(derror[ix])+sqr(error[ix]));
-    generator()->log() << "Chi Square = " << chisq 
-			    << " for 1 degree of freedon for BELLE ";
-    if(ix==0) {
-      generator()->log() << "Ratio of D*/D = ";
-    }
-    else if(ix==1) {
-      generator()->log() << "Ratio of D_s/D = ";
-    }
-    else if(ix==2) {
-      generator()->log() << "Ratio of Lambda_c/D = ";
-    }  
-    generator()->log() << "Hw++ = " << data[ix]  << " +/- " << derror[ix] << "\t"
-			    << "Exp = "  << ratio[ix] << " +/- " << error[ix]  << "\n";
-  }
-}
-
-void BELLECharmAnalysis::doinitrun() {
-  AnalysisHandler::doinitrun();
-  // the bin sizes (same for all the plots)
-  double vals[]={0.00,0.02,0.04,0.06,0.08,0.10,0.12,0.14,0.16,0.18,
-		 0.20,0.22,0.24,0.26,0.28,0.30,0.32,0.34,0.36,0.38,
-		 0.40,0.42,0.44,0.46,0.48,0.50,0.52,0.54,0.56,0.58,
-		 0.60,0.62,0.64,0.66,0.68,0.70,0.72,0.74,0.76,0.78,
-		 0.80,0.82,0.84,0.86,0.88,0.90,0.92,0.94,0.96,0.98,
-		 1.00,1.02,1.04,1.06,1.08,1.10,1.12,1.14,1.16,1.18,
-		 1.20};
-  // the data and errors for D*+
-  // continuum
-  double DstarContAdata []={0.0000  ,0.0000  ,0.0000  ,0.0000  ,0.1086  ,
-			    0.0920  ,0.2600  ,0.1734  ,0.2212  ,0.4413  ,
-			    0.3998  ,0.5073  ,0.6654  ,0.7496  ,1.0015  ,
-			    0.8738  ,1.2712  ,1.2758  ,1.5916  ,1.7495  ,
-			    1.9353  ,2.1832  ,2.3189  ,2.5587  ,2.8917  ,
-			    3.0588  ,3.2292  ,3.4595  ,3.7583  ,3.9273  ,
-			    3.8202  ,3.8493  ,3.8297  ,3.7796  ,3.7061  ,
-			    3.4861  ,3.3356  ,3.2040  ,2.9714  ,2.7053  ,
-			    2.4643  ,2.2032  ,1.9259  ,1.7746  ,1.5298  ,
-			    1.2213  ,0.9208  ,0.7591  ,0.5077  ,0.3008  ,
-			    0.0752  ,0.0000  ,0.0007  ,0.0003  ,0.0003  ,
-			    0.0000  ,0.0000  ,0.0004  ,0.0007  ,0.0000  };
-  double DstarContAerror[]={0.0000  ,0.0000  ,0.0000  ,0.0000  ,0.0945  ,
-			    0.0651  ,0.0782  ,0.0672  ,0.0559  ,0.0606  ,
-			    0.0703  ,0.0802  ,0.1147  ,0.1003  ,0.0519  ,
-			    0.0818  ,0.0591  ,0.0688  ,0.0608  ,0.0508  ,
-			    0.0770  ,0.0695  ,0.1046  ,0.0685  ,0.0827  ,
-			    0.0743  ,0.0942  ,0.0873  ,0.0777  ,0.0740  ,
-			    0.0854  ,0.0804  ,0.0694  ,0.0720  ,0.0725  ,
-			    0.0738  ,0.0674  ,0.0712  ,0.0533  ,0.0598  ,
-			    0.0595  ,0.0542  ,0.0582  ,0.0470  ,0.0481  ,
-			    0.0491  ,0.0377  ,0.0343  ,0.0412  ,0.0287  ,
-			    0.0096  ,0.0000  ,0.0007  ,0.0000  ,0.0000  ,
-			    0.0000  ,0.0000  ,0.0001  ,0.0007  ,0.0000  };
-  double DstarContAsyst []={0.0000  ,0.0000  ,0.0000  ,0.0000  ,0.1089  ,
-			    0.1010  ,0.1116  ,0.0260  ,0.0331  ,0.0470  ,
-			    0.0298  ,0.1081  ,0.0374  ,0.0403  ,0.0775  ,
-			    0.0257  ,0.0770  ,0.0456  ,0.0729  ,0.0675  ,
-			    0.0668  ,0.0638  ,0.0705  ,0.0760  ,0.1014  ,
-			    0.0834  ,0.1208  ,0.1058  ,0.1048  ,0.1141  ,
-			    0.1179  ,0.1175  ,0.1137  ,0.1305  ,0.1276  ,
-			    0.0944  ,0.1488  ,0.0804  ,0.1300  ,0.0827  ,
-			    0.0611  ,0.0556  ,0.0498  ,0.0503  ,0.0384  ,
-			    0.0339  ,0.0235  ,0.0210  ,0.0177  ,0.0221  ,
-			    0.0212  ,0.0000  ,0.0005  ,0.0004  ,0.0003  ,
-			    0.0000  ,0.0002  ,0.0003  ,0.0004  ,0.0000};
-  double DstarContBdata []={0.0023  ,0.0192  ,0.1091  ,0.0119  ,0.2982  ,
-			    0.1810  ,0.5365  ,0.5271  ,0.4393  ,0.5188  ,
-			    1.2347  ,0.9356  ,1.2284  ,1.3936  ,1.6509  ,
-			    1.5206  ,1.0046  ,1.5886  ,1.5468  ,2.4733  ,
-			    2.1732  ,2.2865  ,2.4508  ,3.2556  ,2.9489  ,
-			    3.4497  ,3.2338  ,4.0084  ,3.3482  ,3.7872  ,
-			    4.0491  ,4.0065  ,3.8393  ,3.8573  ,3.9580  ,
-			    3.4841  ,3.2875  ,3.0220  ,3.0135  ,2.6343  ,
-			    2.1812  ,2.1588  ,2.1708  ,1.8158  ,1.4513  ,
-			    1.1350  ,1.0107  ,0.7388  ,0.4409  ,0.1652  ,
-			    0.0076  ,0.0000  ,0.0000  ,0.0000  ,0.0000  ,
-			    0.0002  ,0.0000  ,0.0003  ,0.0000  ,0.0000};
-  double DstarContBerror[]={0.0029  ,0.0235  ,0.0694  ,0.2135  ,0.1164  ,
-			    0.1500  ,0.1942  ,0.2272  ,0.2671  ,0.2697  ,
-			    0.2797  ,0.3122  ,0.2844  ,0.3007  ,0.3027  ,
-			    0.2881  ,0.3061  ,0.2927  ,0.2742  ,0.2868  ,
-			    0.2623  ,0.2652  ,0.2541  ,0.2541  ,0.2410  ,
-			    0.2388  ,0.2307  ,0.2307  ,0.2112  ,0.2102  ,
-			    0.2116  ,0.1995  ,0.1875  ,0.1811  ,0.1778  ,
-			    0.1649  ,0.1562  ,0.1460  ,0.1405  ,0.1307  ,
-			    0.1171  ,0.1131  ,0.1126  ,0.1016  ,0.0929  ,
-			    0.0801  ,0.0792  ,0.0712  ,0.0584  ,0.0415  ,
-			    0.0019  ,0.0000  ,0.0000  ,0.0000  ,0.0000  ,
-			    0.0003  ,0.0000  ,0.0003  ,0.0000  ,0.0000};
-  double DstarContBsyst []={0.0289  ,0.0279  ,0.1111  ,0.1412  ,0.1884  ,
-			    0.2026  ,0.2951  ,0.4560  ,0.3143  ,0.2830  ,
-			    0.8143  ,0.5703  ,0.5426  ,0.8053  ,0.8518  ,
-			    0.7047  ,0.6345  ,0.4422  ,0.6728  ,0.7195  ,
-			    0.5979  ,0.5913  ,0.4242  ,0.8650  ,0.3603  ,
-			    0.3100  ,0.4185  ,0.5449  ,0.7992  ,0.6498  ,
-			    0.3426  ,0.4139  ,0.4198  ,0.3723  ,0.1777  ,
-			    0.3743  ,0.3991  ,0.5463  ,0.2445  ,0.3707  ,
-			    0.5247  ,0.2772  ,0.1936  ,0.1444  ,0.2310  ,
-			    0.2199  ,0.0455  ,0.1016  ,0.1170  ,0.1720  ,
-			    0.0753  ,0.0000  ,0.0008  ,0.0003  ,0.0003  ,
-			    0.0003  ,0.0000  ,0.0001  ,0.0008  ,0.0004};
-  // upsilon(4s)  
-  double DstarResAdata [] ={0.0000  ,0.0000  ,0.0000  ,0.4738  ,1.5171  ,
-			    2.3419  ,2.8561  ,3.4064  ,3.8241  ,4.1637  ,
-			    4.6871  ,5.0245  ,5.3191  ,5.3183  ,4.9756  ,
-			    5.3471  ,5.4127  ,5.6859  ,5.0897  ,4.3337  ,
-			    4.2906  ,4.2940  ,3.8785  ,3.4359  ,3.1051  ,
-			    3.1234  ,3.2755  ,3.5321  ,3.6719  ,3.7688  ,
-			    3.7823  ,3.8011  ,3.9374  ,3.7599  ,3.6048  ,
-			    3.5008  ,3.2785  ,3.0835  ,2.9116  ,2.6687  ,
-			    2.4073  ,2.1714  ,1.9326  ,1.6977  ,1.4383  ,
-			    1.1891  ,0.9458  ,0.7230  ,0.4886  ,0.2788  ,
-			    0.0560  ,0.0004  ,0.0000  ,0.0001  ,0.0001  ,
-			    0.0001  ,0.0004  ,0.0001  ,0.0001  ,0.0002};
-  double DstarResAerror[] ={0.0000  ,0.0000  ,0.0000  ,0.0827  ,0.0814  ,
-			    0.0742  ,0.0695  ,0.0660  ,0.0617  ,0.0582  ,
-			    0.0898  ,0.0762  ,0.0725  ,0.0664  ,0.0639  ,
-			    0.0607  ,0.0604  ,0.0563  ,0.0541  ,0.0488  ,
-			    0.0506  ,0.0500  ,0.0440  ,0.0417  ,0.0398  ,
-			    0.0393  ,0.0406  ,0.0394  ,0.0415  ,0.0402  ,
-			    0.0394  ,0.0391  ,0.0347  ,0.0374  ,0.0372  ,
-			    0.0355  ,0.0345  ,0.0328  ,0.0319  ,0.0292  ,
-			    0.0285  ,0.0281  ,0.0254  ,0.0249  ,0.0247  ,
-			    0.0240  ,0.0232  ,0.0231  ,0.0235  ,0.0185  ,
-			    0.0059  ,0.0002  ,0.0000  ,0.0001  ,0.0000  ,
-			    0.0000  ,0.0004  ,0.0000  ,0.0001  ,0.0002};
-   double DstarResAsyst []={0.0000  ,0.0000  ,0.0000  ,0.4952  ,0.1372  ,
-			    0.1752  ,0.1725  ,0.1311  ,0.1107  ,0.1715  ,
-			    0.1424  ,0.1415  ,0.1428  ,0.1425  ,0.1335  ,
-			    0.1851  ,0.1591  ,0.1564  ,0.1502  ,0.1209  ,
-			    0.1471  ,0.1470  ,0.1160  ,0.0948  ,0.0846  ,
-			    0.0896  ,0.0879  ,0.0911  ,0.0935  ,0.1639  ,
-			    0.0945  ,0.1078  ,0.1546  ,0.0968  ,0.0927  ,
-			    0.0944  ,0.1009  ,0.0796  ,0.0738  ,0.0717  ,
-			    0.0653  ,0.0757  ,0.0494  ,0.0447  ,0.0413  ,
-			    0.0306  ,0.0238  ,0.0204  ,0.0163  ,0.0303  ,
-			    0.0167  ,0.0004  ,0.0001  ,0.0001  ,0.0002  ,
-			    0.0003  ,0.0004  ,0.0001  ,0.0002  ,0.0003};
-  double DstarResBdata [] ={0.1165  ,0.4929  ,1.0685  ,1.4522  ,2.3575  ,
-			    3.2876  ,4.0676  ,4.6098  ,5.0437  ,5.4440  ,
-			    6.0972  ,5.8901  ,6.4027  ,6.1881  ,5.9507  ,
-			    5.7318  ,6.1615  ,6.4023  ,5.5579  ,4.9284  ,
-			    4.5515  ,4.7132  ,3.8666  ,3.7695  ,3.0282  ,
-			    3.3300  ,3.4129  ,3.4566  ,3.6621  ,3.6642  ,
-			    3.5726  ,3.5974  ,3.5789  ,3.4910  ,3.4001  ,
-			    3.3657  ,3.0850  ,2.9208  ,2.7965  ,2.5201  ,
-			    2.3858  ,2.0900  ,1.8334  ,1.6066  ,1.3657  ,
-			    1.1287  ,0.8791  ,0.6908  ,0.4402  ,0.2154  ,
-			    0.0074  ,0.0000  ,0.0000  ,0.0000  ,0.0000  ,
-			    0.0003  ,0.0001  ,0.0000  ,0.0000  ,0.0000};
-  double DstarResBerror[] ={0.0551  ,0.0953  ,0.1464  ,0.1641  ,0.2045  ,
-			    0.2484  ,0.2532  ,0.2739  ,0.2811  ,0.2803  ,
-			    0.2781  ,0.2721  ,0.2662  ,0.2609  ,0.2462  ,
-			    0.2263  ,0.2298  ,0.2155  ,0.1894  ,0.1785  ,
-			    0.1646  ,0.1637  ,0.1423  ,0.1364  ,0.1200  ,
-			    0.1188  ,0.1156  ,0.1084  ,0.1060  ,0.0991  ,
-			    0.0969  ,0.0921  ,0.0869  ,0.0835  ,0.0803  ,
-			    0.0770  ,0.0717  ,0.0685  ,0.0654  ,0.0610  ,
-			    0.0585  ,0.0541  ,0.0505  ,0.0474  ,0.0453  ,
-			    0.0420  ,0.0402  ,0.0405  ,0.0371  ,0.0329  ,
-			    0.0009  ,0.0000  ,0.0000  ,0.0000  ,0.0000  ,
-			    0.0002  ,0.0001  ,0.0001  ,0.0000  ,0.0000};
-  double DstarResBsyst [] ={0.1372  ,0.4965  ,1.0767  ,0.9674  ,0.7464  ,
-			    1.0696  ,1.3322  ,1.2031  ,1.6356  ,1.5783  ,
-			    1.4752  ,1.4304  ,1.0702  ,1.2437  ,0.9721  ,
-			    0.9081  ,1.0710  ,0.9747  ,0.7575  ,0.8353  ,
-			    0.5420  ,0.5751  ,0.6969  ,0.4650  ,0.6019  ,
-			    0.3728  ,0.3793  ,0.5501  ,0.4483  ,0.6431  ,
-			    0.6985  ,0.6916  ,0.7151  ,0.6843  ,0.5956  ,
-			    0.5118  ,0.5377  ,0.4870  ,0.4397  ,0.4362  ,
-			    0.3022  ,0.3202  ,0.3053  ,0.2776  ,0.2307  ,
-			    0.1823  ,0.1645  ,0.1084  ,0.1023  ,0.0940  ,
-			    0.0546  ,0.0005  ,0.0000  ,0.0001  ,0.0002  ,
-			    0.0004  ,0.0004  ,0.0001  ,0.0001  ,0.0002};
-  // combine the data
-  vector<double> bins(vals,vals+61),data(60),error(60);
-  double norm(0.);
-  for(unsigned int ix=0;ix<60;++ix) {
-    if(_onshell) {
-      data[ix]  = DstarResAdata[ix]+DstarResBdata[ix]
-	        -(DstarContAdata[ix]+DstarContBdata[ix]);
-      error[ix] = sqrt(sqr(DstarResAerror[ix])+sqr(DstarResAsyst[ix])+
-		       sqr(DstarResBerror[ix])+sqr(DstarResBsyst[ix])+
-		       sqr(DstarContAerror[ix])+sqr(DstarContAsyst[ix])+
-		       sqr(DstarContBerror[ix])+sqr(DstarContBsyst[ix]));
-    }
-    else {
-      data[ix]  = DstarContAdata[ix]+DstarContBdata[ix];
-      error[ix] = sqrt(sqr(DstarContAerror[ix])+sqr(DstarContAsyst[ix])+
-		       sqr(DstarContBerror[ix])+sqr(DstarContBsyst[ix]));
-    }
-    norm +=data[ix];
-  }
-  norm*=0.02;
-  for(unsigned int ix=0;ix<data.size();++ix) {
-    data [ix] /=norm;
-    error[ix] /=norm;
-  }
-  _histDstarplus = new_ptr(Histogram(bins,data,error));
-  // data and errors for D*0
-  double DstarContCdata [] = {0.0005  ,0.0429  ,0.0628  ,0.0637  ,0.1361  ,
-			      0.2393  ,0.2248  ,0.2236  ,0.0759  ,0.2966  ,
-			      0.3302  ,0.3380  ,0.6534  ,0.6235  ,0.7017  ,
-			      0.9976  ,0.9747  ,1.0301  ,0.9653  ,1.3007  ,
-			      1.2644  ,1.7510  ,1.8537  ,2.1379  ,2.4625  ,
-			      2.6152  ,2.4718  ,2.6468  ,2.6830  ,3.2672  ,
-			      2.5735  ,3.0625  ,2.9439  ,2.8022  ,2.7553  ,
-			      2.7874  ,2.6514  ,2.6271  ,2.3999  ,2.0013  ,
-			      1.8978  ,1.8005  ,1.4439  ,1.2328  ,1.2430  ,
-			      1.0324  ,0.7418  ,0.6244  ,0.3600  ,0.1391  ,
-			      0.0067  ,0.0000  ,0.0000  ,0.0001  ,0.0000  ,
-			      0.0000  ,0.0000  ,0.0000  ,0.0000  ,0.0000};
-  double DstarContCerror[] = {0.0019  ,0.0349  ,0.0552  ,0.0839  ,0.1468  ,
-			      0.0934  ,0.1193  ,0.1710  ,0.1373  ,0.1408  ,
-			      0.1439  ,0.1434  ,0.1367  ,0.1373  ,0.1327  ,
-			      0.1394  ,0.1319  ,0.1305  ,0.1227  ,0.1256  ,
-			      0.1245  ,0.1265  ,0.1240  ,0.1305  ,0.1326  ,
-			      0.1325  ,0.1265  ,0.1303  ,0.1262  ,0.1362  ,
-			      0.1201  ,0.1269  ,0.1221  ,0.1162  ,0.1144  ,
-			      0.1137  ,0.1082  ,0.1059  ,0.0993  ,0.0911  ,
-			      0.0875  ,0.0841  ,0.0747  ,0.0677  ,0.0699  ,
-			      0.0644  ,0.0559  ,0.0526  ,0.0440  ,0.0283  ,
-			      0.0018  ,0.0000  ,0.0000  ,0.0005  ,0.0000  ,
-			      0.0000  ,0.0000  ,0.0000  ,0.0000  ,0.0000};
-  double DstarContCsyst [] = {0.0160  ,0.0541  ,0.0935  ,0.1248  ,0.1730  ,
-			      0.1432  ,0.3045  ,0.2947  ,0.3041  ,0.2320  ,
-			      0.6625  ,0.3682  ,0.4239  ,0.5345  ,0.4599  ,
-			      0.4959  ,0.3333  ,0.2009  ,0.1674  ,0.4672  ,
-			      0.1038  ,0.1506  ,0.1571  ,0.3942  ,0.2303  ,
-			      0.1200  ,0.3101  ,0.3079  ,0.6658  ,0.4874  ,
-			      0.1710  ,0.3015  ,0.3281  ,0.2784  ,0.1781  ,
-			      0.3159  ,0.3318  ,0.4386  ,0.1970  ,0.3156  ,
-			      0.4567  ,0.2463  ,0.0822  ,0.1441  ,0.2078  ,
-			      0.1855  ,0.0286  ,0.0850  ,0.1021  ,0.1365  ,
-			      0.0627  ,0.0000  ,0.0007  ,0.0003  ,0.0008  ,
-			      0.0002  ,0.0000  ,0.0003  ,0.0006  ,0.0000};
-  double DstarResCdata  [] = {0.0499  ,0.2866  ,0.7566  ,1.2445  ,1.7512  ,
-			      2.0055  ,2.7251  ,3.3537  ,3.7734  ,3.9434  ,
-			      3.9614  ,4.6476  ,4.4744  ,4.6342  ,4.3167  ,
-			      4.6727  ,4.8370  ,5.1344  ,4.5411  ,4.1157  ,
-			      4.0264  ,3.8603  ,3.4919  ,2.8508  ,2.4374  ,
-			      2.2697  ,2.3825  ,2.5889  ,2.7219  ,2.9223  ,
-			      2.8554  ,2.8909  ,2.9134  ,2.7963  ,2.6736  ,
-			      2.5551  ,2.5038  ,2.3519  ,2.1896  ,2.0004  ,
-			      1.8195  ,1.5966  ,1.4875  ,1.2618  ,1.0930  ,
-			      0.9624  ,0.7382  ,0.5387  ,0.3747  ,0.1922  ,
-			      0.0100  ,0.0004  ,0.0000  ,0.0002  ,0.0000  ,
-			      0.0003  ,0.0000  ,0.0000  ,0.0000  ,0.0001};
-  double DstarResCerror [] = {0.0137  ,0.0371  ,0.0709  ,0.0813  ,0.0968  ,
-			      0.0982  ,0.1108  ,0.1218  ,0.1224  ,0.1208  ,
-			      0.1185  ,0.1254  ,0.1193  ,0.1205  ,0.1141  ,
-			      0.1137  ,0.1109  ,0.1141  ,0.1029  ,0.0979  ,
-			      0.0944  ,0.0865  ,0.0811  ,0.0716  ,0.0656  ,
-			      0.0623  ,0.0605  ,0.0625  ,0.0613  ,0.0633  ,
-			      0.0607  ,0.0597  ,0.0591  ,0.0567  ,0.0540  ,
-			      0.0526  ,0.0512  ,0.0485  ,0.0461  ,0.0439  ,
-			      0.0415  ,0.0384  ,0.0373  ,0.0341  ,0.0335  ,
-			      0.0335  ,0.0318  ,0.0286  ,0.0299  ,0.0243  ,
-			      0.0010  ,0.0003  ,0.0000  ,0.0002  ,0.0000  ,
-			      0.0002  ,0.0000  ,0.0003  ,0.0000  ,0.0001};
-  double DstarResCsyst  [] = {0.1002  ,0.4131  ,0.9090  ,0.7991  ,0.6240  ,
-			      0.6420  ,0.8793  ,0.7754  ,0.7611  ,0.7890  ,
-			      0.9126  ,0.5415  ,0.5097  ,0.5498  ,0.4939  ,
-			      0.2492  ,0.3606  ,0.3842  ,0.2612  ,0.3417  ,
-			      0.3242  ,0.2607  ,0.3608  ,0.1207  ,0.3845  ,
-			      0.1929  ,0.2109  ,0.4158  ,0.3605  ,0.4936  ,
-			      0.5290  ,0.5272  ,0.5955  ,0.5716  ,0.4944  ,
-			      0.4321  ,0.4581  ,0.4050  ,0.3519  ,0.3660  ,
-			      0.2370  ,0.2660  ,0.2606  ,0.2215  ,0.1866  ,
-			      0.1552  ,0.1378  ,0.0915  ,0.0835  ,0.0781  ,
-			      0.0454  ,0.0005  ,0.0000  ,0.0001  ,0.0001  ,
-			      0.0002  ,0.0003  ,0.0002  ,0.0001  ,0.0002};
-  norm=0.;
-  for(unsigned int ix=0;ix<60;++ix) {
-    if(_onshell) {
-      data[ix]  = DstarResCdata[ix]-DstarContCdata[ix];
-      error[ix] = sqrt(sqr(DstarResCerror[ix])+sqr(DstarResCsyst[ix])+
-		       sqr(DstarContCerror[ix])+sqr(DstarContCsyst[ix]));
-    }
-    else {
-      data[ix]  = DstarContCdata[ix];
-      error[ix] = sqrt(sqr(DstarContCerror[ix])+sqr(DstarContCsyst[ix]));
-    }
-    norm +=data[ix];
-  }
-  norm*=0.02;
-  for(unsigned int ix=0;ix<data.size();++ix) {
-    data [ix] /=norm;
-    error[ix] /=norm;
-  }
-  _histDstar0 = new_ptr(Histogram(bins,data,error));
-  // D0
-  double D0Contdata []={ 0.0169 , 0.0833 , 0.0618 , 0.1986 , 0.4482 , 
-			 0.7078 , 1.2171 , 1.2134 , 1.0833 , 1.7438 , 
-			 2.0325 , 2.2870 , 2.7788 , 3.3657 , 3.8424 , 
-			 4.0673 , 5.2573 , 5.9915 , 6.9013 , 7.9586 , 
-			 8.7103 , 9.7516 ,10.780  ,11.833  ,12.588  ,
-			 13.333 ,14.118  ,14.520  ,14.634  ,14.631  ,
-			 14.792 ,14.038  ,13.677  ,12.910  ,12.316  ,
-			 11.687 ,10.443  , 9.6756 , 8.5980 , 7.7212 ,
-			 6.6372 , 5.6244 , 4.4447 , 3.6675 , 2.7390 , 
-			 1.8597 , 1.1354 , 0.5906 , 0.3842 , 0.1368 , 
-			 0.0005 , 0.0006 , 0.0000 , 0.0001 , 0.0000 , 
-			 0.0000 , 0.0010 , 0.0000 , 0.0000 , 0.0000};
-  double D0Conterror[]={0.0292 ,0.0587 ,0.1030 ,0.1188 ,0.1706 ,
-			0.1790 ,0.1868 ,0.2096 ,0.2049 ,0.2129 ,
-			0.2114 ,0.2049 ,0.2062 ,0.2021 ,0.1936 ,
-			0.1905 ,0.1858 ,0.1839 ,0.1804 ,0.1793 ,
-			0.1770 ,0.1754 ,0.1747 ,0.1741 ,0.1726 ,
-			0.1709 ,0.1700 ,0.1681 ,0.1651 ,0.1617 ,
-			0.1600 ,0.1539 ,0.1503 ,0.1443 ,0.1405 ,
-			0.1347 ,0.1267 ,0.1221 ,0.1157 ,0.1091 ,
-			0.1016 ,0.0952 ,0.0865 ,0.0799 ,0.0631 ,
-			0.0548 ,0.0464 ,0.0367 ,0.0422 ,0.0345 ,
-			0.0171 ,0.0084 ,0.0000 ,0.0284 ,0.0000 ,
-			0.0000 ,0.0037 ,0.0000 ,0.0000 ,0.0000};
-  double D0Contsyst []={ 0.0034  ,0.0371  ,0.0672  ,0.0409  ,0.1235  ,
-			 0.1347  ,0.1904  ,0.1068  ,0.1620  ,0.1482  ,
-			 0.1350  ,0.1249  ,0.2211  ,0.1672  ,0.1875  ,
-			 0.2001  ,0.2818  ,0.2955  ,0.2418  ,0.2760  ,
-			 0.2875  ,0.3735  ,0.5162  ,0.4231  ,0.4262  ,
-			 0.4586  ,0.5054  ,0.5626  ,0.6052  ,0.6230  ,
-			 0.6430  ,0.7133  ,0.6407  ,0.5828  ,0.5499  ,
-			 0.5147  ,0.4593  ,0.5165  ,0.4916  ,0.5091  ,
-			 0.4028  ,0.3546  ,0.3498  ,0.2157  ,0.1926  ,
-			 0.1333  ,0.0482  ,0.0375  ,0.0197  ,0.0362  ,
-			 0.0036  ,0.0024  ,0.0000  ,0.0031  ,0.0000  ,
-			 0.0000  ,0.0006  ,0.0000  ,0.0016  ,0.0000};
-  double D0Resdata  []={0.2158 , 1.3354 , 3.5464 , 6.2104 , 9.1055 ,
-			11.743 ,14.185  ,16.600  ,18.420  ,19.861  ,
-			21.068 ,22.052  ,22.610  ,21.903  ,22.920  ,
-			23.370 ,23.409  ,22.102  ,21.291  ,20.201  ,
-			18.593 ,17.130  ,15.455  ,14.157  ,13.408  ,
-			13.367 ,13.600  ,14.146  ,14.318  ,14.529  ,
-			14.361 ,13.890  ,13.497  ,12.769  ,12.112  ,
-			11.349 ,10.411  , 9.4833 , 8.6169 , 7.6538 ,
-			6.6222 , 5.5604 , 4.5685 , 3.5991 , 2.6699 , 
-			1.7757 , 1.0773 , 0.5975 , 0.3697 , 0.1322 , 
-			0.0012 , 0.0000 , 0.0000 , 0.0000 , 0.0006 , 
-			0.0000 , 0.0000 , 0.0000 , 0.0000 , 0.0013 };
-  double D0Reserror []={0.0139 ,0.0343 ,0.0577 ,0.0799 ,0.0980 ,
-			0.1111 ,0.1227 ,0.1305 ,0.1371 ,0.1411 ,
-			0.1435 ,0.1463 ,0.1492 ,0.1447 ,0.1447 ,
-			0.1440 ,0.1404 ,0.1366 ,0.1321 ,0.1251 ,
-			0.1175 ,0.1098 ,0.1018 ,0.0951 ,0.0894 ,
-			0.0862 ,0.0841 ,0.4752 ,0.0815 ,0.0798 ,
-			0.1961 ,0.1058 ,0.0736 ,0.1009 ,0.0884 ,
-			0.0756 ,0.0735 ,0.0688 ,0.0575 ,0.0616 ,
-			0.0522 ,0.0498 ,0.0472 ,0.0445 ,0.0391 ,
-			0.0337 ,0.0292 ,0.0241 ,0.0307 ,0.0554 ,
-			0.0171 ,0.0000 ,0.0000 ,0.0000 ,0.0020 ,
-			0.0000 ,0.0000 ,0.0000 ,0.0000 ,0.0018};
-  double D0Ressyst  []={0.0241  ,0.0936  ,0.1466  ,0.1804  ,0.2883  ,
-			0.3625  ,0.3514  ,0.4124  ,0.4660  ,0.5604  ,
-			0.6975  ,0.6903  ,0.7772  ,0.7347  ,0.8244  ,
-			0.8277  ,0.8621  ,0.8435  ,0.8492  ,0.7592  ,
-			0.6783  ,0.6762  ,0.6239  ,0.5569  ,0.5639  ,
-			0.5113  ,0.5373  ,0.5896  ,0.6189  ,0.6497  ,
-			0.6166  ,0.6128  ,0.6263  ,0.6027  ,0.5568  ,
-			0.5054  ,0.4987  ,0.5208  ,0.4783  ,0.4779  ,
-			0.4491  ,0.3651  ,0.3119  ,0.2262  ,0.2316  ,
-			0.1255  ,0.0737  ,0.0297  ,0.0277  ,0.0221  ,
-			0.0018  ,0.0000  ,0.0000  ,0.0003  ,0.0009  ,
-			0.0000  ,0.0000  ,0.0004  ,0.0000  ,0.0013};
-  norm=0.;
-  for(unsigned int ix=0;ix<60;++ix) {
-    if(_onshell) {
-      data[ix]  = D0Resdata[ix]-D0Contdata[ix];
-      error[ix] = sqrt(sqr(D0Reserror[ix])+sqr(D0Ressyst[ix])+
-		       sqr(D0Conterror[ix])+sqr(D0Contsyst[ix]));
-    }
-    else {
-      data[ix]  = D0Contdata[ix];
-      error[ix] = sqrt(sqr(D0Conterror[ix])+sqr(D0Contsyst[ix]));
-    }
-    norm +=data[ix];
-  }
-  norm*=0.02;
-  for(unsigned int ix=0;ix<data.size();++ix) {
-    data [ix] /=norm;
-    error[ix] /=norm;
-  }
-  _histD0 = new_ptr(Histogram(bins,data,error));
-  // D+
-  double DplusContdata [] = {0.0000  , 0.0000  , 0.5818  , 0.6357  , 0.1329  ,
-			     0.8692  , 0.4138  , 1.6552  , 2.5470  , 1.3803  ,
-			     2.7601  , 2.1947  , 3.9075  , 3.6200  , 4.2296  ,
-			     4.9135  , 5.2604  , 5.9759  , 7.3663  , 8.1743  ,
-			     8.4325  , 9.7974  ,11.461   ,12.077   ,12.934   ,
-			     13.708  ,14.067   ,14.725   ,14.963   ,15.423   ,
-			     15.320  ,15.190   ,15.055   ,14.245   ,13.537   ,
-			     12.619  ,11.922   ,11.056   , 9.7519  , 9.0101  ,
-			     8.1814  , 6.8664  , 5.6215  , 4.8304  , 3.8260  , 
-			     2.9192  , 1.9412  , 1.2589  , 0.8647  , 0.4013  , 
-			     0.0000  , 0.0030  , 0.0001  , 0.0019  , 0.0024  , 
-			     0.0007  , 0.0000  , 0.0000  , 0.0005  , 0.0000};
-  double DplusConterror[] = {0.0000  ,0.0000  ,0.2483  ,0.3362  ,0.3210  ,
-			     0.4320  ,0.3511  ,0.5107  ,0.4657  ,0.4867  ,
-			     0.4947  ,0.4704  ,0.4833  ,0.4373  ,0.4511  ,
-			     0.4313  ,0.4162  ,0.4001  ,0.4001  ,0.3773  ,
-			     0.3670  ,0.3562  ,0.3507  ,0.3345  ,0.3275  ,
-			     0.3147  ,0.3010  ,0.2905  ,0.2802  ,0.2721  ,
-			     0.2575  ,0.2451  ,0.2352  ,0.2222  ,0.2106  ,
-			     0.1959  ,0.1855  ,0.1750  ,0.1614  ,0.1526  ,
-			     0.1416  ,0.1297  ,0.1156  ,0.1075  ,0.0861  ,
-			     0.0780  ,0.0672  ,0.0567  ,0.0592  ,0.0781  ,
-			     0.0000  ,0.0037  ,0.0204  ,0.0031  ,0.0030  ,
-			     0.0028  ,0.0000  ,0.0000  ,0.0039  ,0.0000};
-  double DplusContsyst [] = {0.0089  ,0.0387  ,0.0883  ,0.1988  ,0.1961  ,
-			     0.1366  ,0.1952  ,0.3483  ,0.8036  ,0.4267  ,
-			     0.3463  ,0.2670  ,0.3700  ,0.6879  ,0.4151  ,
-			     0.3116  ,0.3172  ,0.2360  ,0.6964  ,0.5013  ,
-			     0.5977  ,0.4255  ,0.6292  ,0.4448  ,0.4600  ,
-			     0.5626  ,0.5610  ,0.5647  ,0.5255  ,0.5867  ,
-			     0.5850  ,0.6885  ,0.5657  ,0.5309  ,0.5721  ,
-			     0.5157  ,0.5405  ,0.4071  ,0.3945  ,0.3568  ,
-			     0.3436  ,0.2785  ,0.2288  ,0.1772  ,0.1493  ,
-			     0.1128  ,0.0755  ,0.0946  ,0.0340  ,0.0888  ,
-			     0.0000  ,0.0030  ,0.0024  ,0.0021  ,0.0013  ,
-			     0.0010  ,0.0000  ,0.0012  ,0.0008  ,0.0007};
-  double DplusResdata  [] = {0.1550  , 1.5006  , 3.1119  , 6.4047  , 8.9433  ,
-			     11.700   ,12.478   ,15.654   ,16.602   ,18.075   ,
-			     19.110   ,20.501   ,21.173   ,20.674   ,22.020   ,
-			     21.443   ,22.801   ,23.363   ,22.590   ,20.531   ,
-			     18.777   ,19.212   ,17.918   ,15.831   ,14.004   ,
-			     13.599   ,13.707   ,14.565   ,15.145   ,15.326   ,
-			     15.049   ,14.756   ,14.570   ,14.051   ,13.479   ,
-			     12.685   ,11.859   ,11.030   , 9.9618  , 9.1037  ,
-			     7.8287  , 6.8724  , 5.6991  , 4.7644  , 3.6555  , 
-			     2.7980  , 1.9429  , 1.2478  , 0.7765  , 0.5288  , 
-			     0.0045  , 0.0000  , 0.0000  , 0.0000  , 0.0000  , 
-			     0.0000  , 0.0007  , 0.0013  , 0.0023  , 0.0000};
-  double DplusReserror [] = {0.0407  ,0.1314  ,0.1924  ,0.2836  ,0.3264  ,
-			     0.3597  ,0.3502  ,0.3808  ,0.3652  ,0.3687  ,
-			     0.3687  ,0.3628  ,0.3605  ,0.3390  ,0.3315  ,
-			     0.3106  ,0.2970  ,0.2881  ,0.2702  ,0.2409  ,
-			     0.2328  ,0.2205  ,0.2086  ,0.1887  ,0.1721  ,
-			     0.1684  ,0.1570  ,3.0100  ,0.4975  ,0.1386  ,
-			     1.0654  ,0.2339  ,0.1170  ,0.1102  ,0.2722  ,
-			     0.0977  ,0.1126  ,0.1151  ,0.0818  ,0.0781  ,
-			     0.0715  ,0.0813  ,0.0737  ,0.0581  ,0.0479  ,
-			     0.0461  ,0.0433  ,0.0371  ,0.1249  ,0.0812  ,
-			     0.0070  ,0.0000  ,0.0000  ,0.0000  ,0.0000  ,
-			     0.0000  ,0.0013  ,0.0013  ,0.0013  ,0.0000};
-  double DplusRessyst  [] = {0.0114  ,0.0644  ,0.1420  ,0.3082  ,0.3491  ,
-			     0.5140  ,0.6339  ,0.6431  ,0.7199  ,0.6802  ,
-			     0.6784  ,0.8869  ,1.0151  ,0.8385  ,0.8824  ,
-			     0.8406  ,0.9693  ,0.8910  ,0.8966  ,0.8640  ,
-			     0.7759  ,0.7758  ,0.6574  ,0.5959  ,0.5031  ,
-			     0.5601  ,0.4837  ,0.5873  ,0.5450  ,0.5444  ,
-			     0.5404  ,0.5806  ,0.5533  ,0.5293  ,0.5188  ,
-			     0.4884  ,0.4699  ,0.4564  ,0.3867  ,0.3564  ,
-			     0.3258  ,0.2715  ,0.2275  ,0.1951  ,0.1517  ,
-			     0.1071  ,0.0744  ,0.0695  ,0.0561  ,0.1143  ,
-			     0.0012  ,0.0000  ,0.0000  ,0.0000  ,0.0000  ,
-			     0.0000  ,0.0005  ,0.0004  ,0.0013  ,0.0000};
-  norm=0.;
-  for(unsigned int ix=0;ix<60;++ix) {
-    if(_onshell) {
-      data[ix]  = DplusResdata[ix]-DplusContdata[ix];
-      error[ix] = sqrt(sqr(DplusReserror[ix])+sqr(DplusRessyst[ix])+
-		       sqr(DplusConterror[ix])+sqr(DplusContsyst[ix]));
-    }
-    else {
-      data[ix]  = DplusContdata[ix];
-      error[ix] = sqrt(sqr(DplusConterror[ix])+sqr(DplusContsyst[ix]));
-    }
-    norm +=data[ix];
-  }
-  norm*=0.02;
-  for(unsigned int ix=0;ix<data.size();++ix) {
-    data [ix] /=norm;
-    error[ix] /=norm;
-  }
-  _histDplus = new_ptr(Histogram(bins,data,error));
-  // D_s
-  double DsContdata []={0.0000  ,0.0215  ,0.0523  ,0.0000  ,0.0192  ,
-			0.1315  ,0.2369  ,0.2176  ,0.2092  ,0.0000  ,
-			0.1286  ,0.0000  ,0.1710  ,0.4137  ,0.6091  ,
-			0.4799  ,0.3845  ,0.4657  ,0.6666  ,0.8618  ,
-			0.7695  ,0.9957  ,0.6926  ,1.0742  ,1.2848  ,
-			1.1490  ,1.4815  ,1.7732  ,1.6550  ,2.0110  ,
-			2.2453  ,2.1992  ,2.2760  ,2.4153  ,2.3540  ,
-			2.2840  ,2.1807  ,2.0987  ,2.0491  ,1.8800  ,
-			1.7452  ,1.5000  ,1.3928  ,1.0368  ,0.8881  ,
-			0.6345  ,0.4031  ,0.3867  ,0.1964  ,0.1030  ,
-			0.0001  ,0.0000  ,0.0003  ,0.0000  ,0.0003  ,
-			0.0003  ,0.0000  ,0.0003  ,0.0000  ,0.0000};
-  double DsConterror[]={0.0000  ,0.0215  ,0.0409  ,0.0000  ,0.0874  ,
-			0.1225  ,0.1223  ,0.1021  ,0.1049  ,0.0000  ,
-			0.1247  ,0.0000  ,0.1248  ,0.1241  ,0.1218  ,
-			0.1210  ,0.1126  ,0.1127  ,0.1092  ,0.1101  ,
-			0.1064  ,0.1077  ,0.0966  ,0.1004  ,0.1016  ,
-			0.0934  ,0.0970  ,0.0995  ,0.0943  ,0.0986  ,
-			0.0990  ,0.0972  ,0.0950  ,0.0935  ,0.0912  ,
-			0.0886  ,0.0851  ,0.0832  ,0.0806  ,0.0785  ,
-			0.0757  ,0.0702  ,0.0685  ,0.0601  ,0.0555  ,
-			0.0494  ,0.0409  ,0.0510  ,0.0586  ,0.0406  ,
-			0.0007  ,0.0000  ,0.0003  ,0.0000  ,0.0003  ,
-			0.0003  ,0.0000  ,0.0003  ,0.0000  ,0.0000 };
-  double DsContsyst []={0.0000  ,0.0075  ,0.0086  ,0.0000  ,0.0719  ,
-			0.0695  ,0.0345  ,0.1379  ,0.0277  ,0.1283  ,
-			0.0769  ,0.0936  ,0.1908  ,0.0817  ,0.0814  ,
-			0.0760  ,0.0835  ,0.0390  ,0.1038  ,0.0569  ,
-			0.0855  ,0.0952  ,0.0733  ,0.0524  ,0.0602  ,
-			0.0477  ,0.0827  ,0.1078  ,0.1010  ,0.0976  ,
-			0.0789  ,0.0731  ,0.0954  ,0.1753  ,0.1315  ,
-			0.1019  ,0.0752  ,0.1184  ,0.0687  ,0.0792  ,
-			0.0727  ,0.0610  ,0.0469  ,0.0556  ,0.0445  ,
-			0.0317  ,0.0155  ,0.0144  ,0.0331  ,0.0152  ,
-			0.0002  ,0.0002  ,0.0001  ,0.0000  ,0.0000  ,
-			0.0003  ,0.0000  ,0.0000  ,0.0000  ,0.0000};
-  double DsResdata  []={0.0172  ,0.1635  ,0.4140  ,0.7689  ,1.0447  ,
-			1.5749  ,1.4311  ,1.9089  ,2.1637  ,2.4421  ,
-			2.9070  ,3.0959  ,3.3758  ,4.1464  ,5.2309  ,
-			6.0358  ,6.8050  ,6.2537  ,4.9198  ,2.6739  ,
-			1.1283  ,0.8664  ,0.8912  ,1.1026  ,1.1718  ,
-			1.3390  ,1.5067  ,1.7534  ,1.9282  ,1.9846  ,
-			2.0309  ,2.2831  ,2.3075  ,2.3346  ,2.4522  ,
-			2.2865  ,2.1992  ,2.1336  ,2.0154  ,1.8252  ,
-			1.6409  ,1.4550  ,1.2669  ,0.9831  ,0.8357  ,
-			0.5785  ,0.4427  ,0.3233  ,0.2478  ,0.0932  ,
-			0.0005  ,0.0000  ,0.0000  ,0.0000  ,0.0000  ,
-			0.0001  ,0.0000  ,0.0000  ,0.0000  ,0.0000};
-  double DsReserror []={0.0060  ,0.0327  ,0.0602  ,0.0802  ,0.0850  ,
-			0.1283  ,0.0963  ,0.1264  ,0.1129  ,0.1212  ,
-			0.1440  ,0.1321  ,0.1325  ,0.1383  ,0.1364  ,
-			0.1277  ,0.1306  ,0.1175  ,0.1045  ,0.0769  ,
-			0.0594  ,0.0501  ,0.0495  ,0.0499  ,0.0489  ,
-			0.0945  ,0.0470  ,0.0479  ,0.0772  ,0.0475  ,
-			0.0578  ,0.0475  ,0.0463  ,0.0455  ,0.0464  ,
-			0.0441  ,0.0427  ,0.0420  ,0.0410  ,0.0396  ,
-			0.0388  ,0.0373  ,0.0366  ,0.0334  ,0.0332  ,
-			0.0297  ,0.0294  ,0.0330  ,0.0599  ,0.0316  ,
-			0.0004  ,0.0000  ,0.0000  ,0.0002  ,0.0001  ,
-			0.0001  ,0.0001  ,0.0000  ,0.0000  ,0.0000};
-  double DsRessyst  []={0.0022  ,0.0124  ,0.0197  ,0.0272  ,0.0688  ,
-			0.0534  ,0.0623  ,0.1163  ,0.1213  ,0.0866  ,
-			0.1406  ,0.1193  ,0.1181  ,0.1573  ,0.1862  ,
-			0.2050  ,0.2479  ,0.2265  ,0.1930  ,0.1158  ,
-			0.0467  ,0.0381  ,0.0332  ,0.0418  ,0.0411  ,
-			0.0479  ,0.0587  ,0.0657  ,0.0644  ,0.0752  ,
-			0.0682  ,0.0959  ,0.0943  ,0.0860  ,0.0919  ,
-			0.0824  ,0.0811  ,0.0756  ,0.0804  ,0.0703  ,
-			0.0848  ,0.0767  ,0.0505  ,0.1049  ,0.0305  ,
-			0.0420  ,0.0230  ,0.0132  ,0.0133  ,0.0071  ,
-			0.0002  ,0.0001  ,0.0000  ,0.0001  ,0.0001  ,
-			0.0000  ,0.0000  ,0.0000  ,0.0000  ,0.0000};
-  norm=0.;
-  for(unsigned int ix=0;ix<60;++ix) {
-    if(_onshell) {
-      data[ix]  = DsResdata[ix]-DsContdata[ix];
-      error[ix] = sqrt(sqr(DsReserror[ix])+sqr(DsRessyst[ix])+
-		       sqr(DsConterror[ix])+sqr(DsContsyst[ix]));
-    }
-    else {
-      data[ix]  = DsContdata[ix];
-      error[ix] = sqrt(sqr(DsConterror[ix])+sqr(DsContsyst[ix]));
-    }
-    norm +=data[ix];
-  }
-  norm*=0.02;
-  for(unsigned int ix=0;ix<data.size();++ix) {
-    data [ix] /=norm;
-    error[ix] /=norm;
-  }
-  _histDs = new_ptr(Histogram(bins,data,error));
-  // lambda_c
-  double LambdaContdata []={0.0139  ,0.0000  ,0.0000  ,0.2306  ,0.0000  ,
-			    0.0000  ,0.0000  ,0.1742  ,0.3650  ,0.0595  ,
-			    0.0000  ,0.1462  ,0.1987  ,0.3494  ,0.5546  ,
-			    0.7100  ,0.9732  ,1.2286  ,1.2439  ,0.8432  ,
-			    1.3625  ,1.0046  ,1.8011  ,1.8175  ,2.2466  ,
-			    2.0503  ,2.3058  ,2.6803  ,2.9076  ,2.9698  ,
-			    2.9984  ,2.9810  ,2.6864  ,2.7354  ,2.6587  ,
-			    2.4398  ,1.9472  ,1.8592  ,1.5798  ,1.2745  ,
-			    1.0149  ,0.7507  ,0.5853  ,0.3793  ,0.2852  ,
-			    0.1373  ,0.1369  ,0.1237  ,0.0495  ,0.0109  ,
-			    0.0054  ,0.0000  ,0.0000  ,0.0000  ,0.0035  ,
-			    0.0000  ,0.0000  ,0.0010  ,0.0000  ,0.0000};
-  double LambdaConterror[]={0.0159  ,0.0000  ,0.0638  ,0.1087  ,0.0000  ,
-			    0.0000  ,0.0000  ,0.2015  ,0.2347  ,0.2075  ,
-			    0.0000  ,0.2120  ,0.2144  ,0.2115  ,0.2075  ,
-			    0.1949  ,0.2042  ,0.1816  ,0.1794  ,0.1727  ,
-			    0.1606  ,0.1500  ,0.1608  ,0.1471  ,0.1446  ,
-			    0.1366  ,0.1349  ,0.1309  ,0.1304  ,0.1251  ,
-			    0.1208  ,0.1163  ,0.1129  ,0.1074  ,0.1036  ,
-			    0.0994  ,0.0922  ,0.0884  ,0.0830  ,0.0756  ,
-			    0.0697  ,0.0653  ,0.0619  ,0.0548  ,0.0493  ,
-			    0.0439  ,0.0457  ,0.0466  ,0.0530  ,0.0075  ,
-			    0.0068  ,0.0000  ,0.0000  ,0.0000  ,0.0056  ,
-			    0.0000  ,0.0000  ,0.0060  ,0.0000  ,0.0000};
-  double LambdaContsyst []={0.0212  ,0.0065  ,0.0384  ,0.0460  ,0.0222  ,
-			    0.0127  ,0.0022  ,0.0697  ,0.0694  ,0.1109  ,
-			    0.0000  ,0.0827  ,0.1871  ,0.1175  ,0.5312  ,
-			    0.2119  ,0.0841  ,0.1294  ,0.0923  ,0.2728  ,
-			    0.0993  ,0.1427  ,0.2887  ,0.0801  ,0.1223  ,
-			    0.1335  ,0.1354  ,0.1388  ,0.2330  ,0.1289  ,
-			    0.1052  ,0.1177  ,0.1754  ,0.1521  ,0.1078  ,
-			    0.0872  ,0.0853  ,0.0858  ,0.0924  ,0.0562  ,
-			    0.0434  ,0.0416  ,0.0957  ,0.0204  ,0.0300  ,
-			    0.0225  ,0.0870  ,0.0698  ,0.0301  ,0.0039  ,
-			    0.0060  ,0.0000  ,0.0000  ,0.0005  ,0.0050  ,
-			    0.0000  ,0.0017  ,0.0026  ,0.0000  ,0.0013};
-  double LambdaResdata [] ={0.0754  ,0.4204  ,0.8565  ,1.4055  ,1.6783  ,
-			    2.0153  ,2.4834  ,2.6237  ,2.8581  ,2.7140  ,
-			    2.7020  ,2.3296  ,1.9372  ,1.6154  ,1.2013  ,
-			    1.2710  ,1.1848  ,1.1810  ,1.1716  ,1.2500  ,
-			    1.1281  ,1.5176  ,1.6848  ,1.8331  ,1.8510  ,
-			    2.1514  ,2.5126  ,2.5917  ,2.7706  ,2.8117  ,
-			    2.9390  ,2.8475  ,2.9111  ,2.7268  ,2.4615  ,
-			    2.3572  ,2.1411  ,1.7850  ,1.5107  ,1.2671  ,
-			    0.9243  ,0.7535  ,0.5556  ,0.3460  ,0.2931  ,
-			    0.1487  ,0.1007  ,0.0470  ,0.0034  ,0.0038  ,
-			    0.0018  ,0.0005  ,0.0000  ,0.0030  ,0.0000  ,
-			    0.0021  ,0.0008  ,0.0000  ,0.0000  ,0.0000  };
-  double LambdaReserror[] ={0.0227  ,0.0489  ,0.0673  ,0.0947  ,0.1075  ,
-			    0.1135  ,0.1280  ,0.1356  ,0.1516  ,0.1427  ,
-			    0.1489  ,0.1328  ,0.1239  ,0.1238  ,0.1056  ,
-			    0.1090  ,0.1102  ,0.0975  ,0.0982  ,0.1028  ,
-			    0.0740  ,0.0942  ,0.0882  ,0.0771  ,0.0722  ,
-			    0.0729  ,0.3043  ,0.0667  ,0.1758  ,0.0686  ,
-			    0.0620  ,0.0586  ,0.1371  ,0.0546  ,0.1111  ,
-			    0.0941  ,0.0466  ,0.0770  ,0.1435  ,0.0367  ,
-			    0.0640  ,0.0311  ,0.0292  ,0.0248  ,0.0227  ,
-			    0.0209  ,0.0619  ,0.0198  ,0.0304  ,0.0033  ,
-			    0.0030  ,0.0038  ,0.0000  ,0.0026  ,0.0000  ,
-			    0.0023  ,0.0022  ,0.0000  ,0.0000  ,0.0000  };
-  double LambdaRessyst [] ={0.0067  ,0.0199  ,0.0449  ,0.0837  ,0.0576  ,
-			    0.1153  ,0.1054  ,0.1077  ,0.1346  ,0.0964  ,
-			    0.1063  ,0.2158  ,0.1677  ,0.1223  ,0.1309  ,
-			    0.1205  ,0.0527  ,0.0794  ,0.0610  ,0.1053  ,
-			    0.1826  ,0.0706  ,0.0738  ,0.1364  ,0.1319  ,
-			    0.1011  ,0.0910  ,0.0887  ,0.1353  ,0.1149  ,
-			    0.1423  ,0.1238  ,0.1136  ,0.0949  ,0.0907  ,
-			    0.0931  ,0.0893  ,0.1040  ,0.0685  ,0.0595  ,
-			    0.0356  ,0.0497  ,0.0270  ,0.0218  ,0.0132  ,
-			    0.0254  ,0.0256  ,0.0120  ,0.0178  ,0.0799  ,
-			    0.0016  ,0.0006  ,0.0000  ,0.0015  ,0.0002  ,
-			    0.0029  ,0.0013  ,0.0003  ,0.0000  ,0.0000};
-  norm=0.;
-  for(unsigned int ix=0;ix<60;++ix) {
-    if(_onshell) {
-      data[ix]  = LambdaResdata[ix]-LambdaContdata[ix];
-      error[ix] = sqrt(sqr(LambdaReserror[ix])+sqr(LambdaRessyst[ix])+
-		       sqr(LambdaConterror[ix])+sqr(LambdaContsyst[ix]));
-    }
-    else {
-      data[ix]  = LambdaContdata[ix];
-      error[ix] = sqrt(sqr(LambdaConterror[ix])+sqr(LambdaContsyst[ix]));
-    }
-    norm +=data[ix];
-  }
-  norm*=0.02;
-  for(unsigned int ix=0;ix<data.size();++ix) {
-    data [ix] /=norm;
-    error[ix] /=norm;
-  }
-  _histLambda = new_ptr(Histogram(bins,data,error));
-}
diff --git a/Analysis/BELLECharmAnalysis.h b/Analysis/BELLECharmAnalysis.h
deleted file mode 100644
--- a/Analysis/BELLECharmAnalysis.h
+++ /dev/null
@@ -1,279 +0,0 @@
-// -*- C++ -*-
-//
-// BELLECharmAnalysis.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_BELLECharmAnalysis_H
-#define HERWIG_BELLECharmAnalysis_H
-//
-// This is the declaration of the BELLECharmAnalysis class.
-//
-
-#include "ThePEG/Handlers/AnalysisHandler.h"
-#include "Herwig/Utilities/Histogram.h"
-
-namespace Herwig {
-
-using namespace ThePEG;
-
-/** \ingroup Analysis
- * The BELLECharmAnalysis class is designed to compared the results of
- * Herwig at 10.52 GeV with data from the BELLE experiment.
- *
- * @see \ref BELLECharmAnalysisInterfaces "The interfaces"
- * defined for BELLECharmAnalysis.
- */
-class BELLECharmAnalysis: public AnalysisHandler {
-
-public:
-
-  /**
-   * The default constructor.
-   */
-  BELLECharmAnalysis() : _s(), _onshell(false), _ratioDstar(),
-			 _ratioDs(), _ratioLambda(), _weight()
-  {}
-
-  /** @name Virtual functions required by the AnalysisHandler class. */
-  //@{
-  /**
-   * Analyze a given Event. Note that a fully generated event
-   * may be presented several times, if it has been manipulated in
-   * between. The default version of this function will call transform
-   * to make a lorentz transformation of the whole event, then extract
-   * all final state particles and call analyze(tPVector) of this
-   * analysis object and those of all associated analysis objects. The
-   * default version will not, however, do anything on events which
-   * have not been fully generated, or have been manipulated in any
-   * way.
-   * @param event pointer to the Event to be analyzed.
-   * @param ieve the event number.
-   * @param loop the number of times this event has been presented.
-   * If negative the event is now fully generated.
-   * @param state a number different from zero if the event has been
-   * manipulated in some way since it was last presented.
-   */
-  virtual void analyze(tEventPtr event, long ieve, int loop, int state);
-
-  /**
-   * Analyze the given vector of particles. The default version calls
-   * analyze(tPPtr) for each of the particles.
-   * @param particles the vector of pointers to particles to be analyzed
-   */
-  virtual void analyze(const tPVector & particles);
-
-  /**
-   * Analyze the given particle.
-   * @param particle pointer to the particle to be analyzed.
-   */
-  virtual void analyze(tPPtr particle);
-  //@}
-
-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 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. Called in the run phase just before
-   * a run begins.
-   */
-  virtual void doinitrun();
-
-  /**
-   * Finalize this object. Called in the run phase just after a
-   * run has ended. Used eg. to write out statistics.
-   */
-  virtual void dofinish();
-  //@}
-
-private:
-
-  /**
-   * The static object used to initialize the description of this class.
-   * Indicates that this is a concrete class with persistent data.
-   */
-  static ClassDescription<BELLECharmAnalysis> initBELLECharmAnalysis;
-
-  /**
-   * The assignment operator is private and must never be called.
-   * In fact, it should not even be implemented.
-   */
-  BELLECharmAnalysis & operator=(const BELLECharmAnalysis &);
-
-private:
-
-  /**
-   *  CMS energy squared
-   */
-  Energy2 _s;
-
-  /**
-   *  Whether this is on-shell or continuum
-   */
-  bool _onshell;
-
-  /**
-   *  Histogram for \f$D^{*+}\f$
-   */
-  HistogramPtr _histDstarplus;
-
-  /**
-   *  Histogram for \f$D^{*0}\f$
-   */
-  HistogramPtr _histDstar0;
-
-  /**
-   *  Histogram for \f$D^0\f$
-   */
-  HistogramPtr _histD0;
-
-  /**
-   *  Histogram for \f$D^+\f$
-   */
-  HistogramPtr _histDplus;
-
-  /**
-   *  Histogram for \f$D^+_s\f$
-   */
-  HistogramPtr _histDs;
-
-  /**
-   *  Histogram for \f$\Lambda_c^+\f$
-   */
-  HistogramPtr _histLambda;
-
-  /**
-   *  Ratios
-   */
-  //@{
-  /**
-   *  Ratio for \f$D^{*0}+D^{*+}\f$
-   */
-  double _ratioDstar;
-
-  /**
-   *  Ratio for \f$D_s\f$
-   */
-  double _ratioDs;
-
-  /**
-   *  Ratio for \f$\Lambda_c^+\f$
-   */
-  double _ratioLambda;
-  //@}
-
-  /**
-   *  Statistics for the ratios
-   */
-  //@{
-  /**
-   *  Statistics for \f$D^0+D^+\f$
-   */
-  Statistic _statD;
-
-  /**
-   *  Statistics for  \f$D^{*0}+D^{*+}\f$
-   */
-  Statistic _statDstar;
-  
-  /**
-   *  Statistics for \f$D_s\f$
-   */
-  Statistic _statDs;
-
-  /**
-   *  Statistics for \f$\Lambda_c^+\f$
-   */
-  Statistic _statLambda;
-  //@}
-
-  /**
-   *  The weight for an event
-   */
-  double _weight;
-};
-
-}
-
-#include "ThePEG/Utilities/ClassTraits.h"
-
-namespace ThePEG {
-
-/** @cond TRAITSPECIALIZATIONS */
-
-/** This template specialization informs ThePEG about the
- *  base classes of BELLECharmAnalysis. */
-template <>
-struct BaseClassTrait<Herwig::BELLECharmAnalysis,1> {
-  /** Typedef of the first base class of BELLECharmAnalysis. */
-  typedef AnalysisHandler NthBase;
-};
-
-/** This template specialization informs ThePEG about the name of
- *  the BELLECharmAnalysis class and the shared object where it is defined. */
-template <>
-struct ClassTraits<Herwig::BELLECharmAnalysis>
-  : public ClassTraitsBase<Herwig::BELLECharmAnalysis> {
-  /** Return a platform-independent class name */
-  static string className() { return "Herwig::BELLECharmAnalysis"; }
-  /**
-   * The name of a file containing the dynamic library where the class
-   * BELLECharmAnalysis is implemented. It may also include several, space-separated,
-   * libraries if the class BELLECharmAnalysis depends on other classes (base classes
-   * excepted). In this case the listed libraries will be dynamically
-   * linked in the order they are specified.
-   */
-  static string library() { return "HwAnalysis.so HwLEPAnalysis.so"; }
-};
-
-/** @endcond */
-
-}
-
-#endif /* HERWIG_BELLECharmAnalysis_H */
diff --git a/Analysis/BFragmentationAnalysisHandler.cc b/Analysis/BFragmentationAnalysisHandler.cc
deleted file mode 100644
--- a/Analysis/BFragmentationAnalysisHandler.cc
+++ /dev/null
@@ -1,242 +0,0 @@
-// -*- C++ -*-
-//
-// BFragmentationAnalysisHandler.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 BFragmentationAnalysisHandler class.
-//
-
-#include "BFragmentationAnalysisHandler.h"
-#include "ThePEG/PDT/EnumParticles.h"
-#include "ThePEG/Repository/EventGenerator.h"
-#include "ThePEG/EventRecord/Event.h"
-#include "Herwig/Utilities/StandardSelectors.h"
-#include "ThePEG/Interface/ClassDocumentation.h"
-#include "ThePEG/Persistency/PersistentOStream.h"
-#include "ThePEG/Persistency/PersistentIStream.h"
-
-using namespace Herwig;
-
-void BFragmentationAnalysisHandler::analyze(tEventPtr event, long,
-					    int loop, int state) {
-  if ( loop > 0 || state != 0 || !event ) return;
-  double weight = event->weight();
-  ///////////////////////////
-  // Hadron Level Analysis //
-  ///////////////////////////
-  // extract the weakly decaying B hadrons using set to avoid double counting
-  set<PPtr> allParticles;
-  event->select(inserter(allParticles),WeakBHadronSelector());
-  // convert to vector
-  tPVector particles(allParticles.begin(),allParticles.end());
-  // numerator
-  _emax = 0.5*generator()->maximumCMEnergy();   
-  analyze(particles,weight); 
-
-  ////////////////////////////////////////
-  // Parton Level Analysis (e+e-->bbar) //
-  ////////////////////////////////////////
-  // Get all the particles from the perturbative bit of the events. Find the
-  // b and bbar coming straight out of the Z/photon (b_orig, bbar_orig and 
-  // ZGamma respectively). Then go and find the b and bbar that have their 
-  // maximal off-shellness i.e. just before the first gluon is emitted. 
-  // Finally go off down the b quark lines to find the b's just before they
-  // hadronize (b_end and bbar_end respectively).
-  ParticleSet pert=event->primaryCollision()->step(1)->all();
-  analyze_bquarks(pert,weight);
-}
-
-void BFragmentationAnalysisHandler::analyze(tPPtr part, double weight) {
-  _fragBxE ->addWeighted(part->momentum().e()/_emax, weight);
-  _fragBxEa->addWeighted(part->momentum().e()/_emax, weight);
-}
-
-void BFragmentationAnalysisHandler::analyze_bquarks(ParticleSet pert, 
-						    double weight) {
-  ParticleSet::const_iterator pit;
-  PPtr b_orig,bbar_orig,ZGamma,b_start,bbar_start,b_end,bbar_end;
-  // First go through all the particles looking for b's coming out of Z/gamma's:
-  for(pit=pert.begin();pit!=pert.end();++pit) {
-    PPtr bline = *pit;
-    if(abs((*pit)->id())==5) {
-      while(abs(bline->parents()[0]->id())==5) bline=bline->parents()[0];  
-    }
-    if(bline->id()== 5&&(bline->parents()[0]->id()!=21)) b_orig    = bline;
-    if(bline->id()==-5&&(bline->parents()[0]->id()!=21)) bbar_orig = bline;
-  }
-  if(!b_orig) return;
-  if(!bbar_orig) return;
-  // Note down the Z/Photon that decays to the b & bbar:
-  if(b_orig->parents()[0]==bbar_orig->parents()[0]) 
-      ZGamma = b_orig->parents()[0];
-  PPtr root_b[] = {b_orig,bbar_orig};
-  // Now go and look for the b & bbar just before the first gluon is emitted:
-  for(int ix=0;ix<=1;ix++) {
-      while(root_b[ix]->momentum().m()<=
-	    getParticleData(ParticleID::b)->mass()+1.e-8*GeV) {
-	  for(unsigned int jx=0;jx<root_b[ix]->children().size();jx++) 
-	      if(root_b[ix]->id()==root_b[ix]->children()[jx]->id()) 
-		  root_b[ix]=root_b[ix]->children()[jx]; 
-      }
-  }
-  b_start    = root_b[0];
-  bbar_start = root_b[1];
-  // Now go and find the b and bbar quarks at the end of the shower before 
-  // they turn into hadrons.
-  for(unsigned int ix=0;ix<=1;ix++) {
-      while(root_b[ix]->momentum().m()>=
-	    getParticleData(ParticleID::b)->constituentMass()+1.e-8*GeV) {
-	  for(unsigned int jx=0;jx<root_b[ix]->children().size();jx++) 
-	      if(root_b[ix]->id()==root_b[ix]->children()[jx]->id()) 
-		  root_b[ix]=root_b[ix]->children()[jx]; 
-      }
-  }
-  b_end    = root_b[0];
-  bbar_end = root_b[1];
-  // Fill the energy fraction histograms with that of the b quarks.
-  _fragbquarkxE      ->
-    addWeighted( b_end->momentum().e()/_emax   ,weight);
-  _fragbquarkxE      ->
-    addWeighted( bbar_end->momentum().e()/_emax,weight);
-  _fragbquarkjetmass ->
-    addWeighted( b_start->momentum().m()/GeV   ,weight);
-  _fragbquarkjetmass ->
-    addWeighted( bbar_start->momentum().m()/GeV,weight);
-}
-
-NoPIOClassDescription<BFragmentationAnalysisHandler> 
-BFragmentationAnalysisHandler::initBFragmentationAnalysisHandler;
-// Definition of the static class description member.
-
-void BFragmentationAnalysisHandler::Init() {
-
-  static ClassDocumentation<BFragmentationAnalysisHandler> documentation
-    ("The BFragmentationAnalysisHandler class performs analysis"
-     " of the B fragmentation function",
-     "The B fragmentation function analysis uses data from \\cite{Heister:2001jg,Abe:2002iq}.",
-     "  %\\cite{Heister:2001jg}\n"
-     "\\bibitem{Heister:2001jg}\n"
-     "  A.~Heister {\\it et al.}  [ALEPH Collaboration],\n"
-     "  %``Study of the fragmentation of b quarks into B mesons at the Z peak,''\n"
-     "  Phys.\\ Lett.\\  B {\\bf 512}, 30 (2001)\n"
-     "  [arXiv:hep-ex/0106051].\n"
-     "  %%CITATION = PHLTA,B512,30;%%\n"
-     "%\\cite{Abe:2002iq}\n"
-     "\\bibitem{Abe:2002iq}\n"
-     "  K.~Abe {\\it et al.}  [SLD Collaboration],\n"
-     "  %``Measurement of the b-quark fragmentation function in Z0 decays,''\n"
-     "  Phys.\\ Rev.\\  D {\\bf 65}, 092006 (2002)\n"
-     "  [Erratum-ibid.\\  D {\\bf 66}, 079905 (2002)]\n"
-     "  [arXiv:hep-ex/0202031].\n"
-     "  %%CITATION = PHRVA,D65,092006;%%\n"
-     );
-
-}
-
-void BFragmentationAnalysisHandler::dofinish() {
-  useMe();
-  AnalysisHandler::dofinish();
-  // output the histograms
-  string fname = generator()->filename() + string("-") + name() + string(".top");
-  ofstream output(fname.c_str());
-  using namespace HistogramOptions;
-  double chisq,minfrac=0.05;
-  unsigned int npoint;
-  _fragBxE->chiSquared(chisq,npoint,minfrac);
-  generator()->log() << "Chi Square = " << chisq << " for " << npoint 
-		     << " degrees of freedom for SLD b hadron fragmentation "
-		     << "distribution or " << chisq/npoint << " per degree of freedom\n"; 
-  _fragBxE->topdrawOutput(output,Frame|Errorbars,
-			  "RED",
-			  "B Hadron fragmentation function compared to SLD data",
-			  "                                                    ",
-			  "1/SdS/dx0B1",
-			  "  G G   X X",
-			  "x0B1",
-			  " X X");
-  _fragBxEa->chiSquared(chisq,npoint,minfrac);
-  generator()->log() << "Chi Square = " << chisq << " for " << npoint 
-		     << " degrees of freedom for ALEPH b hadron fragmentation "
-		     << "distribution or " << chisq/npoint << " per degree of freedom\n"; 
-  _fragBxEa->topdrawOutput(output,Frame|Errorbars,
-			   "RED",
-			   "B Hadron framgentation function compared to ALEPH data",
-			   "                                                      ",
-			   "1/SdS/dx0B1",
-			   "  G G   X X",
-			   "x0B1",
-			   " X X");
-  _fragbquarkxE->topdrawOutput(output,Frame|Smooth,
-		       "RED",
-		       "b quark fragmentation function",
-		       "                              ",
-		       "1/SdS/dx0B1",
-		       "  G G   X X",
-		       "x0B1",
-		       " X X");
-  _fragbquarkjetmass->topdrawOutput(output,Frame|Smooth,
-		       "RED",
-		       "b quark jet mass",
-		       "                                                    ",
-		       "1/SdS/dm0J1223",
-		       "  G G   X XX X",
-		       "m0J1223",
-		       " X XX X");
-  output.close();
-}
-
-void BFragmentationAnalysisHandler::doinitrun() {
-  AnalysisHandler::doinitrun();
-  // SLD binning
-  double BxEbins[] = {0.00, 0.04, 0.08, 0.12, 0.16, 
-		      0.20, 0.24, 0.28, 0.32, 0.36, 
-		      0.40, 0.44, 0.48, 0.52, 0.56, 
-		      0.60, 0.64, 0.68, 0.72, 0.76, 
-		      0.80, 0.84, 0.88, 0.92, 0.96, 
-		      1.0};
-  double BxEdata[] = {0.000,0.000,0.000,0.116,0.198,
-		      0.247,0.264,0.308,0.370,0.426,
-		      0.501,0.577,0.685,0.833,1.055,
-		      1.311,1.667,2.080,2.566,2.934,
-		      3.104,2.856,1.954,0.841,0.108};
-  double BxEerror[]= {0.000,0.000,0.000,0.030,0.037,
-		      0.030,0.029,0.032,0.033,0.034,
-		      0.039,0.041,0.042,0.053,0.074,
-		      0.089,0.088,0.084,0.116,0.178,
-		      0.235,0.179,0.162,0.215,0.062};
-  vector<double> bins(BxEbins,BxEbins+26), data(BxEdata,BxEdata+25),
-    error(BxEerror,BxEerror+25);
-  _fragBxE  = new_ptr(Histogram(bins,data,error));
-  // ALEPH binning
-  double BxEabins[] = {0.0   ,0.1   ,0.25  ,0.35  ,0.45  , 
-		       0.55  ,0.6   ,0.65  ,0.7   ,0.725 , 
-		       0.75  ,0.775 ,0.8   ,0.825 ,0.85  , 
-		       0.875 ,0.9   ,0.925 ,0.95  ,0.975 , 
-		       1.};
-  double BxEadata[] = {0.0000,0.1193,0.2810,0.4510,0.7410,
-		       1.0180,1.2760,1.7020,2.1080,2.3520,
-		       2.5360,2.7960,2.9840,3.1000,2.9080,
-		       2.6440,2.0880,1.3480,0.4840,0.0400};
-  double BxEaerrora[] = {0.0000,0.0487,0.0470,0.0390,0.0590,
-			 0.0660,0.0640,0.0660,0.0760,0.0840,
-			 0.0920,0.1040,0.1080,0.1000,0.0880,
-			 0.0880,0.1160,0.1240,0.0760,0.0120};
-  double BxEaerrorb[] = {0.0000,0.0573,0.0350,0.0430,0.0660,
-			 0.0680,0.0640,0.0740,0.0960,0.1120,
-			 0.1240,0.1360,0.1320,0.1240,0.1040,
-			 0.1360,0.1880,0.1880,0.1000,0.0200};
-  double BxEaerror[20];
-  for(unsigned int ix=0;ix<20;++ix){BxEaerror[ix]=sqrt(sqr(BxEaerrora[ix])+
-						       sqr(BxEaerrorb[ix]));}
-  bins  = vector<double>(BxEabins,BxEabins+21);
-  data  = vector<double>(BxEadata,BxEadata+20);
-  error = vector<double>(BxEaerror,BxEaerror+20);
-  _fragBxEa = new_ptr(Histogram(bins,data,error));
-  _fragbquarkxE = new_ptr(Histogram(0.,1.0,100));
-  _fragbquarkjetmass = new_ptr(Histogram(0.,90.0,90));
-}
diff --git a/Analysis/BFragmentationAnalysisHandler.h b/Analysis/BFragmentationAnalysisHandler.h
deleted file mode 100644
--- a/Analysis/BFragmentationAnalysisHandler.h
+++ /dev/null
@@ -1,198 +0,0 @@
-// -*- C++ -*-
-//
-// BFragmentationAnalysisHandler.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_BFragmentationAnalysisHandler_H
-#define HERWIG_BFragmentationAnalysisHandler_H
-//
-// This is the declaration of the BFragmentationAnalysisHandler class.
-//
-
-#include "ThePEG/Repository/CurrentGenerator.h"
-#include "ThePEG/Handlers/AnalysisHandler.h"
-#include "Herwig/Utilities/Histogram.h"
-#include "ThePEG/EventRecord/Event.h"
-
-namespace Herwig {
-
-using namespace ThePEG;
-
-/** \ingroup Analysis
- * The BFragmentationAnalysisHandler class is designed to compare
- * the fragmentation function for weakly decaying B hadrons with data
- * from SLD and ALEPH.
- *
- * @see \ref BFragmentationAnalysisHandlerInterfaces "The interfaces"
- * defined for BFragmentationAnalysisHandler.
- */
-class BFragmentationAnalysisHandler: public AnalysisHandler {
-
-public:
-
-  /**
-   * The default constructor.
-   */
-  BFragmentationAnalysisHandler() : _emax() {}
-
-  /** @name Virtual functions required by the AnalysisHandler class. */
-  //@{
-  /**
-   * Analyze a given Event. Note that a fully generated event
-   * may be presented several times, if it has been manipulated in
-   * between. The default version of this function will call transform
-   * to make a lorentz transformation of the whole event, then extract
-   * all final state particles and call analyze(tPVector) of this
-   * analysis object and those of all associated analysis objects. The
-   * default version will not, however, do anything on events which
-   * have not been fully generated, or have been manipulated in any
-   * way.
-   * @param event pointer to the Event to be analyzed.
-   * @param ieve the event number.
-   * @param loop the number of times this event has been presented.
-   * If negative the event is now fully generated.
-   * @param state a number different from zero if the event has been
-   * manipulated in some way since it was last presented.
-   */
-  virtual void analyze(tEventPtr event, long ieve, int loop, int state);
-
-  /**
-   *  Identifies which step(2) final state particles originate
-   *  from the b/bbar...
-   */
-  void analyze_bquarks(ParticleSet, double);
-
-  /**
-   * Analyze the given particle.
-   * @param particle pointer to the particle to be analyzed.
-   * @param weight The weight for the event
-   */
-  virtual void analyze(tPPtr particle, double weight);
-
-  using AnalysisHandler::analyze;
-  //@}
-
-public:
-
-  /**
-   * 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 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. Called in the run phase just before
-   * a run begins.
-   */
-  virtual void doinitrun();
-
-  /**
-   * Finalize this object. Called in the run phase just after a
-   * run has ended. Used eg. to write out statistics.
-   */
-  virtual void dofinish();
-  //@}
-
-private:
-
-  /**
-   * The static object used to initialize the description of this class.
-   * Indicates that this is a concrete class with persistent data.
-   */
-  static NoPIOClassDescription<BFragmentationAnalysisHandler> initBFragmentationAnalysisHandler;
-
-  /**
-   * The assignment operator is private and must never be called.
-   * In fact, it should not even be implemented.
-   */
-  BFragmentationAnalysisHandler & operator=(const BFragmentationAnalysisHandler &);
-
-private:
-  
-  /**
-   *  Histogram for the SLD binning
-   */
-  HistogramPtr _fragBxE;
-
-  /**
-   *  Histogram for the ALEPH binning
-   */
-  HistogramPtr _fragBxEa;
-
-  /**
-   *  Histograms for quark energy fraction
-   */
-  HistogramPtr _fragbquarkxE;
-
-  /**
-   * Histograms for b jet mass
-   */
-  HistogramPtr _fragbquarkjetmass;
-
-  /**
-   *  Centre-of-mass energy of the collision
-   */
-  Energy _emax;
-
-};
-
-}
-
-#include "ThePEG/Utilities/ClassTraits.h"
-
-namespace ThePEG {
-
-/** @cond TRAITSPECIALIZATIONS */
-
-/** This template specialization informs ThePEG about the
- *  base classes of BFragmentationAnalysisHandler. */
-template <>
-struct BaseClassTrait<Herwig::BFragmentationAnalysisHandler,1> {
-  /** Typedef of the first base class of BFragmentationAnalysisHandler. */
-  typedef AnalysisHandler NthBase;
-};
-
-/** This template specialization informs ThePEG about the name of
- *  the BFragmentationAnalysisHandler class and the shared object where it is defined. */
-template <>
-struct ClassTraits<Herwig::BFragmentationAnalysisHandler>
-  : public ClassTraitsBase<Herwig::BFragmentationAnalysisHandler> {
-  /** Return a platform-independent class name */
-  static string className() { return "Herwig::BFragmentationAnalysisHandler"; }
-  /** Return the name(s) of the shared library (or libraries) be loaded to get
-   *  access to the BFragmentationAnalysisHandler class and any other class on which it depends
-   *  (except the base class). */
-  static string library() { return "HwAnalysis.so HwLEPAnalysis.so"; }
-};
-
-/** @endcond */
-
-}
-
-#endif /* HERWIG_BFragmentationAnalysisHandler_H */
diff --git a/Analysis/CLEOCharmAnalysis.cc b/Analysis/CLEOCharmAnalysis.cc
deleted file mode 100644
--- a/Analysis/CLEOCharmAnalysis.cc
+++ /dev/null
@@ -1,203 +0,0 @@
-// -*- C++ -*-
-//
-// CLEOCharmAnalysis.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 CLEOCharmAnalysis class.
-//
-
-#include "CLEOCharmAnalysis.h"
-#include "ThePEG/Interface/ClassDocumentation.h"
-#include "ThePEG/PDT/EnumParticles.h"
-#include "ThePEG/EventRecord/Event.h"
-#include "ThePEG/Repository/CurrentGenerator.h"
-
-using namespace Herwig;
-
-void CLEOCharmAnalysis::analyze(tEventPtr event, long, int, int) {
-  _s = (event->incoming().first ->momentum()+
-	event->incoming().second->momentum()).m2();
-  double weight = event->weight();
-  set<tPPtr> particles;
-  StepVector steps = event->primaryCollision()->steps();
-  for ( StepVector::const_iterator it = steps.begin()+2;
-	it != steps.end(); ++it ) {
-    (**it).select(inserter(particles), ThePEG::AllSelector());
-  }
-  tPVector output;
-  for(set<tPPtr>::const_iterator it = particles.begin(); 
-      it != particles.end(); ++it) {
-    long id = abs((*it)->id());
-    if(id==ParticleID::Dplus   || id==ParticleID::Dstarplus    ||
-       id==ParticleID::D0      || id==ParticleID::Dstar0       )
-      output.push_back(*it);
-  }
-  analyze(output,weight);
-}
-
-void CLEOCharmAnalysis::analyze(tPPtr particle, double weight) {
-  // Calls analyze() for each particle.
-  double xp = particle->momentum().vect().mag()/
-    sqrt(0.25*_s-sqr(particle->mass()));
-  int id = abs(particle->id());
-  if(id==ParticleID::Dstarplus) {
-    _histDstarplus->addWeighted(xp,weight);
-  }
-  else if(id==ParticleID::Dstar0) {
-    _histDstar0   ->addWeighted(xp,weight);
-  }
-  else if(id==ParticleID::D0) {
-    _histD0       ->addWeighted(xp,weight);
-  }
-  else if(id==ParticleID::Dplus) {
-    _histDplus    ->addWeighted(xp,weight);
-  }
-}
-
-NoPIOClassDescription<CLEOCharmAnalysis> CLEOCharmAnalysis::initCLEOCharmAnalysis;
-// Definition of the static class description member.
-
-void CLEOCharmAnalysis::Init() {
-
-  static ClassDocumentation<CLEOCharmAnalysis> documentation
-    ("CLEO Charm meson analysis class",
-     "The CLEO Charm meson analysis uses data from \\cite{Artuso:2004pj}.",
-     "%\\cite{Artuso:2004pj}\n"
-     "\\bibitem{Artuso:2004pj}\n"
-     "  M.~Artuso {\\it et al.}  [CLEO Collaboration],\n"
-     "  %``Charm meson spectra in $e^{+} e^{-}$ annihilation at 10.5-GeV c.m.e,''\n"
-     "  Phys.\\ Rev.\\  D {\\bf 70}, 112001 (2004)\n"
-     "  [arXiv:hep-ex/0402040].\n"
-     "  %%CITATION = PHRVA,D70,112001;%%\n"
-     );
-
-}
-
-void CLEOCharmAnalysis::dofinish() {
-  useMe();
-  AnalysisHandler::dofinish();
-  string fname = generator()->filename() + 
-    string("-") + name() + string(".top");
-  ofstream output(fname.c_str());
-  using namespace HistogramOptions;
-  double chisq=0.,minfrac=0.05;
-  unsigned int ndegrees;
-  _histDstarplus->chiSquared(chisq,ndegrees,minfrac);
-  generator()->log() << "Chi Square = " << chisq << " for " << ndegrees 
-			  << " degrees of freedom for CLEO D*+ distribution\n";
-  _histDstar0   ->chiSquared(chisq,ndegrees,minfrac);
-  generator()->log() << "Chi Square = " << chisq << " for " << ndegrees 
-			  << " degrees of freedom for CLEO D*0 distribution\n";
-  _histD0       ->chiSquared(chisq,ndegrees,minfrac);
-  generator()->log() << "Chi Square = " << chisq << " for " << ndegrees 
-			  << " degrees of freedom for CLEO D0 distribution\n";
-  _histDplus    ->chiSquared(chisq,ndegrees,minfrac);
-  generator()->log() << "Chi Square = " << chisq << " for " << ndegrees 
-			  << " degrees of freedom for CLEO D+ distribution\n";
-  _histDstarplus->topdrawOutput(output,Frame|Errorbars,
-				"RED",
-				"D2*+3",
-				" X  X",
-				"1/SdS/dx0p1",
-				"  G G   X X",
-				"x0p1",
-				" X X");
-  _histDstar0->topdrawOutput(output,Frame|Errorbars,
-			     "RED",
-			     "D2*03",
-			     " X  X",
-			     "1/SdS/dx0p1",
-			     "  G G   X X",
-			     "x0p1",
-			     " X X");
-  _histD0->topdrawOutput(output,Frame|Errorbars,
-			 "RED",
-			 "D203",
-			 " X X",
-			 "1/SdS/dx0p1",
-			 "  G G   X X",
-			 "x0p1",
-			 " X X");
-  _histDplus->topdrawOutput(output,Frame|Errorbars,
-			    "RED",
-			    "D2+3",
-			    " X X",
-			    "1/SdS/dx0p1",
-			    "  G G   X X",
-			    "x0p1",
-			    " X X");
-}
-
-void CLEOCharmAnalysis::doinitrun() {
-  AnalysisHandler::doinitrun();
-  double vals[]={0.10,0.15,0.20,0.25,0.30,0.35,0.40,0.45,0.50,0.55,
-		 0.60,0.65,0.70,0.75,0.80,0.85,0.90,0.95,1.00};
-  // data and errors for D+
-  double dplusdata     []={ 161, 320, 356, 413, 693,
-			    909,1042,1271,1357,1370,
-			   1291,1129, 952, 694, 449, 223,  74};
-  double dpluserror    []={  83,  92,  92,  94,  60,
-			     56,  53,  38,  38,  36,
-			     34,  29,  25,  19,  13,   7,   4};
-  // data and errors for D0
-  double d0data        []={ 173, 431, 529, 882,1156,
-			   1670,2349,2822,3194,3475,
-			   3371,3007,2549,2008,1383, 829, 339,  90};
-  double d0error       []={ 109, 186, 209,  84,  83,
-			     94, 110, 122,  56,  58,
-			     56,  51,  46,  39,  30,  21,  11,   5};
-  // data and errors for D*+
-  double dstarplusdata []={ 146, 253, 348, 494, 624,
-			    920,1108,1244,1286,1248,
-			   1113, 932, 723, 531, 310, 119};
-  double dstarpluserror[]={  86,  60,  60,  60,  46,
-			     50,  32,  33,  32,  31,
-			     29,  25,  21,  17,  12,   8};
-  // data and errors for D*0
-  double dstar0data    []={ 108, 292, 387, 425, 594, 
-			    546, 897,1085,1162,1230,
-			   1198,1055, 865, 694, 471, 289, 121};
-  double dstar0error   []={ 121, 115, 111, 103,  98,
-			     92, 108,  70,  65,  64,
-			     60,  52,  45,  36,  27,  20,  15};
-  // D+ histogram
-  vector<double> bins,data,error;
-  for(unsigned int ix=0;ix<4;++ix) {
-    if(ix==0) {
-      bins  = vector<double>(vals+1,vals+19);
-      data  = vector<double>(dplusdata ,dplusdata +17);
-      error = vector<double>(dpluserror,dpluserror+17);
-    }
-    else if(ix==1) {
-      bins  = vector<double>(vals,vals+19);
-      data  = vector<double>(d0data ,d0data +18);
-      error = vector<double>(d0error,d0error+18);
-    }
-    else if(ix==2) {
-      bins  = vector<double>(vals+2,vals+19);
-      data  = vector<double>(dstarplusdata ,dstarplusdata +16);
-      error = vector<double>(dstarpluserror,dstarpluserror+16);
-    }
-    else if(ix==3) {
-      bins  = vector<double>(vals+1,vals+19);
-      data  = vector<double>(dstar0data ,dstar0data +17);
-      error = vector<double>(dstar0error,dstar0error+17);
-    }
-    double norm=0.;
-    for(unsigned int iy=0;iy<data.size();++iy) norm+=data[iy];
-    norm *= 0.05; 
-    for(unsigned int iy=0;iy<data.size();++iy) {
-      data [iy] /= norm;
-      error[iy] /= norm;
-    }
-    if(ix==0)      _histDplus=new_ptr(Histogram(bins,data,error));
-    else if(ix==1) _histD0=new_ptr(Histogram(bins,data,error));
-    else if(ix==2) _histDstarplus=new_ptr(Histogram(bins,data,error));
-    else if(ix==3) _histDstar0=new_ptr(Histogram(bins,data,error));
-  }
-}
diff --git a/Analysis/CLEOCharmAnalysis.h b/Analysis/CLEOCharmAnalysis.h
deleted file mode 100644
--- a/Analysis/CLEOCharmAnalysis.h
+++ /dev/null
@@ -1,197 +0,0 @@
-// -*- C++ -*-
-//
-// CLEOCharmAnalysis.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_CLEOCharmAnalysis_H
-#define HERWIG_CLEOCharmAnalysis_H
-//
-// This is the declaration of the CLEOCharmAnalysis class.
-//
-
-#include "ThePEG/Handlers/AnalysisHandler.h"
-#include "Herwig/Utilities/Histogram.h"
-
-namespace Herwig {
-
-using namespace ThePEG;
-
-/** \ingroup Analysis
- * The CLEOCharmAnalysis class compares the results of Herwig at 10.52 GeV
- * with data on Charm hadron spectra from the CLEO experiment
- *
- * @see \ref CLEOCharmAnalysisInterfaces "The interfaces"
- * defined for CLEOCharmAnalysis.
- */
-class CLEOCharmAnalysis: public AnalysisHandler {
-
-public:
-
-  /**
-   * The default constructor.
-   */
-  CLEOCharmAnalysis() : _s() {}
-
-  /** @name Virtual functions required by the AnalysisHandler class. */
-  //@{
-  /**
-   * Analyze a given Event. Note that a fully generated event
-   * may be presented several times, if it has been manipulated in
-   * between. The default version of this function will call transform
-   * to make a lorentz transformation of the whole event, then extract
-   * all final state particles and call analyze(tPVector) of this
-   * analysis object and those of all associated analysis objects. The
-   * default version will not, however, do anything on events which
-   * have not been fully generated, or have been manipulated in any
-   * way.
-   * @param event pointer to the Event to be analyzed.
-   * @param ieve the event number.
-   * @param loop the number of times this event has been presented.
-   * If negative the event is now fully generated.
-   * @param state a number different from zero if the event has been
-   * manipulated in some way since it was last presented.
-   */
-  virtual void analyze(tEventPtr event, long ieve, int loop, int state);
-
-  /**
-   * Analyze the given particle.
-   * @param particle pointer to the particle to be analyzed.
-   * @param weight The weight for the event
-   */
-  virtual void analyze(tPPtr particle, double weight);
-
-  using AnalysisHandler::analyze;
-  //@}
-
-public:
-
-  /**
-   * 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 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. Called in the run phase just before
-   * a run begins.
-   */
-  virtual void doinitrun();
-
-  /**
-   * Finalize this object. Called in the run phase just after a
-   * run has ended. Used eg. to write out statistics.
-   */
-  virtual void dofinish();
-  //@}
-
-private:
-
-  /**
-   * The static object used to initialize the description of this class.
-   * Indicates that this is a concrete class with persistent data.
-   */
-  static NoPIOClassDescription<CLEOCharmAnalysis> initCLEOCharmAnalysis;
-
-  /**
-   * The assignment operator is private and must never be called.
-   * In fact, it should not even be implemented.
-   */
-  CLEOCharmAnalysis & operator=(const CLEOCharmAnalysis &);
-
-private:
-
-  /**
-   *  Histograms
-   */
-  //@{
-  /**
-   *  Histogram for \f$D^+\f$
-   */
-  HistogramPtr _histDplus;
-
-  /**
-   *  Histogram for \f$D^0\f$
-   */
-  HistogramPtr _histD0;
-
-  /**
-   *  Histogram for \f$D^{*+}\f$
-   */
-  HistogramPtr _histDstarplus;
-
-  /**
-   *  Histogram for \f$D^{*0}\f$
-   */
-  HistogramPtr _histDstar0;
-  //@}
-
-  /**
-   *  CMF energy squared
-   */
-  Energy2 _s;
-};
-
-}
-
-#include "ThePEG/Utilities/ClassTraits.h"
-
-namespace ThePEG {
-
-/** @cond TRAITSPECIALIZATIONS */
-
-/** This template specialization informs ThePEG about the
- *  base classes of CLEOCharmAnalysis. */
-template <>
-struct BaseClassTrait<Herwig::CLEOCharmAnalysis,1> {
-  /** Typedef of the first base class of CLEOCharmAnalysis. */
-  typedef AnalysisHandler NthBase;
-};
-
-/** This template specialization informs ThePEG about the name of
- *  the CLEOCharmAnalysis class and the shared object where it is defined. */
-template <>
-struct ClassTraits<Herwig::CLEOCharmAnalysis>
-  : public ClassTraitsBase<Herwig::CLEOCharmAnalysis> {
-  /** Return a platform-independent class name */
-  static string className() { return "Herwig::CLEOCharmAnalysis"; }
-  /**
-   * The name of a file containing the dynamic library where the class
-   * CLEOCharmAnalysis is implemented. It may also include several, space-separated,
-   * libraries if the class CLEOCharmAnalysis depends on other classes (base classes
-   * excepted). In this case the listed libraries will be dynamically
-   * linked in the order they are specified.
-   */
-  static string library() { return "HwAnalysis.so HwLEPAnalysis.so"; }
-};
-
-/** @endcond */
-
-}
-
-#endif /* HERWIG_CLEOCharmAnalysis_H */
diff --git a/Analysis/EventShapes.cc b/Analysis/EventShapes.cc
deleted file mode 100644
--- a/Analysis/EventShapes.cc
+++ /dev/null
@@ -1,397 +0,0 @@
-// -*- C++ -*-
-//
-// EventShapes.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 EventShapes class.
-//
-
-#include "EventShapes.h"
-#include "ThePEG/Interface/ClassDocumentation.h"
-#include "ThePEG/Persistency/PersistentOStream.h"
-#include "ThePEG/Persistency/PersistentIStream.h"
-
-using namespace Herwig;
-
-NoPIOClassDescription<EventShapes> EventShapes::initEventShapes;
-// Definition of the static class description member.
-
-void EventShapes::Init() {
-
-  static ClassDocumentation<EventShapes> documentation
-    ("There is no documentation for the EventShapes class");
-
-}
-
-void EventShapes::calcHemisphereMasses() {
-  Lorentz5Momentum pos, neg;
-  Energy pden(ZERO),epos(ZERO),eneg(ZERO);
-  for(unsigned int ix=0;ix<_pv.size();++ix)
-    {
-      if(_pv[ix].vect() * thrustAxis() > ZERO)
-	{
-	  pos  += _pv[ix];
-	  // can be replaced with, once perp() is giving non-nan results
-	  //	  for nearly parallel vectors.  
-	  // epos += _pv[ix].perp(thrustAxis());
-	  epos += _pv[ix].vect().cross(thrustAxis()).mag();
-	}
-      else
-	{
-	  neg  += _pv[ix];
-	  // see above
-	  //	  eneg += _pv[ix].perp(thrustAxis()); 
-	  eneg += _pv[ix].vect().cross(thrustAxis()).mag();
-	}
-      pden += _pv[ix].vect().mag();	 
-    }
-  // denominator and masses
-  Energy2 den(sqr(pos.e()+neg.e()));
-  _mPlus = pos.m2()/den;
-  _mMinus = neg.m2()/den;
-  if (_mPlus < _mMinus) swap(_mPlus, _mMinus);
-  // jet broadening
-  _bPlus  = 0.5*epos/pden;
-  _bMinus = 0.5*eneg/pden;
-  if (_bPlus < _bMinus) swap(_bPlus, _bMinus);
-}
-
-vector<double> EventShapes::eigenvalues(const double T[3][3]) {
-
-  // b, c, d are the coefficients of the characteristic polynomial, 
-  // a lambda^3 + b lambda^2 + c lambda + d
-  // where a is chosen to be +1.
-  double t11, t12, t13, t22, t23, t33;
-  t11 = T[0][0]; t12 = T[0][1]; t13 = T[0][2]; 
-  t22 = T[1][1]; t23 = T[1][2]; t33 = T[2][2]; 
-  double b = -(t11 + t22 + t33);
-  double c = t11*t22 + t11*t33 + t22*t33 - sqr(t12) - sqr(t13) - sqr(t23);
-  double d = - t11*t22*t33 - 2.*t12*t23*t13 
-    + t11*sqr(t23) + t22*sqr(t13) + t33*sqr(t12); 
-  
-  // use Cardano's formula to compute the zeros 
-  double p = (3.*c - sqr(b))/3.;
-  double q = (2.*sqr(b)*b - 9.*b*c + 27.*d)/27.;
-  // check diskriminant to double precision
-  vector<double> lambda;
-  if (4.*p*sqr(p) + 27.*sqr(q) > 2.0e-16) {
-    for (unsigned int i=0; i<3; ++i) {
-      lambda.push_back(-1.);
-    }
-    cerr << "EventShapes::eigenvalues: found D = "
-	 << 4.*p*sqr(p) + 27.*sqr(q) 
-	 << " > 0! No real Eigenvalues!\n";
-  } else {
-    // get solutions
-    double alpha = acos(-q/2.*sqrt(-27./(p*p*p)))/3.;
-    double w = sqrt(-4.*p/3.);
-    lambda.push_back(w*cos(alpha) - b/3.);
-    lambda.push_back(-w*cos(alpha+M_PI/3.) - b/3.);
-    lambda.push_back(-w*cos(alpha-M_PI/3.) - b/3.);
-  }
-
-  // sort according to size of eigenvalues
-  // such that lambda[0] > lambda[1] > lambda[2]
-  if (lambda[0] < lambda[1]) {
-    swap(lambda[0], lambda[1]); 
-  }
-  if (lambda[0] < lambda[2]) {
-    swap(lambda[0], lambda[2]); 
-  }
-  if (lambda[1] < lambda[2]) {
-    swap(lambda[1], lambda[2]); 
-  }
-
-  return lambda;
-}
-
-
-Axis EventShapes::eigenvector(const double T[3][3], double lam) {
-  // set up matrix of system to be solved
-  double a11, a12, a13, a23, a33;
-  a11 = T[0][0] - lam; 
-  a12 = T[0][1]; 
-  a13 = T[0][2]; 
-  a23 = T[1][2]; 
-  a33 = T[2][2] - lam;
-
-  // intermediate steps from gauss type algorithm
-  double b1, b2, b4;
-  b1 = a11*a33 - sqr(a13); 
-  b2 = a12*a33 - a13*a23; 
-  b4 = a11*a23 - a12*a13;
-
-  // eigenvector
-  Axis u(b2, -b1, b4);
-
-  return u.unit();
-}
-
-
-vector<Axis> EventShapes::
-eigenvectors(const double T[3][3], const vector<double> &lam) {
-  vector<Axis> n;
-  for (unsigned int i=0; i<3; ++i) {
-    n.push_back(eigenvector(T, lam[i]));
-  }
-  return n;
-}
-
-void EventShapes::diagonalizeTensors(bool linear, bool cmboost) {  
-  // initialize
-  double Theta[3][3];
-  for(int i=0; i<3; ++i) {
-    for(int j=0; j<3; ++j) {
-      Theta[i][j] = 0.0;
-    }
-  }
-  double sum = 0.; 
-  Momentum3 sumvec;
-  vector<double> lam;
-  vector<Axis> n; 
-  // get cm-frame
-  Lorentz5Momentum pcm = Lorentz5Momentum(); 
-  Boost beta; 
-  if (cmboost) {
-    for(unsigned int ix=0;ix<_pv.size();++ix) {
-      pcm += _pv[ix];    
-    }
-    beta = pcm.findBoostToCM();
-  }
-  // get Theta_ij
-  for(unsigned int ix=0;ix<_pv.size();++ix) {
-    Lorentz5Momentum dum(_pv[ix]);
-    if (cmboost) {
-      dum.boost( beta );
-    }
-    Momentum3 pvec = dum.vect();
-    double pvec_MeV[3] = {pvec.x()/MeV, pvec.y()/MeV, pvec.z()/MeV};
-    if (pvec.mag() > ZERO) {
-      sumvec += pvec;
-      if (linear) {
-	sum += pvec.mag()*UnitRemoval::InvE;
-      } else {
-	sum += pvec.mag2()*UnitRemoval::InvE2;
-      }
-      for(int i=0; i<3; ++i) {
-	for(int j=i; j<3; ++j) {
-	  if (linear) {
-	    Theta[i][j] += (pvec_MeV[i])*(pvec_MeV[j])*MeV/(pvec.mag());      
-	  } else {
-	    Theta[i][j] += (pvec_MeV[i])*(pvec_MeV[j]);
-	  }
-	}
-      }
-    }
-  }
-  for(int i=0; i<3; ++i) {
-    for(int j=0; j<3; ++j) {
-      Theta[i][j] /= sum;
-    }
-  }
-  
-  // diagonalize it
-  lam = eigenvalues(Theta);
-  n = eigenvectors(Theta, lam);
-
-  if (linear) {
-    _linTen = lam; 
-    _linTenAxis = n; 
-  } else {
-    _spher = lam; 
-    _spherAxis = n; 
-  }
-}
-
-void EventShapes::calculateThrust() { 
-  // explicitly calculate in units of MeV
-  // algorithm based on Brandt/Dahmen Z Phys C1 (1978)
-  // and 'tasso' code from HERWIG
-  // assumes all momenta in cm system, no explicit boost performed here!
-  // unlike for C and D
-
-  _thrust.clear();
-  _thrustAxis.clear(); 
-
-  if (_pv.size() < 2) {
-    for (int i=0; i<3; ++i) {
-      _thrust.push_back(-1);
-      _thrustAxis.push_back(Axis());
-    }
-    return;
-  }
-
-  // thrust
-  vector<Momentum3> p;
-  Energy psum = ZERO;
-  for(unsigned int l=0; l<_pv.size(); ++l) 
-    {
-      p.push_back(_pv[l].vect());
-      psum += p.back().mag();
-    }
-
-  Axis axis;
-  if (p.size() == 2) {
-    _thrust.push_back(1.0);
-    _thrust.push_back(0.0);
-    _thrust.push_back(0.0);
-    axis = p[0].unit();
-    if (axis.z() < 0) axis = -axis;
-    _thrustAxis.push_back(axis);
-    _thrustAxis.push_back(axis.orthogonal());
-    axis = _thrustAxis[0].cross(_thrustAxis[1]);
-    return;
-  }
-
-  if (p.size() == 3) {
-    if (p[0].mag2() < p[1].mag2()) swap(p[0], p[1]);
-    if (p[0].mag2() < p[2].mag2()) swap(p[0], p[2]);
-    if (p[1].mag2() < p[2].mag2()) swap(p[1], p[2]);
-    // thrust
-    axis = p[0].unit();
-    if (axis.z() < 0) axis = -axis;
-    _thrust.push_back(2.*p[0].mag()/psum);
-    _thrustAxis.push_back(axis);
-    // major
-    axis = (p[1] - (axis*p[1])*axis).unit();
-    if (axis.x() < 0) axis = -axis;
-    _thrust.push_back((abs(p[1]*axis) + abs(p[2]*axis))/psum);
-    _thrustAxis.push_back(axis);
-    // minor
-    _thrust.push_back(0.0);
-    axis = _thrustAxis[0].cross(_thrustAxis[1]);
-    _thrustAxis.push_back(axis);
-    return;
-  }
-
-  // ACHTUNG special case with >= 4 coplanar particles will still fail. 
-  // probably not too important... 
-  Energy2 val;
-  calcT(p, val, axis);
-  _thrust.push_back(sqrt(val)/psum);
-  if (axis.z() < 0) axis = -axis;
-  _thrustAxis.push_back(axis.unit()); 
-
-  //major 
-  Momentum3 par;
-  for (unsigned int l=0; l<_pv.size(); ++l) 
-    {
-      par   = (p[l]*axis.unit())*axis.unit();
-      p[l]  = p[l] - par;
-    }
-  calcM(p, val, axis);
-  _thrust.push_back(sqrt(val)/psum);
-  if (axis.x() < 0) axis = -axis;
-  _thrustAxis.push_back(axis.unit()); 
-
-  // minor
-  if (_thrustAxis[0]*_thrustAxis[1] < 1e-10) 
-    {
-      Energy eval = ZERO;
-      axis = _thrustAxis[0].cross(_thrustAxis[1]);
-      _thrustAxis.push_back(axis); 
-      for (unsigned int l=0; l<_pv.size(); ++l) 
-	eval += abs(axis*_pv[l].vect());
-      _thrust.push_back(eval/psum);
-    } 
-  else 
-    {
-      _thrust.push_back(-1.0);
-      _thrustAxis.push_back(Axis()); 
-    }
-}
-
-void EventShapes::calcT(const vector<Momentum3> &p, Energy2 &t, Axis &taxis) {
-  Energy2 tval;
-  t = ZERO;
-  ThreeVector<Energy2> tv;
-  Momentum3 ptot;
-  vector<Momentum3> cpm;
-  for (unsigned int k=1; k < p.size(); ++k) {
-    for (unsigned int j=0; j<k; ++j) {
-      tv = p[j].cross(p[k]);
-      ptot = Momentum3();
-      for (unsigned int l=0; l<p.size(); ++l) {
-	if (l!=j && l!=k) {
-	  if (p[l]*tv > ZERO) { 
-	    ptot += p[l];
-	  } else {
-	    ptot -= p[l];
-	  }
-	}
-      }
-      cpm.clear();
-      cpm.push_back(ptot-p[j]-p[k]);
-      cpm.push_back(ptot-p[j]+p[k]);
-      cpm.push_back(ptot+p[j]-p[k]);
-      cpm.push_back(ptot+p[j]+p[k]);
-      for (vector<Momentum3>::iterator it = cpm.begin();
-	   it != cpm.end(); ++it) {
-	tval = it->mag2();
-	if (tval > t) {
-	  t = tval;
-	  taxis = it->unit();
-	}
-      }
-    }
-  }
-}
-
-void EventShapes::calcM(const vector<Momentum3> &p, Energy2 &m, Axis &maxis) {
-  Energy2 mval;
-  m = ZERO;
-  Momentum3 tv, ptot;
-  vector<Momentum3> cpm;
-  for (unsigned int j=0; j < p.size(); ++j) {
-    tv = p[j];
-    ptot = Momentum3();
-    for (unsigned int l=0; l<p.size(); ++l) {
-      if (l!=j) {
-	if (p[l]*tv > ZERO) { 
-	  ptot += p[l];
-	} else {
-	  ptot -= p[l];
-	}
-      }
-    }
-    cpm.clear();
-    cpm.push_back(ptot-p[j]);
-    cpm.push_back(ptot+p[j]);
-    for (vector<Momentum3>::iterator it = cpm.begin();
-	 it != cpm.end(); ++it) {
-      mval = it->mag2();
-      if (mval > m) {
-	m = mval;
-	maxis = it->unit();
-      }
-    }
-  }
-}
-
-void EventShapes::bookEEC(vector<double> & hi) {
-  // hi is the histogram.  It is understood that hi.front() contains
-  // the bin [-1 < cos(chi) < -1+delta] and hi.back() the bin [1-delta
-  // < cos(chi) < 1].  Here, delta = 2/hi.size().
-  Energy Evis(ZERO);
-  for (unsigned int bin = 0; bin < hi.size(); ++bin) {
-    double delta = 2./hi.size();
-    double coschi = -1+bin*delta;
-    if (_pv.size() > 1) {
-      for (unsigned int i = 0; i < _pv.size()-1; ++i) {
-	Evis += _pv[i].e(); 
-	for (unsigned int j = i+1; j < _pv.size(); ++j) {
-	  double diff = abs(coschi-cos( _pv[i].vect().angle(_pv[j].vect()) )); 
-	  if (delta > diff) 
-	    hi[bin] += _pv[i].e()*_pv[j].e() / MeV2;
-	}
-      }
-    }
-    hi[bin] /= (Evis*Evis) / MeV2;
-  }
-}
-
diff --git a/Analysis/EventShapes.fh b/Analysis/EventShapes.fh
deleted file mode 100644
--- a/Analysis/EventShapes.fh
+++ /dev/null
@@ -1,19 +0,0 @@
-// -*- C++ -*-
-//
-// This is the forward declaration of the EventShapes class.
-//
-#ifndef HERWIG_EventShapes_FH
-#define HERWIG_EventShapes_FH
-
-#include "ThePEG/Config/Pointers.h"
-
-namespace Herwig {
-using namespace ThePEG;
-
-class EventShapes;
-
-ThePEG_DECLARE_POINTERS(EventShapes,EventShapesPtr);
-
-}
-
-#endif
diff --git a/Analysis/EventShapes.h b/Analysis/EventShapes.h
deleted file mode 100644
--- a/Analysis/EventShapes.h
+++ /dev/null
@@ -1,703 +0,0 @@
-// -*- C++ -*-
-//
-// EventShapes.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_EventShapes_H
-#define HERWIG_EventShapes_H
-//
-// This is the declaration of the EventShapes class.
-//
-
-#include "ThePEG/Interface/Interfaced.h"
-#include "ThePEG/Handlers/AnalysisHandler.h"
-#include "ThePEG/Vectors/Lorentz5Vector.h"
-#include "ThePEG/Vectors/ThreeVector.h"
-#include "ThePEG/EventRecord/Particle.h"
-#include "EventShapes.fh"
-
-namespace Herwig {
-
-using namespace ThePEG;
-
-/** \ingroup Analysis
- *
- * The EventShapes class is designed so that certain event shapes, such
- * as the thrust are only calculated once per event given the speed of
- * the calculation.
- *
- * @see \ref EventShapesInterfaces "The interfaces" defined for
- * EventShapes.
- */
-class EventShapes: public Interfaced {
-
-public:
-
-  /**
-   * The default constructor.
-   */
-  EventShapes() : _thrustDone(false), _spherDone(false), _linTenDone(false),
-		  _hemDone(false), _useCmBoost(false), 
-		  _mPlus(), _mMinus(), _bPlus(), _bMinus() 
-  {}
-
-  /**
-   *  Member to reset the particles to be considered
-   */
-  void reset(const tPVector &part) {
-    _pv.resize(part.size());
-    for(unsigned int ix=0;ix<part.size();++ix) _pv[ix]=part[ix]->momentum();
-    _thrustDone = false;
-    _spherDone  = false;
-    _linTenDone = false;
-    _hemDone    = false;
-    _useCmBoost = false; 
-  }
-
-
-public:
-
-  /**
-   *  Member functions to return thrust related shapes
-   */
-  //@{
-  /**
-   *  The thrust
-   */
-  double thrust() {
-    checkThrust(); 
-    return _thrust[0];
-  }
-
-  /**
-   *  The major
-   */ 
-  double thrustMajor() {
-    checkThrust(); 
-    return _thrust[1];
-  }
-
-  /**
-   *  The minor
-   */ 
-  double thrustMinor() {
-    checkThrust(); 
-    return _thrust[2];
-  }
-
-  /**
-   *  The oblateness
-   */ 
-  double oblateness() {
-    checkThrust(); 
-    return _thrust[1]-_thrust[2];
-  }
-
-  /**
-   *  The thrust axis
-   */
-  Axis thrustAxis() {
-    checkThrust(); 
-    return _thrustAxis[0];
-  }
-
-  /**
-   *  The major axis
-   */ 
-  Axis majorAxis() {
-    checkThrust(); 
-    return _thrustAxis[1];
-  }
-
-  /**
-   *  The minor axis
-   */
-  Axis minorAxis() {
-    checkThrust(); 
-    return _thrustAxis[2];
-  }
-  //@}
-
-  /**
-   * Linear momentum tensor related event shapes
-   */
-  //@{
-  /**
-   *  The C parameter
-   */
-  double CParameter() {
-    checkLinTen(); 
-    return 3.*(_linTen[0]*_linTen[1]+_linTen[1]*_linTen[2]
-	       +_linTen[2]*_linTen[0]); 
-  }
-
-  /**
-   *  The D parameter
-   */
-  double DParameter() {
-    checkLinTen(); 
-    return 27.*(_linTen[0]*_linTen[1]*_linTen[2]); 
-  }
-
-  /**
-   *  The eigenvalues in descending order
-   */
-  vector<double> linTenEigenValues() {
-    checkLinTen(); 
-    return _linTen; 
-  }
-
-
-  /**
-   *  The eigenvectors in order of descending eigenvalue
-   */
-  vector<Axis> linTenEigenVectors() {
-    checkLinTen(); 
-    return _linTenAxis; 
-  }
-
-  //@}
-
-  /**
-   * Quadratic momentum tensor related variables
-   */
-  //@{
-  /**
-   *  The sphericity
-   */
-  double sphericity() {
-    checkSphericity(); 
-    return 3./2.*(_spher[1]+_spher[2]); 
-  }
-
-  /**
-   *  The aplanarity
-   */
-  double aplanarity() {
-    checkSphericity(); 
-    return 3./2.*_spher[2];
-  }
-
-
-  /**
-   *  The planarity
-   */
-  double planarity() {
-    checkSphericity(); 
-    return _spher[1]-_spher[2]; 
-  }
-
-  /**
-   *  The sphericity axis
-   */
-  Axis sphericityAxis() {
-    checkSphericity(); 
-    return _spherAxis[0]; 
-  }
-
-
-  /**
-   *  The sphericity eigenvalues
-   */
-  vector<double> sphericityEigenValues() {
-    checkSphericity(); 
-    return _spher; 
-  }
-
-  /**
-   *  The sphericity eigenvectors
-   */
-  vector<Axis> sphericityEigenVectors() {
-    checkSphericity(); 
-    return _spherAxis; 
-  }  //@}
-
-  /**
-   * Jet mass related event shapes
-   */
-  //@{
-  /**
-   *  The high hemishpere mass squared divided by the visible energy
-   *  squared
-   */
-  double Mhigh2() {
-    checkHemispheres();
-    return _mPlus; 
-  } 
-  
-  /**
-   *  The low hemishpere mass squared divided by the visible energy
-   *  squared
-   */
-  double Mlow2() {
-    checkHemispheres();
-    return _mMinus; 
-  } 
-
-  /**
-   *  The difference between the 
-   * hemishpere masses squared divided by the visible energy squared
-   */
-  double Mdiff2() {
-    checkHemispheres();
-    return _mPlus-_mMinus; 
-  } 
-
-  //@}
-
-  /**
-   * Jet broadening related event shapes
-   */
-  //@{
-  /**
-   *  The wide jet broadening
-   */
-  double Bmax() {
-    checkHemispheres(); 
-    return _bPlus;
-  }
-
-  /**
-   *  The narrow jet broadening
-   */
-  double Bmin() {
-    checkHemispheres(); 
-    return _bMinus;
-  }
-
-  /**
-   *  The sum of the jet broadenings
-   */
-  double Bsum() {
-    checkHemispheres(); 
-    return _bPlus+_bMinus;
-  }
-
-
-  /**
-   *  The difference of the jet broadenings
-   */
-  double Bdiff() {
-    checkHemispheres(); 
-    return _bPlus-_bMinus;
-  }
-  //@}
-
-  /**
-   *  Single particle variables which do not depend on event shapes axes
-   */
-  //@{
-
-  /**
-   *  The scaled momentum \f$\xi=-\log\left( p/E_{\rm beam}\right)\f$.
-   */
-  double getXi(const Lorentz5Momentum & p, 
-				   const Energy & Ebeam) {
-    return((Ebeam > 0*MeV && p.vect().mag() > 0*MeV) ? 
-	   log(Ebeam/p.vect().mag()) : -1.); 
-  }
-
-  /**
-   *  Transverse momentum with respect to the beam
-   */
-  Energy getPt(const Lorentz5Momentum & p) {
-    return p.perp(); 
-  }
-
-  /**
-   *  Rapidity with respect to the beam direction
-   */
-  double getRapidity(const Lorentz5Momentum & p) {
-    return (p.t() > p.z() ? p.rapidity() : 1e99); 
-  }
-  //@}
-
-  /**
-   * Single particle variables related to one of the shape axis.
-   */
-  //@{
-  /**
-   *  Transverse momentum with respect to the thrust axis in the event plane
-   */
-  Energy ptInT(const Lorentz5Momentum & p) {
-    checkThrust(); 
-    return p.vect()*_thrustAxis[1]; 
-  }
-  
-  /**
-   *  Transverse momentum with respect to the thrust axis out of the
-   *  event plane
-   */
-  Energy ptOutT(const Lorentz5Momentum & p) {
-    checkThrust(); 
-    return p.vect()*_thrustAxis[2]; 
-  }
-
-  /**
-   *  Rapidity with respect to the thrust axis
-   */
-  double yT(const Lorentz5Momentum & p) {
-    checkThrust(); 
-    return (p.t() > p.vect()*_thrustAxis[0] ? 
-	    p.rapidity(_thrustAxis[0]) : 1e99);
-  }
-
-  /**
-   *  Transverse momentum with respect to the sphericity axis in the
-   *  event plane
-   */
-  Energy ptInS(const Lorentz5Momentum & p) { 
-    checkSphericity(); 
-    return p.vect()*_spherAxis[1]; 
-  }
-
-  /**
-   *  Transverse momentum with respect to the sphericity axis out of the
-   *  event plane
-   */
-  Energy ptOutS(const Lorentz5Momentum & p) {
-    checkSphericity(); 
-    return p.vect()*_spherAxis[2]; 
-  }
-
-  /**
-   *  Rapidity with respect to the sphericity axis
-   */
-  double yS(const Lorentz5Momentum & p) {
-    checkSphericity(); 
-    return (p.t() > p.vect()*_spherAxis[0] ? 
-	    p.rapidity(_spherAxis[0]) : 1e99);
-  }
-  //@}
-
-
-  /**
-   * Energy-energy correlation (EEC) @param hi is the histogram and has
-   * to be provided externally It is understood that the range of the
-   * histogam is -1 < cos(chi) < 1.  hi.front() contains the bin [-1 <
-   * cos(chi) < -1+delta] and hi.back() the bin [1-delta < cos(chi) <
-   * 1].  delta = 2/hi.size(). We use classical indices to access the
-   * vector.
-   */
-  void bookEEC(vector<double> & hi);
-
-  /**
-   * Before writing the histogram it has to be normalized according to
-   * the number of events.
-   */
-  void normalizeEEC(vector<double> & hi, long evts) {
-    for (unsigned int bin = 0; bin < hi.size(); bin++) bin /= (hi.size()*evts);
-  }
-  
-  /**
-   * The asymmetry of EEC is calculated from a given \f$\cos\chi\f$ and
-   * EEC histogram, which is a vector<double> as described above.
-   */
-  double AEEC(vector<double> & hi, double& coschi) {
-    if (coschi > 0. && coschi <= 1.) {
-      int i = static_cast<int>( floor((-coschi+1.)/2.*hi.size()) ); 
-      int j = static_cast<int>( floor(( coschi+1.)/2.*hi.size()) ); 
-      return hi[i]-hi[j];
-    } else {
-      return 1e99;
-    }
-  }
-
-public:
-
-  /**
-   * 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 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);}
-  //@}
-
-private:
-
-  /**
-   *  Check whether the initialization of a certain class of event shapes
-   *  has been calculated and if not do so
-   */
-  //@{
-  /**
-   *  Check if thrust related variables have been calculated and if not
-   *  do so
-   */
-  void checkThrust() {
-    if (!_thrustDone) {
-      _thrustDone = true;
-      calculateThrust(); 
-    }
-  }
-
-  /**
-   *  Check if the linear tensor related variables have been calculated
-   *  and if not do so
-   */
-  void checkLinTen() {
-    if (!_linTenDone) {
-      _linTenDone = true;
-      diagonalizeTensors(true, _useCmBoost); 
-    }
-  }
-
-  /**
-   *  Check if the quadratic tensor related variables have been
-   *  calculated and if not do so
-   */
-  void checkSphericity() {
-    if (!_spherDone) {
-      _spherDone = true;
-      diagonalizeTensors(false, _useCmBoost); 
-    }
-  }
-
-  /**
-   *  Check if the hemisphere mass variables and jet broadenings have
-   *  been calculated and if not do so
-   */
-  void checkHemispheres() {
-    if (!_hemDone) {
-      _hemDone = true;
-      calcHemisphereMasses(); 
-    }
-  }
-  //@}
-
-  /**
-   *  Methods that actually calculate the event shapes
-   */
-  //@{
-  /**
-   *  Calculate the hemisphere masses and jet broadenings
-   */
-  void calcHemisphereMasses();
-
-  /**
-   * Calculate the thrust and related axes
-   */
-  void calculateThrust();
-
-  /**
-   * Diagonalize the tensors @param linear switch between
-   * diagonalization of linear/quadratic tensor.  @param cmboost tells
-   * whether to boost into cm frame of all momenta first, or not
-   * (default off, and no interface to this).
-   */
-  void diagonalizeTensors(bool linear, bool cmboost);
-
-  /**
-   * Quite general diagonalization of a symmetric Matrix T, given as an
-   * array of doubles.  The symmetry is not checked explicitly as this
-   * is clear in the context.  It uses an explicit generic solution of
-   * the eigenvalue problem and no numerical approximation, based on
-   * Cardano's formula.  @param T Matrix to be diagonalised
-   */
-  vector<double> eigenvalues(const double T[3][3]);
-
-  /**
-   * The eigenvector of @param T to a given eigenvalue @param lam
-   */
-  Axis eigenvector(const double T[3][3], double lam);
-
-  /**
-   * The eigenvectors of @param T corresponding to the eigenvectors
-   * @param lam . The ordering of the vectors corresponds to the
-   * ordering of the eigenvalues.
-   */
-  vector<Axis> eigenvectors(const double T[3][3], const vector<double> &lam);
-
-  /**
-   *  Member to calculate the thrust
-   * @param p The three vectors
-   * @param t The thrust-squared (up to an Energy scale factor)
-   * @param taxis The thrust axis
-   */
-  void calcT(const vector<Momentum3> &p, Energy2 &t, Axis &taxis);
-
-  /**
-   *  Member to calculate the major
-   * @param p The three vectors
-   * @param m The major-squared (up to an Energy scale factor)
-   * @param maxis The major axis
-   */
-  void calcM(const vector<Momentum3> &p, Energy2 &m, Axis &maxis);
-  //@}
-
-private:
-
-  /**
-   * The static object used to initialize the description of this class.
-   * Indicates that this is a concrete class with persistent data.
-   */
-  static NoPIOClassDescription<EventShapes> initEventShapes;
-
-  /**
-   * The assignment operator is private and must never be called.
-   * In fact, it should not even be implemented.
-   */
-  EventShapes & operator=(const EventShapes &);
-
-private:
-
-  /**
-   *  Vector of particle momenta to be analysed
-   */
-  vector<Lorentz5Momentum> _pv; 
-  
-  /**
-   *  Various event shape axes
-   */
-  //@{
-  /**
-   *  The thrust related axes
-   */
-  vector<Axis> _thrustAxis;
-
-  /**
-   *  The sphericity related axes
-   */
-  vector<Axis> _spherAxis; 
-
-  /**
-   *  The linearised tensor axes
-   */
-  vector<Axis> _linTenAxis; 
-  //@}
-
-  /**
-   *  Values of axis related event shapes
-   */
-  //@{
-  /**
-   *  Values of thrust related variables
-   */
-  vector<double> _thrust;
-
-  /**
-   *  Values of sphericity related variables
-   */
-  vector<double> _spher;
-
-  /**
-   *  Values of linearized tensor related variables
-   */
-  vector<double> _linTen;
-  //@} 
-
-  /**
-   *  Whether or not certain event axes have been calculated
-   */
-  //@{
-  /**
-   *  Whether or not the thrust is calculated
-   */
-  bool _thrustDone;
-
-  /**
-   *  Whether or not the sphericity is calculated
-   */
-  bool _spherDone;
-
-  /**
-   *  Whether or not the linearizes tensor is calculated 
-   */
-  bool _linTenDone;
-
-  /**
-   *  Whether or not the hemisphere masses have been calculated
-   */
-  bool _hemDone; 
-  //@}
-
-  /**
-   *  Whether ot not to boost to the CMS frame for the tensor diagonalizations
-   */
-  bool _useCmBoost;
-
-  /**
-   *  Hemisphere masses
-   */
-  //@{
-  /**
-   *  The high hemisphere mass
-   */
-  double _mPlus;
-
-  /**
-   *  The low hemisphere mass
-   */
-  double _mMinus;
-  //@}
-
-  /**
-   *  The jet broadenings
-   */
-  //@{
-  /**
-   *  The wide jet broadening
-   */
-  double _bPlus;
-
-  /**
-   *  The narrow jet broadening
-   */
-  double _bMinus; 
-  //@}
-};
-
-}
-
-#include "ThePEG/Utilities/ClassTraits.h"
-
-namespace ThePEG {
-
-/** @cond TRAITSPECIALIZATIONS */
-
-/** This template specialization informs ThePEG about the
- *  base classes of EventShapes. */
-template <>
-struct BaseClassTrait<Herwig::EventShapes,1> {
-  /** Typedef of the first base class of EventShapes. */
-  typedef Interfaced NthBase;
-};
-
-/** This template specialization informs ThePEG about the name of
- *  the EventShapes class and the shared object where it is defined. */
-template <>
-struct ClassTraits<Herwig::EventShapes>
-  : public ClassTraitsBase<Herwig::EventShapes> {
-  /** Return a platform-independent class name */
-  static string className() { return "Herwig::EventShapes"; }
-  /** Return the name(s) of the shared library (or libraries) be loaded to get
-   *  access to the EventShapes class and any other class on which it depends
-   *  (except the base class). */
-  static string library() { return "HwAnalysis.so"; }
-};
-
-/** @endcond */
-
-}
-
-#endif /* HERWIG_EventShapes_H */
diff --git a/Analysis/EventShapesMasterAnalysis.cc b/Analysis/EventShapesMasterAnalysis.cc
deleted file mode 100644
--- a/Analysis/EventShapesMasterAnalysis.cc
+++ /dev/null
@@ -1,61 +0,0 @@
-// -*- C++ -*-
-//
-// EventShapesMasterAnalysis.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 EventShapesMasterAnalysis class.
-//
-
-#include "EventShapesMasterAnalysis.h"
-#include "ThePEG/Interface/Reference.h"
-#include "ThePEG/Interface/ClassDocumentation.h"
-#include "ThePEG/Persistency/PersistentOStream.h"
-#include "ThePEG/Persistency/PersistentIStream.h"
-
-using namespace Herwig;
-
-void EventShapesMasterAnalysis::analyze(tEventPtr event, long ieve,
-					int loop, int state) {
-  AnalysisHandler::analyze(event, ieve, loop, state);
-}
-
-LorentzRotation EventShapesMasterAnalysis::transform(tEventPtr) const {
-  return LorentzRotation();
-  // Return the Rotation to the frame in which you want to perform the analysis.
-}
-
-void EventShapesMasterAnalysis::analyze(const tPVector & particles) {
-  _shapes->reset(particles);
-}
-
-void EventShapesMasterAnalysis::analyze(tPPtr) {}
-
-void EventShapesMasterAnalysis::persistentOutput(PersistentOStream & os) const {
-  os << _shapes;
-}
-
-void EventShapesMasterAnalysis::persistentInput(PersistentIStream & is, int) {
-  is >> _shapes;
-}
-
-ClassDescription<EventShapesMasterAnalysis> EventShapesMasterAnalysis::initEventShapesMasterAnalysis;
-// Definition of the static class description member.
-
-void EventShapesMasterAnalysis::Init() {
-
-  static ClassDocumentation<EventShapesMasterAnalysis> documentation
-    ("The EventShapesMasterAnalysis class is the master class for event"
-     " shapes analyses");
-
-  static Reference<EventShapesMasterAnalysis,EventShapes> interfaceEventShapes
-    ("EventShapes",
-     "Pointer to the object which calculates the event shapes",
-     &EventShapesMasterAnalysis::_shapes, false, false, true, false, false);
-
-}
-
diff --git a/Analysis/EventShapesMasterAnalysis.h b/Analysis/EventShapesMasterAnalysis.h
deleted file mode 100644
--- a/Analysis/EventShapesMasterAnalysis.h
+++ /dev/null
@@ -1,177 +0,0 @@
-// -*- C++ -*-
-//
-// EventShapesMasterAnalysis.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_EventShapesMasterAnalysis_H
-#define HERWIG_EventShapesMasterAnalysis_H
-//
-// This is the declaration of the EventShapesMasterAnalysis class.
-//
-
-#include "ThePEG/Handlers/AnalysisHandler.h"
-#include "EventShapes.h"
-
-namespace Herwig {
-
-using namespace ThePEG;
-
-/** \ingroup Analysis
- * The EventShapesMasterAnalysis class is responsible for extracting the 
- * final state particles from the event record and setting up the object which
- * calculates the event shapes. This is done so that the EventShapes class which 
- * contains a lot of slow code isn't rerun unnecessarily.
- *
- * @see \ref EventShapesMasterAnalysisInterfaces "The interfaces"
- * defined for EventShapesMasterAnalysis.
- */
-class EventShapesMasterAnalysis: public AnalysisHandler {
-
-public:
-
-  /** @name Virtual functions required by the AnalysisHandler class. */
-  //@{
-  /**
-   * Analyze a given Event. Note that a fully generated event
-   * may be presented several times, if it has been manipulated in
-   * between. The default version of this function will call transform
-   * to make a lorentz transformation of the whole event, then extract
-   * all final state particles and call analyze(tPVector) of this
-   * analysis object and those of all associated analysis objects. The
-   * default version will not, however, do anything on events which
-   * have not been fully generated, or have been manipulated in any
-   * way.
-   * @param event pointer to the Event to be analyzed.
-   * @param ieve the event number.
-   * @param loop the number of times this event has been presented.
-   * If negative the event is now fully generated.
-   * @param state a number different from zero if the event has been
-   * manipulated in some way since it was last presented.
-   */
-  virtual void analyze(tEventPtr event, long ieve, int loop, int state);
-
-  /**
-   * Transform the event to the desired Lorentz frame and return the
-   * corresponding LorentzRotation.
-   * @param event a pointer to the Event to be transformed.
-   * @return the LorentzRotation used in the transformation.
-   */
-  virtual LorentzRotation transform(tEventPtr event) const;
-
-  /**
-   * Analyze the given vector of particles. The default version calls
-   * analyze(tPPtr) for each of the particles.
-   * @param particles the vector of pointers to particles to be analyzed
-   */
-  virtual void analyze(const tPVector & particles);
-
-  /**
-   * Analyze the given particle.
-   * @param particle pointer to the particle to be analyzed.
-   */
-  virtual void analyze(tPPtr particle);
-  //@}
-
-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 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);}
-  //@}
-
-private:
-
-  /**
-   * The static object used to initialize the description of this class.
-   * Indicates that this is a concrete class with persistent data.
-   */
-  static ClassDescription<EventShapesMasterAnalysis> initEventShapesMasterAnalysis;
-
-  /**
-   * The assignment operator is private and must never be called.
-   * In fact, it should not even be implemented.
-   */
-  EventShapesMasterAnalysis & operator=(const EventShapesMasterAnalysis &);
-
-private:
-
-  /**
-   *  Pointer to the EventShapes object
-   */
-  EventShapesPtr _shapes;
-
-};
-
-}
-
-#include "ThePEG/Utilities/ClassTraits.h"
-
-namespace ThePEG {
-
-/** @cond TRAITSPECIALIZATIONS */
-
-/** This template specialization informs ThePEG about the
- *  base classes of EventShapesMasterAnalysis. */
-template <>
-struct BaseClassTrait<Herwig::EventShapesMasterAnalysis,1> {
-  /** Typedef of the first base class of EventShapesMasterAnalysis. */
-  typedef AnalysisHandler NthBase;
-};
-
-/** This template specialization informs ThePEG about the name of
- *  the EventShapesMasterAnalysis class and the shared object where it is defined. */
-template <>
-struct ClassTraits<Herwig::EventShapesMasterAnalysis>
-  : public ClassTraitsBase<Herwig::EventShapesMasterAnalysis> {
-  /** Return a platform-independent class name */
-  static string className() { return "Herwig::EventShapesMasterAnalysis"; }
-  /** Return the name(s) of the shared library (or libraries) be loaded to get
-   *  access to the EventShapesMasterAnalysis class and any other class on which it depends
-   *  (except the base class). */
-  static string library() { return "HwAnalysis.so"; }
-};
-
-/** @endcond */
-
-}
-
-#endif /* HERWIG_EventShapesMasterAnalysis_H */
diff --git a/Analysis/IdentifiedParticleAnalysis.cc b/Analysis/IdentifiedParticleAnalysis.cc
deleted file mode 100644
--- a/Analysis/IdentifiedParticleAnalysis.cc
+++ /dev/null
@@ -1,2092 +0,0 @@
-// -*- C++ -*-
-//
-// IdentifiedParticleAnalysis.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 IdentifiedParticleAnalysis class.
-//
-
-#include "IdentifiedParticleAnalysis.h"
-#include "ThePEG/PDT/EnumParticles.h"
-#include "ThePEG/EventRecord/Event.h"
-#include "ThePEG/Repository/EventGenerator.h"
-#include "ThePEG/Interface/Reference.h"
-#include "ThePEG/Interface/ClassDocumentation.h"
-#include "ThePEG/Persistency/PersistentOStream.h"
-#include "ThePEG/Persistency/PersistentIStream.h"
-
-using namespace Herwig;
-
-int IdentifiedParticleAnalysis::getFlavour(const tPVector &pv) {
-  tPVector::const_iterator it;
-  for(it = pv.begin(); it!=pv.end(); ++it) 
-    if (abs((*it)->id()) < 7) break; 
-  return abs((*it)->id());
-}
-
-void IdentifiedParticleAnalysis::
-analyze(tEventPtr event, long ieve, int loop, int state) {
-  AnalysisHandler::analyze(event, ieve, loop, state);
-  if ( loop > 0 || state != 0 || !event ) return;
-  // get the final-state
-  tPVector hadrons=event->getFinalState();
-  // get the partons 
-  tPVector partons=event->primaryCollision()->steps()[0]->
-    getFinalState();
-  int flav = getFlavour(partons);
-  Energy Emax = 0.5*generator()->maximumCMEnergy();  
-  for (tPVector::iterator it = hadrons.begin(); 
-       it != hadrons.end(); ++it ) {
-    // only looking at charged particles
-    if(!(*it)->data().charged()) continue;
-    // all particles
-    double xp = getX((*it)->momentum(), Emax);
-    double pp = (*it)->momentum().vect().mag()/GeV;
-    _xpa->addWeighted(xp,event->weight());
-    if(abs((*it)->id()) == ParticleID::piplus) {
-      _pipma->addWeighted(xp,event->weight());
-      _pipm ->addWeighted(pp,event->weight()); 
-    } 
-    else if(abs((*it)->id()) == ParticleID::Kplus) {
-      _kpma->addWeighted(xp,event->weight()); 
-      _kpm ->addWeighted(pp,event->weight());
-    }
-    else if(abs((*it)->id()) == ParticleID::pplus) {
-      _ppma->addWeighted(xp,event->weight()); 
-      _ppm ->addWeighted(pp,event->weight());
-    }
-    switch(flav) {
-    case 1:
-    case 2:
-    case 3:
-      _xpl ->addWeighted(xp,event->weight()); 
-      if(abs((*it)->id()) == ParticleID::piplus)     
-	_pipml->addWeighted(xp,event->weight());
-      else if(abs((*it)->id()) == ParticleID::Kplus) 
-	_kpml ->addWeighted(xp,event->weight());
-      else if(abs((*it)->id()) == ParticleID::pplus) 
-	_ppml ->addWeighted(xp,event->weight());
-      _udsxp->addWeighted(xp,event->weight());
-      if (xp > 0) 
-	_udsxip->addWeighted( -log(xp),event->weight());
-      break;
-    case 4: 
-      _xpc->addWeighted(xp,event->weight()); 
-      if(abs((*it)->id()) == ParticleID::piplus)
-	_pipmc->addWeighted(xp,event->weight()); 
-      else if(abs((*it)->id()) == ParticleID::Kplus)
-	_kpmc ->addWeighted(xp,event->weight()); 
-      else if(abs((*it)->id()) == ParticleID::pplus) 
-	_ppmc ->addWeighted(xp,event->weight());
-      break;
-    case 5:
-      _xpb ->addWeighted(xp,event->weight()); 
-      if(abs((*it)->id()) == ParticleID::piplus) 
-	_pipmb ->addWeighted(xp,event->weight());
-      else if(abs((*it)->id()) == ParticleID::Kplus) 
-	_kpmb ->addWeighted(xp,event->weight());
-      else if(abs((*it)->id()) == ParticleID::pplus) 
-	_ppmb ->addWeighted(xp,event->weight());
-      break;
-    default:
-      break;
-    }
-  }
-  // finally decaying particles
-  set<tcPPtr> allparticles;
-  StepVector steps = event->primaryCollision()->steps();
-  for ( StepVector::const_iterator it = steps.begin()+2;
-	it != steps.end(); ++it ) {
-    (**it).select(inserter(allparticles), ThePEG::AllSelector());
-  }
-  
-  for(set<tcPPtr>::const_iterator it = allparticles.begin(); 
-      it != allparticles.end(); ++it) {
-    // lambda's
-    long id = abs( (*it)->id());
-    double xe = (*it)->momentum().e()/Emax;
-    double xp = (*it)->momentum().vect().mag()/Emax;
-    switch(id) {
-    case ParticleID::Lambda0:
-      _lpm ->addWeighted( xp,event->weight());
-      break;
-    case ParticleID::Kstarplus:
-      _xpKstarplus ->addWeighted( xp,event->weight());
-      break;
-    case ParticleID::Ximinus:
-      _xpXiminus ->addWeighted( xe,event->weight());
-      _xiXiminus ->addWeighted( -log(xp),event->weight());
-      break;
-    case ParticleID::Sigmastarplus:
-      _xpSigmaplus ->addWeighted( xe,event->weight());
-      _xiSigmaplus ->addWeighted( -log(xp),event->weight());
-      break;
-    case ParticleID::Sigmastarminus:
-      _xpSigmaminus ->addWeighted( xe,event->weight());
-      _xiSigmaminus ->addWeighted( -log(xp),event->weight());
-      break;
-    case ParticleID::Xistar0:
-      _xpXi0 ->addWeighted( xe,event->weight());
-      _xiXi0 ->addWeighted( -log(xp),event->weight());
-      break;
-    case 3124: // lambda(1520)
-      _xpLambda1520 ->addWeighted( xe,event->weight());
-      _xiLambda1520 ->addWeighted(-log(xp),event->weight());
-      break;
-    case ParticleID::Deltaplus2:
-      _xeDelta ->addWeighted(xe,event->weight());
-      break;
-    case ParticleID::f_0:
-      _xpf980 ->addWeighted(xp,event->weight());
-      break;
-    case ParticleID::f_2:
-      _xpf2 ->addWeighted(xp,event->weight());
-      break;
-    case ParticleID::phi:
-      _xpphi ->addWeighted(xp,event->weight());
-      break;
-    case ParticleID::Kstar0:
-      _xpKstar0 ->addWeighted(xp,event->weight());
-      break;
-    case ParticleID::D0:
-      _xeD0 ->addWeighted( xe,event->weight());
-      break;
-    case ParticleID::Dstarplus:
-      _xeDstar ->addWeighted( xe,event->weight());
-      break;
-    case ParticleID::rho0:
-      _xerho0 ->addWeighted( xe,event->weight());
-      break;
-    case ParticleID::pi0:
-      _xepi0 ->addWeighted( xe,event->weight());
-      _xipi0 ->addWeighted(-log(xp),event->weight());
-    case ParticleID::eta:
-      _xeeta ->addWeighted( xe,event->weight());
-      _xieta ->addWeighted(-log(xp),event->weight());
-    case ParticleID::etaprime:
-      _xeetap ->addWeighted( xe,event->weight());
-      _xietap ->addWeighted(-log(xp),event->weight());
-    case ParticleID::rhoplus:
-      _xerhop ->addWeighted( xe,event->weight());
-      _xirhop ->addWeighted(-log(xp),event->weight());
-    case ParticleID::omega:
-      _xeomega ->addWeighted( xe,event->weight());
-      _xiomega ->addWeighted(-log(xp),event->weight());
-    case ParticleID::a_0plus:
-      _xea_0p ->addWeighted( xe,event->weight());
-      _xia_0p ->addWeighted(-log(xp),event->weight());
-    case ParticleID::K0:
-    case ParticleID::K_S0:
-    case ParticleID::K_L0:
-      _xpK0->addWeighted(xp,event->weight());
-    }
-  }
-}
-
-NoPIOClassDescription<IdentifiedParticleAnalysis> 
-IdentifiedParticleAnalysis::initIdentifiedParticleAnalysis;
-// Definition of the static class description member.
-
-void IdentifiedParticleAnalysis::Init() {
-
-  static ClassDocumentation<IdentifiedParticleAnalysis> documentation
-    ("The IdentifiedParticleAnalysis class compares identified"
-     " particle spectra with Z pole data",
-     "The LEP IdentifiedParticle analysis uses data from"
-     "\\cite{Akers:1994ez,Alexander:1995gq,Alexander:1996qj,Ackerstaff:1998ue,Ackerstaff:1997kj,Abbiendi:2000cv,Ackerstaff:1998ap,Acton:1991aa,Abreu:1998nn,Abreu:1993mn,Barate:1999bg,Barate:1996fi,Abe:1998zs}.",
-     "%\\cite{Akers:1994ez}\n"
-     "\\bibitem{Akers:1994ez}\n"
-     "  R.~Akers {\\it et al.}  [OPAL Collaboration],\n"
-     "   ``Measurement of the production rates of charged hadrons in e+ e-\n"
-     "  %annihilation at the Z0,''\n"
-     "  Z.\\ Phys.\\  C {\\bf 63}, 181 (1994).\n"
-     "  %%CITATION = ZEPYA,C63,181;%%\n"
-     "%\\cite{Alexander:1995gq}\n"
-     "\\bibitem{Alexander:1995gq}\n"
-     "  G.~Alexander {\\it et al.}  [OPAL Collaboration],\n"
-     "  %``Delta++ production in hadronic Z0 decays,''\n"
-     "  Phys.\\ Lett.\\  B {\\bf 358}, 162 (1995).\n"
-     "  %%CITATION = PHLTA,B358,162;%%\n"
-     "%\\cite{Alexander:1996qj}\n"
-     "\\bibitem{Alexander:1996qj}\n"
-     "  G.~Alexander {\\it et al.}  [OPAL Collaboration],\n"
-     "  %``Strange baryon production in hadronic Z0 decays,''\n"
-     "  Z.\\ Phys.\\  C {\\bf 73}, 569 (1997).\n"
-     "  %%CITATION = ZEPYA,C73,569;%%\n"
-     "%\\cite{Ackerstaff:1998ue}\n"
-     "\\bibitem{Ackerstaff:1998ue}\n"
-     "  K.~Ackerstaff {\\it et al.}  [OPAL Collaboration],\n"
-     "  %``Production of f0(980), f2(1270) and Phi(1020) in hadronic Z0 decay,''\n"
-     "  Eur.\\ Phys.\\ J.\\  C {\\bf 4}, 19 (1998)\n"
-     "  [arXiv:hep-ex/9802013].\n"
-     "  %%CITATION = EPHJA,C4,19;%%\n"
-     "%\\cite{Ackerstaff:1997kj}\n"
-     "\\bibitem{Ackerstaff:1997kj}\n"
-     "  K.~Ackerstaff {\\it et al.}  [OPAL Collaboration],\n"
-     "  %``Spin alignment of leading K*(892)0 mesons in hadronic Z0 decays,''\n"
-     "  Phys.\\ Lett.\\  B {\\bf 412}, 210 (1997)\n"
-     "  [arXiv:hep-ex/9708022].\n"
-     "  %%CITATION = PHLTA,B412,210;%%\n"
-     "%\\cite{Abbiendi:2000cv}\n"
-     "\\bibitem{Abbiendi:2000cv}\n"
-     "  G.~Abbiendi {\\it et al.}  [OPAL Collaboration],\n"
-     "   ``Multiplicities of pi0, eta, K0 and of charged particles in quark and  gluon\n"
-     "  %jets,''\n"
-     "  Eur.\\ Phys.\\ J.\\  C {\\bf 17}, 373 (2000)\n"
-     "  [arXiv:hep-ex/0007017].\n"
-     "  %%CITATION = EPHJA,C17,373;%%\n"
-     "%\\cite{Ackerstaff:1998ap}\n"
-     "\\bibitem{Ackerstaff:1998ap}\n"
-     "  K.~Ackerstaff {\\it et al.}  [OPAL Collaboration],\n"
-     "  %``Photon and light meson production in hadronic Z0 decays,''\n"
-     "  Eur.\\ Phys.\\ J.\\  C {\\bf 5}, 411 (1998)\n"
-     "  [arXiv:hep-ex/9805011].\n"
-     "  %%CITATION = EPHJA,C5,411;%%\n"
-     "%\\cite{Acton:1991aa}\n"
-     "\\bibitem{Acton:1991aa}\n"
-     "  P.~D.~Acton {\\it et al.}  [OPAL Collaboration],\n"
-     "  %``A Study of charged particle multiplicities in hadronic decays of the Z0,''\n"
-     "  Z.\\ Phys.\\  C {\\bf 53}, 539 (1992).\n"
-     "  %%CITATION = ZEPYA,C53,539;%%\n"
-     "%\\cite{Abreu:1998nn}\n"
-     "\\bibitem{Abreu:1998nn}\n"
-     "  P.~Abreu {\\it et al.}  [DELPHI Collaboration],\n"
-     "   ``Measurement of inclusive rho0, f0(980), f2(1270), K*2(1430)0  and f\'2(1525)\n"
-     "  %production in Z0 decays,''\n"
-     "  Phys.\\ Lett.\\  B {\\bf 449}, 364 (1999).\n"
-     "  %%CITATION = PHLTA,B449,364;%%\n"
-     "%\\cite{Abreu:1993mn}\n"
-     "\\bibitem{Abreu:1993mn}\n"
-     "  P.~Abreu {\\it et al.}  [DELPHI Collaboration],\n"
-     "  %``A Measurement of D meson production in Z0 hadronic decays,''\n"
-     "  Z.\\ Phys.\\  C {\\bf 59}, 533 (1993)\n"
-     "  [Erratum-ibid.\\  C {\\bf 65}, 709 (1995)].\n"
-     "  %%CITATION = ZEPYA,C59,533;%%\n"
-     "%\\cite{Barate:1999bg}\n"
-     "\\bibitem{Barate:1999bg}\n"
-     "  R.~Barate {\\it et al.}  [ALEPH Collaboration],\n"
-     "  %``Study of charm production in Z decays,''\n"
-     "  Eur.\\ Phys.\\ J.\\  C {\\bf 16}, 597 (2000)\n"
-     "  [arXiv:hep-ex/9909032].\n"
-     "  %%CITATION = EPHJA,C16,597;%%\n"
-     "%\\cite{Barate:1996fi}\n"
-     "\\bibitem{Barate:1996fi}\n"
-     "  R.~Barate {\\it et al.}  [ALEPH Collaboration],\n"
-     "  %``Studies of quantum chromodynamics with the ALEPH detector,''\n"
-     "  Phys.\\ Rept.\\  {\\bf 294}, 1 (1998).\n"
-     "  %%CITATION = PRPLC,294,1;%%\n"
-     "%\\cite{Abe:1998zs}\n"
-     "\\bibitem{Abe:1998zs}\n"
-     "  K.~Abe {\\it et al.}  [SLD Collaboration],\n"
-     "   ``Production of pi+, K+, K0, K*0, Phi, p and Lambda0 in hadronic Z0\n"
-     "  %decays,''\n"
-     "  Phys.\\ Rev.\\  D {\\bf 59}, 052001 (1999)\n"
-     "  [arXiv:hep-ex/9805029].\n"
-     "  %%CITATION = PHRVA,D59,052001;%%\n"
-     );
-}
-
-void IdentifiedParticleAnalysis::dofinish() {
-  useMe();
-  AnalysisHandler::dofinish();
-  string fname = generator()->filename() 
-    + string("-") + name() + string(".top");
-  ofstream output(fname.c_str());
-  // chisq
-  double chisq,minfrac=0.05;
-  unsigned int npoint;
-  using namespace HistogramOptions;
-  // Histogram for the \f$\xi\f$ distribution for all particles from all quarks
-  _xpa->normaliseToData();
-  _xpa->chiSquared(chisq,npoint,minfrac);
-  generator()->log() << "Chi Square = " << chisq << " for " << npoint 
-		     << " degrees of freedom for SLD xp (charged, all quarks) "
-		     << "distribution or " << chisq/npoint << " per degree of freedom\n"; 
-  _xpa->topdrawOutput(output,Frame|Errorbars|Ylog,
-		      "RED",
-		      "The scaled momentum of charged particles for all events(SLD)",
-		      "                                                       ",
-		      "1/NdN/dx0p1",
-		      "        X X",
-		      "x0p1",
-		      " X X");
-  // light quarks
-  _xpl->normaliseToData();
-  _xpl->chiSquared(chisq,npoint,minfrac);
-  generator()->log() << "Chi Square = " << chisq << " for " << npoint 
-		     << " degrees of freedom for SLD xp (charged, light quarks) "
-		     << "distribution or " << chisq/npoint << " per degree of freedom\n"; 
-  _xpl->topdrawOutput(output,Frame|Errorbars|Ylog,
-		      "RED",
-		      "The scaled momentum of charged particles for all light quark events(SLD)",
-		      "                                                                   ",
-		      "1/NdN/dx0p1",
-		      "        X X",
-		      "x0p1",
-		      " X X");
-  // OPAL
-  _udsxp->normaliseToData();
-  _udsxp->chiSquared(chisq,npoint,minfrac);
-  generator()->log() << "Chi Square = " << chisq << " for " << npoint 
-		     << " degrees of freedom for OPAL xp (charged, light quarks) "
-		     << "distribution or " << chisq/npoint << " per degree of freedom\n"; 
-  _udsxp->topdrawOutput(output,Frame|Errorbars|Ylog,
-		      "RED",
-		      "The scaled momentum of charged particles for all light quark events(OPAL)",
-		      "                                                                   ",
-		      "1/NdN/dx0p1",
-		      "        X X",
-		      "x0p1",
-		      " X X");
-  _udsxip->normaliseToData();
-  _udsxip->chiSquared(chisq,npoint,minfrac);
-  generator()->log() << "Chi Square = " << chisq << " for " << npoint 
-		     << " degrees of freedom for OPAL xi (charged, light quarks) "
-		     << "distribution or " << chisq/npoint << " per degree of freedom\n"; 
-  _udsxip->topdrawOutput(output,Frame|Errorbars|Ylog,
-		      "RED",
-		      "The scaled momentum of charged particles for all light quark events(OPAL)",
-		      "                                                                   ",
-		      "1/NdN/dX",
-		      "       G",
-		      "X",
-		      "G");
-  // charm 
-  _xpc->normaliseToData();
-  _xpc->chiSquared(chisq,npoint,minfrac);
-  generator()->log() << "Chi Square = " << chisq << " for " << npoint 
-		     << " degrees of freedom for SLD xp (charged, charm quarks) "
-		     << "distribution or " << chisq/npoint << " per degree of freedom\n"; 
-  _xpc->topdrawOutput(output,Frame|Errorbars|Ylog,
-		      "RED",
-		      "The scaled momentum of charged particles for all charm events(SLD)",
-		      "                                                             ",
-		      "1/NdN/dx0p1",
-		      "        X X",
-		      "x0p1",
-		      " X X");
-  // bottom
-  _xpb->normaliseToData();
-  _xpb->chiSquared(chisq,npoint,minfrac);
-  generator()->log() << "Chi Square = " << chisq << " for " << npoint 
-		     << " degrees of freedom for SLD xp (charged, bottom quarks) "
-		     << "distribution or " << chisq/npoint << " per degree of freedom\n";
-  _xpb->topdrawOutput(output,Frame|Errorbars|Ylog,
-		      "RED",
-		      "The scaled momentum of charged particles for all bottom events(SLD)",
-		      "                                                              ",
-		      "1/NdN/dx0p1",
-		      "        X X",
-		      "x0p1",
-		      " X X");
-  // pions all quarks
-  _pipma->normaliseToData();
-  _pipma->chiSquared(chisq,npoint,minfrac);
-  generator()->log() << "Chi Square = " << chisq << " for " << npoint 
-		     << " degrees of freedom for SLD xp (pions, all quarks) "
-		     << "distribution or " << chisq/npoint << " per degree of freedom\n"; 
-  _pipma->topdrawOutput(output,Frame|Errorbars|Ylog,
-		      "RED",
-		      "The scaled momentum of pions for all events(SLD)",
-		      "                                           ",
-		      "1/NdN/dx0p1",
-		      "        X X",
-		      "x0p1",
-		      " X X");
-  // OPAL pions
-  _pipm->normaliseToData();
-  _pipm->chiSquared(chisq,npoint,minfrac);
-  generator()->log() << "Chi Square = " << chisq << " for " << npoint 
-		     << " degrees of freedom for OPAL momentum (pions, all quarks) "
-		     << "distribution or " << chisq/npoint << " per degree of freedom\n"; 
-  _pipm->topdrawOutput(output,Frame|Errorbars|Ylog,
-		      "RED",
-		      "The momentum of pions for all events(OPAL)",
-		      "                                          ",
-		      "1/NdN/dp/GeV2-13",
-		      "            X  X",
-		      "p/GeV",
-		      " ");
-  // light
-  _pipml->normaliseToData();
-  _pipml->chiSquared(chisq,npoint,minfrac);
-  generator()->log() << "Chi Square = " << chisq << " for " << npoint 
-		     << " degrees of freedom for SLD xp (pions, light quarks) "
-		     << "distribution or " << chisq/npoint << " per degree of freedom\n"; 
-  _pipml->topdrawOutput(output,Frame|Errorbars|Ylog,
-		      "RED",
-		      "The scaled momentum of pions for light quark events(SLD)",
-		      "                                           ",
-		      "1/NdN/dx0p1",
-		      "        X X",
-		      "x0p1",
-		      " X X");
-  // charm 
-  _pipmc->normaliseToData();
-  _pipmc->chiSquared(chisq,npoint,minfrac);
-  generator()->log() << "Chi Square = " << chisq << " for " << npoint 
-		     << " degrees of freedom for SLD xp (pions, charm quarks) "
-		     << "distribution or " << chisq/npoint << " per degree of freedom\n";
-  _pipmc->topdrawOutput(output,Frame|Errorbars|Ylog,
-		      "RED",
-		      "The scaled momentum of pions for charm events(SLD)",
-		      "                                           ",
-		      "1/NdN/dx0p1",
-		      "        X X",
-		      "x0p1",
-		      " X X");
-  // bottom
-  _pipmb->normaliseToData();
-  _pipmb->chiSquared(chisq,npoint,minfrac);
-  generator()->log() << "Chi Square = " << chisq << " for " << npoint 
-		     << " degrees of freedom for SLD xp (pions, bottom quarks) "
-		     << "distribution or " << chisq/npoint << " per degree of freedom\n";
-  _pipmb->topdrawOutput(output,Frame|Errorbars|Ylog,
-		      "RED",
-		      "The scaled momentum of pions for bottom quark events(SLD)",
-		      "                                           ",
-		      "1/NdN/dx0p1",
-		      "        X X",
-		      "x0p1",
-		      " X X");
-  // kaons all quarks
-  _kpma->normaliseToData();
-  _kpma->chiSquared(chisq,npoint,minfrac);
-  generator()->log() << "Chi Square = " << chisq << " for " << npoint 
-		     << " degrees of freedom for SLD xp (kaons, all quakrks) "
-		     << "distribution or " << chisq/npoint << " per degree of freedom\n"; 
-  _kpma->topdrawOutput(output,Frame|Errorbars|Ylog,
-		      "RED",
-		      "The scaled momentum of kaons for all events(SLD)",
-		      "                                           ",
-		      "1/NdN/dx0p1",
-		      "        X X",
-		      "x0p1",
-		      " X X");
-  // OPAL kaons
-  _kpm->normaliseToData();
-  _kpm->chiSquared(chisq,npoint,minfrac);
-  generator()->log() << "Chi Square = " << chisq << " for " << npoint 
-		     << " degrees of freedom for OPAL momentum (kaons, all quarks) "
-		     << "distribution or " << chisq/npoint << " per degree of freedom\n"; 
-  _kpm->topdrawOutput(output,Frame|Errorbars|Ylog,
-		      "RED",
-		      "The momentum of kaons for all events(OPAL)",
-		      "                                                   ",
-		      "1/NdN/dp/GeV2-13",
-		      "            X  X",
-		      "p/GeV",
-		      "     ");
-  // light
-  _kpml->normaliseToData();
-  _kpml->chiSquared(chisq,npoint,minfrac);
-  generator()->log() << "Chi Square = " << chisq << " for " << npoint 
-		     << " degrees of freedom for SLD xp (kaons, light quarks) "
-		     << "distribution or " << chisq/npoint << " per degree of freedom\n"; 
-  _kpml->topdrawOutput(output,Frame|Errorbars|Ylog,
-		      "RED",
-		      "The scaled momentum of kaons for light quark events(SLD)",
-		      "                                           ",
-		      "1/NdN/dx0p1",
-		      "        X X",
-		      "x0p1",
-		      " X X");
-  // charm 
-  _kpmc->normaliseToData();
-  _kpmc->chiSquared(chisq,npoint,minfrac);
-  generator()->log() << "Chi Square = " << chisq << " for " << npoint 
-		     << " degrees of freedom for SLD xp (kaons, charm quarks) "
-		     << "distribution or " << chisq/npoint << " per degree of freedom\n"; 
-  _kpmc->topdrawOutput(output,Frame|Errorbars|Ylog,
-		      "RED",
-		      "The scaled momentum of kaons for charm events(SLD)",
-		      "                                           ",
-		      "1/NdN/dx0p1",
-		      "        X X",
-		      "x0p1",
-		      " X X");
-  // bottom
-  _kpmb->normaliseToData();
-  _kpmb->chiSquared(chisq,npoint,minfrac);
-  generator()->log() << "Chi Square = " << chisq << " for " << npoint 
-		     << " degrees of freedom for SLD xp (kaons, bottom quarks) "
-		     << "distribution or " << chisq/npoint << " per degree of freedom\n"; 
-  _kpmb->topdrawOutput(output,Frame|Errorbars|Ylog,
-		      "RED",
-		      "The scaled momentum of kaons for bottom quark events(SLD)",
-		      "                                           ",
-		      "1/NdN/dx0p1",
-		      "        X X",
-		      "x0p1",
-		      " X X");
-  // protons all quarks
-  _ppma->normaliseToData();
-  _ppma->chiSquared(chisq,npoint,minfrac);
-  generator()->log() << "Chi Square = " << chisq << " for " << npoint 
-		     << " degrees of freedom for SLD xp (protons, all quarks) "
-		     << "distribution or " << chisq/npoint << " per degree of freedom\n"; 
-  _ppma->topdrawOutput(output,Frame|Errorbars|Ylog,
-		      "RED",
-		      "The scaled momentum of protons for all events(SLD)",
-		      "                                           ",
-		      "1/NdN/dx0p1",
-		      "        X X",
-		      "x0p1",
-		      " X X");
-  // OPAL protons
-  _ppm->normaliseToData();
-  _ppm->chiSquared(chisq,npoint,minfrac);
-  generator()->log() << "Chi Square = " << chisq << " for " << npoint 
-		     << " degrees of freedom for OPAL momentum (protons, all quarks ) "
-		     << "distribution or " << chisq/npoint << " per degree of freedom\n"; 
-  _ppm->topdrawOutput(output,Frame|Errorbars|Ylog,
-		      "RED",
-		      "The momentum of protons for all events(OPAL)",
-		      "                                                   ",
-		      "1/NdN/dpGeV2-13",
-		      "           X  X",
-		      "p/GeV",
-		      "     ");
-  // light
-  _ppml->normaliseToData();
-  _ppml->chiSquared(chisq,npoint,minfrac);
-  generator()->log() << "Chi Square = " << chisq << " for " << npoint 
-		     << " degrees of freedom for SLD xp (protons, light quarks) "
-		     << "distribution or " << chisq/npoint << "per degree of freedom\n";
-  _ppml->topdrawOutput(output,Frame|Errorbars|Ylog,
-		      "RED",
-		      "The scaled momentum of protons for light quark events(SLD)",
-		      "                                           ",
-		      "1/NdN/dx0p1",
-		      "        X X",
-		      "x0p1",
-		      " X X");
-  // charm 
-  _ppmc->normaliseToData();
-  _ppmc->chiSquared(chisq,npoint,minfrac);
-  generator()->log() << "Chi Square = " << chisq << " for " << npoint 
-		     << " degrees of freedom for SLD xp (protons, charm quarks) "
-		     << "distribution or " << chisq/npoint << " per degree of freedom\n";
-  _ppmc->topdrawOutput(output,Frame|Errorbars|Ylog,
-		      "RED",
-		      "The scaled momentum of protons for charm events(SLD)",
-		      "                                           ",
-		      "1/NdN/dx0p1",
-		      "        X X",
-		      "x0p1",
-		      " X X");
-  // bottom
-  _ppmb->normaliseToData();
-  _ppmb->chiSquared(chisq,npoint,minfrac);
-  generator()->log() << "Chi Square = " << chisq << " for " << npoint 
-		     << " degrees of freedom for SLD xp (protons, bottom quarks) "
-		     << "distribution or " << chisq/npoint << " per degree of freedom\n";
-  _ppmb->topdrawOutput(output,Frame|Errorbars|Ylog,
-		      "RED",
-		      "The scaled momentum of protons for bottom quark events(SLD)",
-		      "                                           ",
-		      "1/NdN/dx0p1",
-		      "        X X",
-		      "x0p1",
-		      " X X");
-  // lambda
-  _lpm->normaliseToData();
-  _lpm->chiSquared(chisq,npoint,minfrac);
-  generator()->log() << "Chi Square = " << chisq << " for " << npoint 
-		     << " degrees of freedom for ALEPH momentum (lambda, all quarks) "
-		     << "distribution or " << chisq/npoint << " per degree of freedom\n"; 
-  _lpm->topdrawOutput(output,Frame|Errorbars|Ylog,
-		      "RED",
-		      "The scaled momentum of L for all events (ALEPH)",
-		      "                       F                      ",
-		      "1/NdN/dp/GeV2-13",
-		      "            X  X",
-		      "p/GeV",
-		      "     ");
-  // K*+
-  _xpKstarplus->normaliseToData();
-  _xpKstarplus->chiSquared(chisq,npoint,minfrac);
-  generator()->log() << "Chi Square = " << chisq << " for " << npoint 
-		     << " degrees of freedom for ALEPH momentum K*+ "
-		     << "distribution or " << chisq/npoint << " per degree of freedom\n";
-  _xpKstarplus->topdrawOutput(output,Frame|Errorbars|Ylog,
-			      "RED",
-			      "The scaled momentum of K2*+3 for all events (ALEPH)",
-			      "                        X  X                       ",
-			      "1/NdN/dx0p1",
-			      "        X X",
-			      "x0p1",
-			      " X X");
-  // xi-
-  _xpXiminus->normaliseToData();
-  _xpXiminus->chiSquared(chisq,npoint,minfrac);
-  generator()->log() << "Chi Square = " << chisq << " for " << npoint 
-		     << " degrees of freedom for OPAL xi- x_E"
-		     << "distribution or " << chisq/npoint << " per degree of freedom\n";
-  _xpXiminus->topdrawOutput(output,Frame|Errorbars|Ylog,
-			    "RED",
-			    "The scaled momentum x0E1 of X2-3 for all events (OPAL)",
-			    "                     X X    FX X                      ",
-			    "1/NdN/dx0E1",
-			    "        X X",
-			    "x0E1",
-			    " X X");
-  _xiXiminus->normaliseToData();
-  _xiXiminus->chiSquared(chisq,npoint,minfrac);
-  generator()->log() << "Chi Square = " << chisq << " for " << npoint 
-		     << " degrees of freedom for OPAL xi- xi"
-		     << "distribution or " << chisq/npoint << " per degree of freedom\n";
-  _xiXiminus->topdrawOutput(output,Frame|Errorbars|Ylog,
-			    "RED",
-			    "The scaled momentum X of X2-3 for all events (OPAL)",
-			    "                    G    FX X                      ",
-			    "1/NdN/dX",
-			    "       G",
-			    "X",
-			    "G");
-  // Sigma*+
-  _xpSigmaplus->normaliseToData();
-  _xpSigmaplus->chiSquared(chisq,npoint,minfrac);
-  generator()->log() << "Chi Square = " << chisq << " for " << npoint 
-		     << " degrees of freedom for OPAL Sigma*+ x_E"
-		     << "distribution or " << chisq/npoint << " per degree of freedom\n";
-  _xpSigmaplus->topdrawOutput(output,Frame|Errorbars|Ylog,
-			    "RED",
-			    "The scaled momentum x0E1 of S2*+3 for all events (OPAL)",
-			    "                     X X    FX  X                      ",
-			    "1/NdN/dx0E1",
-			    "        X X",
-			    "x0E1",
-			    " X X");
-  _xiSigmaplus->normaliseToData();
-  _xiSigmaplus->chiSquared(chisq,npoint,minfrac);
-  generator()->log() << "Chi Square = " << chisq << " for " << npoint 
-		     << " degrees of freedom for OPAL Sigma*+ xi"
-		     << "distribution or " << chisq/npoint << " per degree of freedom\n";
-  _xiSigmaplus->topdrawOutput(output,Frame|Errorbars|Ylog,
-			    "RED",
-			    "The scaled momentum X of S2*+3 for all events (OPAL)",
-			    "                    G    FX  X                      ",
-			    "1/NdN/dX",
-			    "       G",
-			    "X",
-			    "G");
-  // Sigma*-
-  _xpSigmaminus->normaliseToData();
-  _xpSigmaminus->chiSquared(chisq,npoint,minfrac);
-  generator()->log() << "Chi Square = " << chisq << " for " << npoint 
-		     << " degrees of freedom for OPAL Sigma*- x_E"
-		     << "distribution or " << chisq/npoint << " per degree of freedom\n";
-  _xpSigmaminus->topdrawOutput(output,Frame|Errorbars|Ylog,
-			    "RED",
-			    "The scaled momentum x0E1 of S2*-3 for all events (OPAL)",
-			    "                     X X    FX  X                      ",
-			    "1/NdN/dx0E1",
-			    "        X X",
-			    "x0E1",
-			    " X X");
-  _xiSigmaminus->normaliseToData();
-  _xiSigmaminus->chiSquared(chisq,npoint,minfrac);
-  generator()->log() << "Chi Square = " << chisq << " for " << npoint 
-		     << " degrees of freedom for OPAL Sigma*- xi"
-		     << "distribution or " << chisq/npoint << " per degree of freedom\n";
-  _xiSigmaminus->topdrawOutput(output,Frame|Errorbars|Ylog,
-			    "RED",
-			    "The scaled momentum X of S2*-3 for all events (OPAL)",
-			    "                    G    FX  X                      ",
-			    "1/NdN/dX",
-			    "       G",
-			    "X",
-			    "G");
-  // Xi*0
-  _xpXi0->normaliseToData();
-  _xpXi0->chiSquared(chisq,npoint,minfrac);
-  generator()->log() << "Chi Square = " << chisq << " for " << npoint 
-		     << " degrees of freedom for OPAL Xi*0 x_E"
-		     << "distribution or " << chisq/npoint << " per degree of freedom\n";
-  _xpXi0->topdrawOutput(output,Frame|Errorbars|Ylog,
-			    "RED",
-			    "The scaled momentum x0E1 of X2*03 for all events (OPAL)",
-			    "                     X X    FX  X                      ",
-			    "1/NdN/dx0E1",
-			    "        X X",
-			    "x0E1",
-			    " X X");
-  _xiXi0->normaliseToData();
-  _xiXi0->chiSquared(chisq,npoint,minfrac);
-  generator()->log() << "Chi Square = " << chisq << " for " << npoint 
-		     << " degrees of freedom for OPAL Xi*0 xi"
-		     << "distribution or " << chisq/npoint << " per degree of freedom\n";
-  _xiXi0->topdrawOutput(output,Frame|Errorbars|Ylog,
-			    "RED",
-			    "The scaled momentum X of X2*03 for all events (OPAL)",
-			    "                    G    FX  X                      ",
-			    "1/NdN/dX",
-			    "       G",
-			    "X",
-			    "G");
-  // lambda(1520)
-  _xpLambda1520->normaliseToData();
-  _xpLambda1520->chiSquared(chisq,npoint,minfrac);
-  generator()->log() << "Chi Square = " << chisq << " for " << npoint 
-		     << " degrees of freedom for OPAL Lambda(1520) x_E"
-		     << "distribution or " << chisq/npoint << " per degree of freedom\n";
-  _xpLambda1520->topdrawOutput(output,Frame|Errorbars|Ylog,
-			    "RED",
-			    "The scaled momentum x0E1 of L(1520) for all events (OPAL)",
-			    "                     X X    F                            ",
-			    "1/NdN/dx0E1",
-			    "        X X",
-			    "x0E1",
-			    " X X");
-  _xiLambda1520->normaliseToData();
-  _xiLambda1520->chiSquared(chisq,npoint,minfrac);
-  generator()->log() << "Chi Square = " << chisq << " for " << npoint 
-		     << " degrees of freedom for OPAL Lambda(1520) xi"
-		     << "distribution or " << chisq/npoint << " per degree of freedom\n";
-  _xiLambda1520->topdrawOutput(output,Frame|Errorbars|Ylog,
-			    "RED",
-			    "The scaled momentum X of L(1520) for all events (OPAL)",
-			    "                    G    F                            ",
-			    "1/NdN/dX",
-			    "       G",
-			    "X",
-			    "G");
-  // Delta++
-  _xeDelta->normaliseToData();
-  _xeDelta->chiSquared(chisq,npoint,minfrac);
-  generator()->log() << "Chi Square = " << chisq << " for " << npoint 
-		     << " degrees of freedom for OPAL Delta++ x_E"
-		     << "distribution or " << chisq/npoint << " per degree of freedom\n";
-  _xeDelta->topdrawOutput(output,Frame|Errorbars|Ylog,
-			    "RED",
-			    "The scaled momentum x0E1 of D2++3 for all events (OPAL)",
-			    "                     X X    FX  X                      ",
-			    "1/NdN/dx0E1",
-			    "        X X",
-			    "x0E1",
-			    " X X");
-  // f_0
-  _xpf980->normaliseToData();
-  _xpf980->chiSquared(chisq,npoint,minfrac);
-  generator()->log() << "Chi Square = " << chisq << " for " << npoint 
-		     << " degrees of freedom for OPAL f_0(980) x_p"
-		     << "distribution or " << chisq/npoint << " per degree of freedom\n";
-  _xpf980->topdrawOutput(output,Frame|Errorbars|Ylog,
-			    "RED",
-			    "The scaled momentum x0p1 of f001(980) for all events (OPAL)",
-			    "                     X X     X X                           ",
-			    "1/NdN/dx0p1",
-			    "        X X",
-			    "x0p1",
-			    " X X"); 
-  // f_2
-  _xpf2->normaliseToData();
-  _xpf2->chiSquared(chisq,npoint,minfrac);
-  generator()->log() << "Chi Square = " << chisq << " for " << npoint 
-		     << " degrees of freedom for OPAL f_2 x_p"
-		     << "distribution or " << chisq/npoint << " per degree of freedom\n";
-  _xpf2->topdrawOutput(output,Frame|Errorbars|Ylog,
-			    "RED",
-			    "The scaled momentum x0p1 of f021 for all events (OPAL)",
-			    "                     X X     X X                      ",
-			    "1/NdN/dx0p1",
-			    "        X X",
-			    "x0p1",
-			    " X X");
-  // phi
-  _xpphi->normaliseToData();
-  _xpphi->chiSquared(chisq,npoint,minfrac);
-  generator()->log() << "Chi Square = " << chisq << " for " << npoint 
-		     << " degrees of freedom for OPAL phi x_p"
-		     << "distribution or " << chisq/npoint << " per degree of freedom\n";
-  _xpphi->topdrawOutput(output,Frame|Errorbars|Ylog,
-			    "RED",
-			    "The scaled momentum x0p1 of F for all events (OPAL)",
-			    "                     X X    G                      ",
-			    "1/NdN/dx0p1",
-			    "        X X",
-			    "x0p1",
-			    " X X");
-  // K*0
-  _xpKstar0->normaliseToData();
-  _xpKstar0->chiSquared(chisq,npoint,minfrac);
-  generator()->log() << "Chi Square = " << chisq << " for " << npoint 
-		     << " degrees of freedom for OPAL K*0 x_p"
-		     << "distribution or " << chisq/npoint << " per degree of freedom\n";
-  _xpKstar0->topdrawOutput(output,Frame|Errorbars|Ylog,
-			    "RED",
-			    "The scaled momentum x0p1 of K2*03 for all events (OPAL)",
-			    "                     X X     X  X                      ",
-			    "1/NdN/dx0p1",
-			    "        X X",
-			    "x0p1",
-			    " X X");
-  // K0
-  _xpK0->normaliseToData();
-  _xpK0->chiSquared(chisq,npoint,minfrac);
-  generator()->log() << "Chi Square = " << chisq << " for " << npoint 
-		     << " degrees of freedom for OPAL K0 x_p"
-		     << "distribution or " << chisq/npoint << " per degree of freedom\n";
-  _xpK0->topdrawOutput(output,Frame|Errorbars|Ylog,
-		       "RED",
-		       "The scaled momentum x0p1 of K203 for all events (OPAL)",
-		       "                     X X     X X                      ",
-		       "1/NdN/dx0p1",
-		       "        X X",
-		       "x0p1",
-		       " X X");
-  // rho0
-  _xerho0->normaliseToData();
-  _xerho0->chiSquared(chisq,npoint,minfrac);
-  generator()->log() << "Chi Square = " << chisq << " for " << npoint 
-		     << " degrees of freedom for DELPHI rho0 x_E"
-		     << "distribution or " << chisq/npoint << " per degree of freedom\n";
-  _xerho0->topdrawOutput(output,Frame|Errorbars|Ylog,
-			    "RED",
-			    "The scaled momentum x0E1 of R203 for all events (DELPHI)",
-			    "                     X X    GX X                        ",
-			    "1/NdN/dx0E1",
-			    "        X X",
-			    "x0E1",
-			    " X X");
-  // pi0
-  _xepi0->normaliseToData();
-  _xepi0->chiSquared(chisq,npoint,minfrac);
-  generator()->log() << "Chi Square = " << chisq << " for " << npoint 
-		     << " degrees of freedom for OPAL pi0 x_E"
-		     << "distribution or " << chisq/npoint << " per degree of freedom\n";
-  _xepi0->topdrawOutput(output,Frame|Errorbars|Ylog,
-			"RED",
-			"The scaled momentum x0E1 of P203 for all events (OPAL)",
-			"                     X X    GX X                      ",
-			"1/NdN/dx0E1",
-			"        X X",
-			"x0E1",
-			" X X");
-  _xipi0->normaliseToData();
-  _xipi0->chiSquared(chisq,npoint,minfrac);
-  generator()->log() << "Chi Square = " << chisq << " for " << npoint 
-		     << " degrees of freedom for OPAL pi0 xi"
-		     << "distribution or " << chisq/npoint << " per degree of freedom\n";
-  _xipi0->topdrawOutput(output,Frame|Errorbars|Ylog,
-			"RED",
-			"The scaled momentum X of P203 for all events (OPAL)",
-			"                    G    GX X                      ",
-			"1/NdN/dX",
-			"       G",
-			"X",
-			"G");
-  // eta
-  _xeeta->normaliseToData();
-  _xeeta->chiSquared(chisq,npoint,minfrac);
-  generator()->log() << "Chi Square = " << chisq << " for " << npoint 
-		     << " degrees of freedom for OPAL eta x_E"
-		     << "distribution or " << chisq/npoint << " per degree of freedom\n";
-  _xeeta->topdrawOutput(output,Frame|Errorbars|Ylog,
-			"RED",
-			"The scaled momentum x0E1 of H for all events (OPAL)",
-			"                     X X    G                      ",
-			"1/NdN/dx0E1",
-			"        X X",
-			"x0E1",
-			" X X");
-  _xieta->normaliseToData();
-  _xieta->chiSquared(chisq,npoint,minfrac);
-  generator()->log() << "Chi Square = " << chisq << " for " << npoint 
-		     << " degrees of freedom for OPAL eta xi"
-		     << "distribution or " << chisq/npoint << " per degree of freedom\n";
-  _xieta->topdrawOutput(output,Frame|Errorbars|Ylog,
-			"RED",
-			"The scaled momentum X of H for all events (OPAL)",
-			"                    G    G                      ",
-			"1/NdN/dX",
-			"       G",
-			"X",
-			"G");
-  // eta'
-  _xeetap->normaliseToData();
-  _xeetap->chiSquared(chisq,npoint,minfrac);
-  generator()->log() << "Chi Square = " << chisq << " for " << npoint 
-		     << " degrees of freedom for OPAL eta' x_E"
-		     << "distribution or " << chisq/npoint << " per degree of freedom\n";
-  _xeetap->topdrawOutput(output,Frame|Errorbars|Ylog,
-			"RED",
-			"The scaled momentum x0E1 of H' for all events (OPAL)",
-			"                     X X    G                       ",
-			"1/NdN/dx0E1",
-			"        X X",
-			"x0E1",
-			" X X");
-  _xietap->normaliseToData();
-  _xietap->chiSquared(chisq,npoint,minfrac);
-  generator()->log() << "Chi Square = " << chisq << " for " << npoint 
-		     << " degrees of freedom for OPAL eta' xi"
-		     << "distribution or " << chisq/npoint << " per degree of freedom\n";
-  _xietap->topdrawOutput(output,Frame|Errorbars|Ylog,
-			"RED",
-			"The scaled momentum X of H' for all events (OPAL)",
-			"                    G    G                       ",
-			"1/NdN/dX",
-			"       G",
-			"X",
-			"G");
-  // rho+
-  _xerhop->normaliseToData();
-  _xerhop->chiSquared(chisq,npoint,minfrac);
-  generator()->log() << "Chi Square = " << chisq << " for " << npoint 
-		     << " degrees of freedom for OPAL rho+ x_E"
-		     << "distribution or " << chisq/npoint << " per degree of freedom\n";
-  _xerhop->topdrawOutput(output,Frame|Errorbars|Ylog,
-			"RED",
-			"The scaled momentum x0E1 of R2+3 for all events (OPAL)",
-			"                     X X    GX X                      ",
-			"1/NdN/dx0E1",
-			"        X X",
-			"x0E1",
-			" X X");
-  _xirhop->normaliseToData();
-  _xirhop->chiSquared(chisq,npoint,minfrac);
-  generator()->log() << "Chi Square = " << chisq << " for " << npoint 
-		     << " degrees of freedom for OPAL rho+ xi"
-		     << "distribution or " << chisq/npoint << " per degree of freedom\n";
-  _xirhop->topdrawOutput(output,Frame|Errorbars|Ylog,
-			"RED",
-			"The scaled momentum X of R2+3 for all events (OPAL)",
-			"                    G    GX X                      ",
-			"1/NdN/dX",
-			"       G",
-			"X",
-			"G");
-  // omega
-  _xeomega->normaliseToData();
-  _xeomega->chiSquared(chisq,npoint,minfrac);
-  generator()->log() << "Chi Square = " << chisq << " for " << npoint 
-		     << " degrees of freedom for OPAL omega x_E"
-		     << "distribution or " << chisq/npoint << " per degree of freedom\n";
-  _xeomega->topdrawOutput(output,Frame|Errorbars|Ylog,
-			"RED",
-			"The scaled momentum x0E1 of W for all events (OPAL)",
-			"                     X X    G                      ",
-			"1/NdN/dx0E1",
-			"        X X",
-			"x0E1",
-			" X X");
-  _xiomega->normaliseToData();
-  _xiomega->chiSquared(chisq,npoint,minfrac);
-  generator()->log() << "Chi Square = " << chisq << " for " << npoint 
-		     << " degrees of freedom for OPAL omega xi"
-		     << "distribution or " << chisq/npoint << " per degree of freedom\n";
-  _xiomega->topdrawOutput(output,Frame|Errorbars|Ylog,
-			"RED",
-			"The scaled momentum X of W for all events (OPAL)",
-			"                    G    G                      ",
-			"1/NdN/dX",
-			"       G",
-			"X",
-			"G");
-  // a_0+
-  _xea_0p->normaliseToData();
-  _xea_0p->chiSquared(chisq,npoint,minfrac);
-  generator()->log() << "Chi Square = " << chisq << " for " << npoint 
-		     << " degrees of freedom for OPAL a_0+ x_E"
-		     << "distribution or " << chisq/npoint << " per degree of freedom\n";
-  _xea_0p->topdrawOutput(output,Frame|Errorbars|Ylog,
-			"RED",
-			"The scaled momentum x0E1 of A0012+3 for all events (OPAL)",
-			"                     X X     X XX X                      ",
-			"1/NdN/dx0E1",
-			"        X X",
-			"x0E1",
-			" X X");
-  _xia_0p->normaliseToData();
-  _xia_0p->chiSquared(chisq,npoint,minfrac);
-  generator()->log() << "Chi Square = " << chisq << " for " << npoint 
-		     << " degrees of freedom for OPAL a_0+ xi"
-		     << "distribution or " << chisq/npoint << " per degree of freedom\n";
-  _xia_0p->topdrawOutput(output,Frame|Errorbars|Ylog,
-			"RED",
-			"The scaled momentum X of A0012+3 for all events (OPAL)",
-			"                    G     X XX X                      ",
-			"1/NdN/dX",
-			"       G",
-			"X",
-			"G");
-  // D0
-  _xeD0->normaliseToData();
-  _xeD0->chiSquared(chisq,npoint,minfrac);
-  generator()->log() << "Chi Square = " << chisq << " for " << npoint 
-		     << " degrees of freedom for DELPHI D0 x_E"
-		     << "distribution or " << chisq/npoint << " per degree of freedom\n";
-  _xeD0->topdrawOutput(output,Frame|Errorbars|Ylog,
-			    "RED",
-			    "The scaled momentum x0E1 of D203 for all events (DELPHI)",
-			    "                     X X     X X                        ",
-			    "1/NdN/dx0E1",
-			    "        X X",
-			    "x0E1",
-			    " X X");
-  // D*+
-  _xeDstar->normaliseToData();
-  _xeDstar->chiSquared(chisq,npoint,minfrac);
-  generator()->log() << "Chi Square = " << chisq << " for " << npoint 
-		     << " degrees of freedom for ALEPH Dstar x_E"
-		     << "distribution or " << chisq/npoint << " per degree of freedom\n";
-  _xeDstar->topdrawOutput(output,Frame|Errorbars|Ylog,
-			  "RED",
-			  "The scaled momentum x0E1 of D2*+3 for all events (ALEPH)",
-			  "                     X X     X  X                        ",
-			  "1/NdN/dx0E1",
-			  "        X X",
-			  "x0E1",
-			  " X X");
-}
-
-void IdentifiedParticleAnalysis::doinitrun() {
-  AnalysisHandler::doinitrun();
-  // SLD data (all charged)
-  double xpbins[] = {0.005, 0.008, 0.010, 0.012, 0.014, 
-		     0.016, 0.022, 0.027, 0.033, 0.038, 
-		     0.044, 0.049, 0.055, 0.060, 0.066, 
-		     0.071, 0.077, 0.082, 0.088, 0.099, 
-		     0.110, 0.121, 0.143, 0.164, 0.186, 
-		     0.208, 0.230, 0.252, 0.274, 0.296, 
-		     0.318, 0.351, 0.384, 0.417, 0.450, 
-		     0.482, 0.526, 0.570, 0.658, 0.768, 
-		     1.000};
-  double xpdataa[]={509.2   ,513.9   ,485.5   ,443.4   ,398.7   ,
-		    335.8   ,267.2   ,217.8   ,180.7   ,153.2   ,
-		    130.6   ,113.4   , 99.09  , 87.57  , 77.56  ,
-		    69.78   , 62.84  , 56.72  , 48.90  , 40.78  ,
-		    34.39   , 27.35  , 20.53  , 15.64  , 12.25  ,
-		    9.67    ,  7.75  , 6.161  , 5.029  , 4.053  ,
-		    3.139   , 2.338  , 1.748  , 1.326  , 1.008  ,
-		    0.724   , 0.480  , 0.285  , 0.114  , 0.024  };
-  double xperrora[]={9.5  ,7.8  ,6.6  ,5.6  ,4.9  ,
-		     3.9  ,2.9  ,2.3  ,1.9  ,1.6  ,
-		     1.4  ,1.2  ,1.03 ,0.91 ,0.81 ,
-		     0.73 ,0.66 ,0.60 ,0.51 ,0.43 ,
-		     0.37 ,0.29 ,0.23 ,0.18 ,0.15 ,
-		     0.12 ,0.11 ,0.088,0.076,0.065,
-		     0.052,0.042,0.034,0.028,0.023,
-		     0.018,0.013,0.009,0.005,0.001};
-  double xpdatal[] ={507.8 ,505.2 ,465.3 ,421.9 ,371.7 ,
-		     315.5 ,250.5 ,200.3 ,167.3 ,140.4 ,
-		     121.2 ,105.5 , 91.2 ,81.29 ,72.69 ,
-		     65.92 ,58.06 ,53.26 ,45.37 ,38.55 ,
-		     32.84 ,26.05 ,19.79 ,15.75 ,12.16 ,
-		     10.27 , 8.14 , 6.62 ,5.565 ,4.428 ,
-		     3.588 ,2.706 ,2.062 ,1.631 ,1.193 ,
-		     0.912 ,0.632 ,0.398 ,0.172 ,0.027};
-  double xperrorl[]={ 11.9 ,  9.2 ,  7.5 ,  6.3 ,  5.8 ,
-		      4.2 ,  3.2 ,  2.3 ,  2.0 ,  1.6 ,
-		      1.3 ,  1.1 ,  1.0 , 0.89 , 0.81 ,
-		      0.76 , 0.70 , 0.66 , 0.48 , 0.43 ,
-		      0.41 , 0.28 , 0.29 , 0.35 , 0.17 ,
-		      0.14 , 0.11 , 0.10 ,0.087 ,0.076 ,
-		      0.057 ,0.049 ,0.042 ,0.037 ,0.034 ,
-		      0.026 ,0.023 ,0.015 ,0.011 ,0.005 };
-  double xpdatac[] ={468.7  ,485.4  ,507.2  ,464.0  ,422.9  ,
-		     349.1  ,274.1  ,231.5  ,187.5  ,162.3  ,
-		     136.6  ,117.3  , 99.1  ,89.21  ,78.25  ,
-		     69.26  ,62.25  ,55.28  ,49.14  ,40.11  ,
-		     35.64  ,28.94  ,21.99  ,16.51  ,12.69  ,
-		     10.41  , 7.86  , 6.37  ,5.060  ,4.080  ,
-		     3.123  ,2.141  ,1.472  ,0.952  ,0.935  ,
-		     0.485  ,0.372  ,0.140  ,0.027  ,0.011};
-  double xperrorc[]={25.3, 22.6, 20.2, 17.6, 16.9,
-		     12.7,  9.5,  7.3,  6.9,  5.2,
-		     4.2,  3.6,  3.0, 2.65, 2.42, 
-		     2.23, 2.06, 1.93, 1.42, 1.29,
-		     1.22, 0.83, 0.86, 1.03, 0.50,
-		     0.40, 0.32, 0.28,0.241,0.210,
-		     0.156,0.126,0.106,0.090,0.085,
-		     0.061,0.055,0.031,0.016,0.010};
-  double xpdatab[] ={546.1  ,558.5  ,531.9  ,490.8  ,436.5  ,
-		     382.8  ,308.6  ,254.8  ,213.2  ,182.1  ,
-		     154.5  ,134.3  ,118.6  ,102.4  ,91.92  ,
-		     83.63  ,75.06  ,66.58  ,57.31  ,47.80  ,
-		     39.19  ,29.54  ,20.69  ,15.36  ,10.65  ,
-		     8.06  , 6.28  , 4.69  ,3.490  ,2.935  ,
-		     2.041  ,1.534  ,1.111  ,0.736  ,0.510  ,
-		     0.330  ,0.188  ,0.089  ,0.017  ,0.003};
-  double xperrorb[]={ 14.2, 10.3,  8.0,  6.3,  6.7,
-		      4.4,  3.4,  2.6,  2.1,  1.9, 
-		      1.7,  1.6,  1.4,  1.3, 1.22,
-		      1.14, 1.10, 1.04, 0.74, 0.71,
-		      0.67, 0.48, 0.48, 0.55, 0.26, 
-		      0.20, 0.16, 0.13,0.110,0.098,
-		      0.068,0.058,0.051,0.042,0.037,
-		      0.027,0.022,0.012,0.006,0.002};
-  vector<double> bins =vector<double>(xpbins,xpbins+41);
-  vector<double> data =vector<double>(xpdataa,xpdataa+40);
-  vector<double> error=vector<double>(xperrora,xperrora+40);
-  _xpa=new_ptr(Histogram(bins,data,error));
-  data =vector<double>(xpdatal,xpdatal+40);
-  error=vector<double>(xperrorl,xperrorl+40);
-  _xpl=new_ptr(Histogram(bins,data,error));
-  data =vector<double>(xpdatac,xpdatac+40);
-  error=vector<double>(xperrorc,xperrorc+40);
-  _xpc=new_ptr(Histogram(bins,data,error));
-  data =vector<double>(xpdatab,xpdatab+40);
-  error=vector<double>(xperrorb,xperrorb+40);
-  _xpb=new_ptr(Histogram(bins,data,error));
-  // SLD pions data
-  double pipmbins[] = {0.005, 0.008, 0.010, 0.012, 0.014, 
-		       0.016, 0.022, 0.027, 0.033, 0.038, 
-		       0.044, 0.049, 0.055, 0.060, 0.066, 
-		       0.071, 0.077, 0.082, 0.088, 0.099, 
-		       0.110, 0.121, 0.143, 0.164, 0.186, 
-		       0.208, 0.230, 0.252, 0.274, 0.296, 
-		       0.318, 0.351, 0.384, 0.417, 0.450, 
-		       0.482, 0.526, 0.570, 0.658, 0.768, 
-		       1.000};
-  double pipmdataa[]={ 471.8 , 470.4 , 434.6 , 388.8 , 352.7 ,
-		       294.8 , 229.6 , 185.0 , 150.6 , 125.6 ,
-		       106.5 , 90.40 , 77.38 , 67.39 , 59.40 ,
-		       52.57 , 46.76 , 41.70 , 35.26 , 28.89 ,
-		       23.88 , 18.69 , 13.85 , 10.16 , 7.812 ,
-		       6.076 , 4.674 , 3.632 , 2.886 , 2.292 ,
-		       1.749 , 1.275 , 0.921 , 0.680 , 0.499 ,
-		       0.338 , 0.226 , 0.130 ,0.0526 ,0.0113 };
-  double pipmerrorastat[]={1.3,    1.1,    1.1,    1.0,    0.9,
-			   0.5,    0.5,    0.4,    0.4,    0.4,
-			   0.4,   0.35,   0.31,   0.29,   0.27,
-			   0.25,   0.24,   0.23,   0.15,   0.13,
-			   0.12,   0.08,   0.07,   0.06,  0.050,
-			   0.044,  0.039,  0.035,  0.031,  0.028,
-			   0.021,  0.018,  0.016,  0.014,  0.013,
-			   0.010,  0.009,  0.005, 0.0037, 0.0018};
-  double pipmerrorasytm[]={9.2,     6.6,     5.0,     4.0,     3.3,
-			   2.2,     1.3,     0.9,     0.7,     0.9,
-			   1.1,    1.33,    0.91,    0.70,    0.75,
-			   0.60,    0.50,    0.43,    0.36,    0.29, 
-			   0.25,    0.19,    0.14,    0.11,   0.069,
-			   0.061,   0.053,   0.044,   0.037,   0.031,
-			   0.034,   0.028,   0.022,   0.018,   0.014,
-			   0.010,   0.007,   0.005,  0.0029,  0.0013};
-  double pipmdatal[] ={474.0     ,  467.3    ,  418.2    ,  375.5    ,  327.7    ,
-		       275.8    ,  216.0    ,  171.2    ,  140.4    ,  116.4    ,
-		       99.9    ,   85.4    ,  72.85    ,  64.51    ,  56.82    ,
-		       50.84    ,  45.34    ,  40.71    ,  34.60    ,  28.99    ,
-		       24.19    ,  18.97    ,  14.52    ,  11.06    ,   8.67    ,
-		       6.79    ,  5.341    ,  4.214    ,  3.452    ,  2.727    ,
-		       2.138    ,  1.652    ,  1.164    ,  0.874    ,  0.622    ,
-		       0.441    ,  0.300    ,  0.178    ,  0.081    ,  0.016};
-  double pipmerrorlstat[]={13.9 , 10.5 ,  8.4 ,  6.9 ,  5.7 ,
-			   4.2 ,  3.0 ,  2.2 ,  1.9 ,  1.5 ,
-			   1.2 ,  1.0 , 0.89 , 0.79 , 0.72 ,
-			   0.66 , 0.61 , 0.56 , 0.40 , 0.35 ,
-			   0.31 , 0.22 , 0.17 , 0.14 , 0.12 ,
-			   0.10 ,0.085 ,0.073 ,0.064 ,0.056 ,
-			   0.042 ,0.036 ,0.031 ,0.027 ,0.024 ,
-			   0.019 ,0.017 ,0.010 ,0.007 ,0.003};
-  double pipmerrorlsytm[]={0.0,0.0,0.0,0.0,0.0,0.0,0.0,0.0,0.0,0.0,
-			   0.0,0.0,0.0,0.0,0.0,0.0,0.0,0.0,0.0,0.0,
-			   0.0,0.0,0.0,0.0,0.0,0.0,0.0,0.0,0.0,0.0,
-			   0.0,0.0,0.0,0.0,0.0,0.0,0.0,0.0,0.0,0.0};
-  double pipmdatac[] ={425.5     ,  440.5    ,  453.8    ,  409.2    ,  372.8    ,
-		       306.4    ,  234.6    ,  197.4    ,  155.8    ,  132.5    ,
-		       109.3    ,   92.9    ,  77.56    ,  68.23    ,  60.06    ,
-		       51.76    ,  45.28    ,  40.04    ,  33.50    ,  27.45    , 
-		       22.92    ,  18.73    ,  13.72    ,  10.18    ,   7.53    ,
-		       5.76    ,  4.381    ,  3.358    ,  2.487    ,  1.947    ,
-		       1.436    ,  0.817    ,  0.614    ,  0.386    ,  0.429    ,
-		       0.206    ,  0.142    ,  0.066    ,  0.003    ,  0.003};
-  double pipmerrorcstat[]={26.6 , 23.2 , 20.0 , 17.2 , 14.6 ,
-			   10.9 ,  8.0 ,  6.2 ,  6.0 ,  4.3 ,
-			   3.5 ,  2.9 , 2.48 , 2.17 , 1.97  ,
-			   1.81 , 1.67 , 1.55 , 1.12 , 0.99 ,
-			   0.87 , 0.63 , 0.50 , 0.41 , 0.34 ,
-			   0.29 ,0.235 ,0.202 ,0.171 ,0.148 ,
-			   0.108 ,0.087 ,0.074 ,0.063 ,0.061 ,
-			   0.043 ,0.037 ,0.021 ,0.010 ,0.006};
-  double pipmerrorcsytm[]={0.0,0.0,0.0,0.0,0.0,0.0,0.0,0.0,0.0,0.0,
-			   0.0,0.0,0.0,0.0,0.0,0.0,0.0,0.0,0.0,0.0,
-			   0.0,0.0,0.0,0.0,0.0,0.0,0.0,0.0,0.0,0.0,
-			   0.0,0.0,0.0,0.0,0.0,0.0,0.0,0.0,0.0,0.0};
-  double pipmdatab[] ={478.1   ,488.4  ,463.7  ,432.2  ,382.4  ,
-		       333.3  ,261.7  ,214.2  ,175.2  ,145.4  ,
-		       121.4  ,103.3  ,89.24  ,75.47  ,65.97  ,
-		       59.39  ,52.11  ,45.86  ,38.29  ,30.57  ,
-		       24.34  ,18.21  ,12.27  , 8.25  , 5.83  ,
-		       4.14  ,2.984  ,2.303  ,1.642  ,1.365  ,
-		       0.886  ,0.631  ,0.490  ,0.276  ,0.187  ,
-		       0.111  ,0.045  ,0.039  ,0.011  ,0.003};
-  double pipmerrorbstat[]={15.8,  11.9,   9.5,   7.7,   6.5,
-			   4.6,   3.3,   2.7,   2.3,   1.9, 
-			   1.7,   1.5,  1.36,  1.21,  1.12,
-			   1.04,  0.97,  0.90,  0.65,  0.58,
-			   0.51,  0.36,  0.28,  0.22,  0.18,
-			   0.15, 0.128, 0.110, 0.094, 0.085,
-			   0.063, 0.052, 0.047, 0.038, 0.033,
-			   0.025, 0.019, 0.010, 0.005, 0.002};
-  double pipmerrorbsytm[]={0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0,
-			   0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0,
-			   0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0,
-			   0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0};
-  double pipmerrora[40],pipmerrorl[40],pipmerrorc[40],pipmerrorb[40];
-  for(unsigned int ix=0;ix<40;++ix) {
-    pipmerrora[ix]=sqrt(sqr(pipmerrorastat[ix])+sqr(pipmerrorasytm[ix]));
-    pipmerrorl[ix]=sqrt(sqr(pipmerrorlstat[ix])+sqr(pipmerrorlsytm[ix]));
-    pipmerrorc[ix]=sqrt(sqr(pipmerrorcstat[ix])+sqr(pipmerrorcsytm[ix]));
-    pipmerrorb[ix]=sqrt(sqr(pipmerrorbstat[ix])+sqr(pipmerrorbsytm[ix]));
-  }
-  bins =vector<double>(pipmbins,pipmbins+41);
-  data =vector<double>(pipmdataa,pipmdataa+40);
-  error=vector<double>(pipmerrora,pipmerrora+40);
-  _pipma=new_ptr(Histogram(bins,data,error));
-  data =vector<double>(pipmdatal,pipmdatal+40);
-  error=vector<double>(pipmerrorl,pipmerrorl+40);
-  _pipml=new_ptr(Histogram(bins,data,error));
-  data =vector<double>(pipmdatac,pipmdatac+40);
-  error=vector<double>(pipmerrorc,pipmerrorc+40);
-  _pipmc=new_ptr(Histogram(bins,data,error));
-  data =vector<double>(pipmdatab,pipmdatab+40);
-  error=vector<double>(pipmerrorb,pipmerrorb+40);
-  _pipmb=new_ptr(Histogram(bins,data,error));
-  // opal pion data
-  double pibinso[] = {0.227, 0.239, 0.251, 0.263, 0.276, 
-		      0.290, 0.305, 0.320, 0.336, 0.353, 
-		      0.371, 0.390, 0.410, 0.431, 0.453, 
-		      0.476, 0.500, 0.525, 0.552, 0.580, 
-		      0.610, 0.641, 0.673, 0.708, 0.744, 
-		      0.782, 0.822, 0.864, 2.02, 2.12, 
-		      2.23, 
-		      2.34, 2.59, 2.72, 2.86, 3.01, 
-		      3.16, 3.32, 3.49, 3.67, 3.86, 
-		      4.06, 4.95, 6.05, 7.39, 9.02, 
-		      11.02, 13.46, 16.44, 20.08, 29.95, 
-		      45.60};
-  double pidatao[]={  9.89   ,  9.98   , 10.37   , 10.38   , 10.42   ,
-		      10.40   , 10.53   , 10.66   , 10.53   , 10.56   ,
-		      10.46   , 10.23   , 10.29   , 10.02   ,  9.83   ,
-		      9.62   ,  9.46   ,  9.23   ,  9.05   ,  8.71   ,
-		      8.40   ,  8.12   ,  7.87   ,  7.50   ,  7.26   ,
-		      6.95   ,  6.56   ,  0.0	 ,  2.374  ,  2.264  ,
-		      2.103  ,  1.944  ,  1.672  ,  1.550  ,  1.420  ,
-		      1.328  ,  1.221  ,  1.115  ,  1.035  ,  0.955  ,
-		      0.879  ,  0.705  ,  0.478  ,  0.319  ,  0.2052 ,
-		      0.1246 ,  0.0717 ,  0.0386 ,  0.0206 ,  0.0058 ,
-		      0.0006 };
-  double pierrorostat[]={0.07  ,0.07  ,0.07  ,0.07  ,0.07  ,
-			 0.07  ,0.06  ,0.06  ,0.06  ,0.06  ,
-			 0.06  ,0.06  ,0.06  ,0.05  ,0.05  ,
-			 0.05  ,0.05  ,0.05  ,0.05  ,0.04  ,
-			 0.04  ,0.04  ,0.04  ,0.04  ,0.03  ,
-			 0.03  ,0.04  ,0.0   ,0.031 ,0.013 ,
-			 0.018 ,0.010 ,0.009 ,0.013 ,0.008 ,
-			 0.008 ,0.008 ,0.007 ,0.007 ,0.006 ,
-			 0.006 ,0.003 ,0.002 ,0.001 ,0.0012,
-			 0.0008,0.0006,0.0005,0.0004,0.0001,
-			 0.0001};
-  double pierrorosyst[]={0.29   ,0.29   ,0.31   ,0.31   ,0.31   ,
-			 0.31   ,0.31   ,0.31   ,0.31   ,0.31   ,
-			 0.31   ,0.30   ,0.30   ,0.29   ,0.29   ,
-			 0.28   ,0.28   ,0.27   ,0.26   ,0.25   ,
-			 0.25   ,0.24   ,0.23   ,0.22   ,0.21   ,
-			 0.20     ,0.20     ,0.0,0.209   ,0.079   ,
-			 0.036   ,0.027   ,0.024   ,0.024   ,0.022  ,
-			 0.019   ,0.017   ,0.015   ,0.015   ,0.014   ,
-			 0.012   ,0.009   ,0.007   ,0.005   ,0.0032  ,
-			 0.0024  ,0.0016  ,0.0012  ,0.0013  ,0.0004  ,
-			 0.0002 };
-  double pierroro[51];
-  for(unsigned int ix=0;ix<51;++ix)
-    {pierroro[ix]=sqrt(sqr(pierrorostat[ix])+sqr(pierrorosyst[ix]));}
-  bins =vector<double>(pibinso,pibinso+52);
-  data =vector<double>(pidatao,pidatao+51);
-  error=vector<double>(pierroro,pierroro+51);
-  _pipm=new_ptr(Histogram(bins,data,error)); 
-  // SLD kaons
-  double Kbins[] = {0.014, 0.016, 0.022, 0.027, 0.033, 
-		    0.038, 0.044, 0.049, 0.055, 0.060, 
-		    0.066, 0.071, 0.077, 0.082, 0.088, 
-		    0.099, 0.110, 0.121, 0.143, 0.164, 
-		    0.186, 0.208, 0.230, 0.252, 0.274, 
-		    0.296, 0.318, 0.351, 0.384, 0.417, 
-		    0.450, 0.482, 0.526, 0.570, 0.658, 
-		    0.768, 1.000};
-  double Kdataa[]={28.59 ,  21.57 ,  21.62 ,  19.65 ,  18.02 ,
-		   17.27 ,  15.78 , 14.664 , 13.535 , 12.599 ,
-		   12.036 , 11.349 , 10.207 ,  9.571 ,  8.671 ,
-		   7.784 ,  7.237 ,  5.746 ,  3.959 ,  3.473 , 
-		   2.739 ,  2.452 ,  1.903 ,  1.574 ,  1.360 ,
-		   1.118 ,  0.890 ,  0.683 ,  0.567 ,  0.433 ,
-		   0.351 ,  0.264 ,  0.188 ,  0.122 , 0.0485 ,
-		   0.0078};
-  double Kerrorastat[]={0.64 ,   0.20 ,   0.19 ,   0.18 ,   0.16 ,
-			0.17 ,   0.17 ,  0.194 ,  0.189 ,  0.176 ,
-			0.165 ,  0.162 ,  0.164 ,  0.160 ,  0.113 ,
-			0.114 ,  0.120 ,  0.089 ,  0.102 ,  0.134 ,
-			0.047 ,  0.037 ,  0.030 ,  0.027 ,  0.024 ,
-			0.022 ,  0.016 ,  0.014 ,  0.013 ,  0.012 ,
-			0.011 ,  0.008 ,  0.008 ,  0.005 , 0.0037 ,
-			0.0022};
-  double Kerrorasytm[]={9.26,   1.57,   0.80,   0.53,   0.44,
-			0.43,   0.47,  0.442,  0.503,  0.558,
-			0.635,  0.622,  0.603,  0.566,  0.505,
-			0.440,  0.395,  0.369,  0.381,  0.532,
-			0.419,  0.163,  0.063,  0.036,  0.026,
-			0.020,  0.017,  0.016,  0.015,  0.014,
-			0.012,  0.010,  0.008,  0.006, 0.0027,
-			0.0011};
-  double Kdatal[] ={27.05 ,  20.00 ,  19.74 ,  17.52 ,  16.08 ,
-		    15.04 ,  13.54 ,  11.87 ,  11.44 ,  10.64 ,
-		    10.24 ,   9.67 ,   8.13 ,   7.98 ,   7.00 ,
-		    6.36 ,   5.85 ,   4.89 ,   3.41 ,   2.84 ,
-		    2.564 ,  2.401 ,  1.973 ,  1.643 ,  1.481 ,
-		    1.211 ,  1.001 ,  0.746 ,  0.666 ,  0.559 ,
-		    0.426 ,  0.363 ,  0.261 ,  0.183 ,  0.079 ,
-		    0.008};
-  double Kerrorlstat[]={1.27 , 0.42 , 0.40 , 0.37 , 0.37 ,
-			0.34 , 0.34 , 0.34 , 0.33 , 0.30 ,
-			0.29 , 0.29 , 0.27 , 0.28 , 0.19 ,
-			0.19 , 0.20 , 0.15 , 0.17 , 0.22 ,
-			0.082 ,0.067 ,0.054 ,0.048 ,0.044 ,
-			0.039 ,0.029 ,0.025 ,0.023 ,0.022 ,
-			0.020 ,0.016 ,0.015 ,0.010 ,0.007 ,
-			0.004};
-  double Kerrorlsytm[]={0.0,0.0,0.0,0.0,0.0,0.0,0.0,0.0,0.0,0.0,
-			0.0,0.0,0.0,0.0,0.0,0.0,0.0,0.0,0.0,0.0,
-			0.0,0.0,0.0,0.0,0.0,0.0,0.0,0.0,0.0,0.0,
-			0.0,0.0,0.0,0.0,0.0,0.0};
-  double Kdatac[] ={30.92 ,  22.43 ,  22.04 ,  20.82 ,  16.79 ,
-		    16.68 ,  16.46 ,  15.81 ,  12.62 ,  12.24 ,
-		    11.42 ,  10.95 ,  10.88 ,   9.62 ,   9.84 ,
-		    8.08 ,   8.98 ,   6.59 ,   5.50 ,   5.12 ,
-		    3.850 ,  3.087 ,  2.074 ,  1.960 ,  1.681 ,
-		    1.368 ,  1.043 ,  0.874 ,  0.600 ,  0.408 ,
-		    0.408 ,  0.243 ,  0.173 ,  0.064 ,  0.009 ,
-		    0.008};
-  double Kerrorcstat[]={3.86 , 1.37 , 1.27 , 1.17 , 1.15 ,
-			1.15 , 1.06 , 1.08 , 0.99 , 0.92 ,
-			0.87 , 0.85 , 0.84 , 0.81 , 0.59 ,
-			0.58 , 0.63 , 0.45 , 0.51 , 0.68 ,
-			0.245 ,0.190 ,0.145 ,0.132 ,0.119 ,
-			0.104 ,0.076 ,0.068 ,0.058 ,0.050 ,
-			0.050 ,0.037 ,0.034 ,0.020 ,0.011 ,
-			0.008};
-  double Kerrorcsytm[]={0.0,0.0,0.0,0.0,0.0,0.0,0.0,0.0,0.0,0.0,
-			0.0,0.0,0.0,0.0,0.0,0.0,0.0,0.0,0.0,0.0,
-			0.0,0.0,0.0,0.0,0.0,0.0,0.0,0.0,0.0,0.0,
-			0.0,0.0,0.0,0.0,0.0,0.0};
-  double Kdatab[] ={30.21 ,  23.06 ,  22.89 ,  21.64 ,  21.36 ,
-		    21.36 ,  19.90 ,  18.91 ,  18.46 ,  17.43 ,
-		    16.92 ,  15.62 ,  15.11 ,  13.18 ,  12.43 ,
-		    11.56 ,   9.96 ,   7.17 ,   4.58 ,   4.20 ,
-		    2.541 ,  2.009 ,  1.627 ,  1.116 ,  0.830 ,
-		    0.640 ,  0.452 ,  0.337 ,  0.245 ,  0.149 ,
-		    0.108 ,  0.057 ,  0.061 ,  0.012 ,  0.002 ,
-		    0.001};
-  double Kerrorbstat[]={1.99 , 0.62 , 0.60 , 0.55 , 0.53 ,
-			0.56 , 0.57 , 0.60 , 0.58 , 0.54 ,
-			0.53 , 0.52 , 0.52 , 0.50 , 0.36 ,
-			0.37 , 0.38 , 0.27 , 0.29 , 0.36 ,
-			0.126 ,0.096 ,0.078 ,0.062 ,0.053 ,
-			0.045 ,0.032 ,0.028 ,0.024 ,0.020 ,
-			0.018 ,0.012 ,0.013 ,0.005 ,0.003 ,
-			0.001};
-  double Kerrorbsytm[]={0.0 ,0.0 ,0.0 ,0.0 ,0.0 ,0.0 ,0.0 ,0.0 ,0.0 ,0.0 ,
-			0.0 ,0.0 ,0.0 ,0.0 ,0.0 ,0.0 ,0.0 ,0.0 ,0.0 ,0.0 ,
-			0.0 ,0.0 ,0.0 ,0.0 ,0.0 ,0.0 ,0.0 ,0.0 ,0.0 ,0.0 ,
-			0.0 ,0.0 ,0.0 ,0.0 ,0.0 ,0.0};
-  double Kerrora[36],Kerrorl[36],Kerrorc[36],Kerrorb[36];
-  for(unsigned int ix=0;ix<36;++ix)
-    {
-      Kerrora[ix]=sqrt(sqr(Kerrorastat[ix])+sqr(Kerrorasytm[ix]));
-      Kerrorl[ix]=sqrt(sqr(Kerrorlstat[ix])+sqr(Kerrorlsytm[ix]));
-      Kerrorc[ix]=sqrt(sqr(Kerrorcstat[ix])+sqr(Kerrorcsytm[ix]));
-      Kerrorb[ix]=sqrt(sqr(Kerrorbstat[ix])+sqr(Kerrorbsytm[ix]));
-    }
-  bins =vector<double>(Kbins,Kbins+37);
-  data =vector<double>(Kdataa,Kdataa+36);
-  error=vector<double>(Kerrora,Kerrora+36);
-  _kpma=new_ptr(Histogram(bins,data,error));
-  data =vector<double>(Kdatal,Kdatal+36);
-  error=vector<double>(Kerrorl,Kerrorl+36);
-  _kpml=new_ptr(Histogram(bins,data,error));
-  data =vector<double>(Kdatac,Kdatac+36);
-  error=vector<double>(Kerrorc,Kerrorc+36);
-  _kpmc=new_ptr(Histogram(bins,data,error));
-  data =vector<double>(Kdatab,Kdatab+36);
-  error=vector<double>(Kerrorb,Kerrorb+36);
-  _kpmb=new_ptr(Histogram(bins,data,error));
-    // OPAL kaons
-  double Kbinso[] = {0.271, 0.281, 0.292, 0.304, 0.317, 
-		     0.331, 0.346, 0.362, 0.379, 0.397, 
-		     0.416, 0.436, 0.457, 0.480, 0.504, 
-		     0.528, 0.555, 0.583, 0.612, 0.643, 
-		     0.675, 0.709, 0.745, 0.783, 4.05, 
-		     4.95, 
-		     6.05, 7.38, 9.02, 11.01, 13.45, 
-		     16.43, 20.06, 29.93, 45.60};
-  double Kdatao[]={0.363 ,0.373 ,0.367 ,0.374 ,0.375 ,
-		    0.410 ,0.431 ,0.418 ,0.456 ,0.499 ,
-		    0.514 ,0.486 ,0.522 ,0.541 ,0.539 ,
-		    0.557 ,0.587 ,0.590 ,0.586 ,0.591 ,
-		    0.614 ,0.597 ,0.613 ,0.0   ,0.181 ,
-		    0.138 ,0.103 ,0.0767,0.0536,0.0349,
-		    0.0220,0.0127,0.0042,0.0004};
-  double Kerrorostat[]={0.030 ,0.027 ,0.024 ,0.022 ,0.021 ,
-			 0.020 ,0.020 ,0.018 ,0.018 ,0.018 ,
-			 0.017 ,0.011 ,0.011 ,0.011 ,0.011 ,
-			 0.011 ,0.011 ,0.010 ,0.010 ,0.010 ,
-			 0.009 ,0.009 ,0.009 ,0.0   ,0.004 ,
-			 0.003 ,0.001 ,0.0010,0.0006,0.0005,
-			 0.0003,0.0003,0.0001,0.0001};
-  double Kerrorosyst[]={0.028 ,0.028 ,0.025 ,0.023 ,0.019 ,
-			 0.019 ,0.019 ,0.020 ,0.016 ,0.017 ,
-			 0.016 ,0.011 ,0.011 ,0.012 ,0.018 ,
-			 0.020 ,0.014 ,0.048 ,0.016 ,0.044 ,
-			 0.024 ,0.025 ,0.031 , 0.0  ,0.015 ,
-			 0.009 ,0.006 ,0.0042,0.0029,0.0018,
-			 0.0012,0.0007,0.0003,0.0001};
-  double Kerroro[34];
-  for(unsigned int ix=0;ix<34;++ix)
-    {Kerroro[ix]=sqrt(sqr(Kerrorostat[ix])+sqr(Kerrorosyst[ix]));}
-  bins =vector<double>(Kbinso,Kbinso+35);
-  data =vector<double>(Kdatao,Kdatao+34);
-  error=vector<double>(Kerroro,Kerroro+34);
-  _kpm=new_ptr(Histogram(bins,data,error));
-  // SLD proton data
-  double pbins[] = {0.014, 0.016, 0.022, 0.027, 0.033, 
-		    0.038, 0.044, 0.049, 0.055, 0.060, 
-		    0.066, 0.071, 0.077, 0.082, 0.088, 
-		    0.099, 0.110, 0.121, 0.143, 0.164, 
-		    0.186, 0.208, 0.230, 0.252, 0.274, 
-		    0.296, 0.318, 0.351, 0.384, 0.417, 
-		    0.450, 0.482, 0.526, 0.570, 0.658, 
-		    0.768, 1.000};
-  double pdataa[]={14.51 ,  17.32 ,  13.75 ,  11.12 ,  10.75 ,  9.048 ,  7.669 ,  7.410 ,  6.587 ,  5.788 ,  5.344 ,  4.987 ,  4.278 ,  4.117 ,  3.633 ,  3.036 ,  2.568 ,  2.165 ,  1.931 ,  1.603 ,  0.871 ,  0.912 ,  0.775 ,  0.639 ,  0.511 ,  0.419 ,  0.358 ,  0.254 ,  0.173 ,  0.141 , 0.0950 , 0.0688 , 0.0470 , 0.0241 , 0.0093 , 0.0015};
-  double perrorastat[]={ 0.52  ,   0.27  ,   0.29  ,   0.17  ,   0.14  ,  0.123  ,  0.117  ,  0.113  ,  0.109  ,  0.105  ,  0.100  ,  0.104  ,  0.100  ,  0.101  ,  0.072  ,  0.076  ,  0.081  ,  0.069  ,  0.096  ,  0.133  ,  0.045  ,  0.030  ,  0.025  ,  0.022  ,  0.019  ,  0.016  ,  0.011  ,  0.009  ,  0.008  ,  0.007  , 0.0055  , 0.0039  , 0.0032  , 0.0017  , 0.0010  , 0.0003};
-  double perrorasytm[]={5.08,  2.58,  2.50,  1.24,  0.47, 0.350, 0.298, 0.294, 0.259, 0.238, 0.228, 0.229, 0.242, 0.253, 0.269, 0.300, 0.357, 0.398, 0.452, 0.594, 0.255, 0.179, 0.062, 0.044, 0.033, 0.024, 0.018, 0.012, 0.008, 0.005,0.0036,0.0027,0.0018,0.0012,0.0006,0.0001};
-  double pdatal[] ={13.98 , 17.63 , 13.42 , 10.57 ,  9.98 ,  8.37 ,  7.33 ,  7.79 ,  6.62 ,  5.88 ,  5.39 ,  5.22 ,  4.42 ,  4.44 ,  3.65 ,  3.11 ,  2.73 ,  2.15 ,  1.83 ,  1.84 , 0.905 , 1.065 , 0.822 , 0.762 , 0.628 , 0.486 , 0.446 , 0.306 , 0.230 , 0.197 , 0.145 , 0.108 , 0.070 , 0.036 , 0.013 , 0.003};
-  double perrorlstat[]={0.99 , 0.58 , 0.60 , 0.36 , 0.31 , 0.26 , 0.24 , 0.23 , 0.22 , 0.20 , 0.19 , 0.19 , 0.18 , 0.19 , 0.13 , 0.13 , 0.15 , 0.12 , 0.16 , 0.24 ,0.078 ,0.054 ,0.044 ,0.038 ,0.033 ,0.029 ,0.022 ,0.018 ,0.015 ,0.013 ,0.011 ,0.008 ,0.006 ,0.003 ,0.002 ,0.001};
-  double perrorlsytm[]={0.0,0.0,0.0,0.0,0.0,0.0,0.0,0.0,0.0,0.0,0.0,0.0,0.0,0.0,0.0,0.0,0.0,0.0,0.0,0.0,0.0,0.0,0.0,0.0,0.0,0.0,0.0,0.0,0.0,0.0,0.0,0.0,0.0,0.0,0.0,0.0};
-  double pdatac[] ={13.28, 15.22, 13.32,  9.60, 11.64, 10.07,  8.10,  6.09,  6.54,  6.36,  4.62,  4.43,  4.08,  3.67,  4.07,  2.98,  2.30,  2.39,  1.72,  0.31, 0.561, 0.978, 0.907, 0.652, 0.572, 0.494, 0.454, 0.314, 0.170, 0.103, 0.064, 0.015, 0.044, 0.007, 0.015, 0.001};
-  double perrorcstat[]={ 2.94 ,  1.89 ,  1.86 ,  1.16 ,  1.01 ,  0.87 ,  0.76 ,  0.72 ,  0.67 ,  0.63 ,  0.59 ,  0.58 ,  0.55 ,  0.55 ,  0.42 ,  0.41 ,  0.43 ,  0.36 ,  0.50 ,  0.71 , 0.235 , 0.163 , 0.136 , 0.116 , 0.101 , 0.089 , 0.069 , 0.054 , 0.041 , 0.033 , 0.028 , 0.018 , 0.017 , 0.007 , 0.005 , 0.002};
-  double perrorcsytm[]={0.0,0.0,0.0,0.0,0.0,0.0,0.0,0.0,0.0,0.0,0.0,0.0,0.0,0.0,0.0,0.0,0.0,0.0,0.0,0.0,0.0,0.0,0.0,0.0,0.0,0.0,0.0,0.0,0.0,0.0,0.0,0.0,0.0,0.0,0.0,0.0};
-  double pdatab[] ={13.79 , 17.93 , 16.41 , 12.11 , 10.32 ,  9.52 ,  7.72 ,  6.86 ,  6.19 ,  4.96 ,  4.82 ,  4.57 ,  4.07 ,  3.82 ,  3.29 ,  2.68 ,  2.24 ,  1.84 ,  1.91 ,  1.25 , 0.867 , 0.739 , 0.645 , 0.392 , 0.252 , 0.266 , 0.146 , 0.102 , 0.020 , 0.034 , 0.004 , 0.016 , 0.003 , 0.004 , 0.001 , 0.000};
-  double perrorbstat[]={1.49 , 0.78 , 0.93 , 0.52 , 0.42 ,
-			0.40 , 0.36 , 0.32 , 0.32 , 0.29 ,
-			0.29 , 0.29 , 0.29 , 0.29 , 0.21 ,
-			0.22 , 0.23 , 0.19 , 0.27 , 0.36 ,
-			0.121 ,0.072 ,0.060 ,0.047 ,0.038 ,
-			0.035 ,0.022 ,0.018 ,0.012 ,0.011 ,
-			0.007 ,0.006 ,0.003 ,0.002 ,0.001 ,
-			0.000};
-  double perrorbsytm[]={0.0,0.0,0.0,0.0,0.0,0.0,0.0,0.0,0.0,0.0,
-			0.0,0.0,0.0,0.0,0.0,0.0,0.0,0.0,0.0,0.0,
-			0.0,0.0,0.0,0.0,0.0,0.0,0.0,0.0,0.0,0.0,
-			0.0,0.0,0.0,0.0,0.0,0.0};
-  double perrora[36],perrorl[36],perrorc[36],perrorb[36];
-  for(unsigned int ix=0;ix<36;++ix)
-    {
-      perrora[ix]=sqrt(sqr(perrorastat[ix])+sqr(perrorasytm[ix]));
-      perrorl[ix]=sqrt(sqr(perrorlstat[ix])+sqr(perrorlsytm[ix]));
-      perrorc[ix]=sqrt(sqr(perrorcstat[ix])+sqr(perrorcsytm[ix]));
-      perrorb[ix]=sqrt(sqr(perrorbstat[ix])+sqr(perrorbsytm[ix]));
-    }
-  bins =vector<double>(pbins,pbins+37);
-  data =vector<double>(pdataa,pdataa+36);
-  error=vector<double>(perrora,perrora+36);
-  _ppma=new_ptr(Histogram(bins,data,error));
-  data =vector<double>(pdatal,pdatal+36);
-  error=vector<double>(perrorl,perrorl+36);
-  _ppml=new_ptr(Histogram(bins,data,error));
-  data =vector<double>(pdatac,pdatac+36);
-  error=vector<double>(perrorc,perrorc+36);
-  _ppmc=new_ptr(Histogram(bins,data,error));
-  data =vector<double>(pdatab,pdatab+36);
-  error=vector<double>(perrorb,perrorb+36);
-  _ppmb=new_ptr(Histogram(bins,data,error));
-  // OPAL protons
-  double pbinso[] = {0.406, 0.421, 0.438, 0.456, 0.475, 
-		     0.495, 0.517, 0.541, 0.565, 0.592, 
-		     0.620, 0.650, 0.681, 0.714, 0.750, 
-		     0.787, 0.826, 0.867, 0.911, 0.957, 
-		     1.005, 1.056, 1.109, 1.166, 1.225, 
-		     1.287, 1.353, 1.422, 4.05, 4.95, 
-		     6.04, 
-		     7.38, 9.01, 11.01, 13.44, 16.42, 
-		     20.05, 29.90, 45.60};
-  double pdatao[]={0.169      ,0.174       ,0.171        ,0.185      ,
-		   0.181      ,0.202       ,0.215      ,0.228      ,
-		   0.230      ,0.230       ,0.236       ,0.239       ,
-		   0.246       ,0.248       ,0.248      ,0.254      ,
-		   0.260      ,0.260      ,0.257      ,0.263        ,
-		   0.257      ,0.256        ,0.257        ,0.248        ,
-		   0.241        ,0.250        ,0.245        ,0.0	   ,
-		   0.0606      ,0.0517      ,0.0352      ,0.0214      ,
-		   0.0152      ,0.0093      ,0.0045      ,0.0015      ,
-		   0.00056    ,0.000015};
-  double perrorostat[]={0.010         ,0.009         ,0.009         ,0.008         ,
-			0.008         ,0.008         ,0.008         ,0.008         ,
-			0.008         ,0.008         ,0.007         ,0.007         ,
-			0.007         ,0.007         ,0.004         ,0.004         ,
-			0.004         ,0.004         ,0.004         ,0.004         ,
-			0.004         ,0.004         ,0.004         ,0.004         ,
-			0.004         ,0.004         ,0.004         ,0.0	   ,
-			0.0036        ,0.0029        ,0.0011        ,0.0011        ,
-			0.0006        ,0.0004        ,0.0003        ,0.0002        ,
-			0.00005       ,0.000004};
-  double perrorosyst[]={0.013   ,0.015   ,0.012   ,0.015   ,0.006   ,
-			0.010   ,0.012   ,0.014   ,0.010   ,0.007   ,
-			0.012   ,0.008   ,0.006   ,0.009   ,0.009   ,
-			0.008   ,0.007   ,0.007   ,0.006   ,0.007   ,
-			0.021   ,0.027   ,0.029   ,0.027   ,0.017   ,
-			0.016   ,0.021   ,   0.0  ,0.0129  ,0.0062  ,
-			0.0031  ,0.0023  ,0.0021  ,0.0013  ,0.0006  ,
-			0.0005  ,0.00014 ,0.000026};
-  double perroro[38];
-  for(unsigned int ix=0;ix<38;++ix)
-    perroro[ix]=sqrt(sqr(perrorostat[ix])+sqr(perrorosyst[ix]));
-  bins =vector<double>(pbinso,pbinso+39);
-  data =vector<double>(pdatao,pdatao+38);
-  error=vector<double>(perroro,perroro+38);
-  _ppm=new_ptr(Histogram(bins,data,error)); 
-  // OPAL light quarks
-  double udsbinso[] = {0.00, 0.01, 0.02, 0.03, 0.04, 
-		       0.05, 0.06, 0.07, 0.08, 0.09, 
-		       0.10, 0.12, 0.14, 0.16, 0.18, 
-		       0.20, 0.25, 0.30, 0.40, 0.50, 
-		       0.60, 0.80, 1.00};
-  double udsdatao[]={388.  ,390. ,241.  ,176.  ,122.6 ,
-		     95.7   ,79.3   ,65.0   ,53.3   ,43.3   ,
-		     35.1   ,27.7   ,21.2   ,17.1   ,13.3   ,
-		     9.86   ,6.30   ,3.42   ,1.50   ,0.668  ,
-		     0.241   ,  0.031};
-  double udserrorostat[]={5.  ,5.  ,4.  ,3.,2.7   ,2.2 ,
-			  1.9 ,1.6 ,1.6 ,1.5 ,0.9 ,0.7 ,
-			  0.7 ,0.6 ,0.6 ,0.26,0.19,0.09,
-			  0.05,0.033   ,0.008   ,0.007};
-  double udserrorosyst[]={9. ,10.,7. ,5. ,3.9,2.9,
-			  2.3,1.7,1.3,1.0,0.7,0.4,
-			  0.4,0.3,0.3,0.30   ,0.25   ,
-			  0.17   ,0.10   ,0.048  ,0.024  ,0.007};
-  double udserroro[22];
-  for(unsigned int ix=0;ix<22;++ix)
-    {udserroro[ix]=sqrt(sqr(udserrorostat[ix])+sqr(udserrorosyst[ix]));}
-  bins =vector<double>(udsbinso,udsbinso+23);
-  data =vector<double>(udsdatao,udsdatao+22);
-  error=vector<double>(udserroro,udserroro+22);
-  _udsxp=new_ptr(Histogram(bins,data,error));
-  double udsxibinso[] = {0.0, 0.2, 0.4, 0.6, 0.8, 
-			 1.0, 1.2, 1.4, 1.6, 1.8, 
-			 2.0, 2.2, 2.4, 2.6, 2.8, 
-			 3.0, 3.2, 3.4, 3.6, 3.8, 
-			 4.0, 4.2, 4.4, 4.6, 4.8, 
-			 5.0, 5.2, 5.4, 5.6, 5.8};
-  double udsxidatao[]={0.024    , 0.114    , 0.277    , 0.529    ,  0.86      ,
-		       1.31      ,  1.76      ,  2.22      ,  2.70      ,  3.06      ,
-		       3.76      ,  4.03      ,  4.48      ,  5.12      ,  5.22      ,
-		       5.26      ,  6.24      ,  6.02      ,  5.89      ,  6.04      ,
-		       5.85      ,  5.58      ,  5.15      ,  4.21      ,  3.99      ,
-		       2.94      ,  2.14      ,  1.93      ,  1.43};
-  double udsxierrorostat[]={0.006    ,0.003    ,0.009    ,0.016    ,0.02     ,
-			    0.03     ,0.05     ,0.06     ,0.07     ,0.08     ,
-			    0.09     ,0.10     ,0.10     ,0.11     ,0.12     ,
-			    0.13     ,0.12     ,0.12     ,0.13     ,0.12     ,
-			    0.13     ,0.11     ,0.11     ,0.12     ,0.10     ,
-			    0.10     ,0.10     ,0.08     ,0.09};
-  double udsxierrorosyst[]={0.006,0.011,0.025,0.032,0.05 ,0.06 ,
-			    0.07 ,0.06 ,0.06 ,0.09 ,0.11 ,0.13 ,
-			    0.18 ,0.16 ,0.17 ,0.19 ,0.21 ,0.20 ,
-			    0.26 ,0.20 ,0.20 ,0.14 ,0.09 ,0.24 ,
-			    0.14 ,0.15 ,0.12 ,0.13 ,0.23 };
-  double udsxierroro[22];
-  for(unsigned int ix=0;ix<22;++ix)
-    {udsxierroro[ix]=sqrt(sqr(udsxierrorostat[ix])+sqr(udsxierrorosyst[ix]));}
-  bins =vector<double>(udsxibinso,udsxibinso+23);
-  data =vector<double>(udsxidatao,udsxidatao+22);
-  error=vector<double>(udsxierroro,udsxierroro+22);
-  _udsxip=new_ptr(Histogram(bins,data,error));
-  // lambdas
-  double Lbinso[] = {0.012, 0.014, 0.016, 0.018, 0.020, 
-		    0.025, 0.030, 0.035, 0.040, 0.050, 
-		    0.060, 0.080, 0.100, 0.120, 0.140, 
-		    0.160, 0.180, 0.200, 0.250, 0.300, 
-		    0.350, 0.400, 0.500, 0.600, 0.700, 
-		    0.900};
-  double Ldatao[]={2.97    ,3.43    ,3.74    ,3.70    ,3.69    ,3.68    ,
-		   3.70    ,3.41    ,3.18    ,2.66    ,2.04    ,1.52    ,
-		   1.19    ,0.956   ,0.771   ,0.630   ,0.528   ,0.408   ,
-		   0.269   ,0.182   ,0.129   ,0.078   ,0.035   ,0.0118  ,0.0026};
-  double Lerrorostat[]={0.35    ,0.30    ,0.29    ,0.21    ,0.18    ,0.16    ,
-			0.15    ,0.14    ,0.11    ,0.09    ,0.06    ,0.04    ,
-			0.03    ,0.023   ,0.018   ,0.015   ,0.013   ,0.010   ,
-			0.008   ,0.007   ,0.006   ,0.005   ,0.003   ,0.0019  ,0.0012};
-  double Lerrorosyst[]={0.0,0.0,0.0,0.0,0.0,0.0,
-			0.0,0.0,0.0,0.0,0.0,0.0,
-			0.0,0.0,0.0,0.0,0.0,0.0,
-			0.0,0.0,0.0,0.0,0.0,0.0,0.0};
-  double Lerroro[25];
-  for(unsigned int ix=0;ix<25;++ix) 
-    Lerroro[ix]=sqrt(sqr(Lerrorostat[ix])+sqr(Lerrorosyst[ix]));
-  bins =vector<double>(Lbinso,Lbinso+26);
-  data =vector<double>(Ldatao,Ldatao+25);
-  error=vector<double>(Lerroro,Lerroro+25);
-  _lpm=new_ptr(Histogram(bins,data,error));
-  // K*+/- CERN-PPE-96-186
-  double Kstarpmbin[]={0.03    ,0.06    ,0.09    ,0.12    ,0.15    ,
-		       0.18    ,0.22    ,0.26    ,0.32    ,0.44    ,1.00};
-  double Kstarpmdata[]={5.17   ,3.43    ,2.09    ,2.01    ,1.54   ,
-			1.16   ,0.71    ,0.59    ,0.38    ,0.06};
-  double Kstarpmstat[]={0.53    ,0.29    ,0.20    ,0.16    ,0.15    ,
-			0.12    ,0.09    ,0.06    ,0.04    ,0.01};
-  double Kstarpmsyst[]={0.54,0.58,0.22,0.23,0.19,0.22,0.07,0.07,0.03,0.01};
-  double Kstarpmerror[10];
-  for(unsigned int ix=0;ix<10;++ix) 
-    Kstarpmerror[ix] = sqrt(sqr(Kstarpmstat[ix])+sqr(Kstarpmsyst[ix]));
-  bins =vector<double>(Kstarpmbin,Kstarpmbin+11);
-  data =vector<double>(Kstarpmdata,Kstarpmdata+10);
-  error=vector<double>(Kstarpmerror,Kstarpmerror+10);
-  _xpKstarplus = new_ptr(Histogram(bins,data,error));
-  // xi- ALEXANDER 96   ZP C73,569
-  double ximbinsA[]={0.035  ,0.050  ,0.060  ,0.080  ,0.100  ,
-		     0.150  ,0.200  ,0.300  ,0.400  ,0.500};
-  double ximdataA[]={0.341   ,0.254   ,0.180   ,0.114   ,0.0737  ,
-		     0.0438  ,0.0192  ,0.0120  ,0.0084};
-  double ximstatA[]={0.018   ,0.014   ,0.007   ,0.005   ,0.0024  ,
-		     0.0021  ,0.0015  ,0.0012  ,0.0014};
-  double ximsystA[]={0.032   ,0.021   ,0.012   ,0.008   ,0.0048  ,
-		     0.0031  ,0.0014  ,0.0012  ,0.0015};
-  double ximerrorA[9];
-  for(unsigned int ix=0;ix<9;++ix) 
-    ximerrorA[ix] = sqrt(sqr(ximstatA[ix])+sqr(ximsystA[ix]));
-  bins =vector<double>(ximbinsA,ximbinsA+10);
-  data =vector<double>(ximdataA,ximdataA+9);
-  error=vector<double>(ximerrorA,ximerrorA+9);
-  _xpXiminus = new_ptr(Histogram(bins,data,error));
-  double ximbinsB[]={0.6  ,0.8  ,1.0  ,1.2  ,1.4  ,
-		     1.6  ,1.8  ,2.0  ,2.2  ,2.4  ,
-		     2.6  ,2.8  ,3.0  ,3.2  ,3.4  ,3.6};
-  double ximdataB[]={0.0026  ,0.0044  ,0.0044  ,0.0050  ,0.0071  ,
-		     0.0075  ,0.0088  ,0.0086  ,0.0094  ,0.0103  ,
-		     0.0121  ,0.0102  ,0.0100  ,0.0087  ,0.0088};
-  double ximstatB[]={0.0005  ,0.0004  ,0.0004  ,0.0005  ,0.0004  ,
-		     0.0004  ,0.0004  ,0.0004  ,0.0004  ,0.0005  ,
-		     0.0006  ,0.0006  ,0.0007  ,0.0009  ,0.0011};
-  double ximsystB[]={0.0017  ,0.0011  ,0.0005  ,0.0005  ,0.0006  ,
-		     0.0006  ,0.0007  ,0.0006  ,0.0007  ,0.0008  ,
-		     0.0009  ,0.0008  ,0.0009  ,0.0010  ,0.0013};
-  double ximerrorB[15];
-  for(unsigned int ix=0;ix<15;++ix) 
-    ximerrorB[ix] = sqrt(sqr(ximstatB[ix])+sqr(ximsystB[ix]));
-  bins =vector<double>(ximbinsB,ximbinsB+16);
-  data =vector<double>(ximdataB,ximdataB+15);
-  error=vector<double>(ximerrorB,ximerrorB+15);
-  _xiXiminus = new_ptr(Histogram(bins,data,error));
-  // sigma*+ALEXANDER 96   ZP C73,569
-  double sigmapbinsA[]={0.04  ,0.07  ,0.10  ,0.15  ,0.20  ,0.30  ,0.50};
-  double sigmapdataA[]={0.280   ,0.118   ,0.0619  ,0.0403  ,0.0248  ,0.0076};
-  double sigmapstatA[]={0.020   ,0.012   ,0.0060  ,0.0048  ,0.0027  ,0.0013};
-  double sigmapsystA[]={0.021   ,0.009   ,0.0047  ,0.0031  ,0.0019  ,0.0006};
-  double sigmaperrorA[6];
-  for(unsigned int ix=0;ix<6;++ix) 
-    sigmaperrorA[ix] = sqrt(sqr(sigmapstatA[ix])+sqr(sigmapsystA[ix]));
-  bins =vector<double>(sigmapbinsA,sigmapbinsA+7);
-  data =vector<double>(sigmapdataA,sigmapdataA+6);
-  error=vector<double>(sigmaperrorA,sigmaperrorA+6);
-  _xpSigmaplus = new_ptr(Histogram(bins,data,error));
-  double sigmapbinsB[]={0.70  ,1.21  ,1.62  ,1.92  ,2.35  ,2.76  ,3.65};
-  double sigmapdataB[]={0.0030  ,0.0060  ,0.0068  ,0.0072  ,0.0086  ,0.0095};
-  double sigmapstatB[]={0.0005  ,0.0007  ,0.0008  ,0.0007  ,0.0008  ,0.0007};
-  double sigmapsystB[]={0.0002  ,0.0005  ,0.0005  ,0.0005  ,0.0007  ,0.0007};
-  double sigmaperrorB[6];
-  for(unsigned int ix=0;ix<6;++ix) 
-    sigmaperrorB[ix] = sqrt(sqr(sigmapstatB[ix])+sqr(sigmapsystB[ix]));
-  bins =vector<double>(sigmapbinsB,sigmapbinsB+7);
-  data =vector<double>(sigmapdataB,sigmapdataB+6);
-  error=vector<double>(sigmaperrorB,sigmaperrorB+6);
-  _xiSigmaplus = new_ptr(Histogram(bins,data,error));
-  // sigma*+ ALEXANDER 96   ZP C73,569
-  double sigmambinsA[]={0.04  ,0.07  ,0.10  ,0.15  ,0.20  ,0.30  ,0.50};
-  double sigmamdataA[]={0.291   ,0.116   ,0.0646        ,0.0414  ,0.0235  ,0.0062};
-  double sigmamstatA[]={0.021   ,0.013   ,0.0071  ,0.0061  ,0.0040  ,0.0020};
-  double sigmamsystA[]={0.022 ,0.009 ,0.000       ,0.0032,0.0018,0.0005};
-  double sigmamerrorA[6];
-  for(unsigned int ix=0;ix<6;++ix) 
-    sigmamerrorA[ix] = sqrt(sqr(sigmamstatA[ix])+sqr(sigmamsystA[ix]));
-  bins =vector<double>(sigmambinsA,sigmambinsA+7);
-  data =vector<double>(sigmamdataA,sigmamdataA+6);
-  error=vector<double>(sigmamerrorA,sigmamerrorA+6);
-  _xpSigmaminus = new_ptr(Histogram(bins,data,error));
-  double sigmambinsB[]={0.70  ,1.21  ,1.62  ,1.92  ,2.35  ,2.76  ,3.65};
-  double sigmamdataB[]={0.0024  ,0.0057  ,0.0070  ,0.0075  ,0.0085  ,0.0098};
-  double sigmamstatB[]={0.0008  ,0.0010  ,0.0010  ,0.0008  ,0.0009  ,0.0007};
-  double sigmamsystB[]={0.0002,0.0004,0.0005,0.0006,0.0006,0.0007};
-  double sigmamerrorB[6];
-  for(unsigned int ix=0;ix<6;++ix) 
-    sigmamerrorB[ix] = sqrt(sqr(sigmamstatB[ix])+sqr(sigmamsystB[ix]));
-  bins =vector<double>(sigmambinsB,sigmambinsB+7);
-  data =vector<double>(sigmamdataB,sigmamdataB+6);
-  error=vector<double>(sigmamerrorB,sigmamerrorB+6);
-  _xiSigmaminus = new_ptr(Histogram(bins,data,error));
-  // xi*0 ALEXANDER 96   ZP C73,569
-  double xi0binsA[]={0.04  ,0.07  ,0.10  ,0.15  ,0.20  ,0.30};
-  double xi0dataA[]={0.064   ,0.0387  ,0.0239  ,0.0144  ,0.0049};
-  double xi0statA[]={0.014   ,0.0054  ,0.0028  ,0.0025  ,0.0015};
-  double xi0systA[]={0.009 ,0.0042,0.0024,0.0017,0.0006};
-  double xi0errorA[5];
-  for(unsigned int ix=0;ix<5;++ix) 
-    xi0errorA[ix] = sqrt(sqr(xi0statA[ix])+sqr(xi0systA[ix]));
-  bins =vector<double>(xi0binsA,xi0binsA+6);
-  data =vector<double>(xi0dataA,xi0dataA+5);
-  error=vector<double>(xi0errorA,xi0errorA+5);
-  _xpXi0 = new_ptr(Histogram(bins,data,error));
-  double xi0binsB[]={1.21  ,1.62  ,1.92  ,2.36  ,2.79  ,3.83};
-  double xi0dataB[]={0.0012  ,0.0024  ,0.0027  ,0.0027  ,0.0019};
-  double xi0statB[]={0.0004  ,0.0004  ,0.0003  ,0.0004  ,0.0004};
-  double xi0systB[]={0.0002,0.0003,0.0003,0.0003,0.0003};
-  double xi0errorB[5];
-  for(unsigned int ix=0;ix<5;++ix) 
-    xi0errorB[ix] = sqrt(sqr(xi0statB[ix])+sqr(xi0systB[ix]));
-  bins =vector<double>(xi0binsB,xi0binsB+6);
-  data =vector<double>(xi0dataB,xi0dataB+5);
-  error=vector<double>(xi0errorB,xi0errorB+5);
-  _xiXi0 = new_ptr(Histogram(bins,data,error));
-  double lambda1520binsA[]={0.035  ,0.039  ,0.045  ,0.052  ,0.060  ,0.100  ,0.300  ,0.500};
-  double lambda1520dataA[]={0.447  ,0.139  ,0.150  ,0.163  ,0.000  ,0.033  ,0.008};
-  double lambda1520statA[]={0.070    ,0.036   ,0.032   ,0.052   ,0.000   ,0.007   ,0.003};
-  double lambda1520systA[]={0.076,0.018,0.018,0.022,0.000,0.006,0.002};
-  double lambda1520errorA[7];
-  for(unsigned int ix=0;ix<7;++ix) 
-    lambda1520errorA[ix] = sqrt(sqr(lambda1520statA[ix])+sqr(lambda1520systA[ix]));
-  bins =vector<double>(lambda1520binsA,lambda1520binsA+8);
-  data =vector<double>(lambda1520dataA,lambda1520dataA+7);
-  error=vector<double>(lambda1520errorA,lambda1520errorA+7);
-  _xpLambda1520 = new_ptr(Histogram(bins,data,error));
-  double lambda1520binsB[]={0.70  ,1.21  ,2.36  ,3.00  ,3.22  ,3.50  ,3.90,4.54};
-  double lambda1520dataB[]={0.0032  ,0.0060  ,0.0000  ,0.0058  ,0.0037  ,0.0020  ,0.0026};
-  double lambda1520statB[]={0.0010  ,0.0012  ,0.0000  ,0.0018  ,0.0008  ,0.0005  ,0.0004};
-  double lambda1520systB[]={0.0007,0.0010,0.0000,0.0008,0.0005,0.0003,0.0004};
-  double lambda1520errorB[7];
-  for(unsigned int ix=0;ix<7;++ix) 
-    lambda1520errorB[ix] = sqrt(sqr(lambda1520statB[ix])+sqr(lambda1520systB[ix]));
-  bins =vector<double>(lambda1520binsB,lambda1520binsB+8);
-  data =vector<double>(lambda1520dataB,lambda1520dataB+7);
-  error=vector<double>(lambda1520errorB,lambda1520errorB+7);
-  _xiLambda1520 = new_ptr(Histogram(bins,data,error));
-  // delta++
-  double deltabins []={0.05,0.075,0.1,0.15,0.2,0.3,1.0};
-  double deltadata []={1.9,2.8,0.38,0.18,0.073 ,0.006};
-  double deltaerror[]={0.7,0.8,0.09,0.10,0.043,0.0029};
-  bins =vector<double>(deltabins,deltabins+7);
-  data =vector<double>(deltadata,deltadata+6);
-  error=vector<double>(deltaerror,deltaerror+6);
-  _xeDelta = new_ptr(Histogram(bins,data,error));
-  // f_0(980)
-  double f980bins []={0.00  ,0.06  ,0.12  ,0.14  ,0.16  ,0.20  ,0.25  ,0.35  ,0.50  ,1.00};
-  double f980data []={1.04    ,0.57    ,0.30    ,0.20    ,0.21    ,0.13    ,0.085   ,0.046   ,0.0079};
-  double f980error[]={0.09    ,0.05    ,0.06    ,0.05    ,0.03    ,0.02    ,0.011   ,0.005   ,0.0009};
-  bins =vector<double>(f980bins ,f980bins +10);
-  data =vector<double>(f980data ,f980data + 9);
-  error=vector<double>(f980error,f980error+ 9);
-  _xpf980 = new_ptr(Histogram(bins,data,error));
-  // f_2
-  double f2bins []={0.00  ,0.06  ,0.12  ,0.14  ,0.16  ,0.20  ,0.25  ,0.35  ,0.50  ,1.00  };
-  double f2data []={1.00   ,0.69   ,0.41   ,0.25   ,0.27   ,0.22   ,0.091  ,0.035  ,0.008};
-  double f2error[]={0.14   ,0.08   ,0.09   ,0.08   ,0.04   ,0.03   ,0.016  ,0.008  ,0.001};
-  bins =vector<double>(f2bins ,f2bins +10);
-  data =vector<double>(f2data ,f2data + 9);
-  error=vector<double>(f2error,f2error+ 9);
-  _xpf2 = new_ptr(Histogram(bins,data,error));
-// phi
-  double phibins []={0.00  ,0.06  ,0.12  ,0.14  ,0.16  ,0.20  ,0.25  ,0.35  ,0.50  ,1.00};
-  double phidata []={0.464  ,0.316  ,0.285  ,0.197  ,0.167  ,0.133  ,0.096  ,0.045  ,0.010};
-  double phistat []={0.011  ,0.021  ,0.020  ,0.019  ,0.017  ,0.007  ,0.004  ,0.002  ,0.001};
-  double phisyst []={0.005,0.007,0.009,0.006,0.002,0.002,0.001,0.001,0.000};
-  double phierror[9];
-  for(unsigned int ix=0;ix<9;++ix) 
-    phierror[ix] = sqrt(sqr(phistat[ix])+sqr(phisyst[ix]));
-  bins =vector<double>(phibins ,phibins +10);
-  data =vector<double>(phidata ,phidata + 9);
-  error=vector<double>(phierror,phierror+ 9);
-  _xpphi = new_ptr(Histogram(bins,data,error));
-  // K*0
-  double Kstar0bins []={0.0    ,0.01   ,0.03   ,0.1    ,0.125  ,
-			0.14   ,0.16   ,0.2    ,0.3    ,0.4    ,0.5    ,0.7    ,1.0 };
-  double Kstar0data []={1.22   ,4.96   ,4.14   ,2.35   ,1.99   ,
-			1.60   ,1.30   ,0.81   ,0.44   ,0.22   ,0.090  ,0.013  	    };
-  double Kstar0stat []={0.15   ,0.17   ,0.20   ,0.16   ,0.15   ,
-			0.11   ,0.09   ,0.04   ,0.03   ,0.02   ,0.009  ,0.004  	    };
-  double Kstar0syst []={0.04 ,0.15 ,0.19 ,0.13 ,0.09 ,
-			0.10 ,0.06 ,0.05 ,0.03 ,0.01 ,0.003,0.003};
-  double Kstar0error[12];
-  for(unsigned int ix=0;ix<12;++ix) 
-    Kstar0error[ix] = sqrt(sqr(Kstar0stat[ix])+sqr(Kstar0syst[ix]));
-  bins =vector<double>(Kstar0bins ,Kstar0bins +13);
-  data =vector<double>(Kstar0data ,Kstar0data +12);
-  error=vector<double>(Kstar0error,Kstar0error+12);
-  _xpKstar0 = new_ptr(Histogram(bins,data,error));
-  // D0
-  double D0bins []={0.15  ,0.25  ,0.35  ,0.45  ,0.55  ,0.65  ,0.75  ,0.85  ,1.00};
-  double D0data []={41.1  ,101.4  , 58.4  , 52.9  , 53.2  , 36.0  , 13.5  ,  2.0};
-  double D0error[]={11.3  ,13.8  ,10.5  , 8.1  , 8.4  , 8.0  , 3.7  , 2.0};
-  bins =vector<double>(D0bins ,D0bins + 9);
-  data =vector<double>(D0data ,D0data + 8);
-  error=vector<double>(D0error,D0error+ 8);
-  _xeD0 = new_ptr(Histogram(bins,data,error));
-  // Dstar
-  double Dstarbins []={0.10  ,0.15  ,0.20  ,0.25  ,0.30  ,
-		       0.35  ,0.40  ,0.45  ,0.50  ,0.55  ,
-		       0.60  ,0.65  ,0.70  ,0.75  ,0.80  ,
-		       0.85  ,0.90  ,0.95  ,1.00};
-  double Dstardata []={7.47  , 9.03  ,10.42  ,10.76  , 9.89  ,
-		       8.97  , 8.17  , 6.94  , 6.73  , 5.56  ,
-		       4.94  , 3.49  , 3.13  , 2.00  , 1.27  ,
-		       0.50  , 0.27  , 0.06};
-  double Dstarerror[]={0.63  ,0.49  ,0.44  ,0.43  ,0.38  ,
-		       0.35  ,0.32  ,0.28  ,0.27  ,0.24  ,
-		       0.22  ,0.18  ,0.17  ,0.14  ,0.11  ,
-		       0.07  ,0.05  ,0.03};
-  bins =vector<double>(Dstarbins ,Dstarbins +19);
-  data =vector<double>(Dstardata ,Dstardata +18);
-  error=vector<double>(Dstarerror,Dstarerror+18);
-  _xeDstar = new_ptr(Histogram(bins,data,error));
-  // rho0
-  double rho0bins []={0.05 ,0.1  ,0.2  ,0.3  ,0.4  ,0.6  ,0.8  ,1.0};
-  double rho0data []={6.15 ,2.16 ,0.92 ,0.45 ,0.13 ,0.027,0.003};
-  double rho0error[]={0.72 ,0.23 ,0.10 ,0.05 ,0.02 ,0.005,0.002};
-  bins =vector<double>(rho0bins ,rho0bins +8);
-  data =vector<double>(rho0data ,rho0data +7);
-  error=vector<double>(rho0error,rho0error+7);
-  _xerho0 = new_ptr(Histogram(bins,data,error));
-  // pi0
-  double pi0binsA[]={0.007  ,0.009  ,0.011  ,0.013  ,0.016  ,
-		     0.020  ,0.025  ,0.030  ,0.035  ,0.040  ,
-		     0.050  ,0.060  ,0.070  ,0.085  ,0.100  ,
-		     0.125  ,0.150  ,0.200  ,0.300  ,0.400  ,0.500};
-  double pi0dataA[]={254.     ,266.     ,248.     ,211.     ,178.     ,
-		     139.     ,113.     , 94.1    , 77.7    , 62.5    ,
-		     45.7    , 34.7    , 26.2    , 19.4    , 13.2    ,
-		     9.05   ,  5.36   ,  2.26   ,  0.764  ,  0.455};
-  double pi0statA[]={18.     ,12.     , 6.     , 3.     , 2.     ,
-		     2.     , 1.     , 0.9    , 0.8    , 0.4    ,
-		     0.4    , 0.3    , 0.2    , 0.2    , 0.1    ,
-		     0.13   , 0.10   , 0.13   , 0.085  , 0.095};
-  double pi0systA[]={48   ,38   ,28   ,18   ,14   ,
-		     6    ,5    ,4.0  ,4.3  ,3.9  ,
-		     3.0  ,3.0  ,1.8  ,1.4  ,2.9  ,
-		     0.76 ,0.69 ,0.38 ,0.309,0.244};
-  double pi0errorA[20];
-  for(unsigned int ix=0;ix<20;++ix) 
-    pi0errorA[ix] = sqrt(sqr(pi0statA[ix])+sqr(pi0systA[ix]));
-  bins =vector<double>(pi0binsA,pi0binsA+21);
-  data =vector<double>(pi0dataA,pi0dataA+20);
-  error=vector<double>(pi0errorA,pi0errorA+20);
-  _xepi0 = new_ptr(Histogram(bins,data,error));
-  double pi0binsB[]={0.69  ,0.92  ,1.20  ,1.61  ,1.90  ,
-		     2.08  ,2.30  ,2.47  ,2.66  ,2.81  ,
-		     3.00  ,3.22  ,3.36  ,3.51  ,3.70  ,
-		     3.92  ,4.15  ,4.37  ,4.55  ,4.77  ,5.06};
-  double pi0dataB[]={0.204  ,0.266  ,0.558  ,0.931  ,1.240  ,
-		     1.48   ,1.79   ,2.02   ,2.25   ,2.50   ,
-		     2.79   ,2.89   ,3.03   ,3.06   ,3.05   ,
-		     3.11   ,2.92   ,2.78   ,2.42   ,1.74};
-  double pi0statB[]={0.043  ,0.030  ,0.031  ,0.017  ,0.017  
-		     ,0.02   ,0.02   ,0.02   ,0.02   ,0.02   ,
-		     0.02   ,0.03   ,0.03   ,0.03   ,0.03   ,
-		     0.03   ,0.05   ,0.06   ,0.11   ,0.12};
-  double pi0systB[]={0.110 ,0.107 ,0.094 ,0.120 ,0.105 ,
-		     0.32  ,0.13  ,0.14  ,0.20  ,0.16  ,
-		     0.17  ,0.16  ,0.13  ,0.13  ,0.13  ,
-		     0.25  ,0.25  ,0.31  ,0.34  ,0.33};
-  double pi0errorB[20];
-  for(unsigned int ix=0;ix<20;++ix) 
-    pi0errorB[ix] = sqrt(sqr(pi0statB[ix])+sqr(pi0systB[ix]));
-  bins =vector<double>(pi0binsB,pi0binsB+21);
-  data =vector<double>(pi0dataB,pi0dataB+20);
-  error=vector<double>(pi0errorB,pi0errorB+20);
-  _xipi0 = new_ptr(Histogram(bins,data,error));
-  // eta
-  double etabinsA[]={0.025  ,0.035  ,0.050  ,0.075  ,0.100  ,
-		     0.125  ,0.150  ,0.200  ,0.300  ,0.400  ,0.500  ,0.600  ,0.800  ,1.000};
-  double etadataA[]={10.6   , 7.63  , 5.10  , 3.81  , 2.83  ,
-		     2.21   , 1.46  , 0.733 , 0.364 , 0.220 , 0.086   , 0.033   , 0.0013};
-  double etastatA[]={1.5    ,0.78   ,0.38   ,0.21    ,0.12  ,
-		     0.10    ,0.05    ,0.026   ,0.022   ,0.019   ,0.010   ,0.004   ,0.0004};
-  double etasystA[]={2.4   ,1.27  ,0.61  ,0.44  ,0.28  ,
-		     0.22  ,0.13  ,0.062 ,0.047 ,0.031 ,0.019 ,0.008 ,0.0011};
-  double etaerrorA[13];
-  for(unsigned int ix=0;ix<13;++ix) 
-    etaerrorA[ix] = sqrt(sqr(etastatA[ix])+sqr(etasystA[ix]));
-  bins =vector<double>(etabinsA,etabinsA+14);
-  data =vector<double>(etadataA,etadataA+13);
-  error=vector<double>(etaerrorA,etaerrorA+13);
-  _xeeta = new_ptr(Histogram(bins,data,error));
-  double etabinsB[]={0.00  ,0.22  ,0.51  ,0.69  ,0.92  ,
-		     1.20  ,1.61  ,1.90  ,2.08  ,2.31  ,2.60  ,3.03  ,3.42  ,3.82};
-  double etadataB[]={0.0012  ,0.023   ,0.047   ,0.099   ,0.126   ,
-		     0.180   ,0.252   ,0.301   ,0.314   ,0.324   ,0.302   ,0.294   ,0.261};
-  double etastatB[]={0.0004  ,0.003   ,0.006   ,0.008   ,0.008   ,
-		     0.006   ,0.009   ,0.014   ,0.014   ,0.018   ,0.023   ,0.030   ,0.038};
-  double etasystB[]={0.0009 ,0.005  ,0.009  ,0.011  ,0.014  ,
-		     0.014  ,0.021  ,0.027  ,0.028  ,0.032  ,0.028  ,0.038  ,0.046};
-  double etaerrorB[13];
-  for(unsigned int ix=0;ix<13;++ix) 
-    etaerrorB[ix] = sqrt(sqr(etastatB[ix])+sqr(etasystB[ix]));
-  bins =vector<double>(etabinsB,etabinsB+14);
-  data =vector<double>(etadataB,etadataB+13);
-  error=vector<double>(etaerrorB,etaerrorB+13);
-  _xieta = new_ptr(Histogram(bins,data,error));
-  // rho+  
-  double rhopbinsA[]={0.016  ,0.025  ,0.035  ,0.050  ,0.075  ,
-		      0.100  ,0.125  ,0.150  ,0.200  ,0.300  ,0.400  ,0.600  ,0.800, 1.000};
-  double rhopdataA[]={17.3    ,32.3    ,21.3    ,16.7    , 9.89   ,
-		      7.11   , 5.90   , 3.60   , 2.02   , 1.03   , 0.430  , 0.075  , 0.013};
-  double rhopstatA[]={8.1    ,2.5    ,0.7    ,0.4    ,0.40   ,
-		      0.25   ,0.25   ,0.12   ,0.07   ,0.04   ,0.023  ,0.013  ,0.003};
-  double rhopsystA[]={12.2 ,9.7  ,4.5  ,1.8  ,1.46 ,1.04 ,0.78 ,0.48 ,0.21 ,0.27 ,0.081,0.032,0.009};
-  double rhoperrorA[13];
-  for(unsigned int ix=0;ix<13;++ix) 
-    rhoperrorA[ix] = sqrt(sqr(rhopstatA[ix])+sqr(rhopsystA[ix]));
-  bins =vector<double>(rhopbinsA,rhopbinsA+14);
-  data =vector<double>(rhopdataA,rhopdataA+13);
-  error=vector<double>(rhoperrorA,rhoperrorA+13);
-  _xerhop = new_ptr(Histogram(bins,data,error));
-  double rhopbinsB[]={0.0  ,0.5  ,1.0  ,1.5  ,2.0  ,2.5  ,3.0  ,3.5  ,4.0  ,4.5  ,5.0};
-  double rhopdataB[]={0.034  ,0.217  ,0.419  ,0.603  ,0.805  ,0.868  ,0.692  ,0.500  ,0.419  ,0.171};
-  double rhopstatB[]={0.004  ,0.010  ,0.014  ,0.017  ,0.022  ,0.021  ,0.028  ,0.092  ,0.035  ,0.008};
-  double rhopsystB[]={0.019,0.055,0.073,0.078,0.104,0.126,0.165,0.138,0.111,0.081};
-  double rhoperrorB[10];
-  for(unsigned int ix=0;ix<10;++ix) 
-    rhoperrorB[ix] = sqrt(sqr(rhopstatB[ix])+sqr(rhopsystB[ix]));
-  bins =vector<double>(rhopbinsB,rhopbinsB+11);
-  data =vector<double>(rhopdataB,rhopdataB+10);
-  error=vector<double>(rhoperrorB,rhoperrorB+10);
-  _xirhop = new_ptr(Histogram(bins,data,error));
-  // omega
-  double omegabinsA[]={0.025  ,0.035  ,0.050  ,0.075  ,0.100  ,0.125  ,0.150  ,0.200  ,0.300  ,0.400  ,0.600};
-  double omegadataA[]={15.2    , 9.88   , 5.82   , 4.12   , 2.74   , 2.23   , 1.45   , 0.789  , 0.335  , 0.130};
-  double omegastatA[]={2.4    ,0.84   ,0.35   ,0.25   ,0.16   ,0.14   ,0.09   ,0.049  ,0.037  ,0.027};
-  double omegasystA[]={2.1  ,1.48 ,0.75 ,0.54 ,0.32 ,0.24 ,0.17 ,0.099,0.042,0.028};
-  double omegaerrorA[10];
-  for(unsigned int ix=0;ix<10;++ix) 
-    omegaerrorA[ix] = sqrt(sqr(omegastatA[ix])+sqr(omegasystA[ix]));
-  bins =vector<double>(omegabinsA,omegabinsA+11);
-  data =vector<double>(omegadataA,omegadataA+10);
-  error=vector<double>(omegaerrorA,omegaerrorA+10);
-  _xeomega = new_ptr(Histogram(bins,data,error));
-  double omegabinsB[]={0.51  ,0.92  ,1.21  ,1.61  ,1.90  ,2.09  ,2.32  ,2.62  ,3.06  ,3.49  ,4.01};
-  double omegadataB[]={0.064  ,0.116  ,0.193  ,0.250  ,0.301  ,0.299  ,0.344  ,0.330  ,0.344  ,0.293};
-  double omegastatB[]={0.013  ,0.013  ,0.012  ,0.016  ,0.018  ,0.018  ,0.021  ,0.020  ,0.029  ,0.046};
-  double omegasystB[]={0.014,0.014,0.024,0.029,0.032,0.035,0.045,0.043,0.051,0.040};
-  double omegaerrorB[10];
-  for(unsigned int ix=0;ix<10;++ix) 
-    omegaerrorB[ix] = sqrt(sqr(omegastatB[ix])+sqr(omegasystB[ix]));
-  bins =vector<double>(omegabinsB,omegabinsB  +11);
-  data =vector<double>(omegadataB,omegadataB  +10);
-  error=vector<double>(omegaerrorB,omegaerrorB+10);
-  _xiomega = new_ptr(Histogram(bins,data,error));
-  // eta'
-  double etapbinsA[]={0.050  ,0.070  ,0.100  ,0.125  ,0.150  ,0.200  ,0.300  ,0.400  ,0.600  ,0.800};
-  double etapdataA[]={1.01   ,0.462  ,0.460  ,0.293  ,0.354  ,0.137  ,0.088  ,0.034  ,0.013};
-  double etapstatA[]={0.38   ,0.180  ,0.144  ,0.099  ,0.068  ,0.028  ,0.020  ,0.010  ,0.006};
-  double etapsystA[]={0.14 ,0.073,0.082,0.049,0.054,0.017,0.011,0.006,0.003};
-  double etaperrorA[9];
-  for(unsigned int ix=0;ix<9;++ix) 
-    etaperrorA[ix] = sqrt(sqr(etapstatA[ix])+sqr(etapsystA[ix]));
-  bins =vector<double>(etapbinsA,etapbinsA+10);
-  data =vector<double>(etapdataA,etapdataA+9);
-  error=vector<double>(etaperrorA,etaperrorA+9);
-  _xeetap = new_ptr(Histogram(bins,data,error));
-  double etapbinsB[]={0.22  ,0.51  ,0.92  ,1.21  ,1.61  ,1.91  ,2.09  ,2.33  ,2.71  ,3.09};
-  double etapdataB[]={0.009  ,0.017  ,0.030  ,0.034  ,0.061  ,0.039  ,0.050  ,0.036  ,0.052};
-  double etapstatB[]={0.004  ,0.005  ,0.007  ,0.007  ,0.012  ,0.013  ,0.016  ,0.014  ,0.020};
-  double etapsystB[]={0.002,0.003,0.004,0.004,0.009,0.007,0.009,0.006,0.007};
-  double etaperrorB[9];
-  for(unsigned int ix=0;ix<9;++ix) 
-    etaperrorB[ix] = sqrt(sqr(etapstatB[ix])+sqr(etapsystB[ix]));
-  bins =vector<double>(etapbinsB,etapbinsB+10);
-  data =vector<double>(etapdataB,etapdataB+9);
-  error=vector<double>(etaperrorB,etaperrorB+9);
-  _xietap = new_ptr(Histogram(bins,data,error));
-  // a_0+
-  double a0binsA[]={0.050  ,0.070  ,0.100  ,0.125  ,0.150  ,0.200  ,0.300  ,0.400  ,0.600  ,0.800  ,1.000};
-  double a0dataA[]={1.65    ,1.05    ,0.747   ,0.985   ,0.623   ,0.207   ,0.093   ,0.038   ,0.014   ,0.0040};
-  double a0statA[]={1.03    ,0.49    ,0.215   ,0.238   ,0.107   ,0.046   ,0.027   ,0.015   ,0.005   ,0.0018};
-  double a0systA[]={0.75  ,0.73  ,0.214 ,0.560 ,0.171 ,0.069 ,0.040 ,0.015 ,0.006 ,0.0024};
-  double a0errorA[10];
-  for(unsigned int ix=0;ix<10;++ix) 
-    a0errorA[ix] = sqrt(sqr(a0statA[ix])+sqr(a0systA[ix]));
-  bins =vector<double>(a0binsA,a0binsA+11);
-  data =vector<double>(a0dataA,a0dataA+10);
-  error=vector<double>(a0errorA,a0errorA+10);
-  _xea_0p = new_ptr(Histogram(bins,data,error));
-  double a0binsB[]={0.00  ,0.50  ,1.00  ,1.50  ,2.00  ,2.50  ,3.00  ,3.50};
-  double a0dataB[]={0.0071  ,0.019   ,0.040   ,0.088   ,0.076   ,0.104   ,0.093};
-  double a0statB[]={0.0025  ,0.006   ,0.009   ,0.013   ,0.019   ,0.041   ,0.063};
-  double a0systB[]={0.0022,0.007 ,0.012 ,0.023 ,0.030 ,0.041 ,0.050};
-  double a0errorB[7];
-  for(unsigned int ix=0;ix<7;++ix) 
-    a0errorB[ix] = sqrt(sqr(a0statB[ix])+sqr(a0systB[ix]));
-  bins =vector<double>(a0binsB,a0binsB+8);
-  data =vector<double>(a0dataB,a0dataB+7);
-  error=vector<double>(a0errorB,a0errorB+7);
-  _xia_0p = new_ptr(Histogram(bins,data,error));
-  // K_0
-  double K0bins []={0.0114  ,0.020   ,0.030   ,0.040   ,0.050   ,
-		    0.060   ,0.070   ,0.080   ,0.090   ,0.100   ,
-		    0.125   ,0.150   ,0.200   ,0.250   ,0.300   ,
-		    0.350   ,0.400   ,0.450   ,0.500   ,0.600  ,0.800};
-  double K0data []={25.731  ,24.617  ,19.349  ,15.500  ,13.170  ,
-		    11.144  , 9.360  , 8.470  , 7.010  , 5.734  ,
-		    4.488  , 3.100  , 1.945  , 1.266  , 0.860  ,
-		    0.579  , 0.394  , 0.253  , 0.163  , 0.051};
-  double K0stat []={0.232  ,0.120  ,0.116  ,0.061  ,0.072  ,
-		    0.073  ,0.066  ,0.061  ,0.059  ,0.029  ,
-		    0.028  ,0.019  ,0.015  ,0.010  ,0.010  ,
-		    0.009  ,0.008  ,0.005  ,0.003  ,0.001};
-  double K0syst []={1.430,1.300,1.040,0.767,0.690,
-		    0.600,0.500,0.468,0.401,0.312,
-		    0.247,0.169,0.104,0.071,0.050,
-		    0.035,0.026,0.018,0.018,0.010};
-  double K0error[20];
-  for(unsigned int ix=0;ix<20;++ix) 
-    K0error[ix] = sqrt(sqr(K0stat[ix])+sqr(K0syst[ix]));
-  bins =vector<double>(K0bins ,K0bins +21);
-  data =vector<double>(K0data ,K0data +20);
-  error=vector<double>(K0error,K0error+20);
-  _xpK0 = new_ptr(Histogram(bins,data,error));
-}
-
-      
-  
-
-  
-
-   
-
-
-//   // a_0+
-//   double a0binsA[]={};
-//   double a0dataA[]={};
-//   double a0statA[]={};
-//   double a0systA[]={};
-//   double a0errorA[7];
-//   for(unsigned int ix=0;ix<10;++ix) 
-//     a0errorA[ix] = sqrt(sqr(a0statA[ix])+sqr(a0systA[ix]));
-//   bins =vector<double>(a0binsA,a0binsA+11);
-//   data =vector<double>(a0dataA,a0dataA+10);
-//   error=vector<double>(a0errorA,a0errorA+10);
-//   _xea_0p = new_ptr(Histogram(bins,data,error));
-//   double a0binsB[]={};
-//   double a0dataB[]={};
-//   double a0statB[]={};
-//   double a0systB[]={};
-//   double a0errorB[7];
-//   for(unsigned int ix=0;ix<7;++ix) 
-//     a0errorB[ix] = sqrt(sqr(a0statB[ix])+sqr(a0systB[ix]));
-//   bins =vector<double>(a0binsB,a0binsB+8);
-//   data =vector<double>(a0dataB,a0dataB+7);
-//   error=vector<double>(a0errorB,a0errorB+7);
-//   _xia_0p = new_ptr(Histogram(bins,data,error));
-
diff --git a/Analysis/IdentifiedParticleAnalysis.h b/Analysis/IdentifiedParticleAnalysis.h
deleted file mode 100644
--- a/Analysis/IdentifiedParticleAnalysis.h
+++ /dev/null
@@ -1,439 +0,0 @@
-// -*- C++ -*-
-//
-// IdentifiedParticleAnalysis.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_IdentifiedParticleAnalysis_H
-#define HERWIG_IdentifiedParticleAnalysis_H
-//
-// This is the declaration of the IdentifiedParticleAnalysis class.
-//
-
-#include "ThePEG/Repository/CurrentGenerator.h"
-#include "ThePEG/Handlers/AnalysisHandler.h"
-#include "ThePEG/Repository/EventGenerator.h"
-#include "Herwig/Utilities/Histogram.h"
-#include "ThePEG/Vectors/Lorentz5Vector.h"
-
-namespace Herwig {
-
-using namespace ThePEG;
-
-/** \ingroup Analysis
- * The IdentifiedParticleAnalysis class produces various identified particle spectra
- * compared to LEP data.
- *
- * @see \ref IdentifiedParticleAnalysisInterfaces "The interfaces"
- * defined for IdentifiedParticleAnalysis.
- */
-class IdentifiedParticleAnalysis: public AnalysisHandler {
-
-public:
-
-  /** @name Virtual functions required by the AnalysisHandler class. */
-  //@{
-  /**
-   * Analyze a given Event. Note that a fully generated event
-   * may be presented several times, if it has been manipulated in
-   * between. The default version of this function will call transform
-   * to make a lorentz transformation of the whole event, then extract
-   * all final state particles and call analyze(tPVector) of this
-   * analysis object and those of all associated analysis objects. The
-   * default version will not, however, do anything on events which
-   * have not been fully generated, or have been manipulated in any
-   * way.
-   * @param event pointer to the Event to be analyzed.
-   * @param ieve the event number.
-   * @param loop the number of times this event has been presented.
-   * If negative the event is now fully generated.
-   * @param state a number different from zero if the event has been
-   * manipulated in some way since it was last presented.
-   */
-  virtual void analyze(tEventPtr event, long ieve, int loop, int state);
-
-public:
-
-  /**
-   * 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:
-
-  /**
-   *  Work out the flavour of the quarks produced
-   */
-  int getFlavour(const tPVector &);
-
-  double getX(const Lorentz5Momentum & p, const Energy & Ebeam) {
-    return Ebeam > ZERO ? double(p.vect().mag()/Ebeam) : -1.;
-  }
-
-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. Called in the run phase just before
-   * a run begins.
-   */
-  virtual void doinitrun();
-
-  /**
-   * Finalize this object. Called in the run phase just after a
-   * run has ended. Used eg. to write out statistics.
-   */
-  virtual void dofinish();
-  //@}
-
-private:
-
-  /**
-   * The static object used to initialize the description of this class.
-   * Indicates that this is a concrete class with persistent data.
-   */
-  static NoPIOClassDescription<IdentifiedParticleAnalysis>
-  initIdentifiedParticleAnalysis;
-
-  /**
-   * The assignment operator is private and must never be called.
-   * In fact, it should not even be implemented.
-   */
-  IdentifiedParticleAnalysis & operator=(const IdentifiedParticleAnalysis &);
-
-private:
-
-  /**
-   *  Single particle spectra
-   */
-  //@{
-  /**
-   * Histogram for the \f$\xi\f$ distribution for all particles from all quarks
-   */
-  HistogramPtr _xpa;
-
-  /**
-   * Histogram for the \f$\xi\f$ distribution for all particles from light quarks
-   */
-  HistogramPtr _xpl;
-
-  /**
-   * Histogram for the \f$\xi\f$ distribution for all particles from charm quarks
-   */
-  HistogramPtr _xpc;
-
-  /**
-   * Histogram for the \f$\xi\f$ distribution for all particles from bottom quarks
-   */
-  HistogramPtr _xpb;
-
-  /**
-   * Histogram for the \f$\xi\f$ distribution for charged pions from all quarks
-   */
-  HistogramPtr _pipma;
-
-  /**
-   * Histogram for the \f$\xi\f$ distribution for charged pions from light quarks
-   */
-  HistogramPtr _pipml;
-
-  /**
-   * Histogram for the \f$\xi\f$ distribution for charged pions from charm quarks
-   */
-  HistogramPtr _pipmc;
-
-  /**
-   * Histogram for the \f$\xi\f$ distribution for charged pions from bottom quarks
-   */
-  HistogramPtr _pipmb;
-
-  /**
-   * Histogram for the \f$\xi\f$ distribution for charged pions from OPAL
-   */
-  HistogramPtr _pipm;
-
-  /**
-   * Histogram for the \f$\xi\f$ distribution for charged kaons from all quarks
-   */
-  HistogramPtr _kpma;
-
-  /**
-   * Histogram for the \f$\xi\f$ distribution for charged kaons from light quarks
-   */
-  HistogramPtr _kpml;
-
-  /**
-   * Histogram for the \f$\xi\f$ distribution for charged kaons from charm quarks
-   */
-  HistogramPtr _kpmc;
-
-  /**
-   * Histogram for the \f$\xi\f$ distribution for charged kaons from bottom quarks
-   */
-  HistogramPtr _kpmb;
-
-  /**
-   * Histogram for the \f$\xi\f$ distribution for charged kaons from OPAL
-   */
-  HistogramPtr _kpm;
-
-
-  /**
-   * Histogram for the \f$\xi\f$ distribution for protons from all quarks
-   */
-  HistogramPtr _ppma;
-
-  /**
-   * Histogram for the \f$\xi\f$ distribution for protons from light quarks
-   */
-  HistogramPtr _ppml;
-
-  /**
-   * Histogram for the \f$\xi\f$ distribution for protons from charm quarks
-   */
-  HistogramPtr _ppmc;
-
-  /**
-   * Histogram for the \f$\xi\f$ distribution for protons from bottom quarks
-   */
-  HistogramPtr _ppmb;
-
-  /**
-   * Histogram for the \f$\xi\f$ distribution for protons from OPAL
-   */
-  HistogramPtr _ppm;
-
-  /**
-   * Histogram for the \f$x\f$ distribution for light quark events (lin)
-   */ 
-  HistogramPtr _udsxp;
-
-  /**
-   * Histogram for the \f$\xi\f$ distribution for light quark events (lin)
-   */ 
-  HistogramPtr _udsxip;
-
-  /**
-   *  Histogram for the \f$\xi\f$ distribution for \f$\Lambda\f$ 
-   */
-  HistogramPtr _lpm;
-
-  /**
-   *  Histogram for the ALEPH \f$K^{*\pm}\f$ \f$x\f$distribution
-   */
-  HistogramPtr _xpKstarplus;
-
-  /**
-   *  Histogram for the OPAL \f$\Xi^-\f$ \f$x\f$ distribution
-   */
-  HistogramPtr _xpXiminus;
-
-  /**
-   *  Histogram for the OPAL \f$\Xi^-\f$ \f$\xi\f$ distribution
-   */
-  HistogramPtr _xiXiminus;
-
-  /**
-   *  Histogram for the OPAL \f$\Sigma^{*+}\f$ \f$x\f$ distribution
-   */
-  HistogramPtr _xpSigmaplus;
-
-  /**
-   *  Histogram for the OPAL \f$\Sigma^{*+}\f$ \f$\xi\f$ distribution
-   */
-  HistogramPtr _xiSigmaplus;
-
-  /**
-   *  Histogram for the OPAL \f$\Sigma^{*-}\f$ \f$x\f$ distribution
-   */
-  HistogramPtr _xpSigmaminus;
-
-  /**
-   *  Histogram for the OPAL \f$\Sigma^{*-}\f$ \f$\xi\f$ distribution
-   */
-  HistogramPtr _xiSigmaminus;
-
-  /**
-   *  Histogram for the OPAL \f$\Xi^{*0}\f$ \f$x\f$ distribution
-   */
-  HistogramPtr _xpXi0;
-
-  /**
-   *  Histogram for the OPAL \f$\Xi^{*0}\f$ \f$\xi\f$ distribution
-   */
-  HistogramPtr _xiXi0;
-
-  /**
-   *  Histogram for \f$\Lambda(1520)\f$ \f$x\f$ distribution
-   */
-  HistogramPtr _xpLambda1520;
-
-  /**
-   *  Histogram for \f$\Lambda(1520)\f$ \f$\xi\f$ distribution
-   */
-  HistogramPtr _xiLambda1520;
-
-  /**
-   *  Histogram for \f$\Delta^{++}\f$ \f$x\f$ distribution
-   */
-  HistogramPtr _xeDelta;
-
-  /**
-   *  Histogram for \f$f_0(980)\f$ \f$x\f$ distribution
-   */
-  HistogramPtr _xpf980;
-
-  /**
-   *  Histogram for \f$\phi\f$ \f$x\f$ distribution
-   */
-  HistogramPtr _xpphi;
-
-  /**
-   *  Histogram for \f$f_2\f$ \f$x\f$ distribution
-   */
-  HistogramPtr _xpf2;
-
-  /**
-   *  Histogram for \f$K^{*0}\f$ \f$x\f$ distribution
-   */
-  HistogramPtr _xpKstar0;  
-
-  /**
-   *  Histogram for \f$K^0\f$ \f$x\f$ distribution
-   */
-  HistogramPtr _xpK0; 
-
-  /**
-   *  Histogram for \f$\rho^0\f$ \f$x\f$ distribution
-   */
-  HistogramPtr _xerho0;
-
-  /**
-   *  Histogram for the OPAL \f$\pi^0\f$ \f$x\f$ distribution
-   */
-  HistogramPtr _xepi0;
-
-  /**
-   *  Histogram for the OPAL \f$\pi^0\f$ \f$\xi\f$ distribution
-   */
-  HistogramPtr _xipi0;
-
-  /**
-   *  Histogram for the OPAL \f$\eta\f$ \f$x\f$ distribution
-   */
-  HistogramPtr _xeeta;
-
-  /**
-   *  Histogram for the OPAL \f$\eta'\f$ \f$\xi\f$ distribution
-   */
-  HistogramPtr _xieta;
-
-  /**
-   *  Histogram for the OPAL \f$\eta\f$ \f$x\f$ distribution
-   */
-  HistogramPtr _xeetap;
-
-  /**
-   *  Histogram for the OPAL \f$\eta'\f$ \f$\xi\f$ distribution
-   */
-  HistogramPtr _xietap;
-
-  /**
-   *  Histogram for the OPAL \f$\omega\f$ \f$x\f$ distribution
-   */
-  HistogramPtr _xeomega;
-
-  /**
-   *  Histogram for the OPAL \f$\omega'\f$ \f$\xi\f$ distribution
-   */
-  HistogramPtr _xiomega;
-
-  /**
-   *  Histogram for the OPAL \f$\rho^+\f$ \f$x\f$ distribution
-   */
-  HistogramPtr _xerhop;
-
-  /**
-   *  Histogram for the OPAL \f$\rho^+\f$ \f$\xi\f$ distribution
-   */
-  HistogramPtr _xirhop;
-
-  /**
-   *  Histogram for the OPAL \f$a_0^+\f$ \f$x\f$ distribution
-   */
-  HistogramPtr _xea_0p;
-
-  /**
-   *  Histogram for the OPAL \f$a_0^+\f$ \f$\xi\f$ distribution
-   */
-  HistogramPtr _xia_0p;
-
-  /**
-   *  Histogram for \f$D^0\f$ \f$x\f$ distribution
-   */
-  HistogramPtr _xeD0; 
-
-  /**
-   *  Histogram for \f$D^{*+}\f$ \f$x\f$ distribution
-   */
-  HistogramPtr _xeDstar;
-
-};
-
-}
-
-#include "ThePEG/Utilities/ClassTraits.h"
-
-namespace ThePEG {
-
-/** @cond TRAITSPECIALIZATIONS */
-
-/** This template specialization informs ThePEG about the
- *  base classes of IdentifiedParticleAnalysis. */
-template <>
-struct BaseClassTrait<Herwig::IdentifiedParticleAnalysis,1> {
-  /** Typedef of the first base class of IdentifiedParticleAnalysis. */
-  typedef AnalysisHandler NthBase;
-};
-
-/** This template specialization informs ThePEG about the name of
- *  the IdentifiedParticleAnalysis class and the shared object where it is defined. */
-template <>
-struct ClassTraits<Herwig::IdentifiedParticleAnalysis>
-  : public ClassTraitsBase<Herwig::IdentifiedParticleAnalysis> {
-  /** Return a platform-independent class name */
-  static string className() { return "Herwig::IdentifiedParticleAnalysis"; }
-  /** Return the name(s) of the shared library (or libraries) be loaded to get
-   *  access to the IdentifiedParticleAnalysis class and any other class on which it depends
-   *  (except the base class). */
-  static string library() { return "HwAnalysis.so HwLEPAnalysis.so"; }
-};
-
-/** @endcond */
-
-}
-
-#endif /* HERWIG_IdentifiedParticleAnalysis_H */
diff --git a/Analysis/LEPFourJetsAnalysis.cc b/Analysis/LEPFourJetsAnalysis.cc
deleted file mode 100644
--- a/Analysis/LEPFourJetsAnalysis.cc
+++ /dev/null
@@ -1,307 +0,0 @@
-// -*- C++ -*-
-//
-// LEPFourJetsAnalysis.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 LepFourJetsAnalysis class.
-//
-
-#include "LEPFourJetsAnalysis.h"
-#include "ThePEG/EventRecord/Event.h"
-#include "ThePEG/EventRecord/StandardSelectors.h"
-#include "ThePEG/Interface/ClassDocumentation.h"
-#include "ThePEG/Interface/Switch.h"
-#include "ThePEG/Persistency/PersistentOStream.h"
-#include "ThePEG/Persistency/PersistentIStream.h"
-#include "fastjet/PseudoJet.hh"
-#include "fastjet/ClusterSequence.hh"
-#include "ThePEG/Persistency/PersistentOStream.h"
-#include "ThePEG/Persistency/PersistentIStream.h"
-
-using namespace Herwig;
-
-namespace {
-
-  struct ChargedFinalState {
-    static bool AllCollisions() { return false; }
-    static bool AllSteps() { return false; }
-    // ===
-    // pick the last instance from the shower
-    static bool FinalState() { return true; }
-    static bool Intermediate() { return false; }
-    // ===
-    static bool Check(const Particle & p) { 
-      return ParticleTraits<Particle>::iCharge(p);
-    }
-  };
-  
-}
-
-void LEPFourJetsAnalysis::persistentOutput(PersistentOStream & os) const {
-  os << _charged;
-}
-
-void LEPFourJetsAnalysis::persistentInput(PersistentIStream & is, int) {
-  is >> _charged;
-}
-
-void LEPFourJetsAnalysis::analyze(tEventPtr event, long, int, int ) {
-  tPVector particles;
-
-  if (_charged) {
-    event->select(back_inserter(particles),
-		  ThePEG::ParticleSelector<ChargedFinalState>());
-  } else {
-    event->select(back_inserter(particles),SelectFinalState());
-  }
-
-
-  //  copy fastjet particles from event record.  Templated fastjet
-  //  method might leave units ambigouos.  Loop with integer index
-  //  allows backtracing ThePEG particles if needed.
-  vector<fastjet::PseudoJet> fastjet_particles;
-
-  for (unsigned int j=0; j<particles.size(); j++) {
-    fastjet::PseudoJet p(particles[j]->momentum().x()/GeV, 
-			 particles[j]->momentum().y()/GeV, 
-			 particles[j]->momentum().z()/GeV, 
-			 particles[j]->momentum().e()/GeV);
-    p.set_user_index(j);
-    fastjet_particles.push_back(p);
-  }
-  
-  fastjet::RecombinationScheme recomb_scheme = fastjet::E_scheme;
-  fastjet::Strategy strategy = fastjet::Best;
-  fastjet::JetDefinition jet_def(fastjet::ee_kt_algorithm, 
-				 recomb_scheme, strategy);
-  fastjet::ClusterSequence cs(fastjet_particles, jet_def);
-
-  vector<fastjet::PseudoJet> fastjets = cs.exclusive_jets_ycut(0.008);
-  vector<fastjet::PseudoJet> sorted = fastjet::sorted_by_E(fastjets); 
-  vector<Lorentz5Momentum> jets;
-
-  if (sorted.size() == 4) {
-    for (int j=0; j<4; ++j) {
-      if ((cs.constituents(sorted[j])).size() == 1) {
-	throw Exception() << "LEPFourJetsAnalysis: Trying to extract jet " 
-			  << "momenta from a single particle." 
-			  << Exception::warning;
-      }
-      LorentzMomentum newjet(sorted[j].px()*GeV, sorted[j].py()*GeV, 
-			     sorted[j].pz()*GeV, sorted[j].e()*GeV);
-      jets.push_back(newjet);
-    }
-    *_cchiBZ += abs(cosChiBZ(jets));
-    *_cphiKSW += cosPhiKSW(jets);
-    *_cthNR += abs(cosThetaNR(jets));
-    *_ca34 += cosAlpha34(jets);
-  }
-}
-
-ClassDescription<LEPFourJetsAnalysis> 
-LEPFourJetsAnalysis::initLEPFourJetsAnalysis;
-// Definition of the static class description member.
-
-void LEPFourJetsAnalysis::Init() {
-
-  static ClassDocumentation<LEPFourJetsAnalysis> documentation
-    ("The LEP FourJets Analysis class",
-     "The LEP FourJets analysis uses data from \\cite{Heister:2002tq}.",
-     "%\\cite{Heister:2002tq}\n"
-     "\\bibitem{Heister:2002tq}\n"
-     "  A.~Heister {\\it et al.}  [ALEPH Collaboration],\n"
-     "   ``Measurements of the strong coupling constant and the QCD colour factors\n"
-     "  %using four-jet observables from hadronic Z decays,''\n"
-     "  Eur.\\ Phys.\\ J.\\  C {\\bf 27}, 1 (2003).\n"
-     "  %%CITATION = EPHJA,C27,1;%%\n"
-     );
-
-  static Switch<LEPFourJetsAnalysis,bool> interfaceChargedParticles
-    ("ChargedParticles",
-     "Wether or not to use charged particles only for this analysis",
-     &LEPFourJetsAnalysis::_charged, true, false, false);
-  static SwitchOption interfaceChargedParticlesYes
-    (interfaceChargedParticles,
-     "Yes",
-     "Use charged particles only",
-     true);
-  static SwitchOption interfaceChargedParticlesNo
-    (interfaceChargedParticles,
-     "No",
-     "Use all final state particles",
-     false);
-
-}
-
-void LEPFourJetsAnalysis::dofinish() {
-  useMe();
-  AnalysisHandler::dofinish();
-  string fname = generator()->filename() + string("-") 
-    + name() + string(".top");
-  ofstream output(fname.c_str());
-  _ca34->normaliseToData();
-  _cchiBZ->normaliseToData();
-  _cphiKSW->normaliseToData();
-  _cthNR->normaliseToData();
-  // chisq
-  double chisq,minfrac=0.05;
-  unsigned int npoint;
-  generator()->log() << "Output from LEPFourJetsAnalysis \n";
-  _ca34->chiSquared(chisq,npoint,minfrac);
-  generator()->log() << "Chi Square = " << chisq << " for " << npoint 
-		     << " degrees of freedom for alpha_34 four jet distribution or " 
-		     << chisq/npoint << " per degree of freedom \n";  
-  _cchiBZ->chiSquared(chisq,npoint,minfrac);
-  generator()->log() << "Chi Square = " << chisq << " for " << npoint 
-		     << " degrees of freedom for BZ four jet distribution or " 
-		     << chisq/npoint << " per degree of freedom \n";  
-  _cphiKSW->chiSquared(chisq,npoint,minfrac);
-  generator()->log() << "Chi Square = " << chisq << " for " << npoint 
-		     << " degrees of freedom for KSW four jet distribution or " 
-		     << chisq/npoint << " per degree of freedom \n";  
-  _cthNR->chiSquared(chisq,npoint,minfrac);
-  generator()->log() << "Chi Square = " << chisq << " for " << npoint 
-		     << " degrees of freedom for NR four jet distribution or " 
-		     << chisq/npoint << " per degree of freedom \n";  
-  using namespace HistogramOptions;
-  // output the plots
-  _ca34->topdrawOutput(output,Frame|Errorbars|Ylog,
-		       "RED",
-		       "cosA0341 to DELPHI data",
-		       "   GX  X               ",
-		       "1/NdN/dcosA0341",
-		       "          GX  X",
-		       "cosA0341",
-		       "   GX  X");
-  _cchiBZ->topdrawOutput(output,Frame|Errorbars|Ylog,
-			 "RED",
-			 "cos|C0BZ1| to DELPHI data",
-			 "    GX  X                ",
-			 "1/NdN/dcos|C0BZ1|",
-			 "           GX  X ",
-			 "|cosC0BZ1|",
-			 "    GX  X ");
-  _cphiKSW->topdrawOutput(output,Frame|Errorbars|Ylog,
-			 "RED",
-			 "cosF0KSW1 to DELPHI data",
-			 "   FX   X               ",
-			 "1/NdN/dcosF0KSW1",
-			 "          FX   X",
-			 " cosF0KSW1",
-			 "    FX   X");
-  _cthNR->topdrawOutput(output,Frame|Errorbars|Ylog,
-			 "RED",
-			 "|cosQ0NR1| to DELPHI data",
-			 "    GX  X                ",
-			 "1/NdN/d|cosQ0NR1|",
-			 "           GX  X ",
-			 "|cosQ0NR1|",
-			 "    GX  X ");
-}
-
-void LEPFourJetsAnalysis::doinitrun() {
-  AnalysisHandler::doinitrun();
-  // 4 jet angles 
-  double ca34bins[] = {-1.0, -0.9, -0.8, -0.7, -0.6, 
-		       -0.5, -0.4, -0.3, -0.2, -0.1, 
-		       0.0, 0.1, 0.2, 0.3, 0.4, 
-		       0.5, 0.6, 0.7, 0.8, 0.9, 
-		       1.0};
-  double ca34data[]={0.05279   ,0.04785   ,0.04541   ,0.04407   ,0.04461   ,
-		     0.04225   ,0.04163   ,0.04166   ,0.04106   ,0.04180   ,
-		     0.04171   ,0.04197   ,0.04193   ,0.04280   ,0.04245   ,
-		     0.04412   ,0.03966   ,0.03199   ,0.01450   ,0.000417};
-  double ca34errorstat[]={0.00079   ,0.00075   ,0.00073   ,0.00073   ,0.00074   ,
-			  0.00072   ,0.00071   ,0.00071   ,0.00071   ,0.00072   ,
-			  0.00071   ,0.00071   ,0.00071   ,0.00072   ,0.00071   ,
-			  0.00074   ,0.00068   ,0.00058   ,0.00036   ,0.000062};
-  double ca34errorsyst[]={0.00267 ,0.00236 ,0.00229 ,0.00227 ,0.00237 ,
-			  0.00224 ,0.00214 ,0.00225 ,0.00215 ,0.00221 ,
-			  0.00213 ,0.00212 ,0.00208 ,0.00207 ,0.00196 ,
-			  0.00207 ,0.00163 ,0.00113 ,0.00033 ,0.000022};
-  double ca34error[20];
-  for(unsigned int ix=0;ix<20;++ix){ca34error[ix]=sqrt(sqr(ca34errorstat[ix])+
-						       sqr(ca34errorsyst[ix]));}
-  vector<double> bins  = vector<double>(ca34bins ,ca34bins +21);
-  vector<double> data  = vector<double>(ca34data ,ca34data +20);
-  vector<double> error = vector<double>(ca34error,ca34error+20);
-  _ca34= new_ptr(Histogram(bins,data,error));
-  double cchiBZbins[] = {0.00, 0.05, 0.10, 0.15, 0.20, 
-			 0.25, 0.30, 0.35, 0.40, 0.45, 
-			 0.50, 0.55, 0.60, 0.65, 0.70, 
-			 0.75, 0.80, 0.85, 0.90, 0.95, 
-			 1.00};
-  double cchiBZdata[]={0.05455  ,0.05346  ,0.05450  ,0.05782  ,0.05730  ,
-		       0.05880  ,0.05734  ,0.05973  ,0.06074  ,0.06387  ,
-		       0.06483  ,0.06781  ,0.07144  ,0.07206  ,0.07887  ,
-		       0.08601  ,0.09318  ,0.09865  ,0.11785  ,0.24115};
-  double cchiBZerrorstat[]={0.00115  ,0.00113    ,0.00115  ,0.00120  ,0.00120  ,
-			    0.00121  ,0.00118  ,0.00121  ,0.00122  ,0.00125  ,
-			    0.00126  ,0.00128  ,0.00131  ,0.00129  ,0.00136  ,
-			    0.00148  ,0.00146  ,0.00147  ,0.00159  ,0.00244};
-  double cchiBZerrorsyst[]={0.00288,0.00287,0.00289,0.00306,0.00310,
-			    0.00314,0.00299,0.00311,0.00319,0.00330,
-			    0.00340,0.00332,0.00358,0.00329,0.00365,
-			    0.00412,0.00406,0.00401,0.00432,0.01276};
-  double cchiBZerror[20];
-  for(unsigned int ix=0;ix<20;++ix){cchiBZerror[ix]=sqrt(sqr(cchiBZerrorstat[ix])+
-							 sqr(cchiBZerrorsyst[ix]));}
-  bins  = vector<double>(cchiBZbins ,cchiBZbins +21);
-  data  = vector<double>(cchiBZdata ,cchiBZdata +20);
-  error = vector<double>(cchiBZerror,cchiBZerror+20);
-  _cchiBZ= new_ptr(Histogram(bins,data,error));
-  double cphiKSWbins[] = {-1.0, -0.9, -0.8, -0.7, -0.6, 
-			  -0.5, -0.4, -0.3, -0.2, -0.1, 
-			  0.0, 0.1, 0.2, 0.3, 0.4, 
-			  0.5, 0.6, 0.7, 0.8, 0.9, 
-			  1.0};
-  double cphiKSWdata[]={0.06378  ,0.03897  ,0.03558  ,0.03637  ,0.03597  ,
-			0.03759  ,0.03696  ,0.03886  ,0.03801  ,0.03783  ,
-			0.03342  ,0.03096  ,0.03033  ,0.02974  ,0.02976  ,
-			0.02979  ,0.03068  ,0.03399  ,0.04234  ,0.09341};
-  double cphiKSWerrorstat[]={0.00091  ,0.00066  ,0.00062  ,0.00065  ,0.00065  ,
-			     0.00067  ,0.00065  ,0.00068  ,0.00065  ,0.00064  ,
-			     0.00060  ,0.00059  ,0.00060  ,0.00060  ,0.00061  ,
-			     0.00061  ,0.00062  ,0.00065  ,0.00072  ,0.00109};
-  double cphiKSWerrorsyst[]={0.00362,0.00161,0.00143,0.00158,0.00157,
-			     0.00172,0.00165,0.00177,0.00157,0.00143,
-			     0.00130,0.00141,0.00154,0.00158,0.00172,
-			     0.00172,0.00172,0.00191,0.00224,0.00560};
-  double cphiKSWerror[20];
-  for(unsigned int ix=0;ix<20;++ix){cphiKSWerror[ix]=sqrt(sqr(cphiKSWerrorstat[ix])+
-							  sqr(cphiKSWerrorsyst[ix]));}
-  bins  = vector<double>(cphiKSWbins ,cphiKSWbins +21);
-  data  = vector<double>(cphiKSWdata ,cphiKSWdata +20);
-  error = vector<double>(cphiKSWerror,cphiKSWerror+20);
-  _cphiKSW= new_ptr(Histogram(bins,data,error));
-  double cthNRbins[] = {0.00, 0.05, 0.10, 0.15, 0.20, 
-			0.25, 0.30, 0.35, 0.40, 0.45, 
-			0.50, 0.55, 0.60, 0.65, 0.70, 
-			0.75, 0.80, 0.85, 0.90, 0.95, 
-			1.00};
-  double cthNRerror[20];
-  double cthNRdata[]={0.06131  ,0.05888  ,0.05937  ,0.06104  ,0.05949  ,
-		      0.06317  ,0.06632  ,0.06712  ,0.07040  ,0.07274  ,
-		      0.07605  ,0.07707  ,0.08350  ,0.08779  ,0.08856  ,
-		      0.09567  ,0.09632  ,0.10124  ,0.10139  ,0.12596};
-  double cthNRerrorstat[]={0.00119  ,0.00114  ,0.00115  ,0.00118  ,0.00115  ,
-			   0.00121  ,0.00125  ,0.00125  ,0.00129  ,0.00131  ,
-			   0.00135  ,0.00135  ,0.00142  ,0.00147  ,0.00145  ,
-			   0.00154  ,0.00154  ,0.00160  ,0.00158  ,0.00178};
-  double cthNRerrorsyst[]={0.00281,0.00252,0.00272,0.00281,0.00271,
-			   0.00292,0.00321,0.00324,0.00343,0.00354,
-			   0.00377,0.00376,0.00422,0.00436,0.00431,
-			   0.00503,0.00505,0.00534,0.00506,0.00630};
-  for(unsigned int ix=0;ix<20;++ix){cthNRerror[ix]=sqrt(sqr(cthNRerrorstat[ix])+
-							sqr(cthNRerrorsyst[ix]));}
-  bins  = vector<double>(cthNRbins ,cthNRbins +21);
-  data  = vector<double>(cthNRdata ,cthNRdata +20);
-  error = vector<double>(cthNRerror,cthNRerror+20);
-  _cthNR= new_ptr(Histogram(bins,data,error));
-}
-
diff --git a/Analysis/LEPFourJetsAnalysis.h b/Analysis/LEPFourJetsAnalysis.h
deleted file mode 100644
--- a/Analysis/LEPFourJetsAnalysis.h
+++ /dev/null
@@ -1,265 +0,0 @@
-// -*- C++ -*-
-//
-// LEPFourJetsAnalysis.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_LEPFourJetsAnalysis_H
-#define HERWIG_LEPFourJetsAnalysis_H
-//
-// This is the declaration of the LEPFourJetsAnalysis class.
-//
-
-#include "ThePEG/Handlers/AnalysisHandler.h"
-#include "ThePEG/Repository/EventGenerator.h"
-#include "ThePEG/Vectors/Lorentz5Vector.h"
-#include "Herwig/Utilities/Histogram.h"
-#include "ThePEG/Repository/CurrentGenerator.h"
-
-namespace Herwig {
-
-using namespace ThePEG;
-
-/** \ingroup Analysis
- * The LEPFourJetsAnalysis class performs analysis for four jet angles and
- * compares them to LEP data.
- *
- * @see \ref LEPFourJetsAnalysisInterfaces "The interfaces"
- * defined for LEPFourJetsAnalysis.
- */
-class LEPFourJetsAnalysis: public AnalysisHandler {
-
-public:
-
-  /**
-   * Default constructor
-   */
-  LEPFourJetsAnalysis ()
-    : _ca34(), _cchiBZ(), _cphiKSW(), _cthNR(),
-      _charged(true) {}
-
-public:
-
-  /** @name Virtual functions required by the AnalysisHandler class. */
-  //@{
-  /**
-   * Analyze a given Event. Note that a fully generated event
-   * may be presented several times, if it has been manipulated in
-   * between. The default version of this function will call transform
-   * to make a lorentz transformation of the whole event, then extract
-   * all final state particles and call analyze(tPVector) of this
-   * analysis object and those of all associated analysis objects. The
-   * default version will not, however, do anything on events which
-   * have not been fully generated, or have been manipulated in any
-   * way.
-   * @param event pointer to the Event to be analyzed.
-   * @param ieve the event number.
-   * @param loop the number of times this event has been presented.
-   * If negative the event is now fully generated.
-   * @param state a number different from zero if the event has been
-   * manipulated in some way since it was last presented.
-   */
-  virtual void analyze(tEventPtr event, long ieve, int loop, int state);
-  //@}
-
-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 compute the four jet angles, assumes the jets are energy ordered
-   */
-  //@{
-  /**
-   *  Compute \f$\cos\chi_{BZ}\f$
-   */
-  double cosChiBZ(vector<Lorentz5Momentum> p) {
-    if (p.size() == 4) {
-      ThreeVector<Energy2> v1 = p[0].vect().cross(p[1].vect());
-      ThreeVector<Energy2> v2 = p[2].vect().cross(p[3].vect());
-      return cos(v1.angle(v2)); 
-    } 
-    else return 123;
-  }
-
-  /**
-   *  Compute \f$\cos\Phi_{KSW}\f$.
-   */ 
-  double cosPhiKSW(vector<Lorentz5Momentum> p) {
-    if (p.size() == 4) {
-      ThreeVector<Energy2> v1 = p[0].vect().cross(p[3].vect());
-      ThreeVector<Energy2> v2 = p[1].vect().cross(p[2].vect());
-      double alpha1 = v1.angle(v2);
-      v1 = p[0].vect().cross(p[2].vect());
-      v2 = p[1].vect().cross(p[3].vect());
-      double alpha2 = v1.angle(v2);
-      return cos((alpha1+alpha2)/2.);
-    } 
-    else return 123; 
-  }
-
-  /**
-   *  Compute \f$\cos\Theta_{NR}\f$
-   */
-  double cosThetaNR(vector<Lorentz5Momentum> p) {
-    if (p.size() == 4) {
-      ThreeVector<Energy> v1 = p[0].vect() - p[1].vect();
-      ThreeVector<Energy> v2 = p[2].vect() - p[3].vect();
-      return cos(v1.angle(v2));
-    }
-    else return 123; 
-  }
-
-  /**
-   *  Compute \f$\cos\alpha_{34}\f$
-   */
-  double cosAlpha34(std::vector<Lorentz5Momentum> p) {
-    if (p.size() == 4)
-      return cos(p[2].vect().angle(p[3].vect()));
-    else 
-      return 123; 
-  }
-  //@}
-
-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. Called in the run phase just before
-   * a run begins.
-   */
-  virtual void doinitrun();
-
-  /**
-   * Finalize this object. Called in the run phase just after a
-   * run has ended. Used eg. to write out statistics.
-   */
-  virtual void dofinish();
-  //@}
-
-private:
-
-  /**
-   * The static object used to initialize the description of this class.
-   * Indicates that this is a concrete class with persistent data.
-   */
-  static ClassDescription<LEPFourJetsAnalysis> initLEPFourJetsAnalysis;
-
-  /**
-   * The assignment operator is private and must never be called.
-   * In fact, it should not even be implemented.
-   */
-  LEPFourJetsAnalysis & operator=(const LEPFourJetsAnalysis &);
-
-private:
-
-  /**
-   * Histogram for the \f$\cos\alpha_{34}\f$ distribution
-   */
-  HistogramPtr _ca34;
-
-  /**
-   * Histogram for the \f$\cos\chi_{BZ}\f$ distribution
-   */
-  HistogramPtr _cchiBZ;
-
-  /**
-   * Histogram for the \f$\cos\Phi_{KSW}\f$ distribution
-   */
-  HistogramPtr _cphiKSW;
-
-  /**
-   * Histogram for the \f$\cos\Theta_{NR}\f$ distribution
-   */
-  HistogramPtr _cthNR;
-
-  /**
-   * Use charged particles only
-   */
-  bool _charged;
-
-};
-
-}
-
-#include "ThePEG/Utilities/ClassTraits.h"
-
-namespace ThePEG {
-
-/** @cond TRAITSPECIALIZATIONS */
-
-/** This template specialization informs ThePEG about the
- *  base classes of LEPFourJetsAnalysis. */
-template <>
-struct BaseClassTrait<Herwig::LEPFourJetsAnalysis,1> {
-  /** Typedef of the first base class of LEPFourJetsAnalysis. */
-  typedef AnalysisHandler NthBase;
-};
-
-/** This template specialization informs ThePEG about the name of
- *  the LEPFourJetsAnalysis class and the shared object where it is defined. */
-template <>
-struct ClassTraits<Herwig::LEPFourJetsAnalysis>
-  : public ClassTraitsBase<Herwig::LEPFourJetsAnalysis> {
-  /** Return a platform-independent class name */
-  static string className() { return "Herwig::LEPFourJetsAnalysis"; }
-  /** Return the name(s) of the shared library (or libraries) be loaded to get
-   *  access to the LEPFourJetsAnalysis class and any other class on which it depends
-   *  (except the base class). */
-  static string library() { return "HwLEPJetAnalysis.so"; }
-};
-
-/** @endcond */
-
-}
-
-#endif /* HERWIG_LEPFourJetsAnalysis_H */
diff --git a/Analysis/LEPJetAnalysis.cc b/Analysis/LEPJetAnalysis.cc
deleted file mode 100644
--- a/Analysis/LEPJetAnalysis.cc
+++ /dev/null
@@ -1,804 +0,0 @@
-// -*- C++ -*-
-//
-// LEPJetAnalysis.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 LEPJetAnalysis class.
-//
-
-#include "LEPJetAnalysis.h"
-#include "ThePEG/Repository/CurrentGenerator.h"
-#include "ThePEG/EventRecord/Event.h"
-#include "ThePEG/Interface/ClassDocumentation.h"
-#include "Herwig/Utilities/HerwigStrategy.h"
-#include "fastjet/PseudoJet.hh"
-#include "fastjet/ClusterSequence.hh"
-
-using namespace Herwig;
-
-void LEPJetAnalysis::analyze(tEventPtr event, long, int, int ) {
-  ++_nevent;
-  tPVector particles;
-  event->selectFinalState(back_inserter(particles));
-
-  //  copy fastjet particles from event record.  Templated fastjet
-  //  method might leave units ambigouos.  Loop with integer index
-  //  allows backtracing ThePEG particles if needed.
-  vector<fastjet::PseudoJet> fastjet_particles;
-
-  for (unsigned int j=0; j<particles.size(); j++) {
-    fastjet::PseudoJet p(particles[j]->momentum().x()/GeV, 
-			 particles[j]->momentum().y()/GeV, 
-			 particles[j]->momentum().z()/GeV, 
-			 particles[j]->momentum().e()/GeV);
-    p.set_user_index(j);
-    fastjet_particles.push_back(p);
-  }
-  
-  fastjet::RecombinationScheme recomb_scheme = fastjet::E_scheme;
-  fastjet::Strategy strategy = fastjet::Best;
-  fastjet::JetDefinition jet_def(fastjet::ee_kt_algorithm, 
-				 recomb_scheme, strategy);
-  fastjet::ClusterSequence cs(fastjet_particles, jet_def);
-  
-  // ynm distributions
-  *_y23 += cs.exclusive_ymerge(2); 
-  *_y34 += cs.exclusive_ymerge(3); 
-  *_y45 += cs.exclusive_ymerge(4); 
-  *_y56 += cs.exclusive_ymerge(5); 
-
-  const int entr_fr = 37;
-  const int ddentr = 16;
-  for(int j = 0; j<entr_fr; j++) {
-    int Nfound = cs.n_exclusive_jets_ycut(_yc_frac[j]);
-    _njet[j] += double(Nfound);
-    switch (Nfound) {	 
-    case 0: break; 
-    case 1:  _frac1[j]++; break;
-    case 2:  _frac2[j]++; break; 
-    case 3:  _frac3[j]++; break; 
-    case 4:  _frac4[j]++; break; 
-    case 5:  _frac5[j]++; break; 
-    default: _frac6[j]++;
-    }
-  }
-  // DnD-rates 
-  for(int j = 0; j<ddentr; j++) {
-    int Nfound = cs.n_exclusive_jets_ycut(_d2dbins[j]);
-    if (Nfound == 2) _d2dN2[j]++;
-  }
-  for(int j = 0; j<ddentr; j++) {
-    int Nfound = cs.n_exclusive_jets_ycut(_d3dbins[j]);
-    if (Nfound == 2) _d3dN2[j]++;
-    else if (Nfound == 3) _d3dN3[j]++;
-  }
-  for(int j = 0; j<ddentr; j++) {
-    int Nfound = cs.n_exclusive_jets_ycut(_d4dbins[j]);
-    if (Nfound == 2) _d4dN2[j]++;
-    else if (Nfound == 3) _d4dN3[j]++;
-    else if (Nfound == 4) _d4dN4[j]++;
-  }
-}
-
-NoPIOClassDescription<LEPJetAnalysis> LEPJetAnalysis::initLEPJetAnalysis;
-// Definition of the static class description member.
-
-void LEPJetAnalysis::Init() {
-
-  static ClassDocumentation<LEPJetAnalysis> documentation
-    ("LEP Jet data analysis",
-     "The LEP Jet analysis uses data from \\cite{Pfeifenschneider:1999rz,Abreu:1996na}. ",
-     "%\\cite{Pfeifenschneider:1999rz}\n"
-     "\\bibitem{Pfeifenschneider:1999rz}\n"
-     "  P.~Pfeifenschneider {\\it et al.}  [JADE collaboration and OPAL\n"
-     "                  Collaboration],\n"
-     "   ``QCD analyses and determinations of alpha(s) in e+ e- annihilation at\n"
-     "  %energies between 35-GeV and 189-GeV,''\n"
-     "  Eur.\\ Phys.\\ J.\\  C {\\bf 17}, 19 (2000)\n"
-     "  [arXiv:hep-ex/0001055].\n"
-     "  %%CITATION = EPHJA,C17,19;%%\n"
-     "%\\cite{Abreu:1996na}\n"
-     "\\bibitem{Abreu:1996na}\n"
-     "  P.~Abreu {\\it et al.}  [DELPHI Collaboration],\n"
-     "   ``Tuning and test of fragmentation models based on identified particles  and\n"
-     "  %precision event shape data,''\n"
-     "  Z.\\ Phys.\\  C {\\bf 73}, 11 (1996).\n"
-     "  %%CITATION = ZEPYA,C73,11;%%\n"
-     );
-
-}
-
-void LEPJetAnalysis::dofinish() {
-  useMe();
-  AnalysisHandler::dofinish();
-  string fname = generator()->filename() + string("-") 
-    + name() + string(".top");
-  ofstream output(fname.c_str());
-  using namespace HistogramOptions;
-  double chisq,minfrac=0.05;
-  unsigned int npoint;
-  _y23->chiSquared(chisq,npoint,minfrac);
-  generator()->log() << "Chi Square = " << chisq << " for " << npoint 
-		     << " degrees of freedom for OPAL y_23 distribution or " 
-		     << chisq/npoint << " per degree of freedom \n";
-  _y23->topdrawOutput(output,Frame|Errorbars|Ylog,
-		      "RED",
-		      "y0231 compared to OPAL data",
-		      " X  X                      ",
-		      "1/NdN/dy0231",
-		      "        X  X",
-		       "y0231",
-		       " X  X");
-  _y34->chiSquared(chisq,npoint,minfrac);
-  generator()->log() << "Chi Square = " << chisq << " for " << npoint 
-		     << " degrees of freedom for OPAL y_34 distribution or " 
-		     << chisq/npoint << " per degree of freedom \n";
-  _y34->topdrawOutput(output,Frame|Errorbars|Ylog,
-		      "RED",
-		      "y0341 compared to OPAL data",
-		      " X  X                      ",
-		      "1/NdN/dy0341",
-		      "        X  X",
-		       "y0341",
-		       " X  X");
-  _y45->chiSquared(chisq,npoint,minfrac);
-  generator()->log() << "Chi Square = " << chisq << " for " << npoint 
-		     << " degrees of freedom for OPAL y_45 distribution or " 
-		     << chisq/npoint << " per degree of freedom \n";
-  _y45->topdrawOutput(output,Frame|Errorbars|Ylog,
-		      "RED",
-		      "y0451 compared to OPAL data",
-		      " X  X                      ",
-		      "1/NdN/dy0451",
-		      "        X  X",
-		       "y0451",
-		       " X  X");
-  _y56->chiSquared(chisq,npoint,minfrac);
-  generator()->log() << "Chi Square = " << chisq << " for " << npoint 
-		     << " degrees of freedom for OPAL y_56 distribution or " 
-		     << chisq/npoint << " per degree of freedom \n";
-  _y56->topdrawOutput(output,Frame|Errorbars|Ylog,
-		      "RED",
-		      "y0561 compared to OPAL data",
-		      " X  X                      ",
-		      "1/NdN/dy0561",
-		      "        X  X",
-		       "y0561",
-		       " X  X");
-  // data for jet fractions
-  double jet2data[]={0.0   ,  0.0   ,  0.0   ,  0.0   ,  0.0    ,
-		     0.0   ,  0.0   ,  0.0   ,  0.02  ,  0.06   ,
-		     0.17  ,  0.43  ,  1.07  ,  2.35  ,  4.69   ,
-		     8.36  , 13.46  , 19.77  , 26.96  , 34.42   ,
-		     41.62  , 48.29  , 54.25  , 59.88  , 65.05  ,
-		     70.02  , 74.71  , 79.04  , 83.01  , 86.68  ,
-		     89.89  , 92.73  , 95.08  , 97.02  , 98.51  , 99.52  , 99.99};
-  double jet2stat[]={0.0   ,0.0   ,0.0   ,0.0   ,0.0   ,
-		     0.0   ,0.0   ,0.0   ,0.00  ,0.00  ,
-		     0.01  ,0.01  ,0.02  ,0.03  ,0.04  ,
-		     0.05  ,0.07  ,0.08  ,0.08  ,0.09  ,
-		     0.09  ,0.09  ,0.09  ,0.09  ,0.08  ,
-		     0.08  ,0.08  ,0.07  ,0.07  ,0.06  ,
-		     0.05  ,0.05  ,0.04  ,0.03  ,0.02  ,0.01  ,0.00};
-  double jet2syst[]={0.0, 0.0, 0.0, 0.0, 0.0,
-		     0.0, 0.0, 0.0,0.01,0.03,
-		     0.06,0.13,0.27,0.51,0.88,
-		     1.41,1.95,2.39,2.66,2.71,
-		     2.63,2.46,2.26,2.08,1.87,
-		     1.67,1.49,1.31,1.10,0.88,
-		     0.69,0.50,0.31,0.17,0.09,0.04,0.04};
-  double jet3data[]={0.0   , 0.0   , 0.0   , 0.0   , 0.0   ,
-		     0.01  , 0.03  , 0.09  , 0.24  , 0.67  , 
-		     1.63  , 3.57  , 6.82  ,11.57  ,17.39  ,
-		     23.77  ,29.92  ,34.68  ,37.87  ,39.20  ,
-		     38.91  ,37.48  ,35.47  ,32.83  ,29.92  ,
-		     26.68  ,23.25  ,19.79  ,16.38  ,13.06  ,
-		     10.03  , 7.26  , 4.92  , 2.98  , 1.48  , 0.47  , 0.0 };
-  double jet3stat[]={0.0   ,0.0   ,0.0   ,0.0   ,0.0   ,
-		     0.00  ,0.00  ,0.01  ,0.01  ,0.01  ,
-		     0.02  ,0.03  ,0.05  ,0.06  ,0.07  ,
-		     0.08  ,0.08  ,0.08  ,0.08  ,0.08  ,
-		     0.08  ,0.08  ,0.08  ,0.07  ,0.07  ,
-		     0.07  ,0.07  ,0.06  ,0.06  ,0.05  ,
-		     0.05  ,0.04  ,0.03  ,0.03  ,0.02  ,0.01  ,0.0};
-  double jet3syst[]={0.0 ,0.0 ,0.0 ,0.0 ,0.0 ,
-		     0.01,0.01,0.03,0.08,0.21,
-		     0.44,0.78,1.23,1.68,1.97,
-		     2.02,1.73,1.14,0.64,0.59,
-		     0.88,1.12,1.25,1.35,1.37,
-		     1.32,1.24,1.13,0.98,0.81,
-		     0.63,0.46,0.27,0.14,0.06,0.03,0.0};
-  double jet4data[]={ 0.0   ,  0.0 ,  0.02  ,  0.03  ,  0.04  ,
-		      0.09  ,  0.23  ,  0.60  ,  1.55  ,  3.45  ,
-		      6.89  , 11.80  , 17.67  , 23.30  , 27.89  ,
-		      30.19  , 29.93  , 27.81  , 24.05  , 19.72  ,
-		      15.64  , 12.09  ,  9.13  ,  6.74  ,  4.79  ,
-		      3.24  ,  2.06  ,  1.22  ,  0.66  ,  0.30  ,
-		      0.12  ,  0.03  ,  0.0   ,  0.0  ,  0.0   ,  0.0  ,  0.0};
-  double jet4stat[]={0.0   ,0.0   ,0.00  ,0.00  ,0.00  ,
-		     0.01  ,0.01  ,0.01  ,0.02  ,0.03  ,
-		     0.05  ,0.06  ,0.07  ,0.08  ,0.08  ,
-		     0.08  ,0.08  ,0.07  ,0.07  ,0.06  ,
-		     0.06  ,0.05  ,0.05  ,0.04  ,0.04  ,
-		     0.03  ,0.02  ,0.02  ,0.01  ,0.01  ,
-		     0.01  ,0.00  ,0.0   ,0.0   ,0.0   ,0.0   ,0.0};
-  double jet4syst[]={0.0 ,0.0 ,0.02,0.01,0.01,
-		     0.02,0.05,0.14,0.34,0.72,
-		     1.30,1.87,2.09,1.89,1.35,
-		     0.90,0.91,1.15,1.36,1.39,
-		     1.23,1.01,0.83,0.63,0.46,
-		     0.32,0.23,0.16,0.10,0.06,
-		     0.03,0.02,0.0 ,0.0 ,0.0 ,0.0 ,0.0};
-  double jet5data[]={0.02  ,  0.03  ,  0.04  ,  0.07  ,  0.17  ,
-		     0.44  ,  1.14  ,  2.68  ,  5.52  ,  9.82  ,
-		     15.10  , 20.28  , 24.06  , 25.57  , 24.61 ,
-		     21.66  , 17.47  , 12.91  ,  8.83  ,  5.67 ,
-		     3.43  ,  2.02  ,  1.14  ,  0.60  ,  0.30  ,
-		     0.13  ,  0.05  ,  0.01  ,  0.0   ,  0.0   ,
-		     0.0   ,  0.0   ,  0.0  ,  0.0    ,  0.0   ,  0.0  ,  0.0};
-  double jet5stat[]={0.00  ,0.00  ,0.00  ,0.00  ,0.01  ,
-		     0.01  ,0.02  ,0.03  ,0.04  ,0.06  ,
-		     0.07  ,0.07  ,0.08  ,0.07  ,0.07  ,
-		     0.07  ,0.06  ,0.05  ,0.04  ,0.04  ,
-		     0.03  ,0.02  ,0.02  ,0.01  ,0.01  ,
-		     0.01  ,0.00  ,0.00  ,0.0   ,0.0   ,
-		     0.0   ,0.0   ,0.0   ,0.0   ,0.0   ,0.0   ,0.0};
-  double jet5syst[]={0.01,0.01,0.01,0.01,0.02,
-		     0.06,0.20,0.52,1.04,1.61,
-		     1.92,1.78,1.22,0.78,0.85,
-		     1.13,1.30,1.26,1.04,0.73,
-		     0.46,0.27,0.15,0.08,0.04,
-		     0.02,0.01,0.00,0.0 ,0.0 ,
-		     0.0 ,0.0 ,0.0 ,0.0 ,0.0 ,0.0 ,0.0};
-  double jet6data[]={99.98  , 99.97  , 99.95  , 99.90  , 99.78  ,
-		     99.45  , 98.58  , 96.63  , 92.76  , 86.25  ,
-		     76.64  , 64.51  , 51.02  , 37.79  , 25.95  ,
-		     16.48  ,  9.62  ,  5.15  ,  2.53  ,  1.14  ,
-		     0.48  ,  0.20  ,  0.07  ,  0.03  ,  0.01   ,
-		     0.0   ,  0.0  ,  0.0    ,  0.0   ,  0.0    ,
-		     0.0   ,  0.0  ,  0.0    ,  0.0   ,  0.0    ,  0.0  ,  0.0};
-  double jet6stat[]={0.00 ,0.00 ,0.00 ,0.01 ,0.01 ,
-		     0.01 ,0.02 ,0.03 ,0.04 ,0.05 ,
-		     0.06 ,0.07 ,0.07 ,0.07 ,0.07 ,
-		     0.06 ,0.04 ,0.03 ,0.02 ,0.02 ,
-		     0.01 ,0.01 ,0.00 ,0.00 ,0.00 ,
-		     0.0  ,0.0  ,0.0  ,0.0  ,0.0  ,
-		     0.0  ,0.0  ,0.0  ,0.0  ,0.0  ,0.0  ,0.0};
-  double jet6syst[]={ 0.1, 0.1, 0.1, 0.2, 0.3,
-		      0.4, 0.6, 1.0, 1.6, 2.4,
-		      3.3, 4.0, 4.2, 3.8, 3.2,
-		      2.4, 1.7, 1.0, 0.6, 0.3,
-		      0.1, 0.0, 0.0, 0.0, 0.0,
-		      0.0, 0.0, 0.0, 0.0, 0.0,
-		      0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0};
-  double jet2error[37],jet3error[37],jet4error[37],jet5error[37],jet6error[38];
-  for(unsigned int ix=0;ix<37;++ix) {
-    jet2data[ix] /=100.;
-    jet3data[ix] /=100.;
-    jet4data[ix] /=100.;
-    jet5data[ix] /=100.;
-    jet6data[ix] /=100.;
-    jet2error[ix] = sqrt(sqr(jet2stat[ix])+sqr(jet2syst[ix]))/100.;
-    jet3error[ix] = sqrt(sqr(jet3stat[ix])+sqr(jet3syst[ix]))/100.;
-    jet4error[ix] = sqrt(sqr(jet4stat[ix])+sqr(jet4syst[ix]))/100.;
-    jet5error[ix] = sqrt(sqr(jet5stat[ix])+sqr(jet5syst[ix]))/100.;
-    jet6error[ix] = sqrt(sqr(jet6stat[ix])+sqr(jet6syst[ix]))/100.;
-  }
-  for(unsigned int ix=2;ix<7;++ix) {
-    vector<double> data,error;
-    vector<int> obs;
-    switch(ix) {
-    case 2: 
-      data  = vector<double>(jet2data ,jet2data+37 );
-      error = vector<double>(jet2error,jet2error+37);
-      obs   = _frac2;
-      break;
-    case 3: 
-      data  = vector<double>(jet3data ,jet3data+37 );
-      error = vector<double>(jet3error,jet3error+37);
-      obs   = _frac3;
-      break;
-    case 4: 
-      data  = vector<double>(jet4data ,jet4data+37 );
-      error = vector<double>(jet4error,jet4error+37);
-      obs   = _frac4;
-      break;
-    case 5: 
-      data  = vector<double>(jet5data ,jet5data+37 );
-      error = vector<double>(jet5error,jet5error+37);
-      obs   = _frac5;
-      break;
-    case 6: 
-      data  = vector<double>(jet6data ,jet6data+37 );
-      error = vector<double>(jet6error,jet6error+37);
-      obs   = _frac6;
-      break;
-    }
-    output << "NEW FRAME\n";
-    output << "SET WINDOW X 1.6 8 Y 3.5 9\n"; 
-    output << "SET FONT DUPLEX\n";
-    output << "TITLE TOP \"R0" << ix << "1 vs y0cut1\"\n";
-    output << "CASE      \" X X     X   X\"\n";
-    output << "TITLE LEFT \"R0" << ix << "1\"\n";
-    output << "CASE       \" X X\"\n";
-    if (HerwigStrategy::version != "") {
-      output << "TITLE RIGHT \"" << HerwigStrategy::version << "\"\n";
-      output << "CASE        \"\"\n";
-    }
-    output << "SET AXIS BOTTOM OFF\n";
-    output << "SET ORDER X Y DY\n";
-    output << "SET LIMITS X " << _yc_frac[0] << " " << _yc_frac[36] << "\n";
-    output << "SET SCALE X LOG\n";
-    for(unsigned int iy=0;iy<37;++iy) {
-      output << _yc_frac[iy] << "\t" << double(obs[iy])/double(_nevent) << "\n";
-    }
-    output << "JOIN RED\n";
-    for(unsigned int iy=0;iy<37;++iy) {
-      output << _yc_frac[iy] << "\t" << data[iy] << "\t" << error[iy] << "\n";
-    }
-    output << "PLOT " << endl;
-    output << "SET WINDOW X 1.6 8 Y 2.5 3.5\n";
-    output << "SET LIMITS X " << _yc_frac[0] << " " << _yc_frac[36] << "\n";
-    output << "SET SCALE X LOG\n";
-    double ymax=0.;
-    for(unsigned int iy=0;iy<37;++iy) {
-      double y = data[iy]>0. ? error[iy]/data[iy] : 1.;
-      if(y>ymax) ymax=y;
-      output << _yc_frac[iy] << "\t" << y << "\n";
-    }
-    for(int iy=36;iy>=0;--iy) {
-      double y = data[iy]>0. ? error[iy]/data[iy] : 1.;
-      output << _yc_frac[iy] << "\t" << -y << "\n";
-    }
-    output << "set limits y " << -ymax << " " << ymax << "\n";
-    output << "set fill full\n";
-    output << "join yellow fill yellow\n";
-    for(unsigned int iy=0;iy<37;++iy) {
-      output << _yc_frac[iy] << "\t" 
-	     << (double(obs[iy])/double(_nevent)-data[iy])/data[iy] << "\n";
-    }
-    output << "JOIN\n";
-    output << "SET WINDOW X 1.6 8 Y 1.6 2.5\n";
-    output << "SET LIMITS X " << _yc_frac[0] << " " << _yc_frac[36] << "\n";
-    output << "SET SCALE X LOG\n";
-    output << "SET AXIS BOTTOM ON\n";
-    output << "TITLE BOTTOM \"y0" << ix << "1\"\n";
-    output << "CASE         \" X X\n";
-    ymax =0.;
-    double ymin=0.,chisq=0.;
-    int npoint=0;
-    for(unsigned int iy=0;iy<37;++iy) {
-      double point = data[iy]>0.&&error[iy]>0. ? 
-	(double(obs[iy])/double(_nevent)-data[iy])/
-	sqrt(sqr(error[iy])+double(obs[iy])/sqr(double(_nevent))) : 0.;
-      if(point!=0.) ++npoint;
-      if(point<ymin) ymin=point;
-      if(point>ymax) ymax=point;
-      output << _yc_frac[iy] << "\t" << point << "\n";
-      if(point!=0.) {
-	if(error[iy]>0.05*data[ix]) chisq+=sqr(point);
-	else chisq+=sqr(double(obs[iy])/double(_nevent)-data[iy])/
-	  (sqr(0.05*data[ix])+double(obs[iy])/sqr(double(_nevent)));
-      }
-    }
-    output << "set limits y " << ymin << " " << ymax << "\n";
-    output << "JOIN" << endl;
-    generator()->log() << "Chi Square = " << chisq << " for " << npoint
-		       << " degrees of freedom for OPAL R_" << ix 
-		       << " distribution\n";
-  }
-  // n jet distributions
-  double njetdata[]={15.662  , 14.500  , 13.377  , 12.296  , 11.264  ,
-		     10.286  ,  9.363  ,  8.501  ,  7.701  ,  6.964  ,
-		     6.294  ,  5.688  ,  5.142  ,  4.652  ,  4.219  ,
-		     3.837  ,  3.510  ,  3.233  ,  3.008  ,  2.829  ,
-		     2.688  ,  2.576  ,  2.483  ,  2.405  ,  2.336  ,
-		     2.275  ,  2.222  ,  2.177  ,  2.136  ,  2.102  ,
-		     2.073  ,  2.049  ,  2.030  ,  2.015  ,  2.005  ,  2.000};
-  double njetstat[]={0.006 ,0.006 ,0.006 ,0.006 ,0.005 ,
-		     0.005 ,0.005 ,0.005 ,0.004 ,0.004 ,
-		     0.004 ,0.004 ,0.003 ,0.003 ,0.003 ,
-		     0.003 ,0.003 ,0.003 ,0.003 ,0.003 ,
-		     0.002 ,0.002 ,0.002 ,0.002 ,0.002 ,
-		     0.002 ,0.002 ,0.002 ,0.002 ,0.002 ,
-		     0.002 ,0.002 ,0.002 ,0.002 ,0.002 ,0.002 };
-  double njetsyst[]={0.46, 0.42, 0.38, 0.35, 0.33,
-		     0.32, 0.31, 0.30, 0.28, 0.26, 
-		     0.23, 0.20, 0.17, 0.14, 0.12, 
-		     0.10, 0.09, 0.07, 0.06, 0.04, 
-		     0.03, 0.03, 0.02, 0.02, 0.02, 
-		     0.01, 0.01, 0.01, 0.01, 0.00, 
-		     0.00, 0.00, 0.00, 0.00, 0.00, 0.00};
-  double njeterror[36];
-  for(unsigned int ix=0;ix<36;++ix)
-    njeterror[ix]=sqrt(sqr(njetstat[ix])+sqr(njetsyst[ix]));
-  output << "NEW FRAME\n";
-  output << "SET WINDOW X 1.6 8 Y 3.5 9\n"; 
-  output << "SET FONT DUPLEX\n";
-  output << "TITLE TOP \" N0jets1\"\n";
-  output << "CASE      \"  X    X\"\n";
-  output << "TITLE LEFT \" <N0jets1>\"\n";
-  output << "CASE       \"   X    X \"\n";
-  if (HerwigStrategy::version != "") {
-    output << "TITLE RIGHT \"" << HerwigStrategy::version << "\"\n";
-    output << "CASE        \"\"\n";
-  }
-  output << "SET AXIS BOTTOM OFF\n";
-  output << "SET ORDER X Y DY\n";
-  output << "SET LIMITS X " << _yc_frac[1] << " " << _yc_frac[36] << "\n";
-  output << "SET SCALE X LOG Y LOG\n";
-  output << "SET LIMITS Y 2 16\n";
-  for(unsigned int ix=1;ix<37;++ix) {
-    output << _yc_frac[ix] << "\t" << _njet[ix].mean() << "\n";
-  }
-  output << "JOIN RED\n";
-  for(unsigned int ix=0;ix<36;++ix) {
-    output << _yc_frac[ix+1] << "\t" << njetdata[ix] << "\t" << njeterror[ix] << "\n";
-  }
-  output << "PLOT " << endl;
-  output << "SET WINDOW X 1.6 8 Y 2.5 3.5\n";
-  output << "SET LIMITS X " << _yc_frac[1] << " " << _yc_frac[36] << "\n";
-  output << "SET SCALE X LOG Y LIN\n";
-  double ymax=0.;
-  for(unsigned int ix=0;ix<36;++ix) {
-    double y = njetdata[ix]>0. ? njeterror[ix]/njetdata[ix] : 1.;
-    if(y>ymax) ymax=y;
-    output << _yc_frac[ix] << "\t" << y << "\n";
-  }
-  for(int ix=35;ix>=0;--ix) {
-    double y = njetdata[ix]>0. ? njeterror[ix]/njetdata[ix] : 1.;
-    output << _yc_frac[ix] << "\t" << -y << "\n";
-  }
-  output << "set limits y " << -ymax << " " << ymax << "\n";
-  output << "set fill full\n";
-  output << "join yellow fill yellow\n";
-  for(unsigned int ix=1;ix<37;++ix) {
-    output << _yc_frac[ix] << "\t" 
-	   << (_njet[ix].mean()-njetdata[ix-1])/njetdata[ix-1] << "\n";
-  }
-  output << "JOIN\n";
-  output << "SET WINDOW X 1.6 8 Y 1.6 2.5\n";
-  output << "SET SCALE X LOG\n";
-  output << "SET LIMITS X " << _yc_frac[1] << " " << _yc_frac[36] << "\n";
-  output << "SET AXIS BOTTOM ON\n";
-  output << "TITLE BOTTOM \"y0cut1\"\n";
-  output << "CASE         \" X   X\"\n";
-  ymax =0.;
-  double ymin=0.;
-  chisq=0.;
-  npoint=0;
-  for(unsigned int ix=1;ix<37;++ix) {
-    double point = njetdata[ix-1]>0.&&njeterror[ix-1]>0. ? 
-      (_njet[ix].mean()-njetdata[ix-1])/
-      sqrt(sqr(njeterror[ix-1])+_njet[ix].mean_var()) : 0.;
-    if(point!=0.) ++npoint;
-    if(point<ymin) ymin=point;
-    if(point>ymax) ymax=point;
-    output << _yc_frac[ix] << "\t" << point << "\n";
-    if(point!=0.) {
-      if(njeterror[ix-1]>0.05*njetdata[ix-1]) chisq+=sqr(point);
-      else chisq+=sqr(_njet[ix].mean()-njetdata[ix-1])/
-	(sqr(0.05*njetdata[ix-1])+_njet[ix].mean_var());
-    }
-  }
-  output << "set limits y " << ymin << " " << ymax << "\n";
-  output << "JOIN" << endl;
-  generator()->log() << "Chi Square = " << chisq << " for " << npoint
-		     << " degrees of freedom for OPAL N_jet "
-		     << " distribution\n";
-  const int ddentr = 16;
-  // D_2
-  vector<double> d2,d2error;
-  for(int j = 0; j<ddentr-1; j++) {
-    double dy = _d2dbins[j+1]-_d2dbins[j];
-    d2.push_back((_d2dN2[j+1]-_d2dN2[j])/(dy*double(_nevent)));
-    d2error.push_back(sqrt(_d2dN2[j+1]+_d2dN2[j])/(dy*double(_nevent)));
-  }
-  // D_3
-  vector<double> d3,d3error;
-  for(int j = 0; j<ddentr-1; j++) {
-    double dy = _d3dbins[j+1]-_d3dbins[j];
-    d3.push_back((_d3dN2[j+1]-_d3dN2[j]+_d3dN3[j+1]-_d3dN3[j])/(dy*double(_nevent)));
-    d3error.push_back(sqrt(_d3dN2[j+1]+_d3dN2[j]+_d3dN3[j+1]+_d3dN3[j])/
-		      (dy*double(_nevent)));
-  }
-  // D_4
-  vector<double> d4,d4error;
-  for(int j = 0; j<ddentr-1; j++) {
-    double dy = _d4dbins[j+1]-_d4dbins[j];
-    d4.push_back((_d4dN2[j+1]-_d4dN2[j]+_d4dN3[j+1]-_d4dN3[j]
-		  +_d4dN4[j+1]-_d4dN4[j])/(dy*double(_nevent)));
-    d4error.push_back(sqrt(_d4dN2[j+1]+_d4dN2[j]+_d4dN3[j+1]+_d4dN3[j]
-			   +_d4dN4[j+1]+_d4dN4[j])/(dy*double(_nevent)));
-  }
-  double d2data[]={63.81    ,11.589   , 6.040   , 3.823   , 2.697   ,
-		   2.041   , 1.410   , 0.952   , 0.6708  , 0.4831  ,
-		   0.3660  , 0.2830  , 0.2190  , 0.1357  , 0.0605};
-  double d2stat[]={0.12    ,0.052   ,0.038   ,0.030   ,0.026   ,
-		   0.022   ,0.013   ,0.011   ,0.0090  ,0.0077  ,
-		   0.0068  ,0.0061  ,0.0054  ,0.0028  ,0.0022};
-  double d2syst[]={0.64  ,0.116 ,0.060 ,0.038 ,0.027 ,
-		   0.020 ,0.014 ,0.011 ,0.0102,0.0098,
-		   0.0098,0.0102,0.0109,0.0092,0.0055};
-  double d2total[15];
-  double d3data[]={333.97    , 85.51    , 29.49    , 14.78    ,  7.583   ,
-		   3.707   ,  2.119   ,  1.348   ,  0.906   ,  0.646   ,
-		   0.366   ,  0.1965  ,  0.0877  ,  0.0367  ,  0.0073};
-  double d3stat[]={0.64      ,0.31      ,0.18      ,0.13      ,0.067     ,
-		   0.047     ,0.037     ,0.030     ,0.024     ,0.021     ,
-		   0.011     ,0.0076  ,0.0050  ,0.0024  ,0.0010};
-  double d3syst[]={3.34  ,0.86  ,0.29  ,0.15  ,0.076 ,
-		   0.037 ,0.042 ,0.042 ,0.038 ,0.034 ,
-		   0.025 ,0.0177,0.0100,0.0054,0.0014};
-  double d3total[15];
-  double d4data[]={711.0     ,184.32    , 53.35    , 21.18    , 10.15    ,
-		   5.67    ,  2.768   ,  1.203   ,  0.617   ,  0.357   ,
-		   0.215   ,  0.144   ,  0.0745  ,  0.0434  ,  0.0133};
-  double d4stat[]={1.3     ,0.66    ,0.35    ,0.22    ,0.15    ,
-		   0.11    ,0.057   ,0.039   ,0.028   ,0.022   ,
-		   0.017   ,0.015   ,0.0103  ,0.0052  ,0.0028};
-  double d4syst[]={7.1	,1.84	,1.06	,0.53	,0.30	,
-		   0.20	,0.114	,0.060	,0.036	,0.024	,
-		   0.016,0.011	,0.0064,0.0042,0.0014};
-  double d4total[15];
-  for(unsigned int ix=0;ix<15;++ix) {
-    d2total[ix]=sqrt(sqr(d2stat[ix])+sqr(d2syst[ix]));
-    d3total[ix]=sqrt(sqr(d3stat[ix])+sqr(d3syst[ix]));
-    d4total[ix]=sqrt(sqr(d4stat[ix])+sqr(d4syst[ix]));
-  }
-  for(unsigned int ix=2;ix<5;++ix) {
-    vector<double> data,error,obs,obserr,bins;
-    switch(ix) {
-    case 2: 
-      data   = vector<double>(d2data ,d2data+15 );
-      error  = vector<double>(d2total,d2total+15);
-      obs    = d2;
-      obserr = d2error;
-      bins   = _d2dbins;
-      break;
-    case 3: 
-      data   = vector<double>(d3data ,d3data+15 );
-      error  = vector<double>(d3total,d3total+15);
-      obs    = d3;
-      obserr = d3error;
-      bins   = _d3dbins;
-      break;
-    case 4: 
-      data   = vector<double>(d4data ,d4data+15 );
-      error  = vector<double>(d4total,d4total+15);
-      obs    = d4;
-      obserr = d4error;
-      bins   = _d4dbins;
-      break;
-    }
-    output << "NEW FRAME\n";
-    output << "SET WINDOW X 1.6 8 Y 3.5 9\n"; 
-    output << "SET FONT DUPLEX\n";
-    output << "TITLE TOP \"D0" << ix << "1 vs y0cut1\"\n";
-    output << "CASE      \" X X     X   X\"\n";
-    output << "TITLE LEFT \"D0" << ix << "1\"\n";
-    output << "CASE       \" X X\"\n";
-    if (HerwigStrategy::version != "") {
-      output << "TITLE RIGHT \"" << HerwigStrategy::version << "\"\n";
-      output << "CASE        \"\"\n";
-    }
-    output << "SET AXIS BOTTOM OFF\n";
-    output << "SET ORDER X Y DY\n";
-    output << "SET LIMITS X " << bins[0] << " " << bins[ddentr-1] << "\n";
-    output << "SET SCALE Y LOG\n";
-    for(int iy=0;iy<ddentr-1;++iy) {
-      output << 0.5*(bins[iy]+bins[iy+1]) << "\t" << obs[iy] << "\n";
-    }
-    output << "JOIN RED\n";
-    for(int iy=0;iy<ddentr-1;++iy) {
-      output << 0.5*(bins[iy]+bins[iy+1]) << "\t" 
-	     << data[iy] << "\t" << error[iy] << "\n";
-    }
-    output << "PLOT " << endl;
-    output << "SET WINDOW X 1.6 8 Y 2.5 3.5\n";
-    output << "SET LIMITS X " << bins[0] << " " << bins[15] << "\n";
-    output << "SET SCALE Y LIN\n";
-    double ymax=0.;
-    for(unsigned int iy=0;iy<ddentr-1;++iy) {
-      double y = data[iy]>0. ? error[iy]/data[iy] : 1.;
-      if(y>ymax) ymax=y;
-      output << 0.5*(bins[iy]+bins[iy+1]) << "\t" << y << "\n";
-    }
-    for(int iy=ddentr-2;iy>=0;--iy) {
-      double y = data[iy]>0. ? error[iy]/data[iy] : 1.;
-      output << 0.5*(bins[iy]+bins[iy+1]) << "\t" << -y << "\n";
-    }
-    output << "set limits y " << -ymax << " " << ymax << "\n";
-    output << "set fill full\n";
-    output << "join yellow fill yellow\n";
-    for(unsigned int iy=0;iy<ddentr-1;++iy) {
-      output << 0.5*(bins[iy]+bins[iy+1]) << "\t" 
-	     << (obs[iy]-data[iy])/data[iy] << "\n";
-    }
-    output << "JOIN\n";
-    output << "SET WINDOW X 1.6 8 Y 1.6 2.5\n";
-    output << "SET LIMITS X " << bins[0] << " " << bins[15] << "\n";;
-    output << "SET AXIS BOTTOM ON\n";
-    output << "TITLE BOTTOM \"y0" << ix << "1\"\n";
-    output << "CASE         \" X X\n";
-    ymax =0.;
-    double ymin=0.,chisq=0.;
-    int npoint=0;
-    for(unsigned int iy=0;iy<ddentr-1;++iy) {
-      double point = data[iy]>0.&&error[iy]>0. ? 
-	(double(obs[iy])-data[iy])/
-	sqrt(sqr(error[iy])+sqr(obserr[iy])) : 0.;
-      if(point!=0.) ++npoint;
-      if(point<ymin) ymin=point;
-      if(point>ymax) ymax=point;
-      output << 0.5*(bins[iy]+bins[iy+1]) << "\t" << point << "\n";
-      if(point!=0.) {
-	if(error[iy]>0.05*data[ix]) chisq+=sqr(point);
-	else chisq+=sqr(obs[iy]-data[iy])/
-	  (sqr(0.05*data[ix])+sqr(obserr[iy]));
-      }
-    }
-    output << "set limits y " << ymin << " " << ymax << "\n";
-    output << "JOIN" << endl;
-    generator()->log() << "Chi Square = " << chisq << " for " << npoint
-		       << " degrees of freedom for DELPHI D_" << ix 
-		       << " distribution\n";
-  }
-}
-
-void LEPJetAnalysis::doinitrun() {
-  AnalysisHandler::doinitrun();
-  _nevent=0;
-  // y distributions
-  double diffbins[] = {1.00E-05, 1.33E-05, 1.78E-05, 2.37E-05, 3.16E-05, 
-		       4.22E-05, 5.62E-05, 7.50E-05, 1.00E-04, 1.33E-04, 
-		       1.78E-04, 2.37E-04, 3.16E-04, 4.22E-04, 5.62E-04, 
-		       7.50E-04, 1.00E-03, 1.33E-03, 1.78E-03, 2.37E-03, 
-		       3.16E-03, 4.22E-03, 5.62E-03, 7.50E-03, 1.00E-02, 
-		       1.33E-02, 1.78E-02, 2.37E-02, 3.16E-02, 4.22E-02, 
-		       5.62E-02, 7.50E-02, 1.00E-01, 1.33E-01, 1.78E-01, 
-		       2.37E-01, 3.16E-01};
-  double y23data[]= {0.0    ,  0.0    ,  0.0    ,  0.0    ,  2.672  ,
-		     2.984  ,  2.482  ,  5.199  , 11.11   , 24.82   , 
-		     43.76   , 80.73   ,121.9    ,166.2    ,195.5    ,
-		     203.8    ,189.7    ,162.3    ,126.6    , 91.87   , 
-		     63.59   , 42.77   , 30.13   , 20.75   , 14.93   , 
-		     10.56   ,  7.318  ,  5.045  ,  3.483  ,  2.289  ,  
-		     1.521  ,  0.942  ,  0.583  ,  0.336  ,  0.170  ,  0.058};
-  double y23stat[]={0.0    ,0.0    ,0.0    ,0.0    ,2.248  ,
-		    1.821  ,0.662  ,0.867  ,1.05   ,1.45   ,
-		    1.56   ,1.93   ,2.1    ,2.1    ,2.0    ,
-		    1.7    ,1.4    ,1.1    ,0.8    ,0.56   ,
-		    0.40   ,0.28   ,0.20   ,0.15   ,0.11   ,
-		    0.08   ,0.057  ,0.041  ,0.030  ,0.020  ,
-		    0.015  ,0.010  ,0.007  ,0.004  ,0.003  ,0.002};
-  double y23syst[]={0.0  ,0.0  ,0.0  ,0.0  ,2.296,
-		    2.024,1.502,2.085, 4.56, 6.57,
-		    10.18,15.48,19.2 ,23.3 ,25.6 ,
-		    21.5 ,14.3 , 8.6 , 5.2 , 4.43,
-		    3.77, 2.50, 1.38, 0.92, 0.65, 
-		    0.44,0.321,0.270,0.209,0.146,
-		    0.104,0.077,0.046,0.022,0.009,0.011};
-  vector<double> bins(diffbins,diffbins+37);
-  vector<double> data(y23data,y23data+36);
-  vector<double> error(36);
-  for(unsigned int ix=0;ix<36;++ix) error[ix]=sqrt(sqr(y23stat[ix])+sqr(y23syst[ix]));
-  _y23 = new_ptr(Histogram(bins,data,error));
-  double y34data[]={0.0   ,  0.0   ,  0.0   ,  5.910 ,  7.934 ,
-		    14.89  , 34.42  , 64.74  ,138.3   ,242.9   ,
-		    369.6   ,492.9   ,571.7   ,580.0   ,535.1   ,
-		    448.7   ,333.2   ,234.0   ,149.3   , 88.43  ,
-		    50.04  , 28.38  , 15.95  ,  9.092 ,  5.181 ,
-		    2.848 ,  1.479 ,  0.727 ,  0.338 ,  0.134 , 
-		    0.045 ,  0.011 ,  0.0   ,  0.0   ,  0.0   ,  0.0};
-  double y34stat[]={0.0    , 0.0    , 0.0    , 1.837  , 1.577  ,
-		    1.77   , 2.40   , 2.79   , 3.8    , 4.4    ,
-		    4.7    , 4.7    , 4.3    , 3.7    , 3.0    ,
-		    2.3    , 1.7    , 1.2    , 0.8    , 0.52   ,
-		    0.34   , 0.22   , 0.15   , 0.096  , 0.064  ,
-		    0.042  , 0.026  , 0.016  , 0.010  , 0.005  ,
-		    0.003  , 0.001  , 0.0    , 0.0    , 0.0    , 0.0};
-  double y34syst[]={0.0   ,0.0   ,0.0   ,3.084 ,2.557 ,
-		    4.84 , 8.66 ,20.29 ,38.3  ,50.2  ,
-		    60.3  ,66.6  ,59.8  ,45.1  ,30.5  ,
-		    18.1  ,11.6  ,10.0  , 9.0  ,7.43  ,
-		    5.09  ,2.94  ,1.75  ,1.052 ,0.580 ,
-		    0.313 ,0.166 ,0.098 ,0.053 ,0.026 ,
-		    0.014 ,0.007 ,0.0   ,0.0   ,0.0   ,0.0}; 
-  data=vector<double>(y34data,y34data+36);
-  for(unsigned int ix=0;ix<36;++ix) error[ix]=sqrt(sqr(y34stat[ix])+sqr(y34syst[ix]));   
-  _y34 = new_ptr(Histogram(bins,data,error));    
-  double y45data[]={17.50   ,  18.42   ,  19.98   ,  28.13   ,  56.68   ,
-		    113.1    , 233.0    , 446.7    , 711.5    ,1018.6    ,
-		    1197.7    ,1236.0    ,1108.2    , 907.8    , 658.8    ,
-		    439.2    , 269.8    , 150.1    ,  76.52   ,  36.67   ,
-		    16.23   ,   7.154  ,   3.150  ,   1.267  ,   0.537  , 
-		    0.179  ,   0.064  ,   0.014  ,   0.003  ,   0.0    ,
-		    0.0    ,   0.0    ,   0.0    ,   0.0    ,   0.0    ,   0.0};
-  double y45stat[]={8.19     ,5.57          ,3.46     ,3.06     ,3.75        ,
-		    4.6      ,6.1      ,7.7      ,8.6      ,9.1      ,
-		    8.4      ,7.2      ,5.7      ,4.3      ,3.1      ,
-		    2.1      ,1.4      ,0.9      ,0.55     ,0.33     ,
-		    0.19     ,0.112    ,0.067    ,0.037    ,0.023    ,
-		    0.011    ,0.006    ,0.003    ,0.001    ,0.0    ,
-		    0.0      ,0.0      ,0.0      ,0.0      ,0.0      ,0.0};
-  double y45syst[]={10.58   ,10.58   , 7.51   , 8.89   ,10.54   ,
-		    19.5   , 48.8   , 90.5   ,138.9   ,169.5   ,
-		    156.2   ,106.5   , 52.8   , 28.5   , 25.0   ,
-		    23.3   , 20.0   , 15.7   ,10.60   , 6.24   ,
-		    3.15   ,1.43    ,0.63    ,0.28    ,0.11    ,
-		    0.04    ,0.01    ,0.00    ,0.00    ,0.0     ,
-		    0.0     ,0.0     ,0.0     ,0.0     ,0.0     ,0.0}; 
-  data=vector<double>(y45data,y45data+36);
-  for(unsigned int ix=0;ix<36;++ix) error[ix]=sqrt(sqr(y45stat[ix])+sqr(y45syst[ix]));   
-  _y45 = new_ptr(Histogram(bins,data,error)); 
-  double y56data[]={42.43   ,  44.80   ,  78.16   , 155.9    , 309.6    ,
-		    619.9    ,1055.3    ,1586.5    ,2003.2    ,2204.6    ,
-		    2072.6    ,1715.4    ,1255.9    , 841.2    , 503.6    ,
-		    273.2    , 133.7    ,  58.54   ,  23.36   ,   8.336  , 
-		    2.735  ,   0.874  ,   0.253  ,   0.084  ,   0.012  , 
-		    0.003  ,   0.0         ,   0.0    ,   0.0    ,   0.0    ,
-		    0.0    ,   0.0    ,   0.0    ,   0.0    ,   0.0    ,   0.0};
-  double y56stat[]={7.35     , 5.01     , 5.56     , 7.0      , 8.9      ,
-		    11.7      ,13.8      ,15.0      ,14.5      ,13.0      ,
-		    10.5      , 8.0      , 5.7      , 4.0      , 2.6      ,
-		    1.6      , 1.0      , 0.55     , 0.30     , 0.157    ,
-		    0.080    , 0.042    , 0.020    , 0.012    , 0.003    ,
-		    0.002    , 0.0    , 0.0    , 0.0    , 0.0    ,
-		    0.0      , 0.0    , 0.0    , 0.0    , 0.0    , 0.0};
-  double y56syst[]={14.5,12.8,16.0, 20., 44.,
-		    103.,195.,280.,307.,256.,
-		    154., 84., 61., 51., 44.,
-		    33., 21.,12.1, 6.2,2.86,
-		    1.24,0.49,0.19,0.07,0.02,
-		    0.01,0.0 ,0.0 ,0.0 ,0.0 ,
-		    0.0 ,0.0 ,0.0 ,0.0 ,0.0 ,0.0 }; 
-  data=vector<double>(y56data,y56data+36);
-  for(unsigned int ix=0;ix<36;++ix) error[ix]=sqrt(sqr(y56stat[ix])+sqr(y56syst[ix]));   
-  _y56 = new_ptr(Histogram(bins,data,error));  
-  double yc_frac[] = {1.00E-05, 1.33E-05, 1.78E-05, 2.37E-05, 3.16E-05, 
-		      4.22E-05, 5.62E-05, 7.50E-05, 1.00E-04, 1.33E-04, 
-		      1.78E-04, 2.37E-04, 3.16E-04, 4.22E-04, 5.62E-04, 
-		      7.50E-04, 1.00E-03, 1.33E-03, 1.78E-03, 2.37E-03, 
-		      3.16E-03, 4.22E-03, 5.62E-03, 7.50E-03, 1.00E-02, 
-		      1.33E-02, 1.78E-02, 2.37E-02, 3.16E-02, 4.22E-02, 
-		      5.62E-02, 7.50E-02, 1.00E-01, 1.33E-01, 1.78E-01, 
-		      2.37E-01, 3.16E-01};
-  _yc_frac=vector<double>(yc_frac,yc_frac+37);
-  const int entr_fr = 37;
-  _frac1.resize(entr_fr,0);
-  _frac2.resize(entr_fr,0);
-  _frac3.resize(entr_fr,0);
-  _frac4.resize(entr_fr,0);
-  _frac5.resize(entr_fr,0);
-  _frac6.resize(entr_fr,0);
-  _njet.resize(entr_fr);
-  _njet = vector<Statistic>(entr_fr);
-  const int ddentr = 16;
-  double d2dbins[] = {0.000, 0.010, 0.020, 0.030, 0.040, 
-		      0.050, 0.060, 0.080, 0.100, 0.120, 
-		      0.140, 0.160, 0.180, 0.200, 0.250, 
-		      0.300};
-  double d3dbins[] = {0.000, 0.002, 0.004, 0.006, 0.008, 
-		      0.012, 0.016, 0.020, 0.024, 0.028, 
-		      0.032, 0.040, 0.050, 0.060, 0.080, 
-		      0.100};
-  double d4dbins[] = {0.000, 0.001, 0.002, 0.003, 0.004, 
-		      0.005, 0.006, 0.008, 0.010, 0.012, 
-		      0.014, 0.016, 0.018, 0.020, 0.025, 
-		      0.030};
-  _d2dbins=vector<double>(d2dbins,d2dbins+ddentr);
-  _d3dbins=vector<double>(d3dbins,d3dbins+ddentr);
-  _d4dbins=vector<double>(d4dbins,d4dbins+ddentr);
-  _d2dN2.resize(ddentr);
-  _d3dN2.resize(ddentr);
-  _d3dN3.resize(ddentr);
-  _d4dN2.resize(ddentr);
-  _d4dN3.resize(ddentr);
-  _d4dN4.resize(ddentr);
-}
diff --git a/Analysis/LEPJetAnalysis.h b/Analysis/LEPJetAnalysis.h
deleted file mode 100644
--- a/Analysis/LEPJetAnalysis.h
+++ /dev/null
@@ -1,282 +0,0 @@
-// -*- C++ -*-
-//
-// LEPJetAnalysis.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_LEPJetAnalysis_H
-#define HERWIG_LEPJetAnalysis_H
-//
-// This is the declaration of the LEPJetAnalysis class.
-//
-
-#include "ThePEG/Handlers/AnalysisHandler.h"
-#include "Herwig/Utilities/Histogram.h"
-
-namespace Herwig {
-
-using namespace ThePEG;
-
-/** \ingroup Analysis
- * The LEPJetAnalysis class compares the results of Heriwg++ with LEP data for
- * various jet distributions.
- *
- * @see \ref LEPJetAnalysisInterfaces "The interfaces"
- * defined for LEPJetAnalysis.
- */
-class LEPJetAnalysis: public AnalysisHandler {
-
-public:
-
-  /// Default constructor
-  LEPJetAnalysis() : _nevent() {}
-
-  /** @name Virtual functions required by the AnalysisHandler class. */
-  //@{
-  /**
-   * Analyze a given Event. Note that a fully generated event
-   * may be presented several times, if it has been manipulated in
-   * between. The default version of this function will call transform
-   * to make a lorentz transformation of the whole event, then extract
-   * all final state particles and call analyze(tPVector) of this
-   * analysis object and those of all associated analysis objects. The
-   * default version will not, however, do anything on events which
-   * have not been fully generated, or have been manipulated in any
-   * way.
-   * @param event pointer to the Event to be analyzed.
-   * @param ieve the event number.
-   * @param loop the number of times this event has been presented.
-   * If negative the event is now fully generated.
-   * @param state a number different from zero if the event has been
-   * manipulated in some way since it was last presented.
-   */
-  virtual void analyze(tEventPtr event, long ieve, int loop, int state);
-  //@}
-
-public:
-
-  /**
-   * 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 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. Called in the run phase just before
-   * a run begins.
-   */
-  virtual void doinitrun();
-
-  /**
-   * Finalize this object. Called in the run phase just after a
-   * run has ended. Used eg. to write out statistics.
-   */
-  virtual void dofinish();
-  //@}
-
-private:
-
-  /**
-   * The static object used to initialize the description of this class.
-   * Indicates that this is an concrete class without persistent data.
-   */
-  static NoPIOClassDescription<LEPJetAnalysis> initLEPJetAnalysis;
-
-  /**
-   * The assignment operator is private and must never be called.
-   * In fact, it should not even be implemented.
-   */
-  LEPJetAnalysis & operator=(const LEPJetAnalysis &);
-
-private:
-
-  /**
-   *  Histograms ofr the \f$y\f$ distributions
-   */
-  //@{
-  /**
-   *  \f$y_{23}\f$
-   */
-  HistogramPtr _y23;
-
-  /**
-   *  \f$y_{34}\f$
-   */
-  HistogramPtr _y34;
-
-  /**
-   *  \f$y_{45}\f$
-   */
-  HistogramPtr _y45;
-
-  /**
-   *  \f$y_{56}\f$
-   */
-  HistogramPtr _y56;
-  //@}
-
-  /**
-   *  Bins for the y fractions
-   */
-  vector<double> _yc_frac;
-
-  /**
-   *  Points for the y fractions
-   */
-  //@{
-  /**
-   *   1 jet
-   */
-  vector<int> _frac1;
-
-  /**
-   *   2 jet
-   */
-  vector<int> _frac2;
-
-  /**
-   *   3 jet
-   */
-  vector<int> _frac3;
-
-  /**
-   *   4 jet
-   */
-  vector<int> _frac4;
-
-  /**
-   *   5 jet
-   */
-  vector<int> _frac5;
-
-  /**
-   *   6 jet
-   */
-  vector<int> _frac6;
-  //@}
-
-  /**
-   *  Number of events analysed
-   */
-  unsigned int _nevent;
-
-  /**
-   *  N jet distribution
-   */
-  vector<Statistic> _njet;
-
-  /**
-   *  For different jet rates
-   */
-  //@{
-  /**
-   *  Differential two jet rate
-   */
-  vector<double> _d2dbins;
-
-  /**
-   *  Differential three jet rate
-   */
-  vector<double> _d3dbins;
-
-  /**
-   *  Differential four jet rate
-   */
-  vector<double> _d4dbins;
-
-  /**
-   *  differential 2->2
-   */
-  vector<int> _d2dN2;
-
-  /**
-   *  differential 3->2
-   */
-  vector<int> _d3dN2;
-
-  /**
-   *  differential 3->2
-   */
-  vector<int> _d3dN3;
-
-  /**
-   *  differential 4->2
-   */
-  vector<int> _d4dN2;
-
-  /**
-   *  differential 4->3
-   */
-  vector<int> _d4dN3;
-
-  /**
-   *  differential 4->4
-   */
-  vector<int> _d4dN4;
-
-  //@}
-};
-
-}
-
-#include "ThePEG/Utilities/ClassTraits.h"
-
-namespace ThePEG {
-
-/** @cond TRAITSPECIALIZATIONS */
-
-/** This template specialization informs ThePEG about the
- *  base classes of LEPJetAnalysis. */
-template <>
-struct BaseClassTrait<Herwig::LEPJetAnalysis,1> {
-  /** Typedef of the first base class of LEPJetAnalysis. */
-  typedef AnalysisHandler NthBase;
-};
-
-/** This template specialization informs ThePEG about the name of
- *  the LEPJetAnalysis class and the shared object where it is defined. */
-template <>
-struct ClassTraits<Herwig::LEPJetAnalysis>
-  : public ClassTraitsBase<Herwig::LEPJetAnalysis> {
-  /** Return a platform-independent class name */
-  static string className() { return "Herwig::LEPJetAnalysis"; }
-  /**
-   * The name of a file containing the dynamic library where the class
-   * LEPJetAnalysis is implemented. It may also include several, space-separated,
-   * libraries if the class LEPJetAnalysis depends on other classes (base classes
-   * excepted). In this case the listed libraries will be dynamically
-   * linked in the order they are specified.
-   */
-  static string library() { return "HwLEPJetAnalysis.so"; }
-};
-
-/** @endcond */
-
-}
-
-#endif /* HERWIG_LEPJetAnalysis_H */
diff --git a/Analysis/Makefile.am b/Analysis/Makefile.am
--- a/Analysis/Makefile.am
+++ b/Analysis/Makefile.am
@@ -1,59 +1,26 @@
 pkglib_LTLIBRARIES = HwAnalysis.la
-HwAnalysis_la_LDFLAGS = $(AM_LDFLAGS) -module -version-info 10:0:0
+HwAnalysis_la_LDFLAGS = $(AM_LDFLAGS) -module -version-info 11:0:0
 HwAnalysis_la_SOURCES = \
-EventShapes.cc EventShapes.fh EventShapes.h  \
-EventShapesMasterAnalysis.cc EventShapesMasterAnalysis.h \
 BasicConsistency.cc BasicConsistency.h \
 LEPMultiplicityCount.cc LEPMultiplicityCount.h \
 MultiplicityInfo.h \
 LEPBMultiplicity.cc\
 LEPBMultiplicity.h \
 SimpleLHCAnalysis.h SimpleLHCAnalysis.cc\
 TTbarAnalysis.h TTbarAnalysis.cc\
 LPairAnalysis.h LPairAnalysis.cc\
 GammaGammaAnalysis.h GammaGammaAnalysis.cc\
 GammaJetAnalysis.h GammaJetAnalysis.cc\
 HiggsJetAnalysis.h HiggsJetAnalysis.cc \
 ParallelRunAnalysis.h ParallelRunAnalysis.cc \
 DrellYanPT.h DrellYanPT.cc
 
 pkglib_LTLIBRARIES += HwJetsAnalysis.la
-HwJetsAnalysis_la_LDFLAGS = $(AM_LDFLAGS) -module -version-info 3:0:0
+HwJetsAnalysis_la_LDFLAGS = $(AM_LDFLAGS) -module -version-info 4:0:0
 HwJetsAnalysis_la_SOURCES = \
 LeptonsJetsAnalysis.h LeptonsJetsAnalysis.cc \
 JetsPlusAnalysis.h JetsPlusAnalysis.cc \
 HJetsAnalysis.h HJetsAnalysis.cc \
 ZJetsAnalysis.h ZJetsAnalysis.cc \
 TTJetsAnalysis.h TTJetsAnalysis.cc \
 CrossSectionAnalysis.h CrossSectionAnalysis.cc
-
-pkglib_LTLIBRARIES +=  HwLEPAnalysis.la
-HwLEPAnalysis_la_LDFLAGS = $(AM_LDFLAGS) -module -version-info 7:0:0
-HwLEPAnalysis_la_SOURCES = \
-BFragmentationAnalysisHandler.cc BFragmentationAnalysisHandler.h\
-SingleParticleAnalysis.cc SingleParticleAnalysis.h\
-LEPEventShapes.cc LEPEventShapes.h\
-IdentifiedParticleAnalysis.cc IdentifiedParticleAnalysis.h\
-BELLECharmAnalysis.h BELLECharmAnalysis.cc\
-CLEOCharmAnalysis.h CLEOCharmAnalysis.cc
-
-# analysis code which depends on fastjet
-if WANT_LIBFASTJET
-pkglib_LTLIBRARIES += HwLEPJetAnalysis.la
-HwLEPJetAnalysis_la_LDFLAGS = $(AM_LDFLAGS) -module -version-info 9:1:0
-HwLEPJetAnalysis_la_CPPFLAGS = $(AM_CPPFLAGS) $(FASTJETINCLUDE) \
--I$(FASTJETPATH)
-HwLEPJetAnalysis_la_LIBADD = $(FASTJETLIBS)
-HwLEPJetAnalysis_la_SOURCES = \
-LEPJetAnalysis.cc LEPJetAnalysis.h\
-LEPFourJetsAnalysis.cc LEPFourJetsAnalysis.h
-endif
-
-pkglib_LTLIBRARIES += HwTevatronAnalysis.la
-HwTevatronAnalysis_la_LDFLAGS = $(AM_LDFLAGS) -module -version-info 2:0:0
-HwTevatronAnalysis_la_CPPFLAGS = $(AM_CPPFLAGS)
-HwTevatronAnalysis_la_SOURCES = \
-ZpTRun2.cc ZpTRun2.h \
-ZpTRun1.cc ZpTRun1.h \
-Wpt.cc Wpt.h \
-Zrapidity.cc Zrapidity.h
diff --git a/Analysis/SingleParticleAnalysis.cc b/Analysis/SingleParticleAnalysis.cc
deleted file mode 100644
--- a/Analysis/SingleParticleAnalysis.cc
+++ /dev/null
@@ -1,394 +0,0 @@
-// -*- C++ -*-
-//
-// SingleParticleAnalysis.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 SingleParticleAnalysis class.
-//
-
-#include "SingleParticleAnalysis.h"
-#include "ThePEG/Interface/Reference.h"
-#include "ThePEG/Interface/ClassDocumentation.h"
-#include "ThePEG/Persistency/PersistentOStream.h"
-#include "ThePEG/Persistency/PersistentIStream.h"
-
-using namespace Herwig;
-
-void SingleParticleAnalysis::analyze(const tPVector & particles) {
-  useMe();
-  int Ncharged = 0; 
-  for(unsigned int ix=0;ix<particles.size();++ix) {
-    const Lorentz5Momentum p = particles[ix]->momentum();
-    if(!particles[ix]->data().charged()) continue;
-    Ncharged++;
-    *_yT += abs(_shapes->yT(p));
-    *_yS += abs(_shapes->yS(p));
-    *_ptinT += _shapes->ptInT(p)/GeV;
-    *_ptoutT += _shapes->ptOutT(p)/GeV;
-    *_ptinS += _shapes->ptInS(p)/GeV;
-    *_ptoutS += _shapes->ptOutS(p)/GeV;
-  }
-  // make sure the right bin is booked by subtracting a small amount. 
-  *_nch += Ncharged-0.00001;
-}
-
-void SingleParticleAnalysis::persistentOutput(PersistentOStream & os) const {
-  os << _shapes;
-}
-
-void SingleParticleAnalysis::persistentInput(PersistentIStream & is, int) {
-  is >> _shapes;
-}
-
-ClassDescription<SingleParticleAnalysis> 
-SingleParticleAnalysis::initSingleParticleAnalysis;
-// Definition of the static class description member.
-
-void SingleParticleAnalysis::Init() {
-
-  static ClassDocumentation<SingleParticleAnalysis> documentation
-    ("LEP SingleParticle analysis class",
-     "The LEP SingleParticle analysis uses data from \\cite{Abreu:1996na}.",
-     "%\\cite{Abreu:1996na}\n"
-     "\\bibitem{Abreu:1996na}\n"
-     "  P.~Abreu {\\it et al.}  [DELPHI Collaboration],\n"
-     "   ``Tuning and test of fragmentation models based on identified particles  and\n"
-     "  %precision event shape data,''\n"
-     "  Z.\\ Phys.\\  C {\\bf 73}, 11 (1996).\n"
-     "  %%CITATION = ZEPYA,C73,11;%%\n"
-     );
-
-  static Reference<SingleParticleAnalysis,EventShapes> interfaceEventShapes
-    ("EventShapes",
-     "Pointer to the object which calculates the event shapes",
-     &SingleParticleAnalysis::_shapes, false, false, true, false, false);
-}
-
-
-void SingleParticleAnalysis::dofinish() {
-  useMe();
-  AnalysisHandler::dofinish();
-  string fname = generator()->filename() + string("-") + name() + string(".top");
-  ofstream output(fname.c_str());
-  // normalize the data
-  _yT->normaliseToData();
-  _yS->normaliseToData();
-  _ptinT->normaliseToData();
-  _ptoutT->normaliseToData();
-  _ptinS->normaliseToData();
-  _ptoutS->normaliseToData();
-  _nch->prefactor(2.);
-  // chisq
-  double chisq,minfrac=0.05;
-  unsigned int npoint;
-  _yT->chiSquared(chisq,npoint,minfrac);
-  generator()->log() << "Chi Square = " << chisq << " for " << npoint 
-		     << " degrees of freedom for DELPHI rapidity wrt "
-		     << "thrust axis distribution or " 
-		     << chisq/npoint << " per degree of freedom \n";  
-  _yS->chiSquared(chisq,npoint,minfrac);
-  generator()->log() << "Chi Square = " << chisq << " for " << npoint 
-		     << " degrees of freedom for DELPHI rapidity wrt "
-		     << "sphericity axis distribution or " 
-		     << chisq/npoint << " per degree of freedom \n";  
-  _ptinT->chiSquared(chisq,npoint,minfrac);
-  generator()->log() << "Chi Square = " << chisq << " for " << npoint 
-		     << " degrees of freedom for DELPHI pT in the plane wrt "
-		     << "thrust axis distribution " 
-		     << chisq/npoint << " per degree of freedom \n";  
-  _ptoutT->chiSquared(chisq,npoint,minfrac);
-  generator()->log() << "Chi Square = " << chisq << " for " << npoint 
-		     << " degrees of freedom for DELPHI pT out of the plane wrt "
-		     << "thrust axis distribution " 
-		     << chisq/npoint << " per degree of freedom \n";  
-  _ptinS->chiSquared(chisq,npoint,minfrac);
-  generator()->log() << "Chi Square = " << chisq << " for " << npoint 
-		     << " degrees of freedom for DELPHI pT in the plane wrt "
-		     << "sphericity axis distribution " 
-		     << chisq/npoint << " per degree of freedom \n";  
-  _ptoutS->chiSquared(chisq,npoint,minfrac);
-  generator()->log() << "Chi Square = " << chisq << " for " << npoint 
-		     << " degrees of freedom for DELPHI pT out of the wrt "
-		     << "sphericity axis  plane distribution " 
-		     << chisq/npoint << " per degree of freedom \n";  
-  _nch->chiSquared(chisq,npoint,minfrac);
-  generator()->log() << "Chi Square = " << chisq << " for " << npoint 
-		     << " degrees of freedom for OPAL  number of charged "
-		     << "particles distribution or " 
-		     << chisq/npoint << " per degree of freedom \n";  
-  // output the plots
-  using namespace HistogramOptions;
-  _yT->topdrawOutput(output,Frame|Errorbars|Ylog,
-		     "RED",
-		     "Radidity with respect to the thrust axis compared to DELPHI data",
-		     "                                                                ",
-		     "1/NdN/dy0T1",
-		     "        X X",
-		     "y0T1",
-		     " X X");
-  _yS->topdrawOutput(output,Frame|Errorbars|Ylog,
-		     "RED",
-		     "Radidity with respect to the sphericity axis"
-		     " compared to DELPHI data",
-		     "                                            "
-		     "                        ",
-		     "1/NdN/dy0S1",
-		     "        X X",
-		     "y0S1",
-		     " X X");
-  _ptinT->topdrawOutput(output,Frame|Errorbars|Ylog,
-			"RED",
-			"p0T1 in the plane with respect to the thrust axis"
-			" compared to DELPHI data",
-			" X X                                             "
-			"                        ",
-			"1/NdN/dp0T,in1",
-			"        X    X",
-			"p0T,in1",
-			" X    X");
-  _ptoutT->topdrawOutput(output,Frame|Errorbars|Ylog,
-			"RED",
-			"p0T1 out of the plane with respect to the thrust axis"
-			" compared to DELPHI data",
-			" X X                                                 "
-			"                        ",
-			"1/NdN/dp0T,out1",
-			"        X     X",
-			"p0T,out1",
-			" X     X");
-  _ptinS->topdrawOutput(output,Frame|Errorbars|Ylog,
-			"RED",
-			"p0T1 in the plane with respect to the sphericity axis"
-			" compared to DELPHI data",
-			" X X                                                 "
-			"                        ",
-			"1/NdN/dp0T,in1",
-			"        X    X",
-			"p0T,in1",
-			" X    X");
-  _ptoutS->topdrawOutput(output,Frame|Errorbars|Ylog,
-			"RED",
-			"p0T1 out of the plane with respect to the sphericity axis"
-			" compared to DELPHI data",
-			" X X                                                     ",
-			"1/NdN/dp0T,out1",
-			"        X     X",
-			"p0T,out1",
-			" X     X");
-  _nch->topdrawOutput(output,Frame|Errorbars|Ylog,
-		      "RED",
-		      "Multiplcity of charged particles compared to OPAL data",
-		      "                                                      ",
-		      "1/SdS/dN0charged1",
-		      "  G G   X       X",
-		      "N0charged1",
-		      " X       X");
-}
-
-void SingleParticleAnalysis::doinitrun() {
-  AnalysisHandler::doinitrun();
-  vector<double> bins,data,error;
-  // rapidity with respect to thrust axis
-  double vals19[] = {0.000, 0.250, 0.500, 0.750, 1.000, 
-		     1.250, 1.500, 1.750, 2.000, 2.250, 
-		     2.500, 2.750, 3.000, 3.250, 3.500, 
-		     3.750, 4.000, 4.250, 4.500, 5.000, 
-		     5.500, 6.000}; 
-  double data19[]={5.9517,6.4291,6.6831,6.7763,6.7650,
-		   6.7230,6.6085,6.4346,6.1697,5.7692,
-		   5.1450,4.3511,3.4481,2.5852,1.7999,
-		   1.1669,0.7054,0.3997,0.15673,0.03374,
-		   0.00502};
-  double error19stat[]={0.0095,0.0095,0.0094,0.0089 ,0.0085,
-			0.0083,0.0081,0.0080,0.0078 ,0.0076,
-			0.0072,0.0066,0.0059,0.0051 ,0.0043,
-			0.0035,0.0027,0.0020,0.00089,0.00041,
-			0.00016};
-  double error19syst[]={0.5628 ,0.4417 ,0.3319 ,0.2429 ,0.1755 ,
-			0.1277 ,0.0939 ,0.0710 ,0.0617 ,0.0577 ,
-			0.0514 ,0.0435 ,0.0345 ,0.0259 ,0.0180 ,
-			0.0117 ,0.0071 ,0.0041 ,0.00177,0.00043,
-			0.00007};
-  double error19[21];
-  for(unsigned int ix=0;ix<21;++ix){error19[ix]=sqrt(sqr(error19stat[ix])+
-						     sqr(error19syst[ix]));}
-  bins  = vector<double>(vals19 ,vals19 +22);
-  data  = vector<double>(data19 ,data19 +21);
-  error = vector<double>(error19,error19+21);
-  _yT= new_ptr(Histogram(bins,data,error));
-  // rapidity with respect to the sphericity axis
-  double vals20[] = {0.000, 0.250, 0.500, 0.750, 1.000, 
-		     1.250, 1.500, 1.750, 2.000, 2.250, 
-		     2.500, 2.750, 3.000, 3.250, 3.500, 
-		     3.750, 4.000, 4.250, 4.500, 5.000, 
-		     5.500, 6.000};
-  double data20[]={6.5680 ,6.5901 ,6.6094 ,6.6152 ,6.5917 ,
-		   6.5817 ,6.5221 ,6.4097 ,6.1741 ,5.7542 ,
-		   5.1066 ,4.2721 ,3.3718 ,2.5185 ,1.7588 ,
-		   1.1589 ,0.7327 ,0.4402 ,0.1952 ,0.05574,
-		   0.01306};
-  double error20stat[]={0.0097   ,  0.0096   ,  0.0093   ,  0.0088   ,  0.0084   ,
-			0.0082   ,  0.0081   ,  0.0080   ,  0.0079   ,  0.0076   ,
-			0.0072   ,  0.0066   ,  0.0059   ,  0.0051   ,  0.0042   ,
-			0.0034   ,  0.0027   ,  0.0021   ,  0.0010   ,  0.00050  ,
-			0.00024};
-  double error20syst[]={0.5323 ,0.4246 ,0.3329 ,0.2554 ,0.1908 ,
-			0.1393 ,0.0983 ,0.0673 ,0.0617 ,0.0575 ,
-			0.0511 ,0.0427 ,0.0337 ,0.0252 ,0.0176 ,
-			0.0130 ,0.0105 ,0.0078 ,0.0046 ,0.00180,
-			0.00055};
-  double error20[21];
-  for(unsigned int ix=0;ix<21;++ix){error20[ix]=sqrt(sqr(error20stat[ix])+
-						     sqr(error20syst[ix]));}
-  bins  = vector<double>(vals20 ,vals20 +22);
-  data  = vector<double>(data20 ,data20 +21);
-  error = vector<double>(error20,error20+21);
-  _yS= new_ptr(Histogram(bins,data,error));
-  // pt_in with respect to thrust axis
-  double vals21[] = {0.000,  0.100,  0.200,  0.300,  0.400,  
-		     0.500,  0.600,  0.700,  0.800,  1.000,  
-		     1.200,  1.400,  1.600,  1.800,  2.000,  
-		     2.500,  3.000,  3.500,  4.000,  5.000,  
-		     6.000,  7.000,  8.000, 10.000, 12.000, 
-		     14.000}; 
-  double data21[]={46.663    ,39.823    ,29.351    ,21.034    ,15.156    ,
-		   11.149    , 8.348    , 6.430    , 4.5131   , 2.9522   ,
-		   2.0401   , 1.4597   , 1.0796   , 0.8155   , 0.5326   ,
-		   0.2988   , 0.18067  , 0.11471  , 0.06305  , 0.03040  ,
-		   0.01501  , 0.00858  , 0.00376  , 0.00123  , 0.00044};
-  double error21stat[]={0.037    ,0.033    ,0.028    ,0.024    ,0.020    ,
-			0.017    ,0.015    ,0.013    ,0.0076   ,0.0062   ,
-			0.0052   ,0.0044   ,0.0038   ,0.0033   ,0.0017   ,
-			0.0013   ,0.00099  ,0.00079  ,0.00042  ,0.00029  ,
-			0.00021  ,0.00016  ,0.00008  ,0.00004  ,0.00003};
-  double error21syst[]={1.758  ,1.092  ,0.608  ,0.350  ,0.219  ,
-			0.150  ,0.111  ,0.087  ,0.0624 ,0.0420 ,
-			0.0299 ,0.0222 ,0.0171 ,0.0136 ,0.0095 ,
-			0.0057 ,0.00383,0.00273,0.00171,0.00095,
-			0.00054,0.00035,0.00017,0.00006,0.00002};
-  double error21[25];
-  for(unsigned int ix=0;ix<25;++ix){error21[ix]=sqrt(sqr(error21stat[ix])+
-						     sqr(error21syst[ix]));}
-  bins  = vector<double>(vals21 ,vals21 +26);
-  data  = vector<double>(data21 ,data21 +25);
-  error = vector<double>(error21,error21+25);
-  _ptinT= new_ptr(Histogram(bins,data,error));
-  // pt_out  with respect to thrust axis
-  double vals22[] = {0.000, 0.100, 0.200, 0.300, 0.400, 
-		     0.500, 0.600, 0.700, 0.800, 1.000, 
-		     1.200, 1.400, 1.600, 1.800, 2.000, 
-		     2.500, 3.000, 3.500}; 
-  double data22[]={66.160    ,49.794    ,33.544    ,21.407    ,13.466    ,
-		   8.527    , 5.448    , 3.5845   , 2.0309   , 0.9959   ,
-		   0.5288   , 0.2987   , 0.1755   , 0.1086   , 0.05266  ,
-		   0.01885  , 0.00814};
-  double error22stat[]={0.043    ,0.037    ,0.030    ,0.024    ,0.019    ,
-			0.015    ,0.012    ,0.0098   ,0.0052   ,0.0037   ,
-			0.0028   ,0.0021   ,0.0016   ,0.0013   ,0.00058  ,
-			0.00035  ,0.00023};
-  double error22syst[]={1.822  ,1.149  ,0.678  ,0.397  ,0.239  ,
-			0.150  ,0.097  ,0.0658 ,0.0398 ,0.0216 ,
-			0.0127 ,0.0079 ,0.0051 ,0.0034 ,0.00189,
-			0.00080,0.00040};
-  double error22[17];
-  for(unsigned int ix=0;ix<17;++ix){error22[ix]=sqrt(sqr(error22stat[ix])+
-						     sqr(error22syst[ix]));}
-  bins  = vector<double>(vals22 ,vals22 +18);
-  data  = vector<double>(data22 ,data22 +17);
-  error = vector<double>(error22,error22+17);
-  _ptoutT= new_ptr(Histogram(bins,data,error));
-  // pt_in with respect to sphericity axis 
-  double vals23[] = {0.000,  0.100,  0.200,  0.300,  0.400,  
-		     0.500,  0.600,  0.700,  0.800,  1.000,  
-		     1.200,  1.400,  1.600,  1.800,  2.000,  
-		     2.500,  3.000,  3.500,  4.000,  5.000,  
-		     6.000,  7.000,  8.000, 10.000, 12.000,  
-		     14.000};
-  double data23[]={49.206    ,38.461    ,28.203    ,20.391    ,14.926    ,
-		   11.133    , 8.458    , 6.548    , 4.6706   , 3.0684   ,
-		   2.1299   , 1.5201   , 1.1143   , 0.8398   , 0.5334   ,
-		   0.2968   , 0.17343  , 0.10741  , 0.05615  , 0.02473  ,
-		   0.01157  , 0.00561  , 0.00204  , 0.00049  , 0.00012 };
-  double error23stat[]={0.038    ,0.033    ,0.027    ,0.023    ,0.020    ,
-			0.017    ,0.015    ,0.013    ,0.0078   ,0.0064   ,
-			0.0053   ,0.0045   ,0.0039   ,0.0034   ,0.0017   ,
-			0.0013   ,0.00098  ,0.00078  ,0.00040  ,0.00027  ,
-			0.00019  ,0.00013  ,0.00006  ,0.00003  ,0.00001};
-  double error23syst[]={1.672  ,0.984  ,0.571  ,0.349  ,0.233  ,
-			0.168  ,0.129  ,0.102  ,0.0747 ,0.0504 ,
-			0.0359 ,0.0264 ,0.0201 ,0.0159 ,0.0107 ,
-			0.0065 ,0.00418,0.00292,0.00176,0.00089,
-			0.00048,0.00026,0.00010,0.00002,0.00001};
-  double error23[25];
-  for(unsigned int ix=0;ix<25;++ix){error23[ix]=sqrt(sqr(error23stat[ix])+
-						     sqr(error23syst[ix]));}
-  bins  = vector<double>(vals23 ,vals23 +26);
-  data  = vector<double>(data23 ,data23 +25);
-  error = vector<double>(error23,error23+25);
-  _ptinS= new_ptr(Histogram(bins,data,error));
-  // pt_out with respect to sphericity axis 
-  double vals24[] = {0.000, 0.100, 0.200, 0.300, 0.400, 
-		     0.500, 0.600, 0.700, 0.800, 1.000, 
-		     1.200, 1.400, 1.600, 1.800, 2.000, 
-		     2.500, 3.000, 3.500};
-  double data24[]={66.825    ,50.556    ,34.241    ,21.708    ,13.481    ,
-		   8.314    , 5.180    , 3.2986   , 1.7559   , 0.8187   ,
-		   0.4064   , 0.2175   , 0.1232   , 0.0712   , 0.03217  ,
-		   0.01112  , 0.00387};
-  double error24stat[]={0.043    ,0.037    ,0.030    ,0.024    ,0.019    ,
-			0.015    ,0.012    ,0.0094   ,0.0049   ,0.0034   ,
-			0.0024   ,0.0018   ,0.0014   ,0.0011   ,0.00047  ,
-			0.00029  ,0.00017};
-  double error24syst[]={1.506  ,1.102  ,0.726  ,0.451  ,0.277  ,
-			0.170  ,0.106  ,0.0679 ,0.0370 ,0.0181 ,
-			0.0096 ,0.0055 ,0.0034 ,0.0022 ,0.00115,
-			0.00050,0.00021};
-  double error24[17];
-  for(unsigned int ix=0;ix<17;++ix){error24[ix]=sqrt(sqr(error24stat[ix])+
-						     sqr(error24syst[ix]));}
-  bins  = vector<double>(vals24 ,vals24 +18);
-  data  = vector<double>(data24 ,data24 +17);
-  error = vector<double>(error24,error24+17);
-  _ptoutS= new_ptr(Histogram(bins,data,error));
-  // number of charged particles
-  double vals25[]={01., 3., 5., 7., 9.,
-		   11.,13.,15.,17.,19.,
-		   21.,23.,25.,27.,29.,
-		   31.,33.,35.,37.,39.,
-		   41.,43.,45.,47.,49.,
-		   51.,53.,55.};
-  double data25[]={0.0010 ,0.016  ,0.16   ,0.68   , 2.08  ,
-		   4.69  , 8.00  ,10.79  ,12.61  ,12.85  ,
-		   11.83  , 9.99  , 7.85  , 5.95, 4.35  ,
-		   2.97  , 2.02  , 1.29  , 0.81  , 0.47  ,
-		   0.26  , 0.17  , 0.089 , 0.042 , 0.025 ,
-		   0.011 , 0.004};
-  double error25stat[]={0.0010  ,0.020   ,0.03   ,0.05   , 0.08  ,
-			0.12  , 0.16  , 0.18  , 0.19  , 0.20  ,
-			0.19  , 0.17  , 0.15  , 0.13  , 0.11  ,
-			0.09  , 0.08  , 0.06  , 0.05  , 0.04  ,
-			0.03  , 0.02  , 0.016 , 0.011 , 0.009 ,
-			0.007 , 0.004};
-  double error25syst[]={0.0,0.0,0.10, 0.18,  0.19,
-			0.23,  0.19,  0.40,  0.24,  0.34,
-			0.20,  0.35,  0.14,  0.17,  0.17,
-			0.09,  0.09,  0.11,  0.06,  0.05,
-			0.04,  0.05, 0.038, 0.020,  0.015,
-			0.007,  0.004};
-  double error25[27];
-  for(unsigned int ix=0;ix<27;++ix)
-    {
-      error25[ix]=sqrt(sqr(error25stat[ix])+
-		       sqr(error25syst[ix]))/100.;
-      data25[ix]/=100.;
-    }
-  bins  = vector<double>(vals25 ,vals25 +28);
-  data  = vector<double>(data25 ,data25 +27);
-  error = vector<double>(error25,error25+27);
-  _nch=new_ptr(Histogram(bins,data,error));
-}
diff --git a/Analysis/SingleParticleAnalysis.h b/Analysis/SingleParticleAnalysis.h
deleted file mode 100644
--- a/Analysis/SingleParticleAnalysis.h
+++ /dev/null
@@ -1,198 +0,0 @@
-// -*- C++ -*-
-//
-// SingleParticleAnalysis.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_SingleParticleAnalysis_H
-#define HERWIG_SingleParticleAnalysis_H
-//
-// This is the declaration of the SingleParticleAnalysis class.
-//
-
-#include "ThePEG/Repository/CurrentGenerator.h"
-#include "ThePEG/Handlers/AnalysisHandler.h"
-#include "ThePEG/Repository/EventGenerator.h"
-#include "Herwig/Utilities/Histogram.h"
-#include "EventShapes.h"
-
-namespace Herwig {
-
-using namespace ThePEG;
-
-/** \ingroup Analysis
- * The SingleParticleAnalysis class performs the analysis for
- * single particle variables and is intended as a slave handler for the 
- *  EventShapesMasterAnalysis class.
- *
- * @see \ref SingleParticleAnalysisInterfaces "The interfaces"
- * defined for SingleParticleAnalysis.
- */
-class SingleParticleAnalysis: public AnalysisHandler {
-
-public:
-
-  /** @name Virtual functions required by the AnalysisHandler class. */
-  //@{
-
-  /**
-   * Analyze the given vector of particles. The default version calls
-   * analyze(tPPtr) for each of the particles.
-   * @param particles the vector of pointers to particles to be analyzed
-   */
-  virtual void analyze(const tPVector & particles);
-  //@}
-
-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 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. Called in the run phase just before
-   * a run begins.
-   */
-  virtual void doinitrun();
-
-  /**
-   * Finalize this object. Called in the run phase just after a
-   * run has ended. Used eg. to write out statistics.
-   */
-  virtual void dofinish();
- //@}
-
-private:
-
-  /**
-   * The static object used to initialize the description of this class.
-   * Indicates that this is a concrete class with persistent data.
-   */
-  static ClassDescription<SingleParticleAnalysis> initSingleParticleAnalysis;
-
-  /**
-   * The assignment operator is private and must never be called.
-   * In fact, it should not even be implemented.
-   */
-  SingleParticleAnalysis & operator=(const SingleParticleAnalysis &);
-
-private:
-
-  /**
-   * Histogram for the rapidity distribution with respect to the thrust axis
-   */
-  HistogramPtr _yT;
-
-  /**
-   * Histogram for the rapidity distribution with respect to the sphericity axis
-   */
-  HistogramPtr _yS;
-
-  /**
-   * Histogram for the \f$p_{T,in}\f$ distribution with respect to the thrust axis
-   */
-  HistogramPtr _ptinT;
-
-  /**
-   * Histogram for the \f$p_{T,out}\f$ distribution with respect to the thrust axis
-   */
-  HistogramPtr _ptoutT;
-
-  /**
-   * Histogram for the \f$p_{S,in}\f$ distribution with respect to the sphericity axis
-   */
-  HistogramPtr _ptinS;
-
-  /**
-   * Histogram for the \f$p_{S,out}\f$ distribution with respect to the sphericity axis
-   */
-  HistogramPtr _ptoutS;
-
-  /**
-   * Histogram for the number of charged particles
-   */
-  HistogramPtr _nch;
-
-  /**
-   *  Object which calculates the event shapes
-   */
-  EventShapesPtr _shapes;
-};
-
-}
-
-#include "ThePEG/Utilities/ClassTraits.h"
-
-namespace ThePEG {
-
-/** @cond TRAITSPECIALIZATIONS */
-
-/** This template specialization informs ThePEG about the
- *  base classes of SingleParticleAnalysis. */
-template <>
-struct BaseClassTrait<Herwig::SingleParticleAnalysis,1> {
-  /** Typedef of the first base class of SingleParticleAnalysis. */
-  typedef AnalysisHandler NthBase;
-};
-
-/** This template specialization informs ThePEG about the name of
- *  the SingleParticleAnalysis class and the shared object where it is defined. */
-template <>
-struct ClassTraits<Herwig::SingleParticleAnalysis>
-  : public ClassTraitsBase<Herwig::SingleParticleAnalysis> {
-  /** Return a platform-independent class name */
-  static string className() { return "Herwig::SingleParticleAnalysis"; }
-  /** Return the name(s) of the shared library (or libraries) be loaded to get
-   *  access to the SingleParticleAnalysis class and any other class on which it depends
-   *  (except the base class). */
-  static string library() { return "HwAnalysis.so HwLEPAnalysis.so"; }
-};
-
-/** @endcond */
-
-}
-
-#endif /* HERWIG_SingleParticleAnalysis_H */
diff --git a/Analysis/Wpt.cc b/Analysis/Wpt.cc
deleted file mode 100755
--- a/Analysis/Wpt.cc
+++ /dev/null
@@ -1,147 +0,0 @@
-// -*- C++ -*-
-//
-// This is the implementation of the non-inlined, non-templated member
-// functions of the Wpt class.
-//
-
-#include "Wpt.h"
-#include "ThePEG/Interface/Reference.h"
-#include "ThePEG/Interface/Parameter.h"
-#include "ThePEG/EventRecord/Particle.h"
-#include "ThePEG/EventRecord/Event.h"
-#include "ThePEG/PDT/EnumParticles.h"
-#include "ThePEG/PDT/ParticleData.h"
-#include "ThePEG/PDF/BeamParticleData.h"
-#include "ThePEG/Interface/ClassDocumentation.h"
-#include "ThePEG/Persistency/PersistentOStream.h"
-#include "ThePEG/Persistency/PersistentIStream.h"
-#include "Herwig/Utilities/Histogram.h"
-
-
-using namespace Herwig;
-using namespace ThePEG;
-using namespace std;
-
-
-inline IBPtr Wpt::clone() const {
-  return new_ptr(*this);
-}
-
-inline IBPtr Wpt::fullclone() const {
-  return new_ptr(*this);
-}
-
-
-void Wpt::doinitrun() {
-  //Z pt run I CDF data from hep-ex:9803003
-  vector<double> bins, data, error;
-  //23 entries
-  double vals1[] = { 0.,  2.,  4.,  6.,  8.,  10., 12., 14.,  16.,  18.,  20., 25.,
-                     30., 35., 40., 50., 60., 70., 80., 100., 120., 160., 200. };
-
-  //22 entries
-  double data1[] = { 0.47348E-01, 0.89142E-01, 0.74150E-01, 0.57847E-01, 0.44721E-01,
-		     0.33586E-01, 0.27560E-01, 0.20728E-01, 0.16330E-01, 0.13269E-01, 
-		     0.95329E-02, 0.60349E-02, 0.40997E-02, 0.29612E-02, 0.17100E-02, 
-		     0.78358E-03, 0.49786E-03, 0.32469E-03, 0.13550E-03, 0.36365E-04, 
-		     0.19048E-04, 0.33335E-05 };
-  //22 entries
-  double error1[] = {  0.50183E-02, 0.10305E-01, 0.46570E-02, 
-		       0.46999E-02, 0.35607E-02, 0.34406E-02, 0.22816E-02, 
-		       0.21171E-02, 0.15093E-02, 0.11812E-02, 0.71726E-03,
-		       0.58489E-03, 0.46567E-03, 0.35365E-03, 0.20567E-03,
-		       0.14391E-03, 0.14135E-03, 0.11974E-03, 0.46951E-04, 
-		       0.14776E-04, 0.79826E-05, 0.30431E-05 };
-
-
- /*
- 
-  //data normalised to one
-  double data1[] = { 0.0374049,	0.0908118,	0.092412,	0.0742096,	0.0530069,	
-		     0.0318041,	0.0272035,	0.0168022,	0.0136018,	0.0124016,	
-		     0.00743097,	0.00429056,	0.00245032,	0.00167022,	0.000875114,	
-		     0.000333043,	0.000186024,	5.20068e-05,	2.50033e-05,	1.10014e-05 };
-
-  double error1[] = { 0.000660086,	0.000950124,	0.000750098,	0.000580075,	0.000420055,	
-		      0.000300039,	0.000260034,	0.000190025,	0.00015002,	0.00015002,	
-		      8.90116e-05,	6.10079e-05,	4.20055e-05,	3.30043e-05,	2.3203e-05,	
-		      1.5502e-05,	7.50098e-06,	3.80049e-06,	1.30017e-06,	5.00065e-07 };
-  */
-  bins  = vector<double>(vals1 ,vals1 +23);
-  data  = vector<double>(data1 ,data1 +22);
-  error = vector<double>(error1,error1+22);
-  
-  _hpt = new_ptr( Histogram( bins, data, error ) ); 
-
-  
-}
-
-void Wpt::persistentOutput(PersistentOStream & ) const {
-}
-
-void Wpt::persistentInput(PersistentIStream & , int) {
-}
-
-ClassDescription<Wpt> Wpt::initWpt;
-// Definition of the static class description member.
-
-void Wpt::Init() {
-
-  static ClassDocumentation<Wpt> documentation
-    ("There is no documentation for the Wpt class");
-
-}
-
-void Wpt::dofinish() {
- 
-  AnalysisHandler::dofinish();
-  string fname = generator()->filename() + string("-") + name() + string(".top");
-  ofstream outfile(fname.c_str());
-  using namespace HistogramOptions;
-
-  _hpt->topdrawOutput(outfile,Frame|Errorbars|Ylog,
-		      "RED",
-		      "pT of W compared to run I data",
-		      "                           ",
-		      "1/SdS/dpT",
-		      "  G G    ",
-		      "pT",
-		      "   ");
-
-  outfile.close();
-}
-
-void Wpt::analyze(tEventPtr event, long , int loop, int state) {
-  if ( loop > 0 || state != 0 || !event ) return;
-  transform(event);
-  // find the outgoing particles in the hard process
-  ParticleVector outgoing;
-  event->selectFinalState(back_inserter(outgoing));
-  ParticleVector Wdecay;
-  // search for electrons and positions from Z/gamma
-  for( unsigned int ix = 0; ix<outgoing.size();++ix) {
-    int id=outgoing[ix]->id();
-    //check children are 1st gen leptons
-    if(abs(id)==11 || abs(id)==12) {
-      PPtr part=outgoing[ix];
-      do {
-        part=part->parents()[0];
-      }
-      while (part->id()==id);
-      if(abs(part->id())==24) 
-        Wdecay.push_back(outgoing[ix]);
-    }
-  }
-  if(Wdecay.size()!=2) return;
-  Lorentz5Momentum pW=Wdecay[0]->momentum()+Wdecay[1]->momentum();
-  pW.rescaleMass();
-  Energy pt=pW.perp();
-
-  *_hpt += pt/GeV;
-  // remove leptons from outgoing particles
-  for(unsigned int ix=0;ix<Wdecay.size();++ix) {
-    ParticleVector::iterator pit=find(outgoing.begin(),outgoing.end(),Wdecay[ix]);
-    if(pit!=outgoing.end()) outgoing.erase(pit);
-  }
-}
-
diff --git a/Analysis/Wpt.h b/Analysis/Wpt.h
deleted file mode 100644
--- a/Analysis/Wpt.h
+++ /dev/null
@@ -1,173 +0,0 @@
-// -*- C++ -*-
-#ifndef HERWIG_Wpt_H
-#define HERWIG_Wpt_H
-//
-// This is the declaration of the Wpt class.
-//
-#include "ThePEG/Repository/CurrentGenerator.h"
-#include "ThePEG/Repository/EventGenerator.h"
-#include "ThePEG/Handlers/AnalysisHandler.h"
-#include "Herwig/Utilities/Histogram.h"
-
-
-namespace Herwig {
-  
-  using namespace ThePEG;
-  /**
-   * Here is the documentation of the Wpt class.
-   *
-   * @see \ref WptInterfaces "The interfaces"
-   * defined for Wpt.
-   */
-  class Wpt: public AnalysisHandler {
-    
-  public:
-
-  /** @name Standard constructors and destructors. */
-  //@{
-  /**
-   * The default constructor.
-   */
-    inline Wpt() {}
-
-  public:
-    
-    /** @name Virtual functions required by the AnalysisHandler class. */
-    //@{
-    /**
-     * Analyze a given Event. Note that a fully generated event
-     * may be presented several times, if it has been manipulated in
-     * between. The default version of this function will call transform
-     * to make a lorentz transformation of the whole event, then extract
-     * all final state particles and call analyze(tPVector) of this
-     * analysis object and those of all associated analysis objects. The
-     * default version will not, however, do anything on events which
-     * have not been fully generated, or have been manipulated in any
-     * way.
-     * @param event pointer to the Event to be analyzed.
-     * @param ieve the event number.
-     * @param loop the number of times this event has been presented.
-     * If negative the event is now fully generated.
-     * @param state a number different from zero if the event has been
-     * manipulated in some way since it was last presented.
-     */
-    virtual void analyze(tEventPtr event, long ieve, int loop, int state);
-    
-
-  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();
-    
-    /**
-     * Initialize this object. Called in the run phase just before
-     * a run begins.
-     */
-    virtual void doinitrun();
-    
-    /**
-     * Finalize this object. Called in the run phase just after a
-     * run has ended. Used eg. to write out statistics.
-     */
-    virtual void dofinish();
-    
-  protected:
-    
-     /** @name Clone Methods. */
-  //@{
-  /**
-   * Make a simple clone of this object.
-   * @return a pointer to the new object.
-   */
-  inline 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.
-   */
-  inline virtual IBPtr fullclone() const;
-  //@}
-
-  
-  private:
-
-    /**
-     * \f$p_T\f$ histogram
-     */
-    HistogramPtr  _hpt;
-  
-    /**
-     * The static object used to initialize the description of this class.
-     * Indicates that this is a concrete class with persistent data.
-     */
-    static ClassDescription<Wpt> initWpt;
-    
-    /**
-     * The assignment operator is private and must never be called.
-     * In fact, it should not even be implemented.
-     */
-    Wpt & operator=(const Wpt &);
-    
-  };
-  
-}
-
-#include "ThePEG/Utilities/ClassTraits.h"
-
-namespace ThePEG {
-  
-  /** @cond TRAITSPECIALIZATIONS */
-  
-  /** This template specialization informs ThePEG about the
-   *  base classes of Wpt. */
-  template <>
- struct BaseClassTrait<Herwig::Wpt,1> {
-    /** Typedef of the first base class of Wpt. */
-    typedef AnalysisHandler NthBase;
-  };
-
-  /** This template specialization informs ThePEG about the name of
-   *  the Wpt class and the shared object where it is defined. */
-  template <>
-  struct ClassTraits<Herwig::Wpt>
-    : public ClassTraitsBase<Herwig::Wpt> {
-    /** Return a platform-independent class name */
-    static string className() { return "Herwig::Wpt"; }
-    /**
-     * The name of a file containing the dynamic library where the class
-     * Wpt is implemented. It may also include several, space-separated,
-     * libraries if the class Wpt depends on other classes (base classes
-     * excepted). In this case the listed libraries will be dynamically
-     * linked in the order they are specified.
-     */
-    static string library() { return "HwTevatronAnalysis.so"; }
-  };
-  
-  /** @endcond */
-
-}
-
-#endif /* HERWIG_Wpt_H */
-
-
diff --git a/Analysis/ZpTRun1.cc b/Analysis/ZpTRun1.cc
deleted file mode 100755
--- a/Analysis/ZpTRun1.cc
+++ /dev/null
@@ -1,138 +0,0 @@
-// -*- C++ -*-
-//
-// This is the implementation of the non-inlined, non-templated member
-// functions of the ZpTRun1 class.
-//
-
-#include "ZpTRun1.h"
-#include "ThePEG/Interface/Reference.h"
-#include "ThePEG/Interface/Parameter.h"
-#include "ThePEG/EventRecord/Particle.h"
-#include "ThePEG/EventRecord/Event.h"
-#include "ThePEG/PDT/EnumParticles.h"
-#include "ThePEG/PDT/ParticleData.h"
-#include "ThePEG/PDF/BeamParticleData.h"
-#include "ThePEG/Interface/ClassDocumentation.h"
-#include "ThePEG/Persistency/PersistentOStream.h"
-#include "ThePEG/Persistency/PersistentIStream.h"
-#include "Herwig/Utilities/Histogram.h"
-
-
-using namespace Herwig;
-using namespace ThePEG;
-using namespace std;
-
-
-inline IBPtr ZpTRun1::clone() const {
-  return new_ptr(*this);
-}
-
-inline IBPtr ZpTRun1::fullclone() const {
-  return new_ptr(*this);
-}
-
-
-void ZpTRun1::doinitrun() {
-  //Z pt run I CDF data from
-  vector<double> bins, data, error;
-  //50 data points
-
-  double vals1[] = { 0.0, 0.5,  1.0, 1.5, 2.0, 2.5, 3.0, 3.5, 4.0, 4.5, 5.0,  
-		     5.5, 6.0,  6.5, 7.0, 7.5, 8.0, 8.5, 9.0, 9.5, 10., 10.5, 
-		     11., 11.5, 12., 13., 14., 15., 16., 17., 18., 19., 20., 
-		     22., 24.,  26., 28., 30., 34., 38., 42., 46., 50., 60., 
-		     70., 80.,  90., 100.,125.,150.,200., };
-
-  double data1[] = {3.35, 10.1, 14.8, 19.4, 20.2, 23.6, 23.6, 23, 19.9, 19.3, 
-		    17.9, 18, 14.6, 14.5, 13.5, 13.7, 11.9, 10.4, 11.1, 9.56, 
-		    8.35, 7.82, 8.18, 7.48, 7.21, 6.05, 4.73, 5.21, 4.46, 
-		    4.28, 3.51, 3.01, 2.63, 1.82, 1.85, 1.58, 1.41, 1.02, 
-		    0.678, 0.644, 0.434, 0.394, 0.21, 0.107, 0.091, 0.045, 
-		    0.0351, 0.0181, 0.00711, 0.000974 };
-
-  double error1[] = { 0.54, 1, 1.2, 1.4, 1.4, 1.5, 1.4, 1.4, 1.3, 1.2, 1.2, 
-		      1.2, 1, 1, 1, 1, 0.9, 0.9, 0.9, 0.82, 0.76, 0.74, 0.76, 
-		      0.72, 0.53, 0.47, 0.41, 0.44, 0.4, 0.39, 0.35, 0.33, 
-		      0.22, 0.18, 0.17, 0.17, 0.16, 0.1, 0.079, 0.076, 0.062, 
-		      0.059, 0.027, 0.019, 0.0175, 0.0122, 0.0107, 0.0048, 
-		      0.00297, 0.000756 };
-
-  bins  = vector<double>(vals1 ,vals1 +51);
-  data  = vector<double>(data1 ,data1 +50);
-  error = vector<double>(error1,error1+50);
-  
-  _hpt = new_ptr( Histogram( bins, data, error ) ); 
-
-  
-}
-
-void ZpTRun1::persistentOutput(PersistentOStream &) const {
-}
-
-void ZpTRun1::persistentInput(PersistentIStream &, int) {
-}
-
-ClassDescription<ZpTRun1> ZpTRun1::initZpTRun1;
-// Definition of the static class description member.
-
-void ZpTRun1::Init() {
-
-  static ClassDocumentation<ZpTRun1> documentation
-    ("There is no documentation for the ZpTRun1 class");
-
-}
-
-void ZpTRun1::dofinish() {
- 
-  AnalysisHandler::dofinish();
-  string fname = generator()->filename() + string("-") + name() + string(".top");
-  ofstream outfile(fname.c_str());
-  using namespace HistogramOptions;
-
-  _hpt->normaliseToData();
- 
-  _hpt->topdrawOutput(outfile,Frame|Errorbars|Ylog,
-		      "RED",
-		      "pT of Z ( mass 60 GeV to 116 GeV ) compared to CDF run I data",
-		      "                           ",
-		      "1/SdS/dpT",
-		      "  G G       ",
-		      "pT",
-		      "   ");
-
-  outfile.close();
-}
-
-void ZpTRun1::analyze(tEventPtr event, long , int loop, int state) {
-  if ( loop > 0 || state != 0 || !event ) return;
-  transform(event);
-  // find the outgoing particles in the hard process
-  ParticleVector outgoing;
-  event->selectFinalState(back_inserter(outgoing));
-  ParticleVector Zdecay;
-  // search for electrons and positions from Z/gamma
-  for(unsigned int ix=0;ix<outgoing.size();++ix) {
-    int id=outgoing[ix]->id();
-    if(abs(id)==ParticleID::eminus) {
-      PPtr part=outgoing[ix];
-      do {
-	part=part->parents()[0];
-      }
-      while (part->id()==id);
-      if(part->id()==ParticleID::gamma||part->id()==ParticleID::Z0) 
-	Zdecay.push_back(outgoing[ix]);
-    }
-  }
-  if(Zdecay.size()!=2) return;
-  Lorentz5Momentum pZ=Zdecay[0]->momentum()+Zdecay[1]->momentum();
-  pZ.rescaleMass();
-  if(pZ.mass()<66.*GeV||pZ.mass()>116.*GeV) return;
-  Energy pt=pZ.perp();
-  *_hpt += pt/GeV;
-
-  // remove leptons from outgoing particles
-  for(unsigned int ix=0;ix<Zdecay.size();++ix) {
-    ParticleVector::iterator pit=find(outgoing.begin(),outgoing.end(),Zdecay[ix]);
-    if(pit!=outgoing.end()) outgoing.erase(pit);
-  }
-}
diff --git a/Analysis/ZpTRun1.h b/Analysis/ZpTRun1.h
deleted file mode 100644
--- a/Analysis/ZpTRun1.h
+++ /dev/null
@@ -1,173 +0,0 @@
-// -*- C++ -*-
-#ifndef HERWIG_ZpTRun1_H
-#define HERWIG_ZpTRun1_H
-//
-// This is the declaration of the ZpTRun1 class.
-//
-#include "ThePEG/Repository/CurrentGenerator.h"
-#include "ThePEG/Repository/EventGenerator.h"
-#include "ThePEG/Handlers/AnalysisHandler.h"
-#include "Herwig/Utilities/Histogram.h"
-
-
-namespace Herwig {
-  
-  using namespace ThePEG;
-  /**
-   * Here is the documentation of the ZpTRun1 class.
-   *
-   * @see \ref ZpTRun1Interfaces "The interfaces"
-   * defined for ZpTRun1.
-   */
-  class ZpTRun1: public AnalysisHandler {
-    
-  public:
-
-  /** @name Standard constructors and destructors. */
-  //@{
-  /**
-   * The default constructor.
-   */
-    inline ZpTRun1() {}
-
-  public:
-    
-    /** @name Virtual functions required by the AnalysisHandler class. */
-    //@{
-    /**
-     * Analyze a given Event. Note that a fully generated event
-     * may be presented several times, if it has been manipulated in
-     * between. The default version of this function will call transform
-     * to make a lorentz transformation of the whole event, then extract
-     * all final state particles and call analyze(tPVector) of this
-     * analysis object and those of all associated analysis objects. The
-     * default version will not, however, do anything on events which
-     * have not been fully generated, or have been manipulated in any
-     * way.
-     * @param event pointer to the Event to be analyzed.
-     * @param ieve the event number.
-     * @param loop the number of times this event has been presented.
-     * If negative the event is now fully generated.
-     * @param state a number different from zero if the event has been
-     * manipulated in some way since it was last presented.
-     */
-    virtual void analyze(tEventPtr event, long ieve, int loop, int state);
-    
-
-  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();
-    
-    /**
-     * Initialize this object. Called in the run phase just before
-     * a run begins.
-     */
-    virtual void doinitrun();
-    
-    /**
-     * Finalize this object. Called in the run phase just after a
-     * run has ended. Used eg. to write out statistics.
-     */
-    virtual void dofinish();
-    
-  protected:
-    
-     /** @name Clone Methods. */
-  //@{
-  /**
-   * Make a simple clone of this object.
-   * @return a pointer to the new object.
-   */
-  inline 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.
-   */
-  inline virtual IBPtr fullclone() const;
-  //@}
-
-  
-  private:
-    
-    /**
-     * \f$p_T\f$ histogram
-     */
-    HistogramPtr  _hpt;
-  
-    /**
-     * The static object used to initialize the description of this class.
-     * Indicates that this is a concrete class with persistent data.
-     */
-    static ClassDescription<ZpTRun1> initZpTRun1;
-    
-    /**
-     * The assignment operator is private and must never be called.
-     * In fact, it should not even be implemented.
-     */
-    ZpTRun1 & operator=(const ZpTRun1 &);
-    
-  };
-  
-}
-
-#include "ThePEG/Utilities/ClassTraits.h"
-
-namespace ThePEG {
-  
-  /** @cond TRAITSPECIALIZATIONS */
-  
-  /** This template specialization informs ThePEG about the
-   *  base classes of ZpTRun1. */
-  template <>
- struct BaseClassTrait<Herwig::ZpTRun1,1> {
-    /** Typedef of the first base class of ZpTRun1. */
-    typedef AnalysisHandler NthBase;
-  };
-
-  /** This template specialization informs ThePEG about the name of
-   *  the ZpTRun1 class and the shared object where it is defined. */
-  template <>
-  struct ClassTraits<Herwig::ZpTRun1>
-    : public ClassTraitsBase<Herwig::ZpTRun1> {
-    /** Return a platform-independent class name */
-    static string className() { return "Herwig::ZpTRun1"; }
-    /**
-     * The name of a file containing the dynamic library where the class
-     * ZpTRun1 is implemented. It may also include several, space-separated,
-     * libraries if the class ZpTRun1 depends on other classes (base classes
-     * excepted). In this case the listed libraries will be dynamically
-     * linked in the order they are specified.
-     */
-    static string library() { return "HwTevatronAnalysis.so"; }
-  };
-  
-  /** @endcond */
-
-}
-
-#endif /* HERWIG_ZpTRun1_H */
-
-
diff --git a/Analysis/ZpTRun2.cc b/Analysis/ZpTRun2.cc
deleted file mode 100644
--- a/Analysis/ZpTRun2.cc
+++ /dev/null
@@ -1,103 +0,0 @@
-// -*- C++ -*-
-//
-// This is the implementation of the non-inlined, non-templated member
-// functions of the ZpTRun2 class.
-//
-
-#include "ZpTRun2.h"
-#include "ThePEG/Interface/ClassDocumentation.h"
-#include "ThePEG/Repository/EventGenerator.h"
-#include "ThePEG/EventRecord/Event.h"
-#include "ThePEG/PDT/EnumParticles.h"
-
-using namespace Herwig;
-
-inline IBPtr ZpTRun2::clone() const {
-  return new_ptr(*this);
-}
-
-inline IBPtr ZpTRun2::fullclone() const {
-  return new_ptr(*this);
-}
-
-void ZpTRun2::analyze(tEventPtr event, long , int loop, int state) {
-  if ( loop > 0 || state != 0 || !event ) return;
-  transform(event);
-  tParticleVector outgoing = event->primaryCollision()->step(1)->getFinalState();
-  ParticleVector Zdecay;
-  // search for electrons and positions from Z/gamma
-  for(unsigned int ix=0;ix<outgoing.size();++ix) {
-    int id=outgoing[ix]->id();
-    if(abs(id)==ParticleID::eminus) {
-      PPtr part=outgoing[ix];
-      do {
-	part=part->parents()[0];
-      }
-      while (part->id()==id);
-      if(part->id()==ParticleID::gamma||part->id()==ParticleID::Z0) 
-	Zdecay.push_back(outgoing[ix]);
-    }
-  }
-  if(Zdecay.size()!=2) return;
-  Lorentz5Momentum pZ=Zdecay[0]->momentum()+Zdecay[1]->momentum();
-  pZ.rescaleMass();
-  if(pZ.mass()<40.*GeV||pZ.mass()>200.*GeV) return;
-  Energy pT = pZ.perp();
-  if(pT>260.*GeV) return;
-  *_pt += pT/GeV;
-}
-
-NoPIOClassDescription<ZpTRun2> ZpTRun2::initZpTRun2;
-// Definition of the static class description member.
-
-void ZpTRun2::Init() {
-
-  static ClassDocumentation<ZpTRun2> documentation
-    ("There is no documentation for the ZpTRun2 class");
-
-}
-
-void ZpTRun2::dofinish() {
-  AnalysisHandler::dofinish();
-  string fname = generator()->filename() + string("-") + name() + string(".top");
-  ofstream output(fname.c_str());
-  using namespace HistogramOptions;
-  _pt->topdrawOutput(output,Frame|Errorbars|Ylog,"RED",
-		     "pt of Z (mass 40 GeV to 200 GeV) compared to D0 run II data", 
-		     "                           ",
-		     "1/SdS/dpT",
-		     "  G G       ",
-		     "pT",
-		     "   ");
-}
-
-void ZpTRun2::doinitrun() {
-  AnalysisHandler::doinitrun();
-  //data from hep-ex 07120803
-  //normalised to one
-  double abins[] ={ 0.0 , 2.5, 5.0, 7.5,10.0,
-		    12.5,15.0,17.5,20.0,22.5,
-		    25.0,27.5,30.0,40.0,50.0,
-		    60.0,70.0,80.0,90.0,100.0,
-		    140.0,180.0,220.0,260.0};
-  
-  double adata[] = { 0.0533419,	0.0810158,	0.0634688,	0.0444179,
-		     0.0314839,	0.0246659,	0.01865,	0.014238,
-		     0.010929,	0.00942508,	0.00691838,	0.00551469,
-		     0.00391039,	0.00210559,	0.0011029,	
-		     0.000731948,	0.000421119,	0.000250669,	
-		     0.00016043,	6.01598e-05,	1.1029e-05,	
-		     3.00799e-06,	7.11888e-07 };
-
-  double aerror[] = {0.00273679,	0.00225319,	0.0017852,	
-		     0.0014251, 0.0011344,	0.000924408,	0.000783108,	0.000708988,
-		     0.000501329,	0.000448409,	0.000361519,	0.000317069,
-		     0.0001418,	9.24408e-05,	5.84649e-05,	4.48409e-05,
-		     3.61519e-05,	2.24199e-05,	1.8838e-05,	5.84649e-06,
-		     2.12459e-06,	1.0468e-06,	6.14578e-07 };
-
-  vector<double>  bins(abins ,abins +24);
-  vector<double>  data(adata ,adata +23);
-  vector<double> error(aerror,aerror+23);
-  _pt = new_ptr(Histogram(bins,data,error));
-}
diff --git a/Analysis/ZpTRun2.h b/Analysis/ZpTRun2.h
deleted file mode 100644
--- a/Analysis/ZpTRun2.h
+++ /dev/null
@@ -1,151 +0,0 @@
-// -*- C++ -*-
-#ifndef HERWIG_ZpTRun2_H
-#define HERWIG_ZpTRun2_H
-//
-// This is the declaration of the ZpTRun2 class.
-//
-
-#include "ThePEG/Handlers/AnalysisHandler.h"
-#include "Herwig/Utilities/Histogram.h"
-
-namespace Herwig {
-
-using namespace ThePEG;
-
-/**
- * Here is the documentation of the ZpTRun2 class.
- *
- * @see \ref ZpTRun2Interfaces "The interfaces"
- * defined for ZpTRun2.
- */
-class ZpTRun2: public AnalysisHandler {
-
-public:
-
-  /** @name Virtual functions required by the AnalysisHandler class. */
-  //@{
-  /**
-   * Analyze a given Event. Note that a fully generated event
-   * may be presented several times, if it has been manipulated in
-   * between. The default version of this function will call transform
-   * to make a lorentz transformation of the whole event, then extract
-   * all final state particles and call analyze(tPVector) of this
-   * analysis object and those of all associated analysis objects. The
-   * default version will not, however, do anything on events which
-   * have not been fully generated, or have been manipulated in any
-   * way.
-   * @param event pointer to the Event to be analyzed.
-   * @param ieve the event number.
-   * @param loop the number of times this event has been presented.
-   * If negative the event is now fully generated.
-   * @param state a number different from zero if the event has been
-   * manipulated in some way since it was last presented.
-   */
-  virtual void analyze(tEventPtr event, long ieve, int loop, int state);
-  //@}
-
-public:
-
-  /**
-   * 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 Clone Methods. */
-  //@{
-  /**
-   * Make a simple clone of this object.
-   * @return a pointer to the new object.
-   */
-  inline 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.
-   */
-  inline virtual IBPtr fullclone() const;
-  //@}
-
-protected:
-
-  /** @name Standard Interfaced functions. */
-  //@{
-  /**
-   * Initialize this object. Called in the run phase just before
-   * a run begins.
-   */
-  virtual void doinitrun();
-
-  /**
-   * Finalize this object. Called in the run phase just after a
-   * run has ended. Used eg. to write out statistics.
-   */
-  virtual void dofinish();
-  //@}
-
-private:
-
-  /**
-   * The static object used to initialize the description of this class.
-   * Indicates that this is an concrete class without persistent data.
-   */
-  static NoPIOClassDescription<ZpTRun2> initZpTRun2;
-
-  /**
-   * The assignment operator is private and must never be called.
-   * In fact, it should not even be implemented.
-   */
-  ZpTRun2 & operator=(const ZpTRun2 &);
-
-private:
-
-  /**
-   *  \f$p_T\f$ distribution
-   */
-  HistogramPtr _pt;
-
-};
-
-}
-
-#include "ThePEG/Utilities/ClassTraits.h"
-
-namespace ThePEG {
-
-/** @cond TRAITSPECIALIZATIONS */
-
-/** This template specialization informs ThePEG about the
- *  base classes of ZpTRun2. */
-template <>
-struct BaseClassTrait<Herwig::ZpTRun2,1> {
-  /** Typedef of the first base class of ZpTRun2. */
-  typedef AnalysisHandler NthBase;
-};
-
-/** This template specialization informs ThePEG about the name of
- *  the ZpTRun2 class and the shared object where it is defined. */
-template <>
-struct ClassTraits<Herwig::ZpTRun2>
-  : public ClassTraitsBase<Herwig::ZpTRun2> {
-  /** Return a platform-independent class name */
-  static string className() { return "Herwig::ZpTRun2"; }
-  /**
-   * The name of a file containing the dynamic library where the class
-   * ZpTRun2 is implemented. It may also include several, space-separated,
-   * libraries if the class ZpTRun2 depends on other classes (base classes
-   * excepted). In this case the listed libraries will be dynamically
-   * linked in the order they are specified.
-   */
-  static string library() { return "HwTevatronAnalysis.so"; }
-};
-
-/** @endcond */
-
-}
-
-#endif /* HERWIG_ZpTRun2_H */
diff --git a/Analysis/Zrapidity.cc b/Analysis/Zrapidity.cc
deleted file mode 100755
--- a/Analysis/Zrapidity.cc
+++ /dev/null
@@ -1,149 +0,0 @@
-// -*- C++ -*-
-//
-// This is the implementation of the non-inlined, non-templated member
-// functions of the Zrapidity class.
-//
-
-#include "Zrapidity.h"
-
-#include "ThePEG/Interface/Reference.h"
-#include "ThePEG/Interface/Parameter.h"
-#include "ThePEG/EventRecord/Particle.h"
-#include "ThePEG/EventRecord/Event.h"
-#include "ThePEG/PDT/EnumParticles.h"
-#include "ThePEG/PDT/ParticleData.h"
-#include "ThePEG/PDF/BeamParticleData.h"
-
-#include "ThePEG/Interface/ClassDocumentation.h"
-#include "ThePEG/Persistency/PersistentOStream.h"
-#include "ThePEG/Persistency/PersistentIStream.h"
-#include "Herwig/Utilities/Histogram.h"
-
-
-using namespace Herwig;
-using namespace ThePEG;
-using namespace std;
-
-
-inline IBPtr Zrapidity::clone() const {
-  return new_ptr(*this);
-}
-
-inline IBPtr Zrapidity::fullclone() const {
-  return new_ptr(*this);
-}
-
-void Zrapidity::doinitrun() {
- 
-  vector<double>  ybins, ydata, yerror;
-
-  double yvals1[] = { 0.0, 0.1, 0.2, 0.3, 0.4, 0.5, 0.6, 0.7, 0.8, 0.9, 1.0,
-		      1.1, 1.2, 1.3, 1.4, 1.5, 1.6, 1.7, 1.8, 1.9, 2.0, 2.1,
-		      2.2, 2.3, 2.4, 2.5, 2.6, 2.7, 2.8 };
-
-  double ydata1[] = { 0.271598,	0.276609,	0.274604,	0.266586,
-		      0.278613,	0.269593,	0.260573,	0.276609,
-		      0.235518,	0.244538,	0.251553,	0.233514,
-		      0.230507,	0.223492,	0.211465,	0.191421,
-		      0.170375,	0.16837,	0.142313,	0.119262,
-		      0.117258,	0.0912006,	0.0691521,	0.049108,
-		      0.039086,	0.0180397,	0.0140309,	0.00501102 };
-
-  /*
-  double ydata1[] = { 0.271, 0.276, 0.274, 0.266, 0.278, 0.269, 0.26, 0.276, 
-		      0.235, 0.244, 0.251, 0.233, 0.23, 0.223, 0.211, 0.191, 
-		      0.17, 0.168, 0.142, 0.119, 0.117, 0.091, 0.069, 0.049, 
-		      0.039, 0.018, 0.014, 0.005 };
-  
-  double yerror1[] = { 0.015, 0.015, 0.015, 0.015, 0.015, 0.016, 0.017, 0.016, 
-		       0.014, 0.015, 0.014, 0.014, 0.014, 0.013, 0.013, 0.013, 
-		       0.01, 0.014, 0.013, 0.01, 0.009, 0.008, 0.007, 0.006, 
-		       0.005, 0.004, 0.004, 0.006 };
-  */
-  double yerror1[] = { 0.0150331,	0.0150331,	0.0150331,	
-		       0.0150331,	0.0150331,	0.0160353,	
-		       0.0170375,	0.0160353,	0.0140309,	
-		       0.0150331,	0.0140309,	0.0140309,	
-		       0.0140309,	0.0130287,	0.0130287,	
-		       0.0130287,	0.010022,	0.0140309,	
-		       0.0130287,	0.010022,	0.00901984,	
-		       0.00801764,	0.00701543,	0.00601323,	
-		       0.00501102,	0.00400882,	0.00400882,	
-		       0.00601323 };
-  
-  ybins  = vector<double>(yvals1 ,yvals1 +29);
-  ydata  = vector<double>(ydata1 ,ydata1 +28);
-  yerror = vector<double>(yerror1,yerror1+28);
-
-  _hy = new_ptr( Histogram( ybins, ydata, yerror ) );
- 
-}
-
-void Zrapidity::persistentOutput(PersistentOStream & ) const {
-}
-
-void Zrapidity::persistentInput(PersistentIStream & , int) {
-}
-
-ClassDescription<Zrapidity> Zrapidity::initZrapidity;
-// Definition of the static class description member.
-
-void Zrapidity::Init() {
-
-  static ClassDocumentation<Zrapidity> documentation
-    ("There is no documentation for the Zrapidity class");
-
-}
-
-void Zrapidity::dofinish() {
-
-  AnalysisHandler::dofinish();
-  string fname = generator()->filename() + string("-") + name() + string(".top");
-  ofstream outfile(fname.c_str());
-
-  using namespace HistogramOptions;
-
-  _hy->topdrawOutput(outfile,Frame|Errorbars,
-		      "RED",
-		      "y of Z ( mass 71 GeV to 111 GeV ) compared to TVT data",
-		      "                           ",
-		      "1/SdS/dy",
-		      "  G G       ",
-		      "y",
-		      "   ");
-
-  outfile.close();
-}
-
-void Zrapidity::analyze(tEventPtr event, long , int loop, int state) {
-  if ( loop > 0 || state != 0 || !event ) return;
-  transform(event);
-  // find the outgoing particles in the hard process
-  ParticleVector outgoing;
-  event->selectFinalState(back_inserter(outgoing));
-  ParticleVector Zdecay;
-  // search for electrons and positions from Z/gamma
-  for(unsigned int ix=0;ix<outgoing.size();++ix) {
-    int id=outgoing[ix]->id();
-    if(abs(id)==ParticleID::eminus) {
-      PPtr part=outgoing[ix];
-      do {
-	part=part->parents()[0];
-      }
-      while (part->id()==id);
-      if(part->id()==ParticleID::gamma||part->id()==ParticleID::Z0) 
-	Zdecay.push_back(outgoing[ix]);
-    }
-  }
-  if(Zdecay.size()!=2) return;
-  Lorentz5Momentum pZ=Zdecay[0]->momentum()+Zdecay[1]->momentum();
-  pZ.rescaleMass();
-  if(pZ.mass()<71.*GeV||pZ.mass()>111.*GeV) return;
-  *_hy  += pZ.rapidity();
-  // remove leptons from outgoing particles
-  for(unsigned int ix=0;ix<Zdecay.size();++ix) {
-    ParticleVector::iterator pit=find(outgoing.begin(),outgoing.end(),Zdecay[ix]);
-    if(pit!=outgoing.end()) outgoing.erase(pit);
-  }
-
-}
diff --git a/Analysis/Zrapidity.h b/Analysis/Zrapidity.h
deleted file mode 100644
--- a/Analysis/Zrapidity.h
+++ /dev/null
@@ -1,178 +0,0 @@
-// -*- C++ -*-
-#ifndef HERWIG_Zrapidity_H
-#define HERWIG_Zrapidity_H
-//
-// This is the declaration of the Zrapidity class.
-//
-#include "ThePEG/Repository/CurrentGenerator.h"
-#include "ThePEG/Repository/EventGenerator.h"
-#include "ThePEG/Handlers/AnalysisHandler.h"
-#include "Herwig/Utilities/Histogram.h"
-
-
-namespace Herwig {
-  
-  using namespace ThePEG;
-  /**
-   * Here is the documentation of the Zrapidity class.
-   *
-   * @see \ref ZrapidityInterfaces "The interfaces"
-   * defined for Zrapidity.
-   */
-  class Zrapidity: public AnalysisHandler {
-    
-  public:
-
-  /** @name Standard constructors and destructors. */
-  //@{
-  /**
-   * The default constructor.
-   */
-    inline Zrapidity() {} 
-   
-    
-  public:
-    
-    /** @name Virtual functions required by the AnalysisHandler class. */
-    //@{
-    /**
-     * Analyze a given Event. Note that a fully generated event
-     * may be presented several times, if it has been manipulated in
-     * between. The default version of this function will call transform
-     * to make a lorentz transformation of the whole event, then extract
-     * all final state particles and call analyze(tPVector) of this
-     * analysis object and those of all associated analysis objects. The
-     * default version will not, however, do anything on events which
-     * have not been fully generated, or have been manipulated in any
-     * way.
-     * @param event pointer to the Event to be analyzed.
-     * @param ieve the event number.
-     * @param loop the number of times this event has been presented.
-     * If negative the event is now fully generated.
-     * @param state a number different from zero if the event has been
-     * manipulated in some way since it was last presented.
-     */
-    virtual void analyze(tEventPtr event, long ieve, int loop, int state);
-    
-
-  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();
-    
-    /**
-     * Initialize this object. Called in the run phase just before
-     * a run begins.
-     */
-    virtual void doinitrun();
-    
-    /**
-     * Finalize this object. Called in the run phase just after a
-     * run has ended. Used eg. to write out statistics.
-     */
-    virtual void dofinish();
-    
-  protected:
-    
-    /** @name Clone Methods. */
-    //@{
-    /**
-     * Make a simple clone of this object.
-     * @return a pointer to the new object.
-     */
-  inline 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.
-     */
-    inline virtual IBPtr fullclone() const;
-  //@}
-    
-    
-    // If needed, insert declarations of virtual function defined in the
-    // InterfacedBase class here (using ThePEG-interfaced-decl in Emacs).
-    
-    
-  private:
-
-    /**
-     *  Rapidity histogram
-     */   
-    HistogramPtr _hy;
-
-    /**
-     * The static object used to initialize the description of this class.
-     * Indicates that this is a concrete class with persistent data.
-     */
-    static ClassDescription<Zrapidity> initZrapidity;
-    
-    /**
-     * The assignment operator is private and must never be called.
-     * In fact, it should not even be implemented.
-     */
-    Zrapidity & operator=(const Zrapidity &);
-    
-  };
-  
-}
-
-#include "ThePEG/Utilities/ClassTraits.h"
-
-namespace ThePEG {
-  
-  /** @cond TRAITSPECIALIZATIONS */
-  
-  /** This template specialization informs ThePEG about the
-   *  base classes of Zrapidity. */
-  template <>
- struct BaseClassTrait<Herwig::Zrapidity,1> {
-    /** Typedef of the first base class of Zrapidity. */
-    typedef AnalysisHandler NthBase;
-  };
-
-  /** This template specialization informs ThePEG about the name of
-   *  the Zrapidity class and the shared object where it is defined. */
-  template <>
-  struct ClassTraits<Herwig::Zrapidity>
-    : public ClassTraitsBase<Herwig::Zrapidity> {
-    /** Return a platform-independent class name */
-    static string className() { return "Herwig::Zrapidity"; }
-    /**
-     * The name of a file containing the dynamic library where the class
-     * Zrapidity is implemented. It may also include several, space-separated,
-     * libraries if the class Zrapidity depends on other classes (base classes
-     * excepted). In this case the listed libraries will be dynamically
-     * linked in the order they are specified.
-     */
-    static string library() { return "HwTevatronAnalysis.so"; }
-  };
-  
-  /** @endcond */
-
-}
-
-#endif /* HERWIG_Zrapidity_H */
-
-
diff --git a/Decay/Makefile.am b/Decay/Makefile.am
--- a/Decay/Makefile.am
+++ b/Decay/Makefile.am
@@ -1,249 +1,249 @@
 SUBDIRS = FormFactors Tau Baryon VectorMeson Perturbative \
 	  WeakCurrents ScalarMeson TensorMeson Partonic General Radiation
 
 if HAVE_EVTGEN
 SUBDIRS += EvtGen
 endif
 
 noinst_LTLIBRARIES = libHwDecay.la
 
 libHwDecay_la_LIBADD = \
 $(top_builddir)/PDT/libHwPDT.la
 
 nodist_libHwDecay_la_SOURCES =  \
 hwdecay__all.cc
 
 BUILT_SOURCES  = hwdecay__all.cc
 CLEANFILES = hwdecay__all.cc
 
 hwdecay__all.cc : $(DIR_H_FILES) $(DIR_CC_FILES) Makefile
 	@echo "Concatenating .cc files into $@"
 	@$(top_srcdir)/cat_with_cpplines $(DIR_CC_FILES) > $@
 
 EXTRA_DIST = $(ALL_H_FILES) $(ALL_CC_FILES)
 
 DIR_H_FILES = $(addprefix $(srcdir)/,$(ALL_H_FILES))
 ALL_H_FILES = \
 DecayIntegrator.fh DecayIntegrator.h \
 DecayPhaseSpaceChannel.fh DecayPhaseSpaceChannel.h \
 DecayPhaseSpaceMode.fh DecayPhaseSpaceMode.h \
 HwDecayerBase.fh HwDecayerBase.h \
 HwDecayHandler.h \
 DecayVertex.fh DecayVertex.h \
 DecayMatrixElement.fh DecayMatrixElement.h \
 TwoBodyDecayMatrixElement.h \
 GeneralDecayMatrixElement.fh GeneralDecayMatrixElement.h \
 BranchingRatioReweighter.h 
 
 DIR_CC_FILES = $(addprefix $(srcdir)/,$(ALL_CC_FILES))
 ALL_CC_FILES = \
 DecayIntegrator.cc \
 DecayPhaseSpaceChannel.cc \
 DecayPhaseSpaceMode.cc \
 HwDecayerBase.cc \
 HwDecayHandler.cc \
 DecayVertex.cc \
 DecayMatrixElement.cc \
 TwoBodyDecayMatrixElement.cc \
 GeneralDecayMatrixElement.cc \
 BranchingRatioReweighter.cc
 
 
 
 ##################
 
 pkglib_LTLIBRARIES = Hw64Decay.la
 
 Hw64Decay_la_LDFLAGS = \
-$(AM_LDFLAGS) -module -version-info 8:0:0
+$(AM_LDFLAGS) -module -version-info 9:0:0
 
 Hw64Decay_la_SOURCES = \
 Hw64Decayer.h Hw64Decayer.cc
 
 ##################
 
 pkglib_LTLIBRARIES += HwMamboDecay.la
 
 HwMamboDecay_la_LDFLAGS = \
-$(AM_LDFLAGS) -module -version-info 9:0:0
+$(AM_LDFLAGS) -module -version-info 10:0:0
 
 HwMamboDecay_la_SOURCES = \
 MamboDecayer.h MamboDecayer.cc
 
 ##################
 
 noinst_LTLIBRARIES += libHwFormFactor.la
 
 libHwFormFactor_la_SOURCES = \
 FormFactors/BaryonFormFactor.cc \
 FormFactors/ScalarFormFactor.cc \
 FormFactors/BtoSGammaHadronicMass.cc \
 FormFactors/BaryonFormFactor.fh \
 FormFactors/BaryonFormFactor.h \
 FormFactors/ScalarFormFactor.fh \
 FormFactors/ScalarFormFactor.h \
 FormFactors/BtoSGammaHadronicMass.h \
 FormFactors/BtoSGammaHadronicMass.fh
 
 pkglib_LTLIBRARIES += HwFormFactors.la
 
 HwFormFactors_la_LDFLAGS = \
-$(AM_LDFLAGS) -module -version-info 9:1:0
+$(AM_LDFLAGS) -module -version-info 10:0:0
 
 HwFormFactors_la_CPPFLAGS = \
 $(AM_CPPFLAGS) -I$(srcdir)/FormFactors
 
 nodist_HwFormFactors_la_SOURCES = \
 FormFactors/Formfactor__all.cc
 
 ##################
 
 pkglib_LTLIBRARIES += HwTauDecay.la
 
 HwTauDecay_la_LDFLAGS = \
-$(AM_LDFLAGS) -module -version-info 9:0:0
+$(AM_LDFLAGS) -module -version-info 10:0:0
 
 HwTauDecay_la_SOURCES = \
 Tau/TauDecayer.cc
 
 ##################
 
 pkglib_LTLIBRARIES += HwBaryonDecay.la
 
 HwBaryonDecay_la_LDFLAGS = \
-$(AM_LDFLAGS) -module -version-info 8:0:0
+$(AM_LDFLAGS) -module -version-info 9:0:0
 
 HwBaryonDecay_la_LIBADD = \
 $(top_builddir)/PDT/libHwBaryonWidth.la
 
 HwBaryonDecay_la_CPPFLAGS = \
 $(AM_CPPFLAGS) -I$(srcdir)/Baryon
 
 nodist_HwBaryonDecay_la_SOURCES = \
 Baryon/BaryonDecayer__all.cc
 
 ##################
 
 pkglib_LTLIBRARIES += HwVMDecay.la
 
 HwVMDecay_la_LDFLAGS = \
-$(AM_LDFLAGS) -module -version-info 8:0:0
+$(AM_LDFLAGS) -module -version-info 9:0:0
 
 HwVMDecay_la_CPPFLAGS = \
 $(AM_CPPFLAGS) -I$(srcdir)/VectorMeson
 
 nodist_HwVMDecay_la_SOURCES = \
 VectorMeson/VMDecayer__all.cc
 
 ##################
 
 pkglib_LTLIBRARIES += HwPerturbativeDecay.la 
 
 HwPerturbativeDecay_la_LDFLAGS = \
-$(AM_LDFLAGS) -module -version-info 9:0:0
+$(AM_LDFLAGS) -module -version-info 10:0:0
 
 HwPerturbativeDecay_la_CPPFLAGS = \
 $(AM_CPPFLAGS) -I$(srcdir)/Perturbative
 
 nodist_HwPerturbativeDecay_la_SOURCES = \
 Perturbative/Perturbative__all.cc
 
 ##################
 
 pkglib_LTLIBRARIES += HwPerturbativeHiggsDecay.la
 
 HwPerturbativeHiggsDecay_la_LDFLAGS = \
-$(AM_LDFLAGS) -module -version-info 9:0:0
+$(AM_LDFLAGS) -module -version-info 10:0:0
 
 HwPerturbativeHiggsDecay_la_CPPFLAGS = \
 $(AM_CPPFLAGS) -I$(srcdir)/Perturbative
 
 nodist_HwPerturbativeHiggsDecay_la_SOURCES = \
 Perturbative/PerturbativeHiggs__all.cc
 
 ##################
 
 noinst_LTLIBRARIES += libHwWeakCurrent.la
 libHwWeakCurrent_la_SOURCES = \
 WeakCurrents/WeakDecayCurrent.cc \
 WeakCurrents/LeptonNeutrinoCurrent.cc \
 WeakCurrents/WeakDecayCurrent.fh \
 WeakCurrents/WeakDecayCurrent.h \
 WeakCurrents/LeptonNeutrinoCurrent.fh \
 WeakCurrents/LeptonNeutrinoCurrent.h
 
 pkglib_LTLIBRARIES += HwWeakCurrents.la
 
 HwWeakCurrents_la_LDFLAGS = \
-$(AM_LDFLAGS) -module -version-info 9:0:0
+$(AM_LDFLAGS) -module -version-info 10:0:0
 
 HwWeakCurrents_la_CPPFLAGS = \
 $(AM_CPPFLAGS) -I$(srcdir)/WeakCurrents
 
 nodist_HwWeakCurrents_la_SOURCES = \
 WeakCurrents/WeakCurrents__all.cc
 
 ##################
 
 pkglib_LTLIBRARIES += HwSMDecay.la
 
 HwSMDecay_la_LDFLAGS = \
-$(AM_LDFLAGS) -module -version-info 10:0:0
+$(AM_LDFLAGS) -module -version-info 11:0:0
 
 HwSMDecay_la_CPPFLAGS = \
 $(AM_CPPFLAGS) -I$(srcdir)/ScalarMeson
 
 nodist_HwSMDecay_la_SOURCES = \
 ScalarMeson/SMDecayer__all.cc
 
 ##################
 
 pkglib_LTLIBRARIES += HwTMDecay.la
 
 HwTMDecay_la_LDFLAGS = \
-$(AM_LDFLAGS) -module -version-info 8:0:0
+$(AM_LDFLAGS) -module -version-info 9:0:0
 
 HwTMDecay_la_CPPFLAGS = \
 $(AM_CPPFLAGS) -I$(srcdir)/TensorMeson
 
 nodist_HwTMDecay_la_SOURCES = \
 TensorMeson/TMDecayer__all.cc
 
 ##################
 
 pkglib_LTLIBRARIES += HwPartonicDecay.la
 
 HwPartonicDecay_la_LDFLAGS = \
-$(AM_LDFLAGS) -module -version-info 9:0:0
+$(AM_LDFLAGS) -module -version-info 10:0:0
 
 HwPartonicDecay_la_CPPFLAGS = \
 $(AM_CPPFLAGS) -I$(srcdir)/Partonic
 
 nodist_HwPartonicDecay_la_SOURCES = \
 Partonic/Partonic__all.cc
 
 ##################
 
 noinst_LTLIBRARIES += libHwDecRad.la
 
 libHwDecRad_la_SOURCES = \
 Radiation/DecayRadiationGenerator.cc \
 Radiation/QEDRadiationHandler.cc \
 Radiation/DecayRadiationGenerator.h \
 Radiation/DecayRadiationGenerator.fh \
 Radiation/QEDRadiationHandler.fh \
 Radiation/QEDRadiationHandler.h
 
 
 pkglib_LTLIBRARIES += HwSOPHTY.la
 
 HwSOPHTY_la_LDFLAGS = \
-$(AM_LDFLAGS) -module -version-info 3:0:0
+$(AM_LDFLAGS) -module -version-info 4:0:0
 
 HwSOPHTY_la_CPPFLAGS = \
 $(AM_CPPFLAGS) -I$(srcdir)/Radiation
 
 nodist_HwSOPHTY_la_SOURCES = \
 Radiation/Sophty__all.cc
 
 ##################
diff --git a/MatrixElement/DIS/Makefile.am b/MatrixElement/DIS/Makefile.am
--- a/MatrixElement/DIS/Makefile.am
+++ b/MatrixElement/DIS/Makefile.am
@@ -1,6 +1,6 @@
 pkglib_LTLIBRARIES = HwMEDIS.la
 HwMEDIS_la_SOURCES = \
 DISBase.h DISBase.cc \
 MENeutralCurrentDIS.cc  MENeutralCurrentDIS.h  \
 MEChargedCurrentDIS.cc  MEChargedCurrentDIS.h
-HwMEDIS_la_LDFLAGS = $(AM_LDFLAGS) -module -version-info 6:0:0
+HwMEDIS_la_LDFLAGS = $(AM_LDFLAGS) -module -version-info 7:0:0
diff --git a/MatrixElement/Gamma/Makefile.am b/MatrixElement/Gamma/Makefile.am
--- a/MatrixElement/Gamma/Makefile.am
+++ b/MatrixElement/Gamma/Makefile.am
@@ -1,10 +1,10 @@
 pkglib_LTLIBRARIES = HwMEGammaGamma.la HwMEGammaHadron.la
 
 HwMEGammaGamma_la_SOURCES = \
 MEGammaGamma2ff.cc MEGammaGamma2ff.h \
 MEGammaGamma2WW.cc MEGammaGamma2WW.h
-HwMEGammaGamma_la_LDFLAGS = $(AM_LDFLAGS) -module -version-info 3:0:0
+HwMEGammaGamma_la_LDFLAGS = $(AM_LDFLAGS) -module -version-info 4:0:0
 
 HwMEGammaHadron_la_SOURCES = \
 MEGammaP2Jets.cc MEGammaP2Jets.h
-HwMEGammaHadron_la_LDFLAGS = $(AM_LDFLAGS) -module -version-info 3:0:0
+HwMEGammaHadron_la_LDFLAGS = $(AM_LDFLAGS) -module -version-info 4:0:0
diff --git a/MatrixElement/Hadron/Makefile.am b/MatrixElement/Hadron/Makefile.am
--- a/MatrixElement/Hadron/Makefile.am
+++ b/MatrixElement/Hadron/Makefile.am
@@ -1,28 +1,28 @@
 pkglib_LTLIBRARIES = HwMEHadron.la
 HwMEHadron_la_SOURCES = \
 MEqq2gZ2ff.cc MEqq2gZ2ff.h \
 MEqq2W2ff.cc MEqq2W2ff.h   \
 MEPP2GammaJet.h MEPP2GammaJet.cc\
 MEQCD2to2.h MEQCD2to2.cc\
 MEPP2HiggsJet.h MEPP2HiggsJet.cc\
 MEPP2GammaGamma.h MEPP2GammaGamma.cc \
 MEPP2QQ.h    MEPP2QQ.cc   \
 MEPP2QQHiggs.h    MEPP2QQHiggs.cc   \
 MEPP2Higgs.h MEPP2Higgs.cc\
 MEPP2WH.h    MEPP2WH.cc   \
 MEPP2ZH.h    MEPP2ZH.cc   \
 MEPP2WJet.cc MEPP2WJet.h  \
 MEPP2ZJet.cc MEPP2ZJet.h  \
 MEPP2VV.cc   MEPP2VV.h  \
 MEPP2VGamma.cc   MEPP2VGamma.h  \
 MEPP2HiggsVBF.cc   MEPP2HiggsVBF.h  \
 MEPP2SingleTop.cc   MEPP2SingleTop.h  \
 MEMinBias.h MEMinBias.cc \
 MEDiffraction.h MEDiffraction.cc
 
-HwMEHadron_la_LDFLAGS = $(AM_LDFLAGS) -module -version-info 7:0:0
+HwMEHadron_la_LDFLAGS = $(AM_LDFLAGS) -module -version-info 8:0:0
 
 pkglib_LTLIBRARIES += HwMEHadronFast.la
 HwMEHadronFast_la_SOURCES = \
 MEQCD2to2Fast.h MEQCD2to2Fast.cc
-HwMEHadronFast_la_LDFLAGS = $(AM_LDFLAGS) -module -version-info 5:0:0
+HwMEHadronFast_la_LDFLAGS = $(AM_LDFLAGS) -module -version-info 6:0:0
diff --git a/MatrixElement/Lepton/Makefile.am b/MatrixElement/Lepton/Makefile.am
--- a/MatrixElement/Lepton/Makefile.am
+++ b/MatrixElement/Lepton/Makefile.am
@@ -1,10 +1,10 @@
 pkglib_LTLIBRARIES = HwMELepton.la
 HwMELepton_la_SOURCES = \
 MEee2gZ2qq.h MEee2gZ2qq.cc\
 MEee2gZ2ll.h MEee2gZ2ll.cc\
 MEee2ZH.h MEee2ZH.cc\
 MEee2HiggsVBF.h MEee2HiggsVBF.cc \
 MEee2VV.h MEee2VV.cc \
 MEee2VectorMeson.h MEee2VectorMeson.cc \
 MEee2Higgs2SM.h MEee2Higgs2SM.cc
-HwMELepton_la_LDFLAGS = $(AM_LDFLAGS) -module -version-info 6:0:0
+HwMELepton_la_LDFLAGS = $(AM_LDFLAGS) -module -version-info 7:0:0
diff --git a/MatrixElement/Matchbox/Builtin/Amplitudes/Makefile.am b/MatrixElement/Matchbox/Builtin/Amplitudes/Makefile.am
--- a/MatrixElement/Matchbox/Builtin/Amplitudes/Makefile.am
+++ b/MatrixElement/Matchbox/Builtin/Amplitudes/Makefile.am
@@ -1,72 +1,72 @@
 pkglib_LTLIBRARIES = HwMatchboxBuiltin.la
 
 HwMatchboxBuiltin_la_LDFLAGS = \
-$(AM_LDFLAGS) -module -version-info 3:0:0
+$(AM_LDFLAGS) -module -version-info 4:0:0
 
 nodist_HwMatchboxBuiltin_la_SOURCES = \
 Amplitudes__all.cc
 
 BUILT_SOURCES  = Amplitudes__all.cc
 CLEANFILES = Amplitudes__all.cc
 
 Amplitudes__all.cc : $(DIR_H_FILES) $(DIR_CC_FILES) Makefile
 	@echo "Concatenating .cc files into $@"
 	@$(top_srcdir)/cat_with_cpplines $(DIR_CC_FILES) > $@
 
 EXTRA_DIST = $(ALL_H_FILES) $(ALL_CC_FILES)
 
 DIR_H_FILES = $(addprefix $(srcdir)/,$(ALL_H_FILES))
 ALL_H_FILES = \
 MatchboxCurrents.h \
 MatchboxZGammaAmplitude.h \
 MatchboxAmplitudellbarqqbargg.h \
 MatchboxAmplitudellbarqqbarg.h \
 MatchboxAmplitudellbarqqbar.h \
 MatchboxAmplitudellbarqqbarqqbar.h \
 MatchboxAmplitudelnuqqbargg.h \
 MatchboxAmplitudelnuqqbarg.h \
 MatchboxAmplitudelnuqqbar.h \
 MatchboxAmplitudelnuqqbarqqbar.h \
 MatchboxAmplitudehbbbarg.h \
 MatchboxAmplitudehbbbar.h \
 MatchboxAmplitudehggg.h \
 MatchboxAmplitudehgg.h \
 MatchboxAmplitudehqqbarg.h \
 MatchboxAmplitudeqqbarttbar.h \
 MatchboxAmplitudeqqbarttbarg.h \
 MatchboxAmplitudeggttbar.h \
 MatchboxAmplitudeggttbarg.h \
 HelAmps_sm.h \
 Parameters_sm.h \
 MG_qqx2ttx.h \
 MG_qqx2ttxg.h \
 MG_gg2ttx.h \
 MG_gg2ttxg.h
 
 DIR_CC_FILES = $(addprefix $(srcdir)/,$(ALL_CC_FILES))
 ALL_CC_FILES = \
 MatchboxCurrents.cc \
 MatchboxZGammaAmplitude.cc \
 MatchboxAmplitudellbarqqbar.cc \
 MatchboxAmplitudellbarqqbarg.cc \
 MatchboxAmplitudellbarqqbargg.cc \
 MatchboxAmplitudellbarqqbarqqbar.cc \
 MatchboxAmplitudelnuqqbar.cc \
 MatchboxAmplitudelnuqqbarg.cc \
 MatchboxAmplitudelnuqqbargg.cc \
 MatchboxAmplitudelnuqqbarqqbar.cc \
 MatchboxAmplitudehbbbar.cc \
 MatchboxAmplitudehbbbarg.cc \
 MatchboxAmplitudehgg.cc \
 MatchboxAmplitudehggg.cc \
 MatchboxAmplitudehqqbarg.cc \
 MatchboxAmplitudeqqbarttbar.cc \
 MatchboxAmplitudeqqbarttbarg.cc \
 MatchboxAmplitudeggttbar.cc \
 MatchboxAmplitudeggttbarg.cc \
 HelAmps_sm.cc \
 Parameters_sm.cc \
 MG_qqx2ttx.cc \
 MG_qqx2ttxg.cc \
 MG_gg2ttx.cc \
 MG_gg2ttxg.cc
diff --git a/MatrixElement/Matchbox/CVolver/Makefile.am b/MatrixElement/Matchbox/CVolver/Makefile.am
--- a/MatrixElement/Matchbox/CVolver/Makefile.am
+++ b/MatrixElement/Matchbox/CVolver/Makefile.am
@@ -1,9 +1,9 @@
 pkglib_LTLIBRARIES = HwCVolver.la
 
-HwCVolver_la_LDFLAGS = $(AM_LDFLAGS) -module -version-info 2:0:0
+HwCVolver_la_LDFLAGS = $(AM_LDFLAGS) -module -version-info 3:0:0
 
 HwCVolver_la_SOURCES = \
 ColourFlowBasis.cc \
 ColourFlows.cc \
 ColourFlowBasis.h \
 ColourFlows.h
diff --git a/MatrixElement/Matchbox/ColorFull/Makefile.am b/MatrixElement/Matchbox/ColorFull/Makefile.am
--- a/MatrixElement/Matchbox/ColorFull/Makefile.am
+++ b/MatrixElement/Matchbox/ColorFull/Makefile.am
@@ -1,35 +1,35 @@
 pkglib_LTLIBRARIES = HwColorFull.la
 
-HwColorFull_la_LDFLAGS = $(AM_LDFLAGS) -module -version-info 2:0:0
+HwColorFull_la_LDFLAGS = $(AM_LDFLAGS) -module -version-info 3:0:0
 
 HwColorFull_la_SOURCES = \
 Col_amp.cc \
 Col_amp.h \
 Col_basis.cc \
 Col_basis.h \
 Col_functions.cc \
 Col_functions.h \
 Col_str.cc \
 Col_str.h \
 Monomial.cc \
 Monomial.h \
 Orthogonal_basis.cc \
 Orthogonal_basis.h \
 parameters.h \
 Poly_matr.cc \
 Poly_matr.h \
 Polynomial.cc \
 Polynomial.h \
 Poly_vec.cc \
 Poly_vec.h \
 Quark_line.cc \
 Quark_line.h \
 Trace_basis.cc \
 TraceBasis.cc \
 Trace_basis.h \
 TraceBasis.h \
 Trace_type_basis.cc \
 Trace_type_basis.h \
 Tree_level_gluon_basis.cc \
 Tree_level_gluon_basis.h \
 types.h
diff --git a/MatrixElement/Matchbox/Cuts/Makefile.am b/MatrixElement/Matchbox/Cuts/Makefile.am
--- a/MatrixElement/Matchbox/Cuts/Makefile.am
+++ b/MatrixElement/Matchbox/Cuts/Makefile.am
@@ -1,36 +1,36 @@
 pkglib_LTLIBRARIES = HwMatchboxCuts.la
 
 HwMatchboxCuts_la_LDFLAGS = \
-$(AM_LDFLAGS) -module -version-info 2:0:0
+$(AM_LDFLAGS) -module -version-info 3:0:0
 
 nodist_HwMatchboxCuts_la_SOURCES = \
 Cuts__all.cc
 
 BUILT_SOURCES  = Cuts__all.cc
 CLEANFILES = Cuts__all.cc
 
 Cuts__all.cc : $(DIR_H_FILES) $(DIR_CC_FILES) Makefile
 	@echo "Concatenating .cc files into $@"
 	@$(top_srcdir)/cat_with_cpplines $(DIR_CC_FILES) > $@
 
 EXTRA_DIST = $(ALL_H_FILES) $(ALL_CC_FILES)
 
 DIR_H_FILES = $(addprefix $(srcdir)/,$(ALL_H_FILES))
 ALL_H_FILES = \
 IdentifiedParticleCut.h \
 MatchboxDeltaRCut.h \
 MissingPtCut.h \
 FrixionePhotonSeparationCut.h \
 InvariantMassCut.h \
 PairPtCut.h \
 PairRapidityCut.h
 
 DIR_CC_FILES = $(addprefix $(srcdir)/,$(ALL_CC_FILES))
 ALL_CC_FILES = \
 IdentifiedParticleCut.cc \
 MatchboxDeltaRCut.cc \
 MissingPtCut.cc \
 FrixionePhotonSeparationCut.cc \
 InvariantMassCut.cc \
 PairPtCut.cc \
 PairRapidityCut.cc
diff --git a/MatrixElement/Matchbox/External/Makefile.am b/MatrixElement/Matchbox/External/Makefile.am
--- a/MatrixElement/Matchbox/External/Makefile.am
+++ b/MatrixElement/Matchbox/External/Makefile.am
@@ -1,95 +1,95 @@
 SUBDIRS = BLHAGeneric VBFNLO NJet GoSam OpenLoops MadGraph
 
 
 pkglib_LTLIBRARIES =
 
 ##############
 
 if HAVE_GOSAM
 pkglib_LTLIBRARIES += HwMatchboxGoSam.la
 endif
 
 HwMatchboxGoSam_la_LDFLAGS = \
-$(AM_LDFLAGS) -module -version-info 13:0:0
+$(AM_LDFLAGS) -module -version-info 14:0:0
 
 HwMatchboxGoSam_la_CPPFLAGS = $(AM_CPPFLAGS) \
 -DHERWIG_BINDIR="\"$(bindir)\"" \
 -DHERWIG_PKGDATADIR="\"$(pkgdatadir)\"" \
 -DGOSAM_PREFIX="\"$(GOSAMPREFIX)\""
 
 HwMatchboxGoSam_la_SOURCES = \
 GoSam/GoSamAmplitude.cc
 
 
 ###############
 
 if HAVE_VBFNLO
 pkglib_LTLIBRARIES += HwMatchboxVBFNLO.la
 endif
 
-HwMatchboxVBFNLO_la_LDFLAGS = $(AM_LDFLAGS) -module -version-info 2:2:0
+HwMatchboxVBFNLO_la_LDFLAGS = $(AM_LDFLAGS) -module -version-info 3:0:0
 HwMatchboxVBFNLO_la_CPPFLAGS = $(AM_CPPFLAGS)
 HwMatchboxVBFNLO_la_CPPFLAGS += -I$(VBFNLOINCLUDE)
 HwMatchboxVBFNLO_la_CPPFLAGS += -DVBFNLOLIB=$(VBFNLOLIB)
 
 HwMatchboxVBFNLO_la_SOURCES = \
 VBFNLO/VBFNLOAmplitude.cc \
 VBFNLO/VBFNLOPhasespace.cc
 
 
 ###############
 
 if HAVE_OPENLOOPS
 pkglib_LTLIBRARIES += HwMatchboxOpenLoops.la
 endif
 
 HwMatchboxOpenLoops_la_SOURCES = \
 OpenLoops/OpenLoopsAmplitude.cc
 
-HwMatchboxOpenLoops_la_LDFLAGS = $(AM_LDFLAGS) -module -version-info 12:0:0
+HwMatchboxOpenLoops_la_LDFLAGS = $(AM_LDFLAGS) -module -version-info 13:0:0
 
 HwMatchboxOpenLoops_la_CPPFLAGS = $(AM_CPPFLAGS) \
 -DOPENLOOPSLIBS="\"$(OPENLOOPSLIBS)\"" \
 -DOPENLOOPSPREFIX="\"$(OPENLOOPSPREFIX)\""
 
 ##############
 
 
 if HAVE_NJET
 pkglib_LTLIBRARIES += HwMatchboxNJet.la
 endif
 
-HwMatchboxNJet_la_LDFLAGS = $(AM_LDFLAGS) -module -version-info 12:0:0
+HwMatchboxNJet_la_LDFLAGS = $(AM_LDFLAGS) -module -version-info 13:0:0
 
 HwMatchboxNJet_la_CPPFLAGS = $(AM_CPPFLAGS) -I$(NJETINCLUDEPATH) \
 -DNJET_PREFIX="\"$(NJETPREFIX)\"" \
 -DNJET_LIBS="\"$(NJETLIBPATH)\""
 
 HwMatchboxNJet_la_SOURCES = \
 NJet/NJetsAmplitude.cc
 
 
 
 ##############
 
 if HAVE_MADGRAPH
 pkglib_LTLIBRARIES += HwMatchboxMadGraph.la
 endif
 
-HwMatchboxMadGraph_la_LDFLAGS = $(AM_LDFLAGS) -module -version-info 3:1:0
+HwMatchboxMadGraph_la_LDFLAGS = $(AM_LDFLAGS) -module -version-info 4:0:0
 
 HwMatchboxMadGraph_la_SOURCES = \
 MadGraph/MadGraphAmplitude.cc
 
 HwMatchboxMadGraph_la_CPPFLAGS = $(AM_CPPFLAGS) \
 -DHERWIG_BINDIR="\"$(bindir)\"" \
 -DHERWIG_INCLUDEDIR="\"$(includedir)\"" \
 -DHERWIG_PKGDATADIR="\"$(pkgdatadir)\"" \
 -DMADGRAPH_PREFIX="\"$(MADGRAPHPREFIX)\""
 
 
 
 
 
 
 
diff --git a/MatrixElement/Matchbox/Matching/Makefile.am b/MatrixElement/Matchbox/Matching/Makefile.am
--- a/MatrixElement/Matchbox/Matching/Makefile.am
+++ b/MatrixElement/Matchbox/Matching/Makefile.am
@@ -1,24 +1,24 @@
 noinst_LTLIBRARIES = libHwMatchboxMatching.la
 pkglib_LTLIBRARIES = HwQTildeMatching.la HwDipoleMatching.la
 
 libHwMatchboxMatching_la_SOURCES = \
 HardScaleProfile.h \
 HardScaleProfile.cc \
 ShowerApproximation.h \
 ShowerApproximation.cc \
 ShowerApproximationKernel.h \
 ShowerApproximationKernel.cc \
 ShowerApproximationGenerator.h \
 ShowerApproximationGenerator.cc \
 MEMatching.h \
 MEMatching.cc
 
-HwQTildeMatching_la_LDFLAGS = $(AM_LDFLAGS) -module -version-info 2:0:0
+HwQTildeMatching_la_LDFLAGS = $(AM_LDFLAGS) -module -version-info 3:0:0
 HwQTildeMatching_la_SOURCES = \
 QTildeMatching.h \
 QTildeMatching.cc
 
-HwDipoleMatching_la_LDFLAGS = $(AM_LDFLAGS) -module -version-info 2:0:0
+HwDipoleMatching_la_LDFLAGS = $(AM_LDFLAGS) -module -version-info 3:0:0
 HwDipoleMatching_la_SOURCES = \
 DipoleMatching.h \
 DipoleMatching.cc
diff --git a/MatrixElement/Matchbox/Scales/Makefile.am b/MatrixElement/Matchbox/Scales/Makefile.am
--- a/MatrixElement/Matchbox/Scales/Makefile.am
+++ b/MatrixElement/Matchbox/Scales/Makefile.am
@@ -1,32 +1,32 @@
 pkglib_LTLIBRARIES = HwMatchboxScales.la
 
 
-HwMatchboxScales_la_LDFLAGS = $(AM_LDFLAGS) -module -version-info 2:2:0
+HwMatchboxScales_la_LDFLAGS = $(AM_LDFLAGS) -module -version-info 3:0:0
 
 HwMatchboxScales_la_SOURCES = \
 MatchboxHtScale.h \
 MatchboxLeptonMassScale.h \
 MatchboxLeptonPtScale.h \
 MatchboxParticlePtScale.h \
 MatchboxPtScale.h \
 MatchboxHtScale.cc \
 MatchboxLeptonMassScale.cc \
 MatchboxLeptonPtScale.cc \
 MatchboxParticlePtScale.cc \
 MatchboxPtScale.cc \
 MatchboxSHatScale.h \
 MatchboxSHatScale.cc \
 MatchboxTopMassScale.h \
 MatchboxTopMassScale.cc \
 MatchboxTopMTScale.h \
 MatchboxTopMTScale.cc \
 MatchboxTopSumMTScale.h \
 MatchboxTopSumMTScale.cc \
 MatchboxTopMinMTScale.h \
 MatchboxTopMinMTScale.cc \
 MatchboxTriVecScales.h \
 MatchboxTriVecScales.cc \
 MatchboxTopLinearSumMTScale.h \
 MatchboxTopLinearSumMTScale.cc \
 MatchboxTopIndividualMTScale.h \
 MatchboxTopIndividualMTScale.cc
diff --git a/MatrixElement/Powheg/Makefile.am b/MatrixElement/Powheg/Makefile.am
--- a/MatrixElement/Powheg/Makefile.am
+++ b/MatrixElement/Powheg/Makefile.am
@@ -1,17 +1,17 @@
 pkglib_LTLIBRARIES = HwPowhegMEHadron.la HwPowhegMELepton.la
-HwPowhegMEHadron_la_LDFLAGS = $(AM_LDFLAGS) -module -version-info 7:0:1
+HwPowhegMEHadron_la_LDFLAGS = $(AM_LDFLAGS) -module -version-info 8:0:0
 HwPowhegMEHadron_la_SOURCES = \
 MEqq2gZ2ffPowheg.cc MEqq2gZ2ffPowheg.h \
 MEqq2W2ffPowheg.cc  MEqq2W2ffPowheg.h \
 MEPP2HiggsPowheg.cc  MEPP2HiggsPowheg.h \
 MEPP2WHPowheg.cc  MEPP2WHPowheg.h \
 MEPP2ZHPowheg.cc  MEPP2ZHPowheg.h \
 MEPP2VVPowheg.cc  MEPP2VVPowheg.h \
 VVKinematics.cc VVKinematics.h \
 MEPP2GammaGammaPowheg.cc  MEPP2GammaGammaPowheg.h \
 MEPP2HiggsVBFPowheg.cc MEPP2HiggsVBFPowheg.h
 
-HwPowhegMELepton_la_LDFLAGS = $(AM_LDFLAGS) -module -version-info 1:0:0
+HwPowhegMELepton_la_LDFLAGS = $(AM_LDFLAGS) -module -version-info 2:0:0
 HwPowhegMELepton_la_SOURCES = \
 MEee2gZ2qqPowheg.cc MEee2gZ2qqPowheg.h \
 MEee2gZ2llPowheg.cc MEee2gZ2llPowheg.h 
diff --git a/Models/Makefile.am b/Models/Makefile.am
--- a/Models/Makefile.am
+++ b/Models/Makefile.am
@@ -1,181 +1,181 @@
 SUBDIRS = RSModel  StandardModel General Susy UED Zprime \
           Transplanckian ADD Leptoquarks Sextet TTbAsymm \
           LH LHTP Feynrules
 
 noinst_LTLIBRARIES = libHwStandardModel.la
 nodist_libHwStandardModel_la_SOURCES = \
 StandardModel/SM__all.cc
 
 libHwStandardModel_la_CPPFLAGS = \
 $(AM_CPPFLAGS) -I$(srcdir)/StandardModel
 
 noinst_LTLIBRARIES += libHwModelGenerator.la
 nodist_libHwModelGenerator_la_SOURCES = \
 General/ModelGenerator__all.cc
 
 libHwModelGenerator_la_CPPFLAGS = \
 $(AM_CPPFLAGS) -I$(srcdir)/General
 
 
 
 
 if WANT_BSM
 
 pkglib_LTLIBRARIES = \
 HwRSModel.la \
 HwUED.la \
 HwSusy.la \
 HwNMSSM.la \
 HwRPV.la \
 HwZprimeModel.la \
 HwTransplanck.la \
 HwADDModel.la \
 HwLeptoquarkModel.la \
 HwSextetModel.la \
 HwTTbAModel.la \
 HwLHModel.la \
 HwLHTPModel.la
 
 endif
 
 #############
 
 HwRSModel_la_LDFLAGS = \
-$(AM_LDFLAGS) -module -version-info 9:0:0
+$(AM_LDFLAGS) -module -version-info 10:0:0
 
 HwRSModel_la_CPPFLAGS = \
 $(AM_CPPFLAGS) -I$(srcdir)/RSModel
 
 nodist_HwRSModel_la_SOURCES = \
 RSModel/RS__all.cc
 
 #############
 
 HwUED_la_LDFLAGS = \
-$(AM_LDFLAGS) -module -version-info 9:0:0
+$(AM_LDFLAGS) -module -version-info 10:0:0
 
 HwUED_la_CPPFLAGS = \
 $(AM_CPPFLAGS) -I$(srcdir)/UED
 
 nodist_HwUED_la_SOURCES = \
 UED/UED__all.cc
 
 #############
 
 HwSusy_la_LDFLAGS = \
-$(AM_LDFLAGS) -module -version-info 11:0:0
+$(AM_LDFLAGS) -module -version-info 12:0:0
 
 HwSusy_la_CPPFLAGS = \
 $(AM_CPPFLAGS) -I$(srcdir)/Susy
 
 nodist_HwSusy_la_SOURCES = \
 Susy/Susy__all.cc
 
 #############
 
 HwNMSSM_la_LDFLAGS = \
-$(AM_LDFLAGS) -module -version-info 4:0:0
+$(AM_LDFLAGS) -module -version-info 5:0:0
 
 HwNMSSM_la_CPPFLAGS = \
 $(AM_CPPFLAGS) -I$(srcdir)/Susy/NMSSM
 
 nodist_HwNMSSM_la_SOURCES = \
 Susy/NMSSM/NMSSM__all.cc
 
 #############
 
 HwRPV_la_LDFLAGS = \
-$(AM_LDFLAGS) -module -version-info 2:0:0
+$(AM_LDFLAGS) -module -version-info 3:0:0
 
 HwRPV_la_CPPFLAGS = \
 $(AM_CPPFLAGS) -I$(srcdir)/Susy/RPV
 
 nodist_HwRPV_la_SOURCES = \
 Susy/RPV/RPV__all.cc
 
 #############
 
 HwZprimeModel_la_LDFLAGS = \
-$(AM_LDFLAGS) -module -version-info 2:0:0
+$(AM_LDFLAGS) -module -version-info 3:0:0
 
 HwZprimeModel_la_SOURCES = \
 Zprime/ZprimeModel.cc  Zprime/ZprimeModelZPQQVertex.cc
 
 #############
 
 HwTransplanck_la_LDFLAGS = \
-$(AM_LDFLAGS) -module -version-info 3:0:0
+$(AM_LDFLAGS) -module -version-info 4:0:0
 
 HwTransplanck_la_SOURCES = \
 Transplanckian/METRP2to2.cc
 
 #############
 
 HwADDModel_la_LDFLAGS = \
-$(AM_LDFLAGS) -module -version-info 3:0:0
+$(AM_LDFLAGS) -module -version-info 4:0:0
 
 HwADDModel_la_CPPFLAGS = \
 $(AM_CPPFLAGS) -I$(srcdir)/ADD
 
 nodist_HwADDModel_la_SOURCES = \
 ADD/ADD__all.cc
 
 #############
 
 HwLeptoquarkModel_la_LDFLAGS = \
-$(AM_LDFLAGS) -module -version-info 4:0:0
+$(AM_LDFLAGS) -module -version-info 5:0:0
 
 HwLeptoquarkModel_la_CPPFLAGS = \
 $(AM_CPPFLAGS) -I$(srcdir)/Leptoquarks
 
 nodist_HwLeptoquarkModel_la_SOURCES = \
 Leptoquarks/Leptoquark__all.cc
 
 #############
 
 HwSextetModel_la_LDFLAGS = \
-$(AM_LDFLAGS) -module -version-info 2:0:0
+$(AM_LDFLAGS) -module -version-info 3:0:0
 
 HwSextetModel_la_CPPFLAGS = \
 $(AM_CPPFLAGS) -I$(srcdir)/Sextet
 
 nodist_HwSextetModel_la_SOURCES = \
 Sextet/Sextet__all.cc
 
 #############
 
 HwTTbAModel_la_LDFLAGS = \
-$(AM_LDFLAGS) -module -version-info 2:0:0
+$(AM_LDFLAGS) -module -version-info 3:0:0
 
 HwTTbAModel_la_CPPFLAGS = \
 $(AM_CPPFLAGS) -I$(srcdir)/TTbAsymm
 
 nodist_HwTTbAModel_la_SOURCES = \
 TTbAsymm/TTbA__all.cc
 
 #############
 
 HwLHModel_la_LDFLAGS = \
-$(AM_LDFLAGS) -module -version-info 4:0:0
+$(AM_LDFLAGS) -module -version-info 5:0:0
 
 HwLHModel_la_CPPFLAGS = \
 $(AM_CPPFLAGS) -I$(srcdir)/LH
 
 nodist_HwLHModel_la_SOURCES = \
 LH/LH__all.cc
 
 #############
 
 HwLHTPModel_la_LDFLAGS = \
-$(AM_LDFLAGS) -module -version-info 4:0:0
+$(AM_LDFLAGS) -module -version-info 5:0:0
 
 HwLHTPModel_la_LIBADD = \
 $(GSLLIBS)
 
 HwLHTPModel_la_CPPFLAGS = \
 $(AM_CPPFLAGS) $(GSLINCLUDE) -I$(srcdir)/LHTP
 
 nodist_HwLHTPModel_la_SOURCES = \
 LHTP/LHTP__all.cc
 
 #############
diff --git a/NEWS b/NEWS
--- a/NEWS
+++ b/NEWS
@@ -1,1597 +1,1623 @@
 Herwig News							 -*- outline -*-
 ================================================================================
 
+* Herwig 7.1.0 release: 2017-05-19
+
+** Major new release
+   For a more detailed overview and further references please see the release note arXiv:1705.06919
+
+** NLO multijet merging with the dipole shower
+
+** A new soft model
+
+** An interface to EvtGen
+
+** Improved calculation of mass effects in the dipole shower
+
+** Top decays in the dipole shower, and NLO corrections to the decay
+
+** An implementation of the KrkNLO method for simple processes
+
+** Major restructuring and cleanup of default input files
+
+** C++11 is now mandatory and heavily used in the code
+
+** Many smaller bugfixes and improvements
+
+
+
 * Herwig 7.0.4 release: 2016-10-24
 
 ** API
-   The high level API is now properly available as a library, providing an alternative to the Herwig main program. 
+   The high level API is now properly available as a library, providing an
+   alternative to the Herwig main program.
 
 ** Dipole shower
-   Added nloops() function to the AlphaS classes to return the number of loops in the running coupling
+   Added nloops() function to the AlphaS classes to return the number of loops
+   in the running coupling
 
 ** Matchbox
    Improved error handling and clearer messages
 
 ** BSM models
-   Initialize W mass correctly from SLHA file. Improved reading in of decay modes if they already exist.
+   Initialize W mass correctly from SLHA file. Improved reading in of decay
+   modes if they already exist.
 
 ** Sampling
-   Introduced option to reduce reference weight in AlmostUnweighted mode by Kappa factor. Useful for processes where full unweighting is infeasible. 
+   Introduced option to reduce reference weight in AlmostUnweighted mode by
+   Kappa factor. Useful for processes where full unweighting is infeasible.
 
 ** Qtilde shower
-   Better control of scale in splitting functions using the SplittingFunction:ScaleChoice interface.
+   Better control of scale in splitting functions using the
+   SplittingFunction:ScaleChoice interface.
 
 ** Tests
-   New NLO fixed-order input files for testing Matchbox in Tests/ExternNLO. 
+   New NLO fixed-order input files for testing Matchbox in Tests/ExternNLO.
 
 ** Input files
-   Set diagonal CKM options consistently. Added TauTauHVertex and MuMuHVertex to MatchboxDefaults.
-
-
+   Set diagonal CKM options consistently. Added TauTauHVertex and MuMuHVertex
+   to MatchboxDefaults.
 
 * Herwig 7.0.3 release: 2016-07-21
 
 ** subprocess generation filters
    A number of filters has been implemented to speed up process and diagram
    generation for the case of Standard Model like processes; this is
    particularly helpful for processes involving a large number of electroweak
    combinatorics. See the documentation for more details.
 
 ** fix to directory hierarchy
    A bug in the Herwig-scratch directory hierarchy when integrating with
    different seeds has been fixed.
 
 ** fix for relocating MadGraph generated amplitudes
    The directory and symbolic link structure for MadGraph-built amplitudes has
    been changed to allow for relocation of a run directory to a different file
    system hierarchy.
 
 ** z* variable added to LeptonsJetsAnalysis
    The builtin LeptonsJetsAnalysis has been extented to include the normalized
    relative rapidity z*
 
 ** detuning parameter for shower reweighting
    An efficiency tweak when using the shower reweighting facilities has been
    introduced for the veto algorithms in both the QTilde and the Dipole
    shower. See the documentation for more details.
 
 ** BaryonThreeQuarkModelFormFactor
    A scaling bug in the form factor series expansion was fixed.
 
-
 * Herwig 7.0.2 release: 2016-04-29
 
 ** Event reweighting
-  New option of calculating the weights for the effect of varying the scale
-  used in both the default and dipole showers. The method is described in
-  arXiv:1605.08256
+   New option of calculating the weights for the effect of varying the scale
+   used in both the default and dipole showers. The method is described in
+   arXiv:1605.08256
 
 ** mergegrids mode
-  A main mode for the Herwig executable has been added which merges the
-  integration grids from parallel runs.
+   A main mode for the Herwig executable has been added which merges the
+   integration grids from parallel runs.
 
 ** NLO Diphoton production
-  The NLO matrix elements in the POWHEG approach for diphoton production as
-  described in JHEP 1202 (2012) 130, arXiv:1106.3939 have been included as
-  MEPP2GammaGammaPowheg.
+   The NLO matrix elements in the POWHEG approach for diphoton production as
+   described in JHEP 1202 (2012) 130, arXiv:1106.3939 have been included as
+   MEPP2GammaGammaPowheg.
 
 ** BSM Hard process constructor
-  A missing Feynman diagram with a t-channel vector boson has been added to
-  the matrix element for vv2ss
+   A missing Feynman diagram with a t-channel vector boson has been added to
+   the matrix element for vv2ss
 
 ** BSM Decay Modes calculation
-  The behaviour of the option to disable decay modes in BSM Models has been
-  changed so that the partial width for the ignored modes is now calculated
-  and included in the total width, but the branching ratio is set to
-  zero. This is more physical than the previous option where the mode was
-  totally ignored and hence not included in the calculation of the width.
+   The behaviour of the option to disable decay modes in BSM Models has been
+   changed so that the partial width for the ignored modes is now calculated
+   and included in the total width, but the branching ratio is set to
+   zero. This is more physical than the previous option where the mode was
+   t otally ignored and hence not included in the calculation of the width.
 
 ** Mass Generation
-  The behaviour of the GenericMassGenerator has been changed so that modes
-  which have been disabled are only included in the calculation of the total
-  width and not in the partial width used in the numerator of the weight used
-  to select the off-shell mass.
+   The behaviour of the GenericMassGenerator has been changed so that modes
+   which have been disabled are only included in the calculation of the total
+   width and not in the partial width used in the numerator of the weight used
+   to select the off-shell mass.
 
 ** Boost detection
-  Boost could not detect the compiler version for gcc-5.3 and gcc-6.1
-
-
+   Boost could not detect the compiler version for gcc-5.3 and gcc-6.1
 
 * Herwig 7.0.1 release: 2016-01-17
 
 ** Version number written to log file
    The Herwig version number is now included in addition to ThePEG's version.
 
 ** Tau lifetimes
    A bug with lifetimes for hard process Taus is fixed. Thanks to ATLAS
    for the report!
 
 ** Shower FSR retries
    Rare events could take a long time due to an extremely large number
    of FSR retries. These are now capped at a configurable number.
 
 ** Dipole shower
    Reweighting for non-radiating events; fixes for shower profile
    handling; option to downgrade large-Q expansion for alphaS
 
 ** Matchbox builtins
    Added massive currents for q-qbar
 
 ** ShowerAlphaQCD
    can now use user-defined thresholds
 
 ** Input snippets
    W/Z/H on-shell now split into three files; 4-flavour scheme added
 
 ** UFO converter
    The converter now has experimental support for writing out param
    cards of its current settings.
 
 ** LEPJetAnalysis loading fixed
 
 ** Contrib
    HJets++ has moved to a stand-alone project, FxFx has been added
 
 * Herwig 7.0.0 (Herwig++ 3.0.0) release: 2015-12-04
 
 ** Major new release
    A major new release of the Monte Carlo event generator Herwig++ (version
    3.0) is now available. This release marks the end of distinguishing
    Herwig++ and HERWIG development and therefore constitutes the first major
    release of version 7 of the Herwig event generator family. The new version
    features a number of significant improvements to the event simulation,
    including: built-in NLO hard process calculation for all Standard Model
    processes, with matching to both angular ordered and dipole shower modules
    via variants of both subtractive (MC@NLO-type) and multiplicative
    (Powheg-type) algorithms; QED radiation and spin correlations in the
    angular ordered shower; a consistent treatment of perturbative
    uncertainties within the hard process and parton showering, as well as a
    vastly improved documentation. This version includes (for a more detailed
    overview and further references please see the release note
    arXiv:1512.01178):
 
 ** A long list of improvements and fixes for the Matchbox module
 *** includes MC@NLO and Powheg matching to both showers with truncated showering
 
 ** A long list of improvements and fixes for both of the shower modules
 *** includes improvements of numerics issues relevant to 100 TeV pp collisions
 
 ** NLO event simulation and Matchbox development
 *** Interfaces to a number of external libraries
 *** A new workflow for event generation
 *** Electroweak corrections to VV production
 
 ** Parton shower development
 *** QED radiation in the angular ordered shower
 *** Spin correlations in the angular ordered shower
 *** New scale choices in gluon branchings
 
 ** Improvements to event generation workflow
 *** Re-organized and streamlined input files for the new NLO development
 *** A unified treatment of shower and matching uncertainties
 *** New integrator modules featuring parallel integration
 
 ** New default tunes for both shower modules
 
 ** New contrib modules
 *** Electroweak Higgs plus jets production
 *** FxFx merging support
 *** Higgs boson pair production
 
 
 
 * Herwig++-2.7.1 release: 2014-07-07
 
 ** New shower switches to select schemes for momentum reconstruction
 *** QTildeReconstructor:FinalStateReconOption
     has the following options:
 *** Default
     All momenta are rescaled in the rest frame.
 *** MostOffShell
     Put all particles on the new-mass shell and the most off-shell and
     recoiling system are rescaled to ensure 4-momentum is conserved.
 *** Recursive
     Recursively put the most off-shell particle which hasn't yet been
     rescaled on-shell by rescaling the particles and the recoiling
     system.
 *** 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.
 *** RestRecursive
     As above, but recursively treat the currently most-off shell
     (only makes a difference for more than 3 partons)
 
 ** Ticket #378: Hadronization of baryon number violating clusters involving diquarks
    Fixed by only considering non-diquarks to be combined in the
    ClusterFinder.
 
 ** UFO converter can now parse SLHA files for parameter settings
    The UFO converter code can now use SLHA files for modifying
    parameters. The first pass "ufo2herwig" produces the model to be
    compiled. For each parameter card, run "slha2herwig" to get the
    matching input file.
 
 ** Fix for systems using lib64
    The repository is now initialized correctly on systems using lib64
    as the library location.
    
 ** Efficiency optimization
    Better allocation of internal vector variables for a noticeable
    speed increase of 10-20% with LHC events.
 
 
 
 * Herwig++-2.7.0 release: 2013-10-28
 
 ** UFO interface to Feynman rules generators
    Herwig++ now includes "ufo2herwig", a tool that automatically
    creates all required files to run a BSM model from a UFO
    directory. The conversion has been extensively tested against
    Feynrules models MSSM, NMSSM, RS, Technicolor,
    and less extensively with most of the
    other models in the Feynrules model database.
    We expect that following this release there will be no further
    hard-coded new physics models added to Herwig++ and that future
    models will be included using the UFO interface.
 
 ** Shower uncertainties
    A first set of scaling parameters to estimate shower uncertainties
    is provided for both the angular ordered as well as the dipole
    shower; they are Evolver:HardScaleFactor and ShowerAlphaQCD:
    RenormalizationScaleFactor. 
 
 ** Rewrite of Matchbox NLO matching
    The NLO matching implementation has been rewritten and is now more
    flexible and consistent. Profile scales are provided for the
    hardest emission both for the dipole shower and matrix element
    correction matching.
 
 ** BLHA2 Interface and new processes
    Matchbox now features a generic BLHA2 interface to one-loop
    amplitude codes and now also includes W and W+jet production as
    well as Higss production in gluon fusion as builtin processes.
 
 ** Impoved dipole shower kinematics parametrization
    The kinematics parametrization for emissions in the dipole shower
    has been made more efficient.
 
 ** W and Z Powheg decays
    Decays of W and Z bosons now use the Powheg decayers by default.
 
 ** Improved treatment of beam remnants
    The handling of beam remnants has been improved in multiple
    contexts, leading to a much lower error rate at p+/p- collisions.
    An additional value "VeryHard" for ClusterFissioner:RemnantOption
    can be used to disable any special treatment of beam remnant
    clusters.
 
 ** New underlying event tune
    Herwig++ now uses tune UE-EE-5-MRST by default. Other related tunes
    can be obtained from the Herwig++ tunes page
 
 ** Improvements in BSM code
    The UFO development identified many sign fixes in rarely used BSM
    vertices; many improvements were made to general decayers, allowing
    four-body decays in BSM for the first time; Powheg is enabled in
    General two-body decayers; and the handling of colour
    sextets has been improved.
 
 ** A new HiggsPair matrix element in Contrib.
 
 ** A new matrix element for single top production.
 
 ** The Higgs mass is now set to 125.9 GeV (from PDG 2013 update).
 
 ** C++-11 testing
    To help with the coming transition to C++-11, we provide the new
    --enable-stdcxx11 configure flag. Please try to test builds with
    this flag enabled and let us know any problems, but do not use this
    in production code yet. In future releases, this flag will be on by
    default.
 
 ** Other changes
 *** Many new Rivet analyses have been included in the Tests directory.
 *** Cleaned Shower header structure; grouped shower parameters into one struct.
 *** The boolean Powheg flag in HwMEBase changed to an enumeration.
 
 
 
 
 * Herwig++-2.6.3 release: 2013-02-22
 
 ** Decay vertex positioning in HepMC output
    Pseudo-vertices that Herwig++ inserts for technical reasons will
    now not contribute to the Lorentz positions of downstream vertices.
    Thanks to ATLAS for the bug report!
 
 ** Updated Rivet tests 
    Herwig's library of Rivet test runs has been brought up-to-date
    with new analyses that were recently published by the Rivet
    collaboration.
 
 
 
 * Herwig++-2.6.2 release: 2013-01-30
 
 ** Fixes for PDF and scale choices in POWHEG events
    Scale settings for MPI and the regular shower are now correct in
    POWHEG events. This should fix reported anomalies in POWHEG jet rates.
    NLO PDFs are now also set consistently in the example input files.
 
 ** Ticket #373: Branching ratio factors in cross-section
    If any decay modes are selectively disabled, setting the following
    post-handler will cause all reported cross-sections to include the
    branching ratio factor(s) from the previous stages correctly:
 
    create Herwig::BranchingRatioReweighter BRreweight
    insert LHCGenerator:EventHandler:PostDecayHandlers 0 BRreweight
 
 ** Anomalous vertices now possible in MEfftoVH
 
 ** Interactive shell does not quit on error
 
 ** Better warning messages for events from inconsistent LHEF files
 
 ** Possible division by zero error fixed in BSM branching ratio calculations
 
 ** Decayer and ME changes to improve checkpointing
    The checkpointing changes in ThePEG 1.8.2 are implemented here, too. Regular
    dump files are consistent now.
 
 
 
 * Herwig++-2.6.1 release: 2012-10-16
 
 ** Configure switches
    The various switches to turn off compilation of BSM models have
    been unified into a single '--disable-models'. A new flag
    '--disable-dipole' can be used to turn off the compilation of the
    Dipole and Matchbox codes.
 
 ** Ticket #348: Search path for repository 'read' command
    The search path for the 'read' command is configurable on the
    command line with the -i and -I switches. By default, the
    installation location is now included in the search path, so that
    'Herwig++ read LEP.in' will work in an empty directory. The current
    working directory will always be searched first. 
    The rarely used "Herwig++ init" command has been made consistent
    with 'read' and 'run' and should now be used without the '-i' flag.
 
 ** Width treatment in BSM
    The width treatment in BSM decay chains has been greatly improved
    and is now switched on by default in the .model files. To get the
    old behaviour, use 
      set /Herwig/NewPhysics/NewModel:WhichOffshell Selected
 
 ** New BSM models
    Little Higgs models with and without T-parity are now available.
 
 ** Resonance photon lifetime
    A lifetime bug affecting decays of pi0 to e+e-X was fixed. The
    virtual photon is not part of the event record anymore.
 
 ** Ticket #371: Hard diffraction FPE
    Herwig++ 2.6.0 introduced a bug into the diffraction code which
    would abort any runs. This is now fixed.
 
 ** O2AlphaS
    Support for setting quark masses different from the particle data
    objects as introduced in ThePEG 1.8.1 has been enabled.
 
 ** Matchbox
    Several improvements and bug fixes are included for
    Matchbox. Amplitudes relevant to pp -> Z+jet and crossed processes
    at NLO are now available, and various scale choices have been added
    in a more flexible way. All subtraction dipoles for massive quarks
    are now included.
 
 ** Dipole shower
    Parameters to perform scale variations in the shower have been
    added to estimate uncertainties. A bug in showering off gg -> h has
    been fixed.
 
 ** Minor fixes
 *** Two broken colour structures in GeneralHardME
 *** Susy Higgs mixing matrix
 *** BaryonFactorizedDecayer out-of-bounds access
 *** Mass values in SimpleLHCAnalysis
 
 
 
 * Herwig++-2.6.0 release: 2012-05-21 (tagged at SVN r7407)
 
 ** New NLO framework
    Matchbox, a flexible and very general framework for performing NLO
    calculations at fixed order or matched to parton showers is
    provided with this release.
 
 ** Dipole shower algorithm
    A first implementation of the coherent dipole shower algorithm by
    Plätzer and Gieseke (arXiv:0909.5593 and arXiv:1109.6256) is
    available.
 
 ** Alternative samplers and the ExSample library
    The ExSample library by Plätzer (arXiv:1108.6182) is shipped along
    with Herwig++ in an extended version. The extended version provides
    SamplerBase objects which can be used alternatively to the default
    ACDCSampler.
 
 ** New BSM models
 *** New colour sextet diquark model
     A colour sextet diquark model has been included, as described in
     Richardson and Winn (arXiv:1108.6154).
 
 *** Models reproducing the CDF t-tbar asymmetry
     Four models that can reproduce the reported t-tbar asymmetry have
     been included. 
     
 *** Zprime
     A simple standard model extension by one additional heavy neutral
     vector boson.
 
 ** Interface to AlpGen, with MLM merging
    The Contrib directory contains a new interface to the AlpGen matrix
    element generator. AlpGen events must be preprocessed with the
    provided AlpGenToLH.exe tool before they can be used. More
    information can be found in the Herwig++ 2.6 release note.
 
 ** HiggsVBF Powheg
    Higgs boson production by vector boson fusion is available at NLO
    in the POWHEG scheme, as described in d'Errico, Richardson
    (arXiv:1106.2983). The Powheg DIS processes were available in
    Herwig++-2.5.2 already.
    
 ** Statistical colour reconnection
    Alternative mechanisms to minimize the colour length Sum(m_clu)
    before the hadronization stage, based on Metropolis and annealing
    algorithms.
 
 ** Energy extrapolation of underlying-event tunes
    To describe underlying-event data at different c.m. energies, the
    energy-dependent parameter pT_min will now be adjusted
    automatically, following a power-law. The new tune parameters are
    the value at 7000 GeV "MPIHandler:pTmin0", and MPIHandler:Power.
 
 ** Ticket #239: Reporting of minimum-bias cross-section
    When simulating minimum-bias events using the MEMinBias matrix
    element, the correct unitarized cross section can now be reported
    via the standard facilities; it is no longer necessary to extract
    it from the .log file of the run. The corresponding functionality
    is enabled by inserting a MPIXSecReweighter object as a
    post-subprocess handler: 
    create Herwig::MPIXSecReweighter MPIXSecReweighter 
    insert LHCHandler:PostSubProcessHandlers 0 MPIXSecReweighter
 
 ** Dependency on 'boost'
    Herwig++ now requires the boost headers to build; if not detected
    in standard locations, specify with the --with-boost configure
    option.
 
 ** Tests directory
    The Tests directory now contains input cards for almost all Rivet
    analyses. A full comparison run can be initiated with 'make tests'.
 
 ** Minor changes
 *** Default LHC energy now 8 TeV
     All LHC-based defaults have now been updated to use 8 TeV as the
     center-of-mass energy.
 
 *** Herwig::ExtraParticleID -> ThePEG::ParticleID
     The namespace for additional particles has been unified into
     ThePEG::ParticleID
 
 *** MEee2VectorMeson
     The e+e- -> vector meson matrix element has moved from Contrib into
     HwMELepton.so
 
 *** SUSY numerics fixes
     Better handling of rare numerical instabilities.
 
 *** YODA output for Rivet
     The built-in histogramming handler can now output data in the YODA
     format used by Rivet.
 
 *** Consistency checks in SLHA file reader
     Better warnings for inconsistent SusyLHA files
 
 *** better colour flow checking for development
 
 ** Bug fixes
 *** Extremely offshell W from top decay
     Numerical improvements for very off-shell W bosons coming from top
     decays.
 
 *** Ticket #367: problems in using SUSY + LHE
     Susy events from Les Houches event files are now handled better.
 
 *** Infinite loop in remnant decayer
     The remnant decayer will now abort after 100 tries.
 
 *** Fix to HiggsVBF LO diagrams 
     The diagram structure of HiggsVBF LO matrix elements has been fixed.
 
 *** LEP thrust fix 
     The calculation of the transverse momentum of a branching from the
     evolution variable in final-state radiation can now be
     changed. While formally a sub-leading choice this enables a better
     description of the thrust distribution in e+e- collisions at
     small values of the thrust. Currently the default behaviour, where
     the cut-off masses are used in the calculation, remains the same
     as previous versions.
 
 
 
 
 * Herwig++-2.5.2 release: 2011-11-01 (tagged at SVN r6928)
 
 ** Optional new jet vetoing model
    The jet vetoing model by Schofield and Seymour (arXiv:1103.4811) is
    available via Evolver:ColourEvolutionMethod,
    PartnerFinder:PartnerMethod and SplittingFunction:SplittingColourMethod.
    The default behaviour is unchanged.
 
 ** MPI tune
    Version 3 of the MPI tunes is now the default. Please note that the
    pT parameter is energy-dependent and needs to be modified when an
    LHC run is not at 7 TeV.
    The latest tunes are always available at 
      http://projects.hepforge.org/herwig/trac/wiki/MB_UE_tunes
 
 ** MPI PDFs
    MPI PDFs can now be controlled independently.
 
 ** Initialization time speedup
    A new BSMModel base class was introduced between StandardModel and
    the BSM model classes. Together with a restructured decay mode
    initialization, this offers significantly faster startup times for
    BSM runs. ThreeBodyDecays can now always be switched on without a
    large speed penalty.
 
 ** Decay mode file
    Decay mode files in the SLHA format can now be read separately in
    any BSM model with 'set Model:DecayFileName filename'
 
 ** Powheg DIS
    Charged- and neutral-current DIS processes implementing the POWHEG
    method are now available.
 
 ** Diffraction models
    Xi cut implemented in PomeronFlux
 
 ** Ticket #352: Colour reconnection fixed in DIS
 
 ** Ticket #353: Improved numerical stability in chargino decays
 
 ** Ticket #358: Infinite loop in top events with pT cut in shower
 
 ** Ticket #361: Problem with duplicate 2-body modes in BSM
 
 ** Tickets #362 / #363: Crashes with baryon number violating models
    Particle decays in SUSY models with RPV now work correctly in the
    colour 8 -> 3,3,3 case. Colour reshuffling now works for RPV
    clusters.
 
 ** Improved Fastjet detection
    The configure step uses fastjet-config to make sure all header file
    paths are seen.
 
 ** Darwin 11 / OS X Lion
    A configure bug was fixed which prevented 'make check' from
    succeeding on OS X Lion.
 
 ** Vertex classes
    The specification of QED / QCD orders has been moved to the vertex
    constructors, to allow ThePEG consistency checks. WWHH vertices in
    MSSM and NMSSM were fixed. Some Leptoquark and UED vertices fixed.
 
 ** Hadronization
    Cleanup of obsolete code.
 
 
 
 * Herwig++-2.5.1 release: 2011-06-24 (tagged at SVN r6609)
 
 ** Example input files at 7 TeV
    All our example input files for LHC now have their beam energy set
    to 7 TeV instead of 14 TeV.
 
 ** Colour reconnection on by default
    The colour reconnection tunes are now the default setup. Version 2
    of the tunes replaces the *-1 tunes, which had a problem with LEP
    event shapes.
 
 ** Run name tags
    Aded possibility to add a tag to the run name when running with the
    '-t' option. One run file can thus be run with different seeds and
    results stored in different output files.
 
 ** Floating point exceptions
    The new command line option -D enables floating point error checking.
 
 ** General improvements to WeakCurrent decays
 
 ** Remnant decayer
    Hardwired gluon mass was removed.
 
 ** WeakCurrentDecayConstructor
    Instead of specifying separate Particle1...Particle5 vectors for
    the decay modes, the new interface DecayModes can be filled with
    decay tags in the standard syntax.
 
 ** BSM: improvements to handling of vertex and model initialisation
 
 ** Powheg Higgs
    Option to use pT or mT as the scale in alphaS and for the
    factorization scale in the PDFs
 
 ** Ticket #337: Tau polarization wrong in charged Higgs decay
 
 ** Ticket #339: Colour flows in GeneralThreeBody Decayers for 3bar -> 8 3bar 1
 
 ** Ticket #340: Crash for resonant zero-width particles
 
 ** Ticket #341: Varying scale for BSM processes
    The scale used is now ResonantProcessConstructor:ScaleFactor or
    TwoToTwoProcessConstructor:ScaleFactor multiplied by sHat.
 
 ** Ticket #346: Chargino decays
    Chargino decayers now automatically switch between the mesonic
    decays for mass differences less than 2 GeV and the normal partonic
    decays above 2 GeV.
 
 ** Ticket #349: Stop by default on input file errors
    The '--exitonerror' flag is now the default behaviour for the
    Herwig++ binary. To switch back to the old behaviour,
    '--noexitonerror' is required.
 
 ** Ticket #351: Four-body stop decays
 
 ** Tested with gcc-4.6
 
 
 
 * Herwig++-2.5.0 release: 2011-02-08 (tagged at SVN r6274)
 
 ** Uses ThePEG-1.7.0
    Herwig++ 2.5.0 requires ThePEG 1.7.0 to benefit from various
    improvements, particularly: handling of diffractive processes;
    respecting LD_LIBRARY_PATH when loading dynamic libraries,
    including LHAPDF; improvements to repository commands for decay
    modes. See ThePEG's NEWS file for more details.
 
 ** POWHEG improvements
 
 *** New POWHEG processes
     Simulation at NLO accuracy using the POWHEG method is now
     available for hadronic diboson production (pp to WW,WZ,ZZ), Higgs
     decays to heavy quarks, and e+e- to two jets or ttbar, including
     full mass dependence.
 
 *** Input file changes
     The input files for setting up POWHEG process simulation have been
     simplified.  See the example files LHC-Powheg.in and TVT-Powheg.in
     for the improved command list.
 
 *** Structural changes
     The POWHEG backend in the shower code has been restructured to
     make future additions easier: PowhegEvolver has merged with
     Evolver; both the matrix element corrections and real corrections
     in the POWHEG scheme are implemented directly in the ME or Decayer
     classes.
 
 ** New processes at leading order
 
 *** Photon initiated processes
     We have added a matrix element for dijet production in gamma
     hadron collisions.
     
 *** Bottom and charm in heavy quark ME
     The option of bottom and charm quarks is now supported for heavy
     quark production in MEHeavyQuark.
 
 ** Colour reconnection
    The cluster hadronization model has been extended by an option to
    reconnect coloured constituents between clusters with a given
    probability. This new model is different from the colour
    reconnection model used in FORTRAN HERWIG, and improves the
    description of minimum bias and underlying event data.
 
 ** Diffractive Processes
    Both single and double diffractive processes are now supported in
    Herwig++. The Pomeron PDF is implemented using a fit to HERA data,
    and a pion PDF can be used to model reggeon flux.
 
 ** BSM physics
 
 *** New models 
     We have added new BSM models, particularly ADD-type extra
     dimension models and the next-to-minimal supersymmetric standard
     model (NMSSM).  Effects of leptoquarks can as well be simulated.
 
 *** Vertex additions
     We have added flavour changing stop interactions (stop -
     neutralino - charm) and gravitino interactions with particular
     emphasis on numerical stability for very light gravitinos.
     Tri-linear Higgs and Higgs-Higgs/Vector-Vector four-vertices are
     available as well.
 
 *** Input file changes
     The SUSY model can now also extract the SLHA information from the
     header of a Les Houches event file: replace the SLHA file name
     in the example input files with the LH file name.
 
 *** Structure
     The backend structure of the HardProcessConstructor has changed,
     to allow easier inclusion of new process constructors. Some 2->3
     BSM scattering processes involving neutral higgs bosons are now
     included. The spin handling has been improved in the background. 
 
 ** Shower splitting code reorganized
    The selection of spin structures has been decoupled from the choice
    of colour structure. This gives more flexibility in implementing
    new splittings. Selected splittings can be disabled in the input
    files.
 
 ** B mixing
    B mixing, and indirect CP violation in the B meson system are
    included now.
    
 ** Looptools
    The Looptools directory has been updated to reflect T.Hahn's
    Looptools 2.6.
 
 ** Contrib changes
    The ROOT interface has been removed as deprecated. The MCPWNLO code
    has temporarily been removed from the Contrib directory as a major
    review of this code is required. Additionally, there are various
    fixes to all other codes shipped in Contrib.
 
 ** DIS improvements
    The momentum reshuffling in DIS events has been improved.
 
 ** mu and nu beams
    mu, nu_e and nu_mu and their antiparticles are now available as
    beam particles. They are all supported in the DIS matrix
    elements. mu+ mu- collisions are supported in the general
    matrix element code for BSM models, but not yet in the hard-coded
    matrix elements for lepton-lepton scattering.
 
 ** Structural changes
 
 *** Inline code
     Inline code has been merged into the header files, .icc files were
     removed.
 
 *** Silent build
     By default, Herwig++ now builds with silent build rules. To get
     the old behaviour, run 'make V=1'.
 
 *** Debug level
     The debug level on the command line will now always have priority.
 
 *** Event counter
     The event counter has been simplified.
 
 *** Interpolator persistency
     Interpolators can now be written persistently.
 
 ** Ticket #307: Momentum violation check in BasicConsistency
    Added parameters AbsoluteMomentumTolerance and
    RelativeMomentumTolerance
 
 ** Example POWHEG input files
    The example input files for Powheg processes now set the NLO
    alpha_S correctly, and are run as part of 'make check'.
 
 ** Truncated shower
    A problem which lead to the truncated shower not being applied in
    some cases has been fixed.
 
 ** Fixes to numerical problems
    Minor problems with values close to zero were fixed in several
    locations.
 
 ** Remove duplicated calculation of event shapes
    An accidental duplication in the calculation of event shapes was
    removed, they are now only calculated once per event. Several other
    minor issues in the event shape calculations have also been fixed.
 
 ** MRST PDFs fixed
    An initialization problem in the internal MRST PDFs was fixed.
 
 ** Vertex scale choice
    The scale in the Vertex classes can now be zero where
    possible.
 
 ** Treatment of -N flag
    The Herwig++ main program now correctly treats the -N flag
    as optional.
 
 ** Numerical stability improved
    The numerical stability in the 'RunningMass' and
    'QTildeReconstructor' classes has been improved.  The
    stability of the boosts in the SOPTHY code for the
    simulation of QED radiation has been improved.
    The accuracy of boosts in the z-direction has been improved to
    fix problems with extremely high p_T partons.
 
 ** Bugfix in initial state splittings
    A bug in the implementation of the PDF weight in initial-state
    qbar -> qbar g  splittings has been fixed.
 
 ** Bugfix in chargino neutralino vertices
    A bug in the 'chi+- chi0 W-+' and charged
    Higgs-sfermions vertices has been fixed.
 
 ** Remove uninitialized variables written to repository
    A number of uninitialised variables which were written to the
    repository have been initialised to zero to avoid problems on some
    systems.
 
 ** Fix to QED radiation in hadronic collisions
    The longitudinal boost of the centre-of-mass frame in hadronic
    collisions is correctly accounted for now in the generation of QED
    radiation.
 
 ** Fix to numerical problems in two-body decays
    Numerical problems have been fixed, which appeared in the rare case
    that the three-momenta of the decay products in two-body decays are
    zero in the rest frame of the decay particle.
 
 ** A problem with forced splittings in the Remnant was fixed.
 
 ** ME correction for W+- decays applied properly
    The matrix element correction for QCD radiation in W+- decays
    which was not being applied is now correctly used.
 
 ** Top quark decays from SLHA file
    The presence of top quark decay modes in SLHA files is now handled
    correctly.
 
 ** Exceptional shower reconstruction kinematics
    Additional protection against problems due to the shower
    reconstruction leading to partons with x>1 has been added.
 
 ** Ordering of particles in BSM processes
    Changes have been made to allow arbitrary ordering of the outgoing
    particles in BSM processes.
 
 ** Bugfixes in tau decays
    Two bugs involving tau decays have been fixed. The wrong masses
    were used in the 'KPiCurrent' class for the scalar form factors
    and a mistake in the selection of decay products lead to
    tau- --> pi0 K- being generated instead of tau- --> eta K-.
 
 ** Avoid crashes in baryon number violating processes.
    To avoid crashes, better protection has been introduced for the
    case where diquarks cannot be formed from the quarks in a
    baryon-number violating process. In addition, the parents of the
    baryon-number violating clusters have been changed to avoid
    problems with the conversion of the events to HepMC.
 
 ** QED radiation in W- decays
    A bug in the 'QEDRadiationHandler' class which resulted
    in no QED radiation being generated in W- decays has been fixed.
 
 ** A number of minor fixes to the SUSY models have been made.
 
 ** Partial width calculations in BSM models  
    A fix for the direction of the incoming particle in the calculation
    of two-body partial widths in BSM models has been made.
 
 ** LoopTools improvements   
    The LoopTools cache is now cleared more frequently to
    reduce the amount of memory used by the particle.
 
 ** Negative gluino masses are now correctly handled.
 
 ** A problem with mixing matrices which are not square has been fixed. 
 
 ** Removed duplicate diagram
    The 'MEee2gZ2ll' class has been fixed to only include the
    photon exchange diagram once rather than twice as previously.
 
 ** Fix for duplicate particles in DecayConstructor
    A problem has been fixed which occurred if the same particle was
    included in the list of DecayConstructor:DecayParticles.
 
 ** Fixes for UED model vertices
    A number of minor problems in the vertices for the UED model have
    been fixed.
 
 ** Include missing symmetry factor
    The missing identical-particle symmetry factor in
    'MEPP2GammaGamma' has been included.
 
 ** Fix floating point problem in top decays
    A floating point problem in the matrix element correction for top
    decays has been fixed.
 
 
 
 * Herwig++-2.4.2 release: 2009-12-11 (tagged at SVN r5022)
 
 ** Ticket #292: Tau decay numerical instability
    The momentum assignment in tau decays contained numerical
    instabilities which have been fixed by postponing the tau decay
    until after the parton shower. A new interface setting
    DecayHandler:Excluded is available to prevent decays in the shower
    step. This is enabled by default for tau only.
 
 ** Ticket #290: Missing MSSM colour structure
    The missing colour structure for gluino -> gluon neutralino was added.
 
 ** Ticket #294: Zero momentum in some decays
    Some rare phase space points lead to zero momentum in two-body
    decays. This has been fixed.
 
 ** Ticket #295: Stability of QED radiation for lepton collider processes
    The numerical stability of QED radiation momenta was improved
    further.
 
 ** Ticket #296: K0 oscillation vertex was wrong
    The oscillation from K0 to K0_L/S now takes place at the production
    vertex of K0.
 
 ** Ticket #289: Undefined variables in repository
    On some system configurations, undefined variables were written to
    the repository. These have been fixed.
 
 ** Fixed QED radiation for hadron processes
    The longitudinal boost of the centre-of-mass frame in hadronic
    collisions is correctly accounted for now.
 
 ** Numerical stability fixes 
    Small fixes in RunningMass and QTildeReconstructor.
 
 ** Powheg example input files
    The example input files for Powheg processes now set the NLO
    alpha_S correctly, and are run as part of 'make check'.
 
 ** OS X builds for Snow Leopard
    Snow Leopard machines will now be recognized as a 64bit
    architecture.
 
 
 
 
 * Herwig++-2.4.1 release: 2009-11-19 (tagged at SVN r4932)
 
 ** Uses ThePEG-1.6.0 
    Herwig++ now requires ThePEG-1.6.0 to benefit from the improved
    helicity code there. If you have self-written vertex classes, see
    ThePEG's NEWS file for conversion instructions.
 
 ** Vertex improvements
    ThePEG's new helicity code allowed major simplification of the vertex
    implementations for all Standard Model and BSM physics models.
 
 ** New Transplanckian scattering model
    An example configuration is in LHC-TRP.in
 
 ** BSM ModelGenerator as branching ratio calculator
    The BSM ModelGenerator has a new switch to output the branching
    ratios for a given SLHA file in SLHA format, which can then be used
    elsewhere.
 
 ** BSM debugging: HardProcessConstructor
    New interface 'Excluded' to exclude certain particles from
    intermediate lines.  
 
 ** Chargino-Neutralino-W vertex fixed
 
 ** Spin correlations
    are now switched on by default for all perturbative decays.
 
 ** Ticket #276: Scale choice in BSM models' HardProcessConstructor
    New interface 'ScaleChoice' to choose process scale between 
    - sHat (default for colour neutral intermediates) and 
    - transverse mass (default for all other processes).
 
 ** Ticket #287: Powheg process scale choice
    The default choice is now the mass of the colour-singlet system.
    
 ** Ticket #278: QED radiation for BSM
    Soft QED radiation is now enabled in BSM decays and all
    perturbative decays by default. 
 
 ** Ticket #279: Full 1-loop QED radiation for Z decays
    Soft QED radiation in Z decays is now fully 1-loop by default.
 
 ** Ticket #280: Redirect all files to stdout
    This is now implemented globally. The files previously ending in
    -UE.out and -BSMinfo.out are now appended to the log file. They now
    also obey the EventGenerator:UseStdout flag.
 
 ** Ticket #270: LaTeX output updated
    After each run, a LaTeX file is produced that contains the full
    list of citations. Please include the relevant ones in publications.
 
 ** Ticket #256: Mac OS X problems
    An initialization problem that affected only some configurations has
    been identified and fixed.
 
 ** Tests directory added
    This contains many .in files, to exercise most matrix
    elements. 
 
 ** Minor fixes
 *** Prevent rare x>1 partons in shower reconstruction.
 *** SUSY-LHA parameter EXTPAR can be used to set tan beta
 *** Improved Fastjet detection at configure time
 
 
 
 
 
 * Herwig++-2.4.0 release: 2009-09-01 (tagged at SVN r4616)
 
 ** New matrix elements
    We have added a built-in implementation of several new matrix elements:
    PP --> WW / WZ / ZZ
    PP --> W gamma / Z gamma
    PP --> VBF Higgs
    PP --> Higgs tt / Higgs bb
    e+e- --> WW / ZZ
    gamma gamma --> ff / WW 
 
 
 
 ** Base code improvements
 *** Ticket #257: Remnant handling
     A problem with forced splittings in the Remnant was fixed.
 
 *** Ticket #264: Soft matrix element correction
     A problem with emissions form antiquarks was fixed. 
 
 
 
 ** PDF sets
 *** New default set
     MRST LO** is the new default PDF set. LO* is also available built-in.
 
 *** Shower PDFs can be set separately from the hard process
     Use the 'ShowerHandler:PDF' interface.
 
 
 
 ** Parameter tunes
     Shower, hadronization and underlying event parameters were retuned
     against LEP and Tevatron data respectively.
 
 
 
 ** BSM module improvements
 *** Ticket #259: read error for some UED models
     Arbitrary ordering of outgoing lines in the process description is now
     possible.
 
 *** Ticket #266: branching ratio sums
     The warning threshold for branching ratios not summing to 1 has
     been relaxed. It is now a user interface parameter.
 
 *** Ticket #267: Top decay modes
     Top decay modes listed in SLHA files are now handled correctly.
 
 
 
 ** QED radiation 
 *** Ticket #241: Soft QED radiation is now enabled by default
 
 *** Ticket #265: Radiation off W+ and W- is now handled correctly
 
 
 
 ** Interfaces
 *** Ticket #243: Fastjet
     Fastjet is now the only supported jet finder code. All example
     analyses have been converted to use Fastjet.
 
 *** KtJet and CLHEP interfaces have been removed.
 
 *** New interfaces to AcerDet and PGS available in Contrib
 
 *** MCPWnlo distributed in Contrib
 
 *** HepMC and Rivet interfaces moved to ThePEG
 
 
 
 ** Ticket #239: Inelastic cross-section for MinBias
    This information is now available in the ...-UE.out files.
 
 
 
 ** Technical changes
 *** Ticket #186
     Configure now looks for ThePEG in the --prefix location first.
 
 *** Configure information
     Important configuration information is listed at the end of the
     'configure' run and in the file 'config.thepeg'. Please provide
     this file in any bug reports.
 
 *** New ZERO object
     The ZERO object can be used to set any dimensionful quantity to
     zero. This avoids explicit constructs like 0.0*GeV.
 
 *** Exception specifiers removed
     Client code changes are needed in doinit() etc., simply remove the
     exception specifier after the function name.
 
 *** Ticket #263: Tau polarizations can be forced in TauDecayer
 
 
 
 
 
 * Herwig++-2.3.2 release: 2009-05-08 (tagged at SVN r4249)
 
 ** SUSY enhancements
 
 *** Ticket #245: Select inclusive / exclusive production
     Using the new 'HardProcessConstructor:Processes' switch options
     'SingleParticleInclusive', 'TwoParticleInclusive' or 'Exclusive'
 *** Improved three-body decay generation
     Several problems were fixed, incl. tickets #249 #250 #251
     Thanks to J.Tattersall and K.Rolbiecki for the stress-testing!
 *** Looptools fix
     Release 2.3.1 had broken the Looptools initialization.
 *** Improved warning message texts
 
 ** Ticket #237:
    Values of q2last can now be zero where possible.
 
 ** Ticket #240:
    The Herwig++ main program now correctly treats the -N flag as optional.
 
 ** Ticket #246:
    Extreme pT partons fixed by improving accuracy of z boosts.
 
 ** DIS
    Improved parton shower momentum reshuffling.
 
 ** Minimum Bias events
    The zero-momentum interacting particle used for
    bookkeeping is now labelled as a pomeron. 
 
 ** User Makefile
    Makefile-UserModules does not enable -pedantic anymore. User's ROOT
    code will not compile otherwise.
 
 ** Build system
    Small fixes in the build system.
 
 
 
 * Herwig++-2.3.1 release: 2009-03-31 (tagged at SVN r4140)
 ** Initial state showers
    The PDF veto was wrongly applied to qbar->qbar g splittings.
 
 ** User interaction
    The Makefile-UserModules now includes the Herwig version number.
    The -N flag to 'Herwig++ run' is optional now, as was always intended.
 
 ** Contrib
    The contrib directory is now included in the tarball. The omission
    was accidental.
 
 ** Numerical accuracy
    Minor problems with values close to zero were fixed in several
    locations.
 
 ** LEP event shapes
    An accidental duplication was removed, they are now only calculated
    once per event.
 
 ** MRST PDF code
    Initialization problem fixed.
 
 ** Mac OS X
    The configure script was improved to detect libraries better.
 
 ** Libtool
    Updated to version 2.2.6
 
 
 * Herwig++-2.3.0 release: 2008-12-02 (tagged at SVN r3939)
 ** Major release, with many new features and bug fixes
 
 ** Extension to lepton-hadron collisions
 
 ** Inclusion of several processes accurate at next-to-leading order
    in the POsitive Weight Hardest Emission Generator (POWHEG) scheme
 
 ** Inclusion of three-body decays and finite-width effects
    in BSM processes
 
 ** New procedure for reconstructing kinematics of the parton shower
    based on the colour structure of the hard scattering process
 
 ** New model for baryon decays including excited baryon multiplets
 
 ** Addition of a soft component to the multiple scattering model
    of the underlying event and the option to choose more than one hard
    scattering explicitly
 
 ** New matrix elements for DIS and e+e- processes
 
 ** New /Contrib directory added
    containing external modules that will hopefully be of use to some
    users but are not expected to be needed by most users and are not
    supported at the same level as the main Herwig++ code
 
 ** Minor changes to improve the physics simulation:
 
 *** IncomingPhotonEvolver added
     to allow the simulation of partonic processes with incoming photons
     in hadron collisions
 
 *** KTRapidityCut added
     to allow cuts on the p_T and rapidity, rather than just the p_T and
     pseudorapidity used in SimpleKTCut. This is now used by default for
     cuts on massive particles such as the $W^\pm$, $Z^0$ and Higgs
     bosons and the top quark
 
 *** Several changes to the decayers of B mesons
     both to resolve problems with the modelling of partonic decays and
     improve agreement with $\Upsilon(4s)$ data
 
 *** Changes to allow values other than transverse mass of final-state particles as maximum transverse momentum for radiation in parton shower
     either SCALUP for Les Houches events or the scale of the hard
     process for internally generated hard processes
 
 *** Changed defaults for intrinsic transverse momentum in hadron collisions
     to 1.9GeV, 2.1GeV and 2.2GeV for the Tevatron and LHC at 10 TeV and
     14 TeV, respectively
 
 *** Pdfinfo object is now created in the HepMC interface
     However in order to support all versions of HepMC containing this
     feature the PDF set is not specified as not all versions contain
     this information
 
 *** New option of only decaying particles with lifetimes below user specified value
 
 *** New options for the cut-off in the shower
     and some obsolete parameters removed
 
 *** Added option of switching off certain decay modes in BSM models
 
 *** Added a Matcher for Higgs boson
     to allow cuts to be placed on it
 
 *** Diffractive particles deleted from default input files
     they were not previously used
 
 ** Technical changes:
 
 *** Some AnalysisHandler classes comparing to LEP data have been renamed
     e.g. MultiplicityCount becomes LEPMultiplicityCount to avoid
     confusion with those supplied in /Contrib for observables at the
     Upsilon(4s) resonance
 
 *** Reorganisation to remove the majority of the .icc files
     by moving inlined functions to headers in an effort to improve
     compile time
 
 *** Restructured the decay libraries to reduce the amount of memory allocation
     and de-allocation which improves run-time performance
 
 *** The switch to turn off LoopTools has been removed
     because LoopTools is now used by several core modules. As LoopTools
     does not work on 64-bit platforms with g77 this build option is not
     supported
 
 *** Removed support for obsolete version of HepMC supplied with CLHEP
     and improved the support for different units options with HepMC
 
 *** EvtGen interface has been removed until it is more stable
 
 *** Support for ROOT has been removed
     it was not previously used
 
 *** CKKW infrastructure has been removed from the release
     until a concrete implementation is available
 
 *** Default optimisation has been increased from -O2 to -O3
 
 *** Handling of the fortran compiler has been improved
     mainly due to improvements in the autotools
 
 *** Use of FixedAllocator for Particle objects in ThePEG has been removed
     as it had no performance benefits
 
 ** Bugs fixed:
 
 *** Problems with the mother/daughter relations in the hard process
     and diagram selection in W+- and Z0 production in association with a
     hard jet
 
 *** In general matrix element code for fermion-vector to fermion-scalar
     where the outgoing fermion is coloured and the scalar neutral
 
 *** In the selection of diagrams in some associated squark gaugino processes
 
 *** h0->mu+mu- was being generated when h0->tau+tau-
 
 *** Normalisation in the Histogram class for non unit-weight events
 
 *** Protection against negative PDF values has been improved
     these can occur when using NLO PDF sets
 
 *** Lifetime for BSM particles is now automatically calculated
     at the same time as the width
 
 *** Hadrons containing a top quark now treated like hadrons containing BSM particles
     in order to support this possibility
 
 *** Several ambiguous uses of unsigned int
 
 *** Several variables that may have been used undefined
 
 *** Several memory leaks at initialisation
 
 *** The configuration now aborts if no fortran compiler is found
     as this is required to compile Looptools
 
 *** Several minor floating point errors that did not affect results
 
 
 
 * Herwig++-2.2.1 release: 2008-07-09 (tagged at SVN r3434)
 ** Ticket #181: BSM shower with a decay close to threshold
    Now fixed.
 
 ** Ticket #191: Split SUSY crash
    Improved error message. 
 
 ** Ticket #192: using SCALUP as the pT veto in the shower
    Now implemented.
 
 ** Ticket #194: production processes of ~chi_1(2)-
    Fixed bug in the diagram creation.
 
 ** Removed unused particles
    DiffractiveParticles.in was removed, they were never produced.
 
 ** Hadronization
    Top quark clusters now possible, handled as 'exotic' clusters.
 
 ** Improved handling of decay modes
    See ThePEG-1.3.0. 'defaultparticle' command is now obsolete. 
 
 ** Multi-Parton interactions
    Increased phase space sampling to have less than 1% uncertainty on
    average multiplicity.
 
 ** New libtool version
    gfortran is now used as default if it is available. Set FC=g77 to
    override this. 
 
 ** Fixed several memory leaks
 
 ** Memory allocation
    Now using plain 'new' and 'delete'.
 
 
 * Herwig++-2.2.0 release: 2008-04-18 (tagged at SVN r3195)
 ** Major release: now as stand-alone library
    Herwig++ is now a stand-alone dlopen() plugin to ThePEG.
    No compile-time linking to Herwig code is required. The Herwig++
    binary is a simple executable steering ThePEG, which can
    be replaced by other frontends (such as setupThePEG / runThePEG).  
 
 ** New matrix elements
    p p   -> W + jet / Z + jet / W + higgs / Z + higgs
    e+ e- -> Z + higgs
 
 ** Looptools 
    Updated to version 2.2.
 
 ** Ticket #141: segfault from using 'run' command
    Fixed by using default allocators in Herwig++, and the
    Repository::cleanup() method in ThePEG 1.2.0. 
 
 ** Ticket #157: broken gsl library path on some 64bit systems
    Paths with lib64 are correctly identified now.
 
 ** Ticket #159: p_t spectrum of ttbar pair
    Fixed identical particle multiplier in Sudakov form factor.
 
 ** Ticket #161: glibc segfault
    Rare segfault in MPI handler fixed.
 
 ** Ticket #165: rare infinite loop in four-body decay
    All 4-body decays without dedicated decayers now use the Mambo algorithm.
    A loop guard has been introduced to 3-body decays to avoid infinite retries.
 
 ** Ticket #166: rare infinite loop in top ME correction
    These very rare events (O(1) in 10^7) close to mass threshold
    now are discarded.
 
 ** Higgs width fixes
 
 ** SatPDF
    Optionally, the PDF extrapolation behaviour outside a given range 
    can now be specified.
 
 ** gcc 4.3
    Herwig++-2.2 compiles cleanly with the new gcc 4.3 series.
 
 
 
 
 * Herwig++-2.1.4 release: 2008-03-03 (tagged at SVN r3024)
 ** Ticket #152: Vertex positions
    All vertex positions of unphysical particles are set to zero until
    a fix for the previous nonsensical values can be implemented.
 
 
 
 
 * Herwig++-2.1.3 release: 2008-02-25 (tagged at SVN r2957)
 ** Ticket #129: Baryon decays
    Fix for baryon decay modes.
 
 ** Ticket #131: HepMC
    Check if IO_GenEvent exists
 
 ** Ticket #134: Hadronization
    Smearing of hadron directions in cluster decay fixed.
 
 ** Ticket #137: HepMC
    HepMC conversion allows specification of energy and length units to
    be used. 
 
 ** Ticket #139: Neutral kaons
    Ratio K_L / K_S corrected.
 
 ** Ticket #140 / #141: Crash on shutdown
    Event generation from the 'read' stage or an interface now shuts
    down cleanly. Fixes a crash bug introduced in 2.1.1 which affected
    external APIs to ThePEG / Herwig.
 
 ** Ticket #146: BSM models can be disabled
    To save build time, some or all of the BSM models can be disabled
    using the '--enable-models' configure switch.
 
 ** Reorganised .model files
    The .model files now include the model-specific particles, too.
 
 ** Re-tune
    Re-tuned hadronization parameters to LEP data. 
 
 ** Other fixes in
    QSPAC implementation in Shower; Multi-parton interaction tuning;
    MRST initialization
 
 
 
 
 * Herwig++-2.1.2 release: 2008-01-05 (tagged at SVN r2694)
 ** Ticket #127
    Thanks to a patch submitted by Fred Stober, HepMCFile now can
    output event files in all supported formats. 
 
 ** Ticket #128
    Fixed incorrect value of pi in histogram limits.
 
 ** Other fixes in
    CKKW Qtilde clusterers, BSM width cut, SUSY mixing matrices.
 
 
 
 
 * Herwig++-2.1.1 release: 2007-12-08 (tagged at SVN r2589)
 ** Bug #123
    Fixed a bug with particle lifetimes which resulted in nan for some
    vertex positions.
 
 ** Secondary scatters
    Fixed bug which gave intrinsic pT to secondary scatters.
 
 ** gcc abs bug detection
    configure now checks for and works around
    http://gcc.gnu.org/bugzilla/show_bug.cgi?id=34130
 
 ** CKKW reweighting
    Fixed wrong check for top quarks.
 
 ** MPIHandler
    Fixed call order ambiguity.
 
 
 
 
 * Herwig++-2.1.0 release: 2007-11-20 (tagged at SVN r2542)
 ** Major new release
    Herwig++-2.1 includes significant improvements, including
    multi-parton interactions, BSM physics and a new hadronic decay
    model, tuned to LEP data.
 
    For an overview of the changes, please see the release note
    arXiv:0711.3137
 
 
 
 
 * Herwig++-2.0.3 release: 2007-08-21 (tagged at SVN r2101)
 
 ** Bug #90
    nan in top decay ME corrections fixed.
 
 ** unlisted
    Colour flow fix in LightClusterDecayer
 
 ** unlisted
    Updated version of MultiplicityCount analysis handler.
 
 
 
 
 * Herwig++-2.0.2 release: 2007-07-06 (tagged at SVN r1716)
 
 ** Bug #80
    Separation of HepMC from CLHEP is handled properly now.
 
 ** Bug #83
    Workaround for OS X header problem
 
 ** unlisted
    Veto on very hard emissions from Shower.
 
 ** unlisted
    Detailed documentation in .in files
 
 
 
 
 * Herwig++-2.0.1 release: 2006-12-05 (tagged at SVN r1195)
 
 ** Bug #54
    ClusterFissioner vertex calculation fixed.
 
 ** Bug #57
    Crash when showering W+jet events supplied by Les Houches interface.
 
 ** Bug #59
    Fix for #57 applied to LHC events.
 
 ** Bug #60
    Segfault when PDF is set to NoPDF.
 
 ** Bug #61
    Missing weight factor for I=0 mesons
 
 ** Bug #62
    Spinor vertex calculations broken when spinor rep is not default rep.
 
 ** Bug #63
    Top decay never produces tau.
 
 ** Bug #69
    TTbar and HiggsJet analysis handlers fixed.
 
 ** unlisted 
    Reorganization of Hadronization module gives 30% speedup. 
    Thanks to Vincenzo Innocente at CMS for his profiling work!
 
 ** unlisted
    cleaner automake files in include/ and src/
 
 ** unlisted 
    Hw64 hadron selection algorithm 'abortnow' fixed.
 
 ** unlisted 
    Top/LeptonDalitzAnalysis removed (only worked with modified code).
 
 ** unlisted
    removed f'_0 from particle list, decays were not handled
 
 
 
 
 * Herwig++-2.0.0 release: 2006-09-28 (tagged at SVN r1066)
 
 ** Full simulation of hadron collisions
diff --git a/PDF/Makefile.am b/PDF/Makefile.am
--- a/PDF/Makefile.am
+++ b/PDF/Makefile.am
@@ -1,52 +1,52 @@
 EXTRA_DIST = diffraction
 
 pkglib_LTLIBRARIES = HwPomeronPDF.la
 HwPomeronPDF_la_SOURCES = \
 PomeronPDF.cc PomeronPDF.h
 ## add this to produce tests of the PDFs
 ## HwDIFFRACTIVEPDF_la_CPPFLAGS=$(AM_CPPFLAGS) -DDIFFRACTIVEPDF_TESTING
-HwPomeronPDF_la_LDFLAGS = $(AM_LDFLAGS) -module -version-info 2:0:0
+HwPomeronPDF_la_LDFLAGS = $(AM_LDFLAGS) -module -version-info 3:0:0
 
 pkglib_LTLIBRARIES += HwReggeonPDF.la
 HwReggeonPDF_la_SOURCES = \
 ReggeonPDF.cc ReggeonPDF.h
 ## add this to produce tests of the PDFs
 ## HwDIFFRACTIVEPDF_la_CPPFLAGS=$(AM_CPPFLAGS) -DDIFFRACTIVEPDF_TESTING
-HwReggeonPDF_la_LDFLAGS = $(AM_LDFLAGS) -module -version-info 2:0:0
+HwReggeonPDF_la_LDFLAGS = $(AM_LDFLAGS) -module -version-info 3:0:0
 
 pkglib_LTLIBRARIES += HwPomeronFlux.la
 HwPomeronFlux_la_SOURCES = \
 PomeronFlux.h PomeronFlux.cc
-HwPomeronFlux_la_LDFLAGS = $(AM_LDFLAGS) -module -version-info 3:0:0
+HwPomeronFlux_la_LDFLAGS = $(AM_LDFLAGS) -module -version-info 4:0:0
 
 ## bound into HwShower.la
 noinst_LTLIBRARIES = libHwRemDecayer.la
 libHwRemDecayer_la_SOURCES = \
 HwRemDecayer.h HwRemDecayer.cc HwRemDecayer.fh
 
 ## bound into HwShower.la
 noinst_LTLIBRARIES += libHwMPIPDF.la
 libHwMPIPDF_la_SOURCES = \
 MPIPDF.h MPIPDF.cc MPIPDF.fh \
 MinBiasPDF.h MinBiasPDF.cc MinBiasPDF.fh
 
 pkglib_LTLIBRARIES += HwSatPDF.la
 HwSatPDF_la_SOURCES = \
 SatPDF.h SatPDF.cc
 
-HwSatPDF_la_LDFLAGS = $(AM_LDFLAGS) -module -version-info 5:0:0
+HwSatPDF_la_LDFLAGS = $(AM_LDFLAGS) -module -version-info 6:0:0
 
 pkglib_LTLIBRARIES += HwIncomingPhotonEvolver.la
 HwIncomingPhotonEvolver_la_SOURCES = \
 IncomingPhotonEvolver.h IncomingPhotonEvolver.cc
 
-HwIncomingPhotonEvolver_la_LDFLAGS = $(AM_LDFLAGS) -module -version-info 5:0:0
+HwIncomingPhotonEvolver_la_LDFLAGS = $(AM_LDFLAGS) -module -version-info 6:0:0
 
 install-data-local:
 	for i in `find $(srcdir)/diffraction -name '*.data'`; \
 	do \
 	$(install_sh_DATA) $$i $(DESTDIR)$(pkgdatadir)/PDF/$${i#$(srcdir)/}; \
 	done
 
 uninstall-local:
 	rm -rf $(DESTDIR)$(pkgdatadir)/PDF
diff --git a/README b/README
--- a/README
+++ b/README
@@ -1,14 +1,14 @@
 ========
 Herwig 7
 ========
 
-This is the release of Herwig 7.0.4, a multi purpose event
+This is the release of Herwig 7.1.0, a multi purpose event
 generator for high energy physics.
 
 The Herwig++ distribution contains an adapted version of LoopTools 2.6
 <http://www.feynarts.de/looptools/>. 
 
 BUILD AND INSTALL
 =================
 Please refer to https://herwig.hepforge.org/tutorials/ for detailed 
 instructions.
diff --git a/Sampling/GeneralSampler.h b/Sampling/GeneralSampler.h
--- a/Sampling/GeneralSampler.h
+++ b/Sampling/GeneralSampler.h
@@ -1,496 +1,494 @@
 // -*- C++ -*-
 //
 // GeneralSampler.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_GeneralSampler_H
 #define Herwig_GeneralSampler_H
 //
 // This is the declaration of the GeneralSampler class.
 //
 
 #include "ThePEG/Handlers/SamplerBase.h"
 #include "BinSampler.h"
 
 namespace Herwig {
 
 using namespace ThePEG;
 
 /**
  * \ingroup Matchbox
  * \author Simon Platzer
  *
  * \brief A GeneralSampler class
  *
  * @see \ref GeneralSamplerInterfaces "The interfaces"
  * defined for GeneralSampler.
  */
 class GeneralSampler: public SamplerBase {
 
 public:
 
   /** @name Standard constructors and destructors. */
   //@{
   /**
    * The default constructor.
    */
   GeneralSampler();
 
   /**
    * The destructor.
    */
   virtual ~GeneralSampler();
   //@}
 
 public:
 
   /** @name Virtual functions from SamplerBase. */
   //@{
   /**
    * Initialize the the sampler, possibly doing presampling of the
    * phase space.
    */
   virtual void initialize();
 
   /**
    * Generarate a new phase space point and return a weight associated
    * with it. This weight should preferably be 1.
    */
   virtual double generate();
 
   /**
    * Reject the last chosen phase space point.
    */
   virtual void rejectLast();
 
   /**
    * If the sampler is able to sample several different functions
    * separately, this function should return the last chosen
    * function. This default version always returns 0.
    */
   virtual int lastBin() const { return lastSampler() ? lastSampler()->bin() : 0; }
 
   /**
    * Return the total integrated cross section determined from the
    * Monte Carlo sampling so far.
    */
   virtual CrossSection integratedXSec() const {
     currentCrossSections();
     return theIntegratedXSec;
   }
 
   /**
    * Return the error on the total integrated cross section determined
    * from the Monte Carlo sampling so far.
    */
   virtual CrossSection integratedXSecErr() const {
     currentCrossSections();
     return theIntegratedXSecErr;
   }
 
   /**
    * Return the overestimated integrated cross section.
    */
   virtual CrossSection maxXSec() const { 
     if ( theAddUpSamplers )
       return SamplerBase::maxXSec();
     return theMaxWeight*nanobarn;
   }
 
   /**
    * Return the sum of the weights returned by generate() so far (of
    * the events that were not rejeted).
    */
   virtual double sumWeights() const { return theSumWeights; }
 
   /**
    * Return the sum of the weights squaredreturned by generate() so far (of
    * the events that were not rejeted).
    */
   virtual double sumWeights2() const { return theSumWeights2; }
 
   /**
    * Return the number of attempts
    */
   virtual double attempts() const { 
     if ( theAddUpSamplers )
       return SamplerBase::attempts();
     return theAttempts;
   }
 
   /**
    * Return the number of accepts
    */
   double accepts() const { return theAccepts; }
 
   //@}
 
   /**
    * Return the samplers
    */
   const map<double,Ptr<BinSampler>::ptr>& samplers() const { return theSamplers; }
 
   /**
    * Return the bin sampler
    */
   Ptr<BinSampler>::ptr binSampler() const { return theBinSampler; }
 
   /**
    * Return the last selected bin sampler
    */
   Ptr<BinSampler>::tptr lastSampler() const { return theLastSampler; }
 
   /**
    * True if we should do weighted events
    */
   bool weighted() const { return eventHandler()->weighted(); }
 
-
   /** 
-   * True if the sampler runs in Allmostunweighted mode.
+   * Return true if this sampler is generating almost unweighted events.
    */ 
-
-  bool almostUnweighted() const { return theAlmostUnweighted; }
+  virtual bool almostUnweighted() const { return theAlmostUnweighted; }
 
 public:
 
   /**
    * Return the XML element containing the grids
    */
   const XML::Element& grids() const { return theGrids; }
 
   /**
    * Access the XML element containing the grids
    */
   XML::Element& grids() { return theGrids; }
 
   /**
    * Write out grids
    */
   void writeGrids() const;
 
   /**
    * Read in grids
    */
   void readGrids();
   
   /**
    * Return the number of integration jobs which were actually created.
    */
   unsigned int integrationJobsCreated() {
     return theIntegrationJobsCreated;
   }
 
   /**
    * An external hook to prepare the sampler for generating events, e.g. by
    * combining grid files from parallel integration runs.
    */
   virtual void prepare();
 
 protected:
 
   /**
    * Access the samplers
    */
   map<double,Ptr<BinSampler>::ptr>& samplers() { return theSamplers; }
 
   /**
    * Set the last selected bin sampler
    */
   void lastSampler(Ptr<BinSampler>::tptr s) { theLastSampler = s; }
 
   /**
    * Calculate cross sections from samplers at current state.
    */
   void currentCrossSections() const;
 
   /**
    * Update the sampler selection
    */
   void updateSamplers();
 
 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 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;
   //@}
 
 
 // If needed, insert declarations of virtual function defined in the
 // InterfacedBase class here (using ThePEG-interfaced-decl in Emacs).
 
 
 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();
 
   /**
    * Finalize this object. Called in the run phase just after a
    * run has ended. Used eg. to write out statistics.
    */
   virtual void dofinish();
 
   /**
    * Rebind pointer to other Interfaced objects. Called in the setup phase
    * after all objects used in an EventGenerator has been cloned so that
    * the pointers will refer to the cloned objects afterwards.
    * @param trans a TranslationMap relating the original objects to
    * their respective clones.
    * @throws RebindException if no cloned object was found for a given
    * pointer.
    */
   virtual void rebind(const TranslationMap & trans);
 
   /**
    * Return a vector of all pointers to Interfaced objects used in this
    * object.
    * @return a vector of pointers.
    */
   virtual IVector getReferences();
 
 private:
 
   /**
    * Whether or not additional information should be printed to cout.
    */
   bool theVerbose;
 
   /**
    * The XML element containing the grids
    */
   XML::Element theGrids;
 
   /**
    * The bin sampler to use.
    */
   Ptr<BinSampler>::ptr theBinSampler;
 
   /**
    * The selector map for the bin samplers.
    */
   map<double,Ptr<BinSampler>::ptr> theSamplers;
 
   /**
    * The last selected bin sampler.
    */
   Ptr<BinSampler>::tptr theLastSampler;
 
   /**
    * The integrated cross section
    */
   mutable CrossSection theIntegratedXSec;
 
   /**
    * The integrated cross section error
    */
   mutable CrossSection theIntegratedXSecErr;
 
   /**
    * The number of events after which cross sections should truly be
    * updated. This is used to prevent exhaustive combination of
    * statistics when HepMC events are written out.
    */
   size_t theUpdateAfter;
 
   /**
    * The number of calls to currentCrossSections since the last
    * update.
    */
   mutable size_t crossSectionCalls;
 
   /**
    * True, if currentCrossSections has been called since the last call
    * to generate.
    */
   mutable bool gotCrossSections;
 
   /**
    * The sum of weights
    */
   double theSumWeights;
 
   /**
    * The sum of weights squared
    */
   double theSumWeights2;
 
   /**
    * The number of attempts
    */
   double theAttempts;
 
   /**
    * The number of accepts
    */
   double theAccepts;
 
   /**
    * The maximum weight encountered
    */
   double theMaxWeight;
 
   /**
    * True, if cross sections are to be combined from each sampler
    * individually
    */
   bool theAddUpSamplers;
 
   /**
    * True, if the global maximum weight should be used as
    * reference. If not, the maximum weights of individual samplers are
    * used, and selection probabilities fro the samplers are adjusted
    * accordingly.
    */
   bool theGlobalMaximumWeight;
 
   /**
    * True, if subprocesses should be selected flat. This is a debug
    * flag, cross section information and distributions will not be
    * correct.
    */
   bool theFlatSubprocesses;
 
   /**
    * True, if we are generating events.
    */
   bool isSampling;
 
   /**
    * A minimum selection probability for each sampler
    */
   double theMinSelection;
 
   /**
    * True, if information for combining unnormalized runs should be
    * printed out
    */
   bool runCombinationData;
 
   /**
    * True, if we should perform an almost unweighted sampling
    */
   bool theAlmostUnweighted;
 
   /**
    * Number of points which exceeded the maximum
    */
   unsigned long maximumExceeds;
 
   /**
    * The average relative deviation from the maximum weight
    */
   double maximumExceededBy;
 
   /**
    * The correct cross section as one would exspect with
    * almostUnweighted. 
    */
 
   double correctWeights;
 
   /**
    * Enhancement factor to the maximum weight.
    * This is to get less maximumExceeds. 
    */
 
   double theMaxEnhancement;
 
   /**
    * True, if grids have already been read.
    */
   bool didReadGrids;
 
   /**
    * True, if parallel subprocess integration should be enabled
    */
   bool theParallelIntegration;
 
   /**
    * The number of subprocesses to integrate per job
    */
   unsigned int theIntegratePerJob;
 
   /**
    * The maximum number of integration jobs to be created
    */
   unsigned int theIntegrationJobs;
 
   /**
    * The number of integration jobs which were actually created
    */
   unsigned int theIntegrationJobsCreated;
   
   /**
    * Indicate that initialization is only reading a grid.
    */
   bool justAfterIntegrate;
 
   /**
    * True, if grids should be written at the end of a run
    */
   bool theWriteGridsOnFinish;
 
 private:
 
   /**
    * The assignment operator is private and must never be called.
    * In fact, it should not even be implemented.
    */
   GeneralSampler & operator=(const GeneralSampler &);
 
 };
 
 }
 
 #endif /* Herwig_GeneralSampler_H */
diff --git a/Sampling/Makefile.am b/Sampling/Makefile.am
--- a/Sampling/Makefile.am
+++ b/Sampling/Makefile.am
@@ -1,40 +1,40 @@
 SUBDIRS = CellGrids
 
 pkglib_LTLIBRARIES = HwSampling.la
 
-HwSampling_la_LDFLAGS = $(AM_LDFLAGS) -module -version-info 5:0:0
+HwSampling_la_LDFLAGS = $(AM_LDFLAGS) -module -version-info 6:0:0
 HwSampling_la_SOURCES = \
 GeneralStatistics.h GeneralStatistics.cc \
 MultiIterationStatistics.h MultiIterationStatistics.cc \
 BinSampler.h BinSampler.cc \
 GeneralSampler.h GeneralSampler.cc \
 MonacoSampler.h MonacoSampler.cc \
 Remapper.h Remapper.cc \
 exsample/cell.icc \
 exsample/generator.h \
 exsample/linear_interpolator.icc \
 exsample/config.h \
 exsample/selectors.h \
 exsample/adaption_info.h \
 exsample/selectors.icc \
 exsample/adaption_info.icc \
 exsample/exponential_generator.h \
 exsample/exponential_generator.icc \
 exsample/generator.icc \
 exsample/statistics.h \
 exsample/linear_interpolator.h \
 exsample/cell.h \
 exsample/utility.h \
 exsample/binary_tree.h \
 exsample/statistics.icc
 
 HwSampling_la_LIBADD = \
 CellGrids/libHwCellGrids.la
 
 EXTRA_DIST = herwig-mergegrids.py
 
 install-exec-local:
 	$(install_sh_SCRIPT) $(srcdir)/herwig-mergegrids.py $(DESTDIR)$(bindir)/herwig-mergegrids
 
 uninstall-local:
 	rm -f  $(DESTDIR)$(bindir)/herwig-mergegrids
diff --git a/Shower/Dipole/AlphaS/Makefile.am b/Shower/Dipole/AlphaS/Makefile.am
--- a/Shower/Dipole/AlphaS/Makefile.am
+++ b/Shower/Dipole/AlphaS/Makefile.am
@@ -1,14 +1,14 @@
 pkglib_LTLIBRARIES = HwDipoleShowerAlphaS.la
 
-HwDipoleShowerAlphaS_la_LDFLAGS = $(AM_LDFLAGS) -module -version-info 4:0:1
+HwDipoleShowerAlphaS_la_LDFLAGS = $(AM_LDFLAGS) -module -version-info 5:0:0
 
 HwDipoleShowerAlphaS_la_SOURCES =  \
 alpha_s.h \
 alpha_s.cc \
 lo_alpha_s.h \
 lo_alpha_s.cc \
 nlo_alpha_s.h \
 nlo_alpha_s.cc \
 gsl.h \
 gsl.tcc \
 gsl.cc
diff --git a/Shower/Dipole/Kernels/DipoleSplittingKernel.cc b/Shower/Dipole/Kernels/DipoleSplittingKernel.cc
--- a/Shower/Dipole/Kernels/DipoleSplittingKernel.cc
+++ b/Shower/Dipole/Kernels/DipoleSplittingKernel.cc
@@ -1,408 +1,408 @@
 // -*- C++ -*-
 //
 // DipoleSplittingKernel.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 DipoleSplittingKernel class.
 //
 
 #include "DipoleSplittingKernel.h"
 #include "ThePEG/Interface/ClassDocumentation.h"
 #include "ThePEG/Interface/Reference.h"
 #include "ThePEG/Interface/Parameter.h"
 #include "ThePEG/Interface/Switch.h"
 
 #include "ThePEG/Persistency/PersistentOStream.h"
 #include "ThePEG/Persistency/PersistentIStream.h"
 
 #include "Herwig/Shower/ShowerHandler.h"
 
 using namespace Herwig;
 
 DipoleSplittingKernel::DipoleSplittingKernel() 
   : HandlerBase(), theScreeningScale(0.0*GeV), 
     thePresamplingPoints(2000), theMaxtry(100000),
     theFreezeGrid(500000),
     theDetuning(1.0),
     theStrictLargeN(false), 
     theFactorizationScaleFactor(1.0),
     theRenormalizationScaleFactor(1.0),
     theRenormalizationScaleFreeze(1.*GeV), 
     theFactorizationScaleFreeze(1.*GeV),
     theVirtualitySplittingScale(false),
     theCMWScheme(0),
     presampling(false) {}
 
 DipoleSplittingKernel::~DipoleSplittingKernel() {}
 
 
 // If needed, insert default implementations of virtual function defined
 // in the InterfacedBase class here (using ThePEG-interfaced-impl in Emacs).
 
 
 void DipoleSplittingKernel::persistentOutput(PersistentOStream & os) const {
   os << theAlphaS << ounit(theScreeningScale,GeV)
      << theSplittingKinematics << thePDFRatio
      << thePresamplingPoints << theMaxtry << theFreezeGrid << theDetuning
      << theFlavour << theMCCheck << theStrictLargeN
      << theFactorizationScaleFactor
      << theRenormalizationScaleFactor
      << ounit(theRenormalizationScaleFreeze,GeV)
      << ounit(theFactorizationScaleFreeze,GeV)
      << theVirtualitySplittingScale<<theCMWScheme<<theUseThisKernel;
 }
 
 void DipoleSplittingKernel::persistentInput(PersistentIStream & is, int) {
   is >> theAlphaS >> iunit(theScreeningScale,GeV) 
      >> theSplittingKinematics >> thePDFRatio
      >> thePresamplingPoints >> theMaxtry >> theFreezeGrid >> theDetuning
      >> theFlavour >> theMCCheck >> theStrictLargeN
      >> theFactorizationScaleFactor
      >> theRenormalizationScaleFactor
      >> iunit(theRenormalizationScaleFreeze,GeV)
      >> iunit(theFactorizationScaleFreeze,GeV)
      >> theVirtualitySplittingScale>>theCMWScheme>>theUseThisKernel;
 }
 
 double DipoleSplittingKernel::alphaPDF(const DipoleSplittingInfo& split,
 				       Energy optScale,
 				       double rScaleFactor,
 				       double fScaleFactor) const {
 
   Energy pt = optScale == ZERO ? split.lastPt() : optScale;
 
   Energy2 scale = ZERO;
   if ( !virtualitySplittingScale() ) {
     scale = sqr(pt) + sqr(theScreeningScale);
   } else {
     scale = sqr(splittingKinematics()->QFromPt(pt,split)) + sqr(theScreeningScale);
   }
 
 
  
   Energy2 fScale = sqr(theFactorizationScaleFactor*fScaleFactor)*scale;
   fScale = max( fScale , sqr(factorizationScaleFreeze()) );
-
-  if(split.calcFixedExpansion()){
-    scale=sqr(split.fixedScale());
-  }
  
   Energy2 rScale = sqr(theRenormalizationScaleFactor*rScaleFactor)*scale;
   rScale = max( rScale , sqr(renormalizationScaleFreeze()) );
 
+  if(split.calcFixedExpansion()){
+    fScale = max( sqr(split.fixedScale()) , sqr(factorizationScaleFreeze()) );
+    rScale = max( sqr(split.fixedScale()) , sqr(renormalizationScaleFreeze()) );
+  }
 
   double alphas = 1.0;
   double pdf = 1.0;
 
   // check if we are potentially reweighting and cache evaluations
   bool evaluatePDF = true;
   bool evaluateAlphaS = true;
   bool variations = 
     !ShowerHandler::currentHandler()->showerVariations().empty() &&
     !presampling;
   if ( variations ) {
     
     map<double,double>::const_iterator pit = thePDFCache.find(fScaleFactor);
     evaluatePDF = (pit == thePDFCache.end());
     if ( !evaluatePDF ) {
       pdf = pit->second;
     }
     map<double,double>::const_iterator ait = theAlphaSCache.find(rScaleFactor);
     evaluateAlphaS = (ait == theAlphaSCache.end());
     if ( !evaluateAlphaS ) {
       alphas = ait->second;
     }
   }
 
   if ( evaluateAlphaS ){
-    if (theCMWScheme==0) {
+    if (theCMWScheme==0||split.calcFixedExpansion()) {
       alphas = alphaS()->value(rScale);
     }else if(theCMWScheme==1){
       
       alphas = alphaS()->value(rScale);
       alphas *=1.+(3.*(67./18.-1./6.*sqr(Constants::pi))
                    -5./9.*alphaS()->Nf(rScale))*
                alphas/2./Constants::pi;
       
     }else if(theCMWScheme==2){
       double kg=exp(-(67.-3.*sqr(Constants::pi)-10/3*alphaS()->Nf(rScale))
                     /(33.-2.*alphaS()->Nf(rScale)));
       Energy2 cmwscale2=max(kg*rScale, sqr(renormalizationScaleFreeze()) );
       alphas = alphaS()->value(cmwscale2);
       
     }else{
       throw Exception()
       << "This CMW-Scheme is not implemented."
       << Exception::abortnow;
     
     }
   }
   if ( evaluatePDF ) {
     if ( split.index().initialStateEmitter() ) {
       assert(pdfRatio());
       pdf *= 
 	split.lastEmitterZ() * 
 	(*pdfRatio())(split.index().emitterPDF(), fScale,
 		      split.index().emitterData(),split.emitterData(),
 		      split.emitterX(),split.lastEmitterZ());
     }
 
     if ( split.index().initialStateSpectator() ) {
       assert(pdfRatio());
       pdf *= 
 	split.lastSpectatorZ() * 
 	(*pdfRatio())(split.index().spectatorPDF(), fScale,
 		      split.index().spectatorData(),split.spectatorData(),
 		      split.spectatorX(),split.lastSpectatorZ());
     }
   }
 
   if ( evaluatePDF && variations ) {
     thePDFCache[fScaleFactor] = pdf;
   }
 
   if ( evaluateAlphaS && variations ) {
     theAlphaSCache[rScaleFactor] = alphas;
   }
 
   double ret = pdf*
                (split.calcFixedExpansion()?
                 1.:(alphas / (2.*Constants::pi)));
 
   if ( ret < 0. )
     ret = 0.;
 
   return ret;
 
 }
 
 void DipoleSplittingKernel::accept(const DipoleSplittingInfo& split,
 				   double, double,
 				   map<string,double>& weights) const {
   if ( ShowerHandler::currentHandler()->showerVariations().empty() )
     return;
   double reference = alphaPDF(split);
   assert(reference > 0.);
   for ( map<string,ShowerVariation>::const_iterator var =
 	  ShowerHandler::currentHandler()->showerVariations().begin();
 	var != ShowerHandler::currentHandler()->showerVariations().end(); ++var ) {
     if ( ( ShowerHandler::currentHandler()->firstInteraction() 
 	   && var->second.firstInteraction ) ||
 	 ( !ShowerHandler::currentHandler()->firstInteraction() 
            && var->second.secondaryInteractions ) ) {
       double varied = alphaPDF(split,ZERO,
 			       var->second.renormalizationScaleFactor,
 			       var->second.factorizationScaleFactor);
       if ( varied != reference ) {
 	map<string,double>::iterator wi = weights.find(var->first);
 	if ( wi != weights.end() )
 	  wi->second *= varied/reference;
 	else
 	  weights[var->first] = varied/reference;
       }
     }
   }
 }
 
 void DipoleSplittingKernel::veto(const DipoleSplittingInfo& split,
 				 double p, double r,
 				 map<string,double>& weights) const {
   if ( ShowerHandler::currentHandler()->showerVariations().empty() )
     return;
   double reference = alphaPDF(split);
   // this is dangerous, but we have no other choice currently -- need to
   // carefully check for the effects; the assumption is that if the central
   // one ius zero, then so will be the variations.
   if ( reference == 0.0 )
     return;
   for ( map<string,ShowerVariation>::const_iterator var =
 	  ShowerHandler::currentHandler()->showerVariations().begin();
 	var != ShowerHandler::currentHandler()->showerVariations().end(); ++var ) {
     if ( ( ShowerHandler::currentHandler()->firstInteraction() 
            && var->second.firstInteraction ) ||
 	 ( !ShowerHandler::currentHandler()->firstInteraction() 
            && var->second.secondaryInteractions ) ) {
       double varied = alphaPDF(split,ZERO,
 			       var->second.renormalizationScaleFactor,
 			       var->second.factorizationScaleFactor);
       if ( varied != reference ) {
 	map<string,double>::iterator wi = weights.find(var->first);
 	if ( wi != weights.end() )
 	  wi->second *= (r - varied*p/reference) / (r-p);
 	else
 	  weights[var->first] = (r - varied*p/reference) / (r-p);
       }
     }
   }
 }
 
 AbstractClassDescription<DipoleSplittingKernel> 
 DipoleSplittingKernel::initDipoleSplittingKernel;
 // Definition of the static class description member.
 
 void DipoleSplittingKernel::Init() {
 
   static ClassDocumentation<DipoleSplittingKernel> documentation
     ("DipoleSplittingKernel is the base class for all kernels "
      "used within the dipole shower.");
 
   static Reference<DipoleSplittingKernel,AlphaSBase> interfaceAlphaS
     ("AlphaS",
      "The strong coupling to be used by this splitting kernel.",
      &DipoleSplittingKernel::theAlphaS, false, false, true, true, false);
 
 
   static Parameter<DipoleSplittingKernel,Energy> interfaceScreeningScale
     ("ScreeningScale",
      "A colour screening scale",
      &DipoleSplittingKernel::theScreeningScale, GeV, 0.0*GeV, 0.0*GeV, 0*GeV,
      false, false, Interface::lowerlim);
 
 
   static Reference<DipoleSplittingKernel,DipoleSplittingKinematics> 
      interfaceSplittingKinematics
     ("SplittingKinematics",
      "The splitting kinematics to be used by this splitting kernel.",
      &DipoleSplittingKernel::theSplittingKinematics, false, false, true, false, false);
 
 
   static Reference<DipoleSplittingKernel,PDFRatio> interfacePDFRatio
     ("PDFRatio",
      "Set the optional PDF ratio object to evaluate this kernel",
      &DipoleSplittingKernel::thePDFRatio, false, false, true, true, false);
 
   static Parameter<DipoleSplittingKernel,unsigned long> interfacePresamplingPoints
     ("PresamplingPoints",
      "The number of points used to presample this kernel.",
      &DipoleSplittingKernel::thePresamplingPoints, 2000, 1, 0,
      false, false, Interface::lowerlim);
 
   static Parameter<DipoleSplittingKernel,unsigned long> interfaceMaxtry
     ("Maxtry",
      "The maximum number of attempts to generate a splitting.",
      &DipoleSplittingKernel::theMaxtry, 10000, 1, 0,
      false, false, Interface::lowerlim);
 
   static Parameter<DipoleSplittingKernel,unsigned long> interfaceFreezeGrid
     ("FreezeGrid",
      "",
      &DipoleSplittingKernel::theFreezeGrid, 500000, 1, 0,
      false, false, Interface::lowerlim);
 
   static Reference<DipoleSplittingKernel,ParticleData> interfaceFlavour
     ("Flavour",
      "Set the flavour to be produced if ambiguous.",
      &DipoleSplittingKernel::theFlavour, false, false, true, true, false);
 
   static Reference<DipoleSplittingKernel,DipoleMCCheck> interfaceMCCheck
     ("MCCheck",
      "[debug option] MCCheck",
      &DipoleSplittingKernel::theMCCheck, false, false, true, true, false);
 
   interfaceMCCheck.rank(-1);
 
   static Switch<DipoleSplittingKernel,bool> interfaceStrictLargeN
     ("StrictLargeN",
      "Work in a strict large-N limit.",
      &DipoleSplittingKernel::theStrictLargeN, false, false, false);
   static SwitchOption interfaceStrictLargeNYes
     (interfaceStrictLargeN,
      "Yes",
      "Replace C_F -> C_A/2 where present",
      true);
   static SwitchOption interfaceStrictLargeNNo
     (interfaceStrictLargeN,
      "No",
      "Keep C_F=4/3",
      false);
 
   interfaceStrictLargeN.rank(-2);
 
   static Switch<DipoleSplittingKernel,unsigned int> interfaceCMWScheme
     ("CMWScheme",
      "Use the CMW Scheme related Kg expression to the splitting",
     &DipoleSplittingKernel::theCMWScheme, 0, false, false);
   static SwitchOption interfaceCMWSchemeNo
     (interfaceCMWScheme,"No","No CMW-Scheme", 0);
   static SwitchOption interfaceCMWSchemeLinear
   (interfaceCMWScheme,"Linear",
    "Linear CMW multiplication: alpha_s(q) -> alpha_s(q)(1+K_g*alpha_s(q)/2pi )",1);
   static SwitchOption interfaceCMWSchemeFactor
   (interfaceCMWScheme,"Factor",
    "Use factor in alpha_s argument: alpha_s(q) -> alpha_s(k_g*q) with  kfac=exp(-(67-3pi^2-10/3*Nf)/(33-2Nf)) ",2);
 
   static Parameter<DipoleSplittingKernel,double> interfaceFactorizationScaleFactor
     ("FactorizationScaleFactor",
      "The factorization scale factor.",
      &DipoleSplittingKernel::theFactorizationScaleFactor, 1.0, 0.0, 0,
      false, false, Interface::lowerlim);
 
   interfaceFactorizationScaleFactor.rank(-2);
 
   static Parameter<DipoleSplittingKernel,double> interfaceRenormalizationScaleFactor
     ("RenormalizationScaleFactor",
      "The renormalization scale factor.",
      &DipoleSplittingKernel::theRenormalizationScaleFactor, 1.0, 0.0, 0,
      false, false, Interface::lowerlim);
 
   interfaceRenormalizationScaleFactor.rank(-2);
 
   static Parameter<DipoleSplittingKernel,Energy> interfaceRenormalizationScaleFreeze
     ("RenormalizationScaleFreeze",
      "The freezing scale for the renormalization scale.",
      &DipoleSplittingKernel::theRenormalizationScaleFreeze, 
       GeV, 1.0*GeV, 0.0*GeV, 0*GeV,
      false, false, Interface::lowerlim);
 
   static Parameter<DipoleSplittingKernel,Energy> interfaceFactorizationScaleFreeze
     ("FactorizationScaleFreeze",
      "The freezing scale for the factorization scale.",
      &DipoleSplittingKernel::theFactorizationScaleFreeze, GeV, 1.0*GeV, 0.0*GeV, 0*GeV,
      false, false, Interface::lowerlim);
 
   static Switch<DipoleSplittingKernel,bool> interfaceVirtualitySplittingScale
     ("VirtualitySplittingScale",
      "Use the virtuality as the splitting scale.",
      &DipoleSplittingKernel::theVirtualitySplittingScale, false, false, false);
   static SwitchOption interfaceVirtualitySplittingScaleYes
     (interfaceVirtualitySplittingScale,
      "Yes",
      "Use vrituality.",
      true);
   static SwitchOption interfaceVirtualitySplittingScaleNo
     (interfaceVirtualitySplittingScale,
      "No",
      "Use transverse momentum.",
      false);
 
   static Parameter<DipoleSplittingKernel,double> interfaceDetuning
   ("Detuning",
    "A value to detune the overestimate kernel.",
    &DipoleSplittingKernel::theDetuning, 1.0, 1.0, 0,
    false, false, Interface::lowerlim);
   
   
   static Switch<DipoleSplittingKernel,bool> interfaceUseThisKernel
   ("UseKernel",
    "Turn On and of the Kernel.",
    &DipoleSplittingKernel::theUseThisKernel, true, false, false);
   static SwitchOption interfaceUseThisKernelYes
   (interfaceUseThisKernel,
    "Yes",
    "Use this Kernel.",
    true);
   static SwitchOption interfaceUseThisKernelNo
   (interfaceUseThisKernel,
    "No",
    "Dont use this Kernel.",
    false);
   
 
 }
 
diff --git a/Shower/Dipole/KrknloEventReweight.cc b/Shower/Dipole/KrkNLO/KrknloEventReweight.cc
rename from Shower/Dipole/KrknloEventReweight.cc
rename to Shower/Dipole/KrkNLO/KrknloEventReweight.cc
diff --git a/Shower/Dipole/KrknloEventReweight.h b/Shower/Dipole/KrkNLO/KrknloEventReweight.h
rename from Shower/Dipole/KrknloEventReweight.h
rename to Shower/Dipole/KrkNLO/KrknloEventReweight.h
diff --git a/Shower/Dipole/Makefile.am b/Shower/Dipole/Makefile.am
--- a/Shower/Dipole/Makefile.am
+++ b/Shower/Dipole/Makefile.am
@@ -1,22 +1,22 @@
 SUBDIRS = Base Kernels Kinematics Utility AlphaS Merging 
 
 pkglib_LTLIBRARIES = HwDipoleShower.la
 
-HwDipoleShower_la_LDFLAGS = $(AM_LDFLAGS) -module -version-info 7:0:0
+HwDipoleShower_la_LDFLAGS = $(AM_LDFLAGS) -module -version-info 8:0:0
 
 HwDipoleShower_la_LIBADD = \
 	Base/libHwDipoleShowerBase.la \
 	Kernels/libHwDipoleShowerKernels.la \
 	Kinematics/libHwDipoleShowerKinematics.la \
 	Utility/libHwDipoleShowerUtility.la \
 	Merging/libHwDipoleShowerMerging.la
 
 HwDipoleShower_la_SOURCES =  \
 	DipoleShowerHandler.h DipoleShowerHandler.fh DipoleShowerHandler.cc
 
 
 pkglib_LTLIBRARIES += HwKrknloEventReweight.la
 HwKrknloEventReweight_la_SOURCES = \
-	KrknloEventReweight.h KrknloEventReweight.cc
+	KrkNLO/KrknloEventReweight.h KrkNLO/KrknloEventReweight.cc
 
 HwKrknloEventReweight_la_LDFLAGS = $(AM_LDFLAGS) -module -version-info 1:0:0
diff --git a/Shower/Dipole/Merging/Merger.cc b/Shower/Dipole/Merging/Merger.cc
--- a/Shower/Dipole/Merging/Merger.cc
+++ b/Shower/Dipole/Merging/Merger.cc
@@ -1,1618 +1,1621 @@
   // -*- C++ -*-
   //
   // Merger.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 Merger class.
   //
 
 #include "Merger.h"
 #include "Node.h"
 #include "MergingFactory.h"
   // other includes when needed below.
 using namespace Herwig;
 
 IBPtr Merger::clone() const {
   return new_ptr( *this );
 }
 
 IBPtr Merger::fullclone() const {
   return new_ptr( *this );
 }
 
 
 
 
 
 namespace {
   double decideClustering(const NodePtr sub,const NodePtr head,bool& pro){
     if( sub !=  head ){// at least one history step -> unitarisation
       if ( UseRandom::rndbool() ){ pro = true;    return -2.;   }
       else{                        pro = false;   return  2.;   }
     }                  // no ordered history        -> no projection
     else{                          pro = false;   return  1.;   }
   }
 }
 
 CrossSection Merger::MergingDSigDRBornStandard( ){
     // get the history for the process
   const NodePtr productionNode =
          currentNode()-> getHistory( true, DSH()->hardScaleFactor() );
     // decide if to cluster
   weight = decideClustering(productionNode, currentNode(), projected);
     // check if we only want to calculate the current multiplicity.
   if(notOnlyMulti())                                      return ZERO;
     // Check for cuts on the production proces.
   if ( !productionNode->xcomb()->willPassCuts() )         return ZERO;
     // calculate the staring scale for the production node
   Energy startscale = CKKW_StartScale( productionNode );
     // fill history with caluclation of sudakov supression
   fillHistory( startscale , productionNode , currentNode() );
     // fill the projector -> return the scale of the last splitting
   currentNode()->runningPt( fillProjector( projected ? 1 : 0 ) );
     // the weight has three components to get shower history weight
   weight *= history.back().weight*  // Sudakov suppression
             alphaReweight()*        // alpha_s reweight
             pdfReweight();          // pdf reweight
     // If weight is zero return.
   if( weight == ZERO )                                    return ZERO;
     //calculate the cross section
   return weight*TreedSigDR( startscale ,  1. );
 }
 
 
 
 
 CrossSection Merger::MergingDSigDRVirtualStandard( ){
    // get the history for the process
   const NodePtr productionNode =  currentNode()-> getHistory( true , DSH()->hardScaleFactor() );
    // decide if to cluster
   weight = decideClustering(productionNode,currentNode(),projected);
     // Check for cuts on the production proces.
   if ( !productionNode->xcomb()->willPassCuts() )return ZERO;
     // calculate the staring scale
   Energy startscale = CKKW_StartScale( productionNode );
     // fill history with caluclation of sudakov supression
   fillHistory( startscale , productionNode , currentNode() );
     // fill the projector -> return the scale of the last splitting
   currentNode()->runningPt( fillProjector( projected ? 1 : 0 ) );
     // the weight has three components to get shower history weight
   double ww1 = history.back().weight;
   double ww2 = alphaReweight(true);
   double ww3 = pdfReweight();
   weight *= ww1*ww2*ww3;
     // If weight is zero return.
   if( weight == 0. )return ZERO;
     // calculate the cross section for virtual contribution
     // and various insertion operators.
   CrossSection matrixElement = LoopdSigDR( startscale );
     // Now calculate the expansion of the shower history.
     // first: the born contibution:
   CrossSection bornWeight =  currentME()->dSigHatDRB();
     // second: expansion of pdf ,alpha_s-ratio and sudakov suppression.
   double w1 = -sumPdfReweightExpansion();
   double w2 = -sumAlphaSReweightExpansion();
   double w3 = -sumFillHistoryExpansion();
     // put together the expansion weights.
   CrossSection expansionweight  = 
 	bornWeight*SM().alphaS()/( 2.*ThePEG::Constants::pi );
 
 
 
   if (theShowerExpansionWeights == 0){
 	expansionweight  *=0.;
   }else if ( theShowerExpansionWeights == 1 ){
 	expansionweight  *=w1+w2+w3;
   }else if ( theShowerExpansionWeights == 2 ){
   	expansionweight  *=w1+w2+w3*pow(as( startscale*DSH()->renFac() )/SM().alphaS(),currentME()->orderInAlphaS())/ww2;
   }else if ( theShowerExpansionWeights == 3 ){
         expansionweight  *=(w1+w2+w3)*pow(as( startscale*DSH()->renFac() )/SM().alphaS(),currentME()->orderInAlphaS())/ww2;
   }else if ( theShowerExpansionWeights == 4 ){
         expansionweight  *= w1+w3+w2*pow(as( startscale*DSH()->renFac() )/SM().alphaS(),currentME()->orderInAlphaS())/ww2;
   }else assert(false && theShowerExpansionWeights);
 
     // [ DEBUG ]
   if ( currentNode()->legsize() == 5 && Debug::level > 2 )
     debugVirt(weight,w1,w2,w3,matrixElement,ww1,ww2,ww3,productionNode,bornWeight);
     // return with correction that ME was calculated with fixed alpha_s
   return weight* as( startscale*DSH()->renFac() )/
          SM().alphaS()* ( matrixElement+expansionweight );
 }
 
 
 
 
 CrossSection Merger::MergingDSigDRRealStandard(){
   if ( currentNode()->children().empty() ) {
     throw Exception()
     << "Real emission contribution without underlying born."
     << "These are finite contibutions already handled in LO merging."
     << Exception::abortnow;
   }
     // check for IR Safe Cutoff
   if( !currentNode()->allAbove( theIRSafePT ) )return ZERO;
   
   auto inOutPair =  currentNode()->getInOut();
   NodePtr randomChild =  currentNode()->randomChild();
   bool meRegion =matrixElementRegion(
                             inOutPair.first ,
                             inOutPair.second ,
                             randomChild->pT() ,
                             theMergePt );
   
   
   if ( meRegion )return MergingDSigDRRealAllAbove(  );
   if ( UseRandom::rndbool() )
   return 2.*MergingDSigDRRealBelowSubReal(  );
   return 2.*MergingDSigDRRealBelowSubInt(  );
 }
 
 CrossSection Merger::MergingDSigDRRealAllAbove( ){
     //If all dipoles pts are above , we cluster to this dipole.
   NodePtr CLNode =  currentNode()->randomChild();
     // Check if phase space poing is in ME region--> else rm PSP
   if ( !CLNode->children().empty() ) {
     auto inOutPair =  CLNode->getInOut();
     NodePtr randomChild =  CLNode->randomChild();
     if( !matrixElementRegion( inOutPair.first ,
                               inOutPair.second ,
                               randomChild->pT() ,
                               theMergePt ) )return ZERO;
   }
   
     // first find the history for the acctual Node
   NodePtr productionNode =  currentNode()-> getHistory( true , DSH()->hardScaleFactor() );
     // If CLNode is not part of the history , dont calculate the Real contribution
     // else multiply the real contribution with N ( number of children ).
     // this returns the sudakov suppression according to
     // the clustering of the born parts.
   bool inhist = CLNode->isInHistoryOf( productionNode );
   if(productionNode== currentNode())assert(!inhist);
     // get the history for the clustered Node.
   productionNode = CLNode-> getHistory( false , DSH()->hardScaleFactor() );
     // decide if to cluster
   weight = decideClustering(productionNode,CLNode,projected);
     // Check for cuts on the production process.
   if ( !productionNode->xcomb()->willPassCuts() )return ZERO;
     // calculate the staring scale
   Energy startscale = CKKW_StartScale( productionNode );
     // fill history with caluclation of sudakov supression
   fillHistory( startscale , productionNode , CLNode );
     // fill the projector -> return the scale of the last splitting
   currentNode()->runningPt( fillProjector( projected ? 2 : 1 ) );
     // the weight has three components to get shower history weight
   weight *= history.back().weight*alphaReweight(true)*pdfReweight();
   if( weight == 0. )return ZERO;
     // The inhist flag produces the correct cluster density.
   CrossSection me = ( inhist?TreedSigDR( startscale ):ZERO );
     // calculate the dipole
   CrossSection dip = CLNode->calcDip( startscale* currentME()->renFac() );
   
   CrossSection res =  	weight*as( startscale*DSH()->renFac() )/SM().alphaS()*
  			currentNode()->children().size()*
   		       	( me - dip );
     // [ DEBUG ]
   if ( currentNode()->legsize() == 6&&Debug::level > 2 )
      debugReal("RAA",weight,me,dip);
   
   return res;
 }
 
 CrossSection Merger::MergingDSigDRRealBelowSubReal(  ){
    // Choose a random child to produce history from. 
   NodePtr HistNode = currentNode()->randomChild();
    // Check that this subleading point is in ME region.
   if ( !HistNode->children().empty() ) {
     auto inOutPair = HistNode->getInOut();
     NodePtr randomChild =  HistNode->randomChild(); // Here we make sure that clustering and splitting are invertible
     if( !matrixElementRegion( inOutPair.first , inOutPair.second , randomChild->pT() , theMergePt ) )return ZERO;
   }
   
    // As the HistNode is now in ME region, we can cluster according to LO merging.
    // In this clustering we do not require a orering for the last step to the currentNode.
   const NodePtr productionNode = HistNode-> getHistory( false , DSH()->hardScaleFactor() );
    // If the real emission contribution should be unitarised, we decide here if we cluster. 
    // This applies to NLO corrections for the first emission w.r.t. the production process the first time.
   weight = decideClustering(productionNode,HistNode,projected);
    // The production node needs to fulfill the cut criterion of the production process.
   if ( !productionNode->xcomb()->willPassCuts() && !currentNode()->xcomb()->willPassCuts() )return ZERO;
    // Calculate the starting scale w.r.t. the production process.
   Energy startscale = CKKW_StartScale( productionNode );
    // If the production process does not fullfill the cut criterion use the real emission point (DEBUG)
   if (!productionNode->xcomb()->willPassCuts()) startscale = CKKW_StartScale( currentNode() );
    // DEBUG trial
   //currentNode()->xcomb()->lastProjector( productionNode->xcomb());
    // Calculate the sudakov weights starting from the production node to the histNode
   fillHistory( startscale , productionNode , HistNode );
    // Set the running Pt of the process as it is used in the vetoed parton shower.
   currentNode()->runningPt( fillProjector( projected ? 1 : 0 ) );
   currentNode()->runningPt(max(HistNode->pT(),theMergePt));
    // Calculate the alpha_S ratios and pdf ratios.
    weight *= history.back().weight*alphaReweight(true)*pdfReweight();
   
   if( weight == 0. )return ZERO;
 
    // Start calculation of subtraction contribution. 
   CrossSection sumPS = ZERO;
 
    // Iterate over all subtraction contributions.
   for( auto const & child : currentNode()->children() ){
     if ( child->allAbove( mergePt() ) && child->xcomb()->willPassCuts() ){
       Energy relevantScale=child->children().empty()?CKKW_StartScale( child ):child->maxChildPt();
       if( ( child )->pT()>mergePt()/theRealSubtractionRatio ){
 	if( child ->pT()<relevantScale&&(child->inShowerPS(relevantScale))){  //DEBUG: CKKW_StartScale( child);????
           sumPS += child->calcPs( startscale* currentME()->renFac() );
 	}
       }else{
 	if( child ->pT()<relevantScale){
     	  sumPS += child->calcDip( startscale* currentME()->renFac() );
         }
       }
      }
   }
   
   CrossSection me = ZERO;
   if(currentNode()->xcomb()->willPassCuts()){
     me = TreedSigDR( startscale );
   } 
 
 
    // [ DEBUG ]
   if ( currentNode()->legsize() == 6&&Debug::level > 2 )
       debugReal("RBSR",weight,me,sumPS);
    //Here we subtract the PS ( and below the dynamical cutoff the Dip )  
   return weight*as( startscale*DSH()->renFac() )/SM().alphaS()*
   ( me-sumPS );
 }
 
 
 
 CrossSection Merger::MergingDSigDRRealBelowSubInt( ){
   
   if( currentNode()->children().empty() )return ZERO;
   NodePtr CLNode =  currentNode()->randomChild();
   if( CLNode->pT()<mergePt()/theRealSubtractionRatio )return ZERO;
   
   if ( !CLNode->children().empty() ) {
     auto inOutPair = CLNode->getInOut( );
     NodePtr randomChild =  CLNode->randomChild(); // Here we make sure that clustering and splitting are invertible
     if( !matrixElementRegion( inOutPair.first , inOutPair.second , randomChild->pT() , theMergePt ) )return ZERO;
   }
   
   
   const NodePtr productionNode = CLNode-> getHistory( false , DSH()->hardScaleFactor() );
   
   weight = decideClustering(productionNode,CLNode,projected);
 
   if ( !CLNode->allAbove( mergePt() ) )return ZERO;
   
   if ( !productionNode->xcomb()->willPassCuts() )return ZERO;
   
   Energy startscale = CKKW_StartScale( productionNode );
   
   fillHistory( startscale , productionNode , CLNode );
   
   currentNode()->runningPt( fillProjector( projected ? 2 : 1 ) );
   
   weight *= history.back().weight*alphaReweight(true)*pdfReweight();
 
   if( weight == 0. )return ZERO;
     
   pair<CrossSection , CrossSection> DipAndPs =
   CLNode->calcDipandPS( startscale* currentME()->renFac() );
     // [ DEBUG ]
   if ( currentNode()->legsize() == 6&&Debug::level > 2 )
      debugReal("RBSI",weight,DipAndPs.second,DipAndPs.first);
   
   Energy relevantScale=CLNode->children().empty()?CKKW_StartScale( CLNode ):CLNode->maxChildPt();
   bool calcPScontribution=CLNode->pT()<relevantScale&&(CLNode->inShowerPS(relevantScale));
     //Here we add the PS and subtrac the Dip ( only above the dynamical cutoff )
   return weight*as( startscale*DSH()->renFac() )/SM().alphaS()*
   currentNode()->children().size()*( (calcPScontribution?DipAndPs.second:ZERO)-DipAndPs.first );
 }
 
 
 CrossSection Merger::MergingDSigDRBornGamma( ){
   
   double weightCL = 0.;
   weight = 1.;
   
   if ( !currentNode()->children().empty() ) {
     auto const inOutPair = currentNode()->getInOut();
       // Here we make sure that clustering and splitting are invertible.
     NodePtr randomChild =  currentNode()->randomChild();
       // Check if point is part of the ME region.
     if( !matrixElementRegion( inOutPair.first ,
                               inOutPair.second ,
                               randomChild->pT() ,
                               theMergePt ) )weight *= 0.;
   }
   
   const NodePtr productionNode = currentNode()->getHistory( true , DSH()->hardScaleFactor() );
   NodePtr CLNode;
   NodePtr BornCL;
   
   
   if( !currentNode()->children().empty() ){
     if ( UseRandom::rndbool() ){
       CLNode =  currentNode()->randomChild();
       bool inhist = CLNode->isInHistoryOf( productionNode );
       weight *= inhist?( -2.*int( currentNode()->children().size() ) ):0.;
       projected = true;
       weightCL = 2.*int( currentNode()->children().size() );
       BornCL = CLNode-> getHistory( false , DSH()->hardScaleFactor() );
     }else{
       weight = 2.;
       projected = false;
     }
   }else{
     weight = 1.;
     projected = false;
   }
   
   
   if ( treefactory()->onlymulti() != -1&&
        treefactory()->onlymulti() !=
          int( currentNode()->legsize()-(projected ? 1 : 0) ) )
     return ZERO;
   
   
   if( !currentNode()->allAbove( mergePt()*(1.-1e-6)  ) )weight = 0.;
   if( CLNode&&!CLNode->allAbove( mergePt()*(1.-1e-6) ) )weightCL = 0.;
   if ( !productionNode->xcomb()->willPassCuts() ){
     return ZERO;
   }
   
   CrossSection res = ZERO;
   bool maxMulti = currentNode()->legsize() == int( maxLegsLO() );
   
   
   if( weight != 0. ){
     Energy startscale = CKKW_StartScale( productionNode );
     fillHistory( startscale , productionNode , currentNode() );
     currentNode()->runningPt( fillProjector( (projected ? 1 : 0) ) );
     weight *= history.back().weight*alphaReweight()*pdfReweight();
     if( weight == 0.&&weightCL == 0. )return ZERO;
     
     res += weight*TreedSigDR( startscale , ( !maxMulti&&!projected )?theGamma:1. );
   }
   
   if( CLNode&&theGamma != 1. ){
     Energy startscale = CKKW_StartScale( BornCL );
     fillHistory( startscale , BornCL , CLNode );
     currentNode()->runningPt( fillProjector( projected ? 1 : 0 ) );
     weightCL *= history.back().weight*alphaReweight()*pdfReweight();
     CrossSection diff = ZERO;
      currentME()->factory()->setAlphaParameter( 1. );
     diff -=  weightCL*CLNode->dipole()->dSigHatDR( sqr( startscale* currentME()->renFac() ) );
      currentME()->factory()->setAlphaParameter( theGamma );
     
     string alp = ( CLNode->dipole()->aboveAlpha()?"Above":"Below" );
     
     diff += weightCL*CLNode->dipole()->dSigHatDR( sqr( startscale* currentME()->renFac() ) );
      currentME()->factory()->setAlphaParameter( 1. );
     
     res += diff;
   }
   return res;
 }
 
 
 
 
 CrossSection Merger::TreedSigDR( Energy startscale , double diffAlpha ){
   currentME()->setScale( sqr( startscale ) , sqr( startscale ) );
   CrossSection res =  currentME()->dSigHatDRB();
   /*bool useDipolesForME=false;
   if (useDipolesForME && !currentNode()->children().empty()){
 	res=ZERO;
 	for (auto const & child : currentNode()->children() )
 	    res-=child->dipole()->dSigHatDR(sqr( startscale ));	
   }
   */
   if ( projected && emitDipoleMEDiff ) {
     CrossSection resDip=ZERO;
     for (auto const & child : currentNode()->children() )
       resDip-=child->dipole()->dSigHatDR(sqr( startscale ));
     setEmissionProbability(1.-min(resDip/res,res/resDip));
   }else{
     setEmissionProbability(0.);	
   }
 
   if ( diffAlpha != 1. ) {
     res +=  currentME()->dSigHatDRAlphaDiff( diffAlpha );
   }
   if( std::isnan( double( res/nanobarn ) ) ){
     generator()->logWarning(Exception()
                             << "Merger: TreedSigDR is nan"
                             << Exception::warning);
     res = ZERO;};
   return res;
 }
 
 CrossSection Merger::LoopdSigDR( Energy startscale ){
    currentME()->setScale( sqr( startscale ) , sqr( startscale ) );
    currentME()->doOneLoopNoBorn();
    CrossSection res =  currentME()->dSigHatDRV()+
                        currentME()->dSigHatDRI();
    currentME()->noOneLoopNoBorn();
   return res;
 }
 
 Energy Merger::fillProjector( int pjs ){
     // in the shower handler the scale is multiplied
     // by DSH()->hardScaleFactor() so here we need
     // to devide by the factor.
   double xiQSh = history.begin()->node->legsize() == N0()?DSH()->hardScaleFactor():1.;
   if( pjs == 0 ){
      return ( history.size() == 1?1.:( 1./xiQSh ) )*history.back().scale;
   }
   for( auto const & hs : history )
   if ( isProjectorStage( hs.node , pjs )&&pjs !=  0 ){
     currentNode()->xcomb()->lastProjector( hs.node->xcomb() );
     return ( hs.node == history[0].node?1.:( 1./xiQSh ) )*hs.scale;
   }
   
   throw Exception() << "Could not fill projector." << Exception::abortnow;
   return ZERO;
 }
 
 double Merger::pdfReweight(){ // TODO factorization scale inside
   
   double res = 1.;
   // consider both sides.
   for( int side : {0 , 1} ){
     // The side scale defines the scale that the leg is changig thou the history.
     // We start reweighting at the seed process.
     // We only need to calculate the pdf if the emission whould change the leg,
     // otherwise the leg remains the same.
     // If no emission is prduced from this leg the pdf ratios from this leg are always 1.
     Energy sidescale=history[0].scale*(
 		       history[0].node->legsize() == N0()  ?
                        currentME()->facFac():
                        DSH()->facFac());
     bool sidechanged=false;
     // only if the incoming parton is coloured.
     if( history[0].node->xcomb()->mePartonData()[side]->coloured() ){
       // go though the history.
       for ( auto const & hs : history ){
           //pdf-ratio only to the last step
         if ( !hs.node->parent() ) continue;
         if ( hs.node == history.back().node ) continue;
         if ( !hs.node->dipole() ){
           throw Exception()
           << "\nMerger: pdfReweight: history step has no dipol. "
           << Exception::abortnow;
           return 0.;
         }
 	// if the emitter is the side the emission changes the momentum fraction.
 	if(!(hs.node->dipole()->bornEmitter()==side||
 	// II dipoles dont change the momentum fraction of the spectator only FI
 	   ( hs.node->dipole()->bornSpectator()==side &&  hs.node->dipole()->bornEmitter()>1)))
 		continue;
         const bool fromIsME = false;
         const bool toIsME   = history[0].node == hs.node;
         res *= pdfratio( hs.node,
               		 //numerator
 	                 sidescale,
 			 // denominator
                          DSH()->facFac()*hs.node->pT(),
                          side,
                          fromIsME,
                          toIsME);
 	sidescale= DSH()->facFac()*hs.node->pT();
         sidechanged=true;
       }
 
       const bool fromIsME = true;
       const bool toIsME   = !sidechanged && history[0].node->legsize() == N0();
 
       res *= pdfratio( history.back().node,
                        sidescale,
                        history[0].scale * currentME()->facFac(),
                        side,
                        fromIsME,
                        toIsME );
     }
   }
   if ( std::isnan( res ) )
      generator()->logWarning(Exception()
                           << "Merger: pdfReweight is nan."
                           << Exception::warning);
 
   return res;
 }
 
 
 double Merger::cmwAlphaS(Energy q)const{
   using Constants::pi;
     // No cmw-scheme
   if (theCMWScheme==0) 
     return as( q );
     // Linear cmw-scheme
   else if(theCMWScheme==1){
     double als=as( q );
     return als *
            (1.+(3.*(67./18.-1./6.*sqr(pi))
                  -5./9.*Nf(q))* als/2./pi);
   }
     // cmw-scheme as factor in argument.
   else if(theCMWScheme==2){
     double kg=exp(-(67.-3.*sqr(pi)-10/3*Nf(q))
                   /(     2.     *(33.-2.*Nf(q))));
     //Note factor 2 since we here dealing with Energy
     return as(max(kg*q,1_GeV));
   }else{
     throw Exception()
     << "This CMW-Scheme is not implemented."
     << Exception::abortnow;
   }
   return -1;
 }
 
 
 
 
 double Merger::alphaReweight(bool nocmw){
   double res = 1.;
   
   Energy Q_R = ( history[0].node->legsize() == N0()?
                  currentME()->renFac():
                 DSH()->renFac() )*
                 history[0].scale;
   
   using Constants::pi;
   const auto Q_qed=history[0].node->nodeME()->factory()->scaleChoice()->renormalizationScaleQED();
   const auto Oew=history[0].node->nodeME()->orderInAlphaEW();
   const auto Oqcd=history[0].node->nodeME()->orderInAlphaS();
 
   if (!history[0].node->children().empty()) {
     assert(Oqcd!=0);
   }
   
   res *= pow( SM().alphaEMME( Q_qed )/ SM().alphaEMMZ() , Oew );
   
   res *= pow( (nocmw?as(Q_R):cmwAlphaS(Q_R)) / SM().alphaS() , Oqcd );
 
   
   
   
   for ( auto const & hs : history )
   if ( hs.node!= history.back().node ){
     Energy q_i = DSH()->renFac()* hs.node->pT();
     res *= cmwAlphaS(q_i) / SM().alphaS();
   }
   
   if ( std::isnan( res ) )
       generator()->logWarning(Exception()
                << "Merger: alphaReweight is nan. "<< Exception::warning);
   return res;
 }
 
 void Merger::fillHistory( Energy scale , NodePtr begin , NodePtr endNode ){
   
   history.clear();
   double sudakov0_n = 1.;
   
   history.push_back( {begin , sudakov0_n , scale} );
   
   
   double xiQSh = history.begin()->node->legsize() == N0()?
                  DSH()->hardScaleFactor():1.;
   
   scale *= xiQSh;
   if ( begin->parent()||!isUnitarized ) {
     while ( begin->parent() && ( begin !=  endNode ) ) {
       if ( !dosudakov( begin , scale , begin->pT() , sudakov0_n ) ){
         history.push_back( { begin->parent() , 0. , scale } );
       }
       
       if ( std::isnan( sudakov0_n ) )
              generator()->logWarning(Exception()
                   << "Merger: sudakov"<<scale/GeV<<" "
                   <<begin->pT()/GeV<<"0_n is nan. "
                   << Exception::warning);
       
       scale = begin->pT();
       history.push_back( { begin->parent() , sudakov0_n , begin->pT() } );
       begin = begin->parent();
     }
     
     Energy notunirunning = scale;
     
     if ( !isUnitarized&&N()+N0() > int( currentNode()->legsize() ) ) {
       if ( !dosudakov( begin , notunirunning , mergePt() , sudakov0_n ) ){
         history.back().weight = 0.;
       }else{
         history.back().weight = sudakov0_n;
       }
     }
   }
   if( history.size() == 1 )scale /= DSH()->hardScaleFactor();
 }
 
 
 
 
 double Merger::sumPdfReweightExpansion()const{
   double res = 0.;
   Energy beam1Scale = history[0].scale*
                     ( history[0].node->legsize() == N0()?
                       currentME()->facFac():
                       DSH()->facFac() );
   Energy beam2Scale = history[0].scale*
                     ( history[0].node->legsize() == N0()?
                       currentME()->facFac():
                       DSH()->facFac() );
   
   for ( auto const & hs : history ){
       //pdf expansion only to the last step
     if( !hs.node->parent() )continue;
     if( hs.node->xcomb()->mePartonData()[0]->coloured()&&
         hs.node->nodeME()->lastX1()>0.99 )return 0.;
     if( hs.node->xcomb()->mePartonData()[1]->coloured()&&
         hs.node->nodeME()->lastX2()>0.99 )return 0.;
     
     if( hs.node->nodeME()->lastX1()<0.00001 )return 0.;
     if( hs.node->nodeME()->lastX2()<0.00001 )return 0.;
     
     if ( hs.node->dipole()->bornEmitter() == 0 ){
       res += pdfExpansion( hs.node , 0 ,
                        beam1Scale , 
                        ( hs.node->pT() ) , 
                        hs.node->nodeME()->lastX1() , 
                        Nf( history[0].scale ) , 
                        history[0].scale );
       beam1Scale = ( hs.node->pT() )*DSH()->facFac();
     }
     else if ( hs.node->dipole()->bornEmitter() == 1 ){
       res += pdfExpansion( hs.node , 1 ,
                        beam2Scale , 
                        ( hs.node->pT() ) , 
                        hs.node->nodeME()->lastX2() , 
                        Nf( history[0].scale ) , 
                        history[0].scale );
       beam2Scale = ( hs.node->pT() )*DSH()->facFac();
     }
     // if we're here we know hs.node->dipole()->bornEmitter() > 1
     // works only in collinear scheme
     else if ( hs.node->dipole()->bornSpectator() == 0 ){
       res += pdfExpansion( hs.node , 0 ,
                        beam1Scale , 
                        ( hs.node->pT() ) , 
                        hs.node->nodeME()->lastX1() , 
                        Nf( history[0].scale ) , 
                        history[0].scale );
       beam1Scale = ( hs.node->pT() )*DSH()->facFac();
     }
     else if ( hs.node->dipole()->bornSpectator() == 1 ){
       res += pdfExpansion( hs.node , 1 ,
                        beam2Scale , 
                        ( hs.node->pT() ) , 
                        hs.node->nodeME()->lastX2() , 
                        Nf( history[0].scale ) , 
                        history[0].scale );
       beam2Scale = ( hs.node->pT() )*DSH()->facFac();
     }
   }
   
   if ( currentNode()->xcomb()->mePartonData()[0]->coloured() ){
     res += pdfExpansion( history.back().node , 0 ,
                      beam1Scale , 
                      history[0].scale* currentME()->facFac() , 
                      ( history.back() ).node->nodeME()->lastX1() , 
                      Nf( history[0].scale ) , 
                      history[0].scale );
     
   }
   if ( currentNode()->xcomb()->mePartonData()[1]->coloured() ) {
     res += pdfExpansion( history.back().node , 1 ,
                      beam2Scale , 
                      history[0].scale* currentME()->facFac() , 
                      ( history.back() ).node->nodeME()->lastX2() , 
                      Nf( history[0].scale ) , 
                      history[0].scale );
   }
   return res;
 }
 
 
 
 
 
 #include "Herwig/MatrixElement/Matchbox/Phasespace/RandomHelpers.h"
 double Merger::pdfExpansion( NodePtr node  ,
                              int side , Energy  running ,
                              Energy next , double x ,
                              int nlp , Energy fixedScale ) const {
   
   tcPDPtr particle , parton;
   tcPDFPtr pdf;
   if ( side == 0 ) {
     particle = node->nodeME()->lastParticles().first->dataPtr();
     parton = node->nodeME()->lastPartons().first->dataPtr();
     pdf  = node->xcomb()->partonBins().first->pdf();
   }else{
     assert( side == 1 );
     particle = node->nodeME()->lastParticles().second->dataPtr();
     parton = node->nodeME()->lastPartons().second->dataPtr();
     pdf  = node->xcomb()->partonBins().second->pdf();
   }
   
     //copied from PKOperator
   double res = 0.;
   int number = 10;
   for ( int nr = 0;nr<number;nr++ ){
     double restmp = 0;
     
     using namespace RandomHelpers;
     double r = UseRandom::rnd();
     double eps = 1e-3;
     
     pair<double , double> zw  =
     generate( ( piecewise() , 
                flat( 0.0 , x ) , 
                match( inverse( 0.0 , x , 1.0 ) +
                       inverse( 1.0+eps , x , 1.0 ) ) ) , r );
     
     double z = zw.first;
     double mapz = zw.second;
     double PDFxparton = pdf->xfx( particle , parton , sqr( fixedScale ) , x )/x;
     double CA = SM().Nc();
     double CF = ( SM().Nc()*SM().Nc()-1.0 )/( 2.*SM().Nc() );
     
     
     if ( abs( parton->id() ) < 7 ) {
       
       double PDFxByzgluon = pdf->xfx( particle ,
                                      getParticleData( ParticleID::g ) ,
                                      sqr( fixedScale ) , x/z )*z/x;
       double PDFxByzparton = pdf->xfx( particle , parton ,
                                       sqr( fixedScale ) , x/z )*z/x;
       assert( abs( parton->id() ) < 7 );
       
       restmp += CF*( 3./2.+2.*log( 1.-x ) ) * PDFxparton;
       if ( z > x ) {
         restmp += 0.5 * ( sqr( z ) + sqr( 1.-z ) ) * PDFxByzgluon / z;
         restmp += CF*2.*( PDFxByzparton - z*PDFxparton )/( z*( 1.-z ) );
         restmp -=  CF*PDFxByzparton * ( 1.+z )/z;
       }
     }else{
       
       assert( parton->id() == ParticleID::g );
       double PDFxByzgluon = pdf->xfx( particle ,
                                       getParticleData( ParticleID::g ) ,
                                       sqr( fixedScale ) , x/z )*z/x;
+      // Pqg
       if ( z > x ){
         double factor = CF * ( 1. + sqr( 1.-z ) ) / sqr( z );
         for ( int f = -nlp; f <=  nlp; ++f ) {
           if ( f == 0 )
           continue;
           restmp += pdf->xfx( particle , getParticleData( f ) ,
                               sqr( fixedScale ) , x/z )*z/x*factor;
         }
       }
-      
+      // Pgg 
       restmp += ( ( 11./6. ) * CA
                   - ( 1./3. )*Nf( history[0].scale )
                   + 2.*CA*log( 1.-x ) ) *PDFxparton;
       if ( z > x ) {
         restmp += 2. * CA * ( PDFxByzgluon - z*PDFxparton ) / ( z*( 1.-z ) );
         restmp += 2.* CA *( ( 1.-z )/z - 1. + z*( 1.-z ) ) * PDFxByzgluon / z;
       }
       
     }
-    if ( PDFxparton<1e-8 )restmp =  0.;
-    res += 1*restmp*log( sqr( running/next ) )/PDFxparton*mapz;
+    if ( PDFxparton<1e-8 )
+	restmp =  0.;
+    else
+    	res += 1*restmp*log( sqr( running/next ) )/PDFxparton*mapz;
     
   }
   return res/number;
 }
 
 
 
 double Merger::sumAlphaSReweightExpansion()const{
   double res = 0.;
   const auto Oqcd=history[0].node->nodeME()->orderInAlphaS();
   res += alphasExpansion( history[0].scale* DSH()->renFac() ,
                             history[0].scale* currentME()->renFac() )*
                             Oqcd;
 
     // dsig is calculated with fixed alpha_s
   for ( auto const & hs : history ){
       //expansion only to the last step
     if( !hs.node->parent() )continue;
-    res += alphasExpansion( hs.node->pT()*DSH()->renFac()  , history[0].scale );
+    res += alphasExpansion( hs.node->pT()*DSH()->renFac()  ,currentME()->renFac()*history[0].scale );
   }
   return res;
 }
 
 double Merger::sumFillHistoryExpansion(){
   double res = 0.;
   double xiQSh = history[0].node->legsize() == N0()?DSH()->hardScaleFactor():1.;
   for ( auto const & hs : history ){
     if( !hs.node->parent() )continue;
     doHistExpansion( hs.node , ( hs.node == history[0].node?xiQSh:1. )*hs.scale ,
                      hs.node->pT() , history[0].scale , res );
   }
   return res;
 }
 
 
 MergingFactoryPtr Merger::treefactory()const{return theTreeFactory;}
 
 
 void Merger::doinit(){
   if ( !DSH()->hardScaleIsMuF() ) {
     throw Exception()
     << "Merger: Merging is currently only sensible "
     << "if we are using the hardScale as MuF."
     << Exception::abortnow;
   }
 }
 
 
 namespace{
 void setXCombScales(StdXCombPtr xc,Energy2 scale){
     xc->lastShowerScale                       ( scale );
     xc->partonBinInstances().first->scale     ( scale );
     xc->partonBinInstances().second->scale    ( scale );
 }
 }
 
 CrossSection Merger::MergingDSigDR() {
   
   history.clear();
   assert(currentNode()==theFirstNodeMap[ currentME()]);
 
   if(DSH()->doesSplitHardProcess()){
 	throw Exception()
   	<< "Merger: The splithardprocess option is currently not supported."
   	<< Exception::abortnow;	
   }
 
 
       //get the PDF's (from ShowerHandler.cc)
   if (!DSH()->getPDFA()||!DSH()->firstPDF().particle()){
      tSubProPtr sub = currentNode()->xcomb()->construct();
      const auto pb=currentNode()->xcomb()->partonBins();
      tcPDFPtr first  = DSH()->getPDFA() ?
           tcPDFPtr(DSH()->getPDFA()) : DSH()->firstPDF().pdf();
      tcPDFPtr second = DSH()->getPDFB() ?
           tcPDFPtr(DSH()->getPDFB()) : DSH()->secondPDF().pdf();
      DSH()->resetPDFs( {first,second },pb );
   }
 
  
  
   DSH()->eventHandler( generator()->eventHandler() );
   
   CrossSection res = ZERO;
   if( currentNode()->subtractedReal() ){
     res = MergingDSigDRRealStandard();
     theCurrentMaxLegs = maxLegsNLO();
   }else if( currentNode()->virtualContribution() ){
     res = MergingDSigDRVirtualStandard();
     theCurrentMaxLegs = maxLegsNLO();
   }else if( theGamma!= 1. ){
     res = MergingDSigDRBornGamma();
     theCurrentMaxLegs = maxLegsLO();
   }else{
     res = MergingDSigDRBornStandard();
     theCurrentMaxLegs = maxLegsLO();
   }
   
   auto lxc= currentME()->lastXCombPtr();
   setXCombScales(lxc,sqr( currentNode()->runningPt()));
 
 
   auto lp= currentME()->lastXCombPtr()->lastProjector();
   
   if( lp )
     setXCombScales( lp, sqr( currentNode()->runningPt()));
   
   if ( res == ZERO ){
     history.clear();
     return ZERO;
   }
   
   
   cleanup( currentNode() );
   lxc->subProcess( SubProPtr() );
   
   history.clear();
   
   if( !std::isfinite( double( res/nanobarn ) ) ){
     generator()->logWarning(Exception()
        << "Merger weight is " << res/nanobarn<< " -> setting to 0"
        << Exception::warning);
     return ZERO;
   }
   
   return res;
   
 }
 
 
 
 
 #include "Herwig/PDF/HwRemDecayer.h"
 void Merger::CKKW_PrepareSudakov( NodePtr node , Energy running ){
   tSubProPtr sub = node->xcomb()->construct();
   const auto pb=node->xcomb()->partonBins();
   DSH()->setCurrentHandler();
   DSH()->currentHandler()->generator()->currentEventHandler(currentNode()->xcomb()->eventHandlerPtr() );
   DSH()->currentHandler()->remnantDecayer()->setHadronContent( currentNode()->xcomb()->lastParticles() );
   DSH()->eventRecord().clear();
   DSH()->eventRecord().slimprepare( sub , dynamic_ptr_cast<tStdXCombPtr>( node->xcomb() ) , DSH()->pdfs() , currentNode()->xcomb()->lastParticles() );
   DSH()->hardScales( sqr( running ) );
 }
 
 
 Energy Merger::CKKW_StartScale( NodePtr node ) const {
   Energy res = generator()->maximumCMEnergy();
   const int N=node->legsize();
   const auto & data=node->nodeME()->mePartonData();
   const auto & momenta=node->nodeME()->lastMEMomenta();
   if( !node->children().empty() ){
     for ( int i = 0; i<N ; i++ ){ if ( !data[i]->coloured() )continue;
       for ( int j = 2; j<N ; j++ ){ if ( i == j||!data[j]->coloured() )continue;
 	for ( int k = 0; k<N ; k++ ){ if ( !data[k]->coloured() || i == k || j == k )continue;
 	  if(i<2){
 	    if(k<2) {
 		res =  min( res , IILTK->lastPt( momenta[i] , momenta[j] , momenta[k] ));
 	    }
 	    else    {
 
                 res =  min( res ,
                 (data[k]->mass()+data[j]->mass()+data[i]->mass()>ZERO)?
                 IFMTK->lastPt( momenta[i] , momenta[j] , momenta[k] ):
                 IFLTK->lastPt( momenta[i] , momenta[j] , momenta[k] ));
             }
 	  }else{
 	    if(k<2) {
                 res =  min( res ,
                 (data[k]->mass()+data[j]->mass()+data[i]->mass()>ZERO)?
                 FIMTK->lastPt( momenta[i] , momenta[j] , momenta[k] ):
                 FILTK->lastPt( momenta[i] , momenta[j] , momenta[k] ));
 
 	    }
 	    else    {
 		res =  min( res , 
 		(data[k]->mass()+data[j]->mass()+data[i]->mass()>ZERO)?
 		FFMTK->lastPt( momenta[i] , momenta[j] , momenta[k] ):
 		FFLTK->lastPt( momenta[i] , momenta[j] , momenta[k] ));
 	    }
 	  }
 	}
       }
     }
   }else{
     node->nodeME()->factory()->scaleChoice()->setXComb( node->xcomb() );
     res =  sqrt( node->nodeME()->factory()->scaleChoice()->renormalizationScale() );
   }
   node->nodeME()->factory()->scaleChoice()->setXComb( node->xcomb() );
   res = max( res , sqrt( node->nodeME()->factory()->scaleChoice()->renormalizationScale() ) );
   return res;
 }
 
 
 
 
 double Merger::alphasExpansion( Energy next , Energy fixedScale ) const {
   double betaZero = ( 11./6. )*SM().Nc() - ( 1./3. )*Nf( history[0].scale );
   double K=3.*( 67./18.-1./6.*sqr(Constants::pi) ) -5./9.*Nf( history[0].scale);
   return ( betaZero*log( sqr( fixedScale/next ) ) )+( theCMWScheme>0?K:0. );
 }
 
 
 double Merger::pdfratio( NodePtr  node ,
                          Energy  numerator_scale ,
                          Energy denominator_scale ,
                          int side ,
                          bool fromIsME,
                          bool toIsME ){
   StdXCombPtr bXc = node->xcomb();
   if( !bXc->mePartonData()[side]->coloured() )
   throw Exception()
   << "Merger: pdf-ratio required for non-coloured particle."
   << Exception::abortnow;
   
   
   double from = 1.; 
   double to   = 1.;
   if ( side == 0 ){
     if ( denominator_scale == numerator_scale && fromIsME==toIsME ) {
       return 1.;
     }
 
 
     if (fromIsME) {
       from = node->nodeME()->pdf1( sqr( denominator_scale ) );
     }else{
       from = DSH()->firstPDF().xfx(node->xcomb()->lastPartons().first->dataPtr(),
                                   sqr( denominator_scale ),
                                   node->xcomb()->lastX1())/node->xcomb()->lastX1();
     }
 
 
     if (toIsME) {
       to = node->nodeME()->pdf1( sqr( numerator_scale ) );
     }else{
       to = DSH()->firstPDF().xfx(node->xcomb()->lastPartons().first->dataPtr(),
                                   sqr( numerator_scale ),
                                   node->xcomb()->lastX1())/node->xcomb()->lastX1();
     }
     
     if ( ( to < 1e-8||from < 1e-8 )&&( to/from>10000000. ) ){
       generator()->logWarning(Exception()
                               << "Merger: pdfratio to = " << to << " from = " << from
                               << Exception::warning);
       return 0.;
     }
   }
   else{
     if ( denominator_scale == numerator_scale && fromIsME==toIsME ) {
       return 1.;
     }
     
     if (fromIsME) {
       from = node->nodeME()->pdf2( sqr( denominator_scale ) );
     }else{
       from =DSH()->secondPDF().xfx(node->xcomb()->lastPartons().second->dataPtr(),
                                   sqr( denominator_scale ),
                                   node->xcomb()->lastX2())/node->xcomb()->lastX2();
     }
 
 
     if (toIsME) {
       to = node->nodeME()->pdf2( sqr( numerator_scale ) );
     }else{
       to = DSH()->secondPDF().xfx(node->xcomb()->lastPartons().second->dataPtr(),
                                 sqr( numerator_scale ),
                                 node->xcomb()->lastX2())/node->xcomb()->lastX2();
     }
     
     if ( ( to < 1e-8||from < 1e-8 )&&( to/from>10000000. ) ){
       generator()->logWarning(Exception()
                               << "Merger: pdfratio to = "
                               << to << " from = " << from
                               << Exception::warning);
       return 0.;}
   }
   return to/from;
 }
 
 
 
 bool Merger::dosudakov( NodePtr node , Energy running , Energy next , double& sudakov0_n ) {
   CKKW_PrepareSudakov( node , running );
   for( DipoleChain const & chain : DSH()->eventRecord().chains() ){
     for( Dipole const & dip : chain.dipoles() ){
       sudakov0_n *= singlesudakov( dip , next , running , { true , false } );
       sudakov0_n *= singlesudakov( dip , next , running , { false , true } );
       if ( sudakov0_n == 0.0 ){
           cleanup( node );
         return false;
       }
     }
   }
     cleanup( node );
   return true;
 }
 
 bool Merger::doHistExpansion( NodePtr node , Energy  running , Energy next , Energy fixedScale , double& histExpansion ) {
   CKKW_PrepareSudakov( node , running );
   for( DipoleChain const & chain : DSH()->eventRecord().chains() ){
     for( Dipole const & dip : chain.dipoles() ){
       histExpansion += singleHistExpansion( dip , next , running , fixedScale , { true , false } );;
       histExpansion += singleHistExpansion( dip , next , running , fixedScale , { false , true } );
     }
   }
   cleanup( node );
   return true;
 }
 
 
 
 bool Merger::isProjectorStage( NodePtr  node , int pjs )const{
   return ( pjs == int( ( currentNode()->legsize() - node->legsize() ) ) );
 }
 
 void Merger::cleanup( NodePtr node ) {
   DSH()->eventRecord().clear();
   if( !node->xcomb()->subProcess() )return;
   ParticleVector vecfirst = node->xcomb()->subProcess()->incoming().first->children();
   for( auto const & particle : vecfirst )
   node->xcomb()->subProcess()->incoming().first->abandonChild( particle );
   
   ParticleVector vecsecond = node->xcomb()->subProcess()->incoming().second->children();
   for( auto const & particle : vecsecond )
   node->xcomb()->subProcess()->incoming().second->abandonChild( particle );
   node->xcomb()->subProcess( SubProPtr() );
 }
 
 double Merger::singlesudakov( Dipole dip  , Energy next , Energy running , pair<bool , bool> conf ){
   
   double res = 1.;
   tPPtr emitter = dip.emitter( conf );
   tPPtr spectator = dip.spectator( conf );
   DipoleSplittingInfo candidate( dip.index( conf ) , conf , 
                                 dip.emitterX( conf ) , 
                                 dip.spectatorX( conf ) , 
                                 emitter , spectator );
   
   
   if ( DSH()->generators().find( candidate.index() ) == DSH()->generators().end() ) DSH()->getGenerators( candidate.index() );
   
   auto const & gens = DSH()->generators().equal_range( candidate.index() );
   
   for ( auto   gen = gens.first; gen !=  gens.second; ++gen ) {
     if ( !( gen->first == candidate.index() ) )
     continue;
     
     Energy dScale  = 	gen->second->splittingKinematics()->dipoleScale( emitter->momentum() , spectator->momentum() );
     candidate.scale( dScale );
     candidate.continuesEvolving();
     Energy ptMax = gen->second->splittingKinematics()->ptMax( candidate.scale() , candidate.emitterX() , candidate.spectatorX() , 
                                                              candidate.index() , *gen->second->splittingKernel() );
     
     candidate.hardPt( min( running , ptMax ) );
     
     if ( candidate.hardPt()>next ){
       res *= gen->second->sudakov( candidate , next );
     }
   }
   
   return res;
 }
 
 
 double Merger::singleHistExpansion( Dipole dip  , Energy next , Energy running , Energy fixedScale , pair<bool , bool> conf ){
   
   double res = 0.;
   tPPtr emitter = dip.emitter( conf );
   tPPtr spectator = dip.spectator( conf );
   DipoleSplittingInfo candidate( dip.index( conf ) , 
                                  conf , dip.emitterX( conf ) , 
                                  dip.spectatorX( conf ) , 
                                  emitter , spectator );
   
   if ( DSH()->generators().find( candidate.index() ) ==
        DSH()->generators().end() )
        DSH()->getGenerators( candidate.index() );
   
   auto const & gens = DSH()->generators().equal_range( candidate.index() );
   
   for ( auto gen = gens.first; gen !=  gens.second; ++gen ) {
     if ( !( gen->first == candidate.index() ) )
     continue;
     Energy dScale = gen->second->splittingKinematics()->dipoleScale(
                           emitter->momentum() , spectator->momentum() );
     candidate.scale( dScale );
     candidate.continuesEvolving();
     Energy ptMax = gen->second->
                    splittingKinematics()->ptMax(
                       candidate.scale() , candidate.emitterX() , 
                       candidate.spectatorX() , candidate.index() , 
                       *gen->second->splittingKernel() );
     
     candidate.hardPt( min( running , ptMax ) );
     if ( candidate.hardPt()>next ){
       res += gen->second->sudakovExpansion( candidate , next , fixedScale );
     }
   }
 	 
 	 return res;
 }
 
 
 
 
 void Merger::firstNodeMap( MatchboxMEBasePtr a , NodePtr b ){
   theFirstNodeMap.insert( { a , b } );
 }
 
 
 
 map<MatchboxMEBasePtr , NodePtr> Merger::firstNodeMap()const{return theFirstNodeMap;}
 
 
 
 
 void Merger::setXComb( tStdXCombPtr xc ){
   currentNode()->setXComb( xc );
 }
 void Merger::setKinematics(  ){
   currentNode()->setKinematics();
 }
 void Merger::clearKinematics(  ){
   currentNode()->clearKinematics();
 }
 
 void Merger::flushCaches(){
   if (currentNode()&&currentNode()->xcomb()->lastParticles().first) {
     currentNode()->flushCaches();
   }
 }
 
 bool Merger::generateKinematics( const double * r ){
   return currentNode()->firstgenerateKinematics( r , ! currentNode()->subtractedReal() );
 }
 
 bool Merger::matrixElementRegion( PVector incoming , PVector outgoing , Energy winnerScale , Energy cutscale )const{
   
 
   Energy ptx = Constants::MaxEnergy;
   bool foundwinnerpt = false;
   using namespace boost;
     //FF
   
   for( auto const & em : outgoing ){ if ( ! em->coloured() ) continue;
     for( auto const & emm : outgoing ){ if ( !emm->coloured() ) continue; if ( em == emm ) continue;
       for( auto const & spe : outgoing ){ if ( !spe->coloured() ) continue; if ( em == spe||emm == spe ) continue;
         
         if ( !( em->id() == -emm->id()||emm->id()>6 ) )continue;
         
         Energy pt = ZERO;
         if ( em->momentum().m()<= 10_MeV &&
             emm->momentum().m()<= 10_MeV &&
             spe->momentum().m()<= 10_MeV  ) {
           pt = FFLTK->lastPt( em->momentum() , emm->momentum() , spe->momentum() );
         }else{
           pt = FFMTK->lastPt( em->momentum() , emm->momentum() , spe->momentum() );
         }
         
         if ( abs( pt-winnerScale ) < 10_MeV  ) {
           foundwinnerpt = true;
         }
         ptx  = min( ptx , pt );
       }
     }
   }
   
     //FI
   for( auto const & spe : incoming ){ if ( ! spe->coloured() ) continue;
     for( auto const & emm : outgoing ){ if ( ! emm->coloured() ) continue;
       for( auto const & em : outgoing ){ if ( ! em->coloured() ) continue; if ( em == emm ) continue;
         
         if ( !( em->id() == -emm->id() || emm->id()>6 ) )continue;
         
 
         Energy pt = ZERO;
         if ( em->momentum().m()<= 10_MeV &&
             emm->momentum().m()<= 10_MeV &&
             spe->momentum().m()<= 10_MeV  ) {
           pt = FILTK->lastPt( em->momentum() , emm->momentum() , spe->momentum() );
         }else{
           pt = FIMTK->lastPt( em->momentum() , emm->momentum() , spe->momentum() );
         }
         
         
         if ( abs( pt-winnerScale )<10_MeV  ) {
           foundwinnerpt = true;
         }
         
         if( pt > ZERO )
         ptx  = min( ptx , pt );
       }
     }
   }
   
     //IF
   for( auto const & em : incoming ){ if ( ! em->coloured() ) continue;
     for( auto const & emm : outgoing ){ if ( ! emm->coloured() ) continue;
       for( auto const & spe : outgoing ){ if ( ! spe->coloured() ) continue; if ( emm == spe ) continue;
         
         if ( !( em->id()>6|| em->id() == emm->id() ||emm->id()>6 ) )continue;
         
         Energy pt = ZERO;
         
         if ( em->momentum().m()<= 10_MeV &&
              emm->momentum().m()<= 10_MeV &&
              spe->momentum().m()<= 10_MeV  ) {
             //massless
           pt = IFLTK->lastPt( em->momentum() , emm->momentum() , spe->momentum()  );
         }else{
             //massiv
           pt = IFMTK->lastPt( em->momentum() , emm->momentum() , spe->momentum()  );
         }
         
         
         if ( abs( pt-winnerScale )< 10_MeV ) {
           foundwinnerpt = true;
         }
         ptx  = min( ptx , pt );
       }
     }
   }
   
     //II
   for( auto const & em : incoming ){ if ( ! em->coloured() ) continue;
     for( auto const & spe : incoming ){ if ( ! spe->coloured() ) continue; if ( em == spe ) continue;
       for( auto const & emm : outgoing ){ if ( ! emm->coloured() ) continue;
         if ( !( em->id()>6||em->id() == emm->id() ||emm->id()>6 ) )continue;
         
         Energy  pt = IILTK->lastPt( em->momentum() , emm->momentum() , spe->momentum() );
         
         if ( abs( pt-winnerScale )< 10_MeV ) {
           foundwinnerpt = true;
         }
         ptx  = min( ptx , pt );
       }
     }
   }
   
   if( !foundwinnerpt ){
     generator()->logWarning( Exception()
                             << "Merger: Could not find winner with pt."
                             << "Run with -d3 to get phase space points. "
                             << Exception::warning );
     
     if( Debug::level > 2 ) {
       generator()->log() << "\nWarning: could not find winner with pt: " << winnerScale/GeV;
       for( auto const & emm : incoming ){
         generator()->log() << "\n" << emm->id() << " " << emm->momentum()/GeV << " " << emm->momentum().m()/GeV << flush;
       }
       for( auto const & emm : outgoing ){
         generator()->log() <<"\n" << emm->id() << " " << emm->momentum()/GeV << " " << emm->momentum().m()/GeV << flush;
       }
     }
     
   }
   
   return ( ptx>cutscale ) ;
   
 }
 
 bool Merger::notOnlyMulti() const {
   return ( treefactory()->onlymulti() != -1&&
           treefactory()->onlymulti() !=
           int( currentNode()->legsize()-( projected ? 1 : 0 ) ) );
 }
 
 int Merger::M()const{return theTreeFactory->M();}
 
 int Merger::N()const{return theTreeFactory->N();}
 
 void Merger::debugVirt(double weight,double w1,double w2,double w3,
                        CrossSection matrixElement,double ww1,double ww2,
                        double ww3, NodePtr node,CrossSection bornWeight)const{
   Energy minPT = Constants::MaxEnergy;
   for( auto const & no :currentNode()->children() )minPT = min( no->pT() , minPT );
   
   generator()->log() << "\nVIRT " << minPT/GeV << " " << weight << " " << w1;
   generator()->log() << " " << w2;
   generator()->log() << " " << w3;
   generator()->log() << " " << ( matrixElement/nanobarn ) << " " << ww1 << " " << ww2 << " " << ww3 << " " << node->pT()/GeV << " " << node->nodeME()->mePartonData()[3]->mass()/GeV << " " << ( bornWeight*SM().alphaS()/( 2.*ThePEG::Constants::pi )/nanobarn );
 }
 
 
 
 void Merger::debugReal(string realstr, double weight,
                        CrossSection me, CrossSection dip)const {
   Energy minPT = Constants::MaxEnergy;
   for( auto const & no :currentNode()->children() )minPT = min( no->pT() , minPT );
   
   generator()->log() << "\n"<<realstr <<" "<< minPT/GeV << " " << weight << " " << ( me-dip )/nanobarn << " " << me/nanobarn << " " << dip/nanobarn;
   
 }
 
   // If needed , insert default implementations of virtual function defined
   // in the InterfacedBase class here ( using ThePEG-interfaced-impl in Emacs ).
 
 #include "ThePEG/Persistency/PersistentOStream.h"
 void Merger::persistentOutput( PersistentOStream & os ) const {
   os << theShowerExpansionWeights << theCMWScheme << projected <<
   isUnitarized << isNLOUnitarized  <<
   theOpenZBoundaries << theChooseHistory <<
   theN0 << theOnlyN   << weight <<
   theGamma << theSmearing <<  ounit( theIRSafePT , GeV ) <<
   ounit( theMergePt , GeV ) <<  ounit( theCentralMergePt , GeV )
   << theLargeNBasis << FFLTK << FILTK <<
   IFLTK << IILTK << FFMTK << FIMTK << IFMTK <<
   theDipoleShowerHandler << theTreeFactory << 
   theFirstNodeMap<<theRealSubtractionRatio << emitDipoleMEDiff;
   
 }
 #include "ThePEG/Persistency/PersistentIStream.h"
 void Merger::persistentInput( PersistentIStream & is , int ) {
   is >> theShowerExpansionWeights >> theCMWScheme >> projected >>
   isUnitarized >> isNLOUnitarized >>
   theOpenZBoundaries >>
   theChooseHistory >> theN0 >> theOnlyN >>
   weight >> 
   theGamma >>   theSmearing >>  iunit( theIRSafePT , GeV ) >>
   iunit( theMergePt , GeV ) >>
   iunit( theCentralMergePt , GeV ) >> theLargeNBasis >>
   FFLTK >> FILTK >> IFLTK >>
   IILTK >> FFMTK >> FIMTK >>
   IFMTK >> theDipoleShowerHandler >>  theTreeFactory >> 
   theFirstNodeMap >> theRealSubtractionRatio >> emitDipoleMEDiff;
 }
 
   // *** 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 ).
 #include "ThePEG/Utilities/DescribeClass.h"
 DescribeClass<Merger , Herwig::MergerBase>
 describeHerwigMerger( "Herwig::Merger" , "HwDipoleShower.so" );
 
   //ClassDescription<Merger> Merger::initMerger;
   // Definition of the static class description member.
 
 #include "ThePEG/Interface/ClassDocumentation.h"
 #include "ThePEG/Interface/Parameter.h"
 #include "ThePEG/Interface/Reference.h"
 #include "ThePEG/Interface/Switch.h"
 
 void Merger::Init() {
   
   static ClassDocumentation<Merger> documentation
   ( "The Merger class takes care of merging multiple LO & NLO cross sections." );
   
  ////////////////////////////////////////////////// 
   
   static Switch<Merger , unsigned int>
   interfaceShowerExpansionWeights
   ( "ShowerExpansionWeights" ,
    "Calculate the expansions of the shower history to be NLO accurate, in different schemes." ,
    &Merger::theShowerExpansionWeights ,
    3 , false , false );
   
   static SwitchOption
   interfaceShowerExpansionWeightsScheme0
   ( interfaceShowerExpansionWeights ,
    "NoWeights" ,
    "Switch off the expansion." ,
    0 );
   static SwitchOption
   interfaceShowerExpansionWeightsScheme1
   ( interfaceShowerExpansionWeights ,
    "FlatAndHistoryReweighted" ,
    "Sum alphaS expansion and weight with same Historyweight as LO." ,
    1 );
   static SwitchOption
   interfaceShowerExpansionWeightsScheme2
   ( interfaceShowerExpansionWeights ,
    "NoAlphaSReweightForSudakovExpansion" ,
    "Switch off the expansion." ,
    2 );
   static SwitchOption
   interfaceShowerExpansionWeightsScheme3
   ( interfaceShowerExpansionWeights ,
    "NoAlphaSReweightForAllExpansions" ,
    "Switch off the expansion." ,
    3 );
   static SwitchOption
   interfaceShowerExpansionWeightsScheme4
   ( interfaceShowerExpansionWeights ,
    "NoAlphaSReweightForAlphaSExpansion" ,
    "Switch off the expansion." ,
    4 ); 
 
  /////////////////////////////////////////////////////////////////////7
 
  
   static Switch<Merger , unsigned int>
   interfacetheCMWScheme
   ( "CMWScheme" ,
    "Use CMW-Scheme to calculate the alpha_s for the shower expressions." ,
    &Merger::theCMWScheme ,
    0 ,
    false , false );
   static SwitchOption interfacetheCMWSchemeNo
   (interfacetheCMWScheme,
    "No",
    "No CMW-Scheme",
    0);
   static SwitchOption interfacetheCMWSchemeLinear
   (interfacetheCMWScheme,
    "Linear",
    "Linear CMW multiplication: alpha_s(q) -> alpha_s(q)(1+K_g*alpha_s(q)/2pi )",
    1);
   static SwitchOption interfacetheCMWSchemeFactor
   (interfacetheCMWScheme,
    "Factor",
    "Use factor in alpha_s argument: alpha_s(q) -> alpha_s(fac*q) with fac=exp(-(67-3pi^2-10/3*Nf)/(33-2Nf)) ",
    2);
   
 
   static Parameter<Merger , Energy> interfaceMergerScale
   ( "MergingScale" ,  "The MergingScale." , 
    &Merger::theCentralMergePt ,
    GeV , 20.0*GeV , 0.0*GeV , 0*GeV ,
    false , false , Interface::lowerlim );
   
   
   
   static Parameter<Merger , double> interfacegamma
   ( "gamma" , 
    "gamma parameter." , 
    &Merger::theGamma , 1.0 , 0.0 , 0 , 
    false , false , Interface::lowerlim );
    interfacegamma.rank(-1); 
   
  
   static Switch<Merger,int> interfaceOpenZBoundariesM
   ("OpenZBoundaries", "",
    &Merger::theOpenZBoundaries, 0, false, false);
   static SwitchOption interfaceOpenZBoundariesMhardScale
   (interfaceOpenZBoundariesM,   "Hard",   "",   0);
   static SwitchOption interfaceOpenZBoundariesMfull
   (interfaceOpenZBoundariesM,   "Full",   "",   1);
   static SwitchOption interfaceOpenZBoundariesMDipoleScale
   (interfaceOpenZBoundariesM,   "DipoleScale",   "",   2);
  
  
  
   static Switch<Merger , bool>
   interfaceemitDipoleMEDiff
   ( "emitDipoleMEDiff" , 
   "Allow emissions of the unitarisation contribution with prob. 1-min(B_n/sum Dip_n,sum Dip_n/B_n)" , 
   &Merger::emitDipoleMEDiff , false , false , false );
   static SwitchOption interfaceemitDipoleMEDiffYes
   ( interfaceemitDipoleMEDiff , "Yes" , "" , true );
   static SwitchOption interfaceemitDipoleMEDiffNo
   ( interfaceemitDipoleMEDiff , "No" , "" , false );
   interfaceemitDipoleMEDiff.rank(-1);
  
   
 
 
   static Parameter<Merger , Energy>  interfaceIRSafePT
   ( "IRSafePT" ,
   "Set the pt for which a matrixelement should be treated as IR-safe." ,
   &Merger::theIRSafePT ,
   GeV , 0.0 * GeV , ZERO , Constants::MaxEnergy ,
   true , false , Interface::limited );
   interfaceIRSafePT.setHasDefault( false );
   
   
   static Parameter<Merger , double>  interfacemergePtsmearing(
   "MergingScaleSmearing" ,
   "Set the percentage the merging pt should be smeared." ,
   &Merger::theSmearing ,
   0. , 0. ,  0.0 , 0.5 ,
   true , false , Interface::limited );
   
  
   static Parameter<Merger , int>  interfacechooseHistory(
   "chooseHistory" ,
   "Various   ways of choosing the history weights: 0(default):dipole xs, 1:dipole/born, 2:flat, 3: 1/pt_dip" ,
   &Merger::theChooseHistory ,
   3 , -1 , 0 ,
   false , false , Interface::lowerlim );
   
   
   static Parameter<Merger , double>  interfacetheRealSubtractionRatio(
   "RealSubtractionRatio" ,
   "If the pt of the Dipole divided by the merging scale is lower than the ratio, the dipole is used to subtract the real emission. Otherwise the shower approximation is used, " ,
   &Merger::theRealSubtractionRatio , 0. , 0. ,
   1. , 10.0 ,
   true , false , Interface::limited );
 
 }
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
diff --git a/Shower/QTilde/Default/QTildeReconstructor.cc b/Shower/QTilde/Default/QTildeReconstructor.cc
--- a/Shower/QTilde/Default/QTildeReconstructor.cc
+++ b/Shower/QTilde/Default/QTildeReconstructor.cc
@@ -1,2930 +1,2942 @@
 // -*- C++ -*-
 //
 // QTildeReconstructor.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 QTildeReconstructor class.
 //
 
 #include "QTildeReconstructor.h"
 #include "ThePEG/PDT/EnumParticles.h"
 #include "ThePEG/Repository/EventGenerator.h"
 #include "ThePEG/EventRecord/Event.h"
 #include "ThePEG/Interface/Parameter.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/Core/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>
 
 using namespace Herwig;
 
 DescribeClass<QTildeReconstructor,KinematicsReconstructor>
 describeQTildeReconstructor("Herwig::QTildeReconstructor", "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 QTildeReconstructor::persistentOutput(PersistentOStream & os) const {
   os << _reconopt << _initialBoost << ounit(_minQ,GeV) << _noRescale 
      << _noRescaleVector << _finalStateReconOption
      << _initialStateReconOption;
 }
 
 void QTildeReconstructor::persistentInput(PersistentIStream & is, int) {
   is >> _reconopt >> _initialBoost >> iunit(_minQ,GeV) >> _noRescale 
      >> _noRescaleVector >> _finalStateReconOption
      >> _initialStateReconOption;  
 }
 
 void QTildeReconstructor::Init() {
 
   static ClassDocumentation<QTildeReconstructor> 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<QTildeReconstructor,unsigned int> interfaceReconstructionOption
     ("ReconstructionOption",
      "Option for the kinematics reconstruction",
      &QTildeReconstructor::_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<QTildeReconstructor,Energy> interfaceMinimumQ2
     ("MinimumQ2",
      "The minimum Q2 for the reconstruction of initial-final systems",
      &QTildeReconstructor::_minQ, GeV, 0.001*GeV, 1e-6*GeV, 10.0*GeV,
      false, false, Interface::limited);
 
   static RefVector<QTildeReconstructor,ParticleData> interfaceNoRescale
     ("NoRescale",
      "Particles which shouldn't be rescaled to be on shell by the shower",
      &QTildeReconstructor::_noRescaleVector, -1, false, false, true, false, false);
 
   static Switch<QTildeReconstructor,unsigned int> interfaceInitialInitialBoostOption
     ("InitialInitialBoostOption",
      "Option for how the boost from the system before ISR to that after ISR is applied.",
      &QTildeReconstructor::_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<QTildeReconstructor,unsigned int> interfaceFinalStateReconOption
     ("FinalStateReconOption",
      "Option for how to reconstruct the momenta of the final-state system",
      &QTildeReconstructor::_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 Switch<QTildeReconstructor,unsigned int> interfaceInitialStateReconOption
     ("InitialStateReconOption",
      "Option for the reconstruction of initial state radiation",
      &QTildeReconstructor::_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);
 
 }
 
 void QTildeReconstructor::doinit() {
   KinematicsReconstructor::doinit();
   _noRescale = set<cPDPtr>(_noRescaleVector.begin(),_noRescaleVector.end());
 }
 
 bool QTildeReconstructor::
 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()) {
 	  jetGrandParent->showerKinematics()->reconstructLast(particleJetParent,
 							      _progenitor->mass());
 	}
 	else {
 	  jetGrandParent->showerKinematics()->reconstructLast(particleJetParent);
 	}
       }
     }
     // otherwise
     else {
       Energy dm = particleJetParent->data().constituentMass();
       if (abs(dm-particleJetParent->momentum().m())>0.001*MeV
 	  &&particleJetParent->dataPtr()->stable()
 	  &&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 QTildeReconstructor::
 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 
 QTildeReconstructor::solveKfactor(const Energy & root_s, 
 				  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 QTildeReconstructor::
 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 QTildeReconstructor::
 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 QTildeReconstructor::
 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 QTildeReconstructor::
 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 QTildeReconstructor::
 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 QTildeReconstructor::
 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 QTildeReconstructor::
 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  QTildeReconstructor::"
 			<< "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  QTildeReconstructor::"
 		      << "inverseRescalingFactor " 
 		      << Exception::eventerror;
   return lambda;
 }
 
 bool QTildeReconstructor::
 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 QTildeReconstructor::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 QTildeReconstructor::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 QTildeReconstructor::
 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 QTildeReconstructor::
 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 "
 			    << "QTildeReconstructor::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 "
 			    << "QTildeReconstructor::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 "
 		      << "QTildeReconstructor::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 QTildeReconstructor::
 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 QTildeReconstructor::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 QTildeReconstructor::
 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) {
-    if(betam<0.5) { 
-      gamma = 1./sqrt(1.-sqr(betam));
-    }
-    else {
-      gamma = ( kps+ qs + Q2)/
-	sqrt(2.*kps*qs + kps*Q2 + qs*Q2 + sqr(Q2) + 2.*q*newq.e()*kp*sqrt(kps + Q2));
-    }
+    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 QTildeReconstructor::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 QTildeReconstructor::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 QTildeReconstructor::
 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);
   }
   // 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);
       }
     }
   }
   // 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 QTildeReconstructor::
 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 QTildeReconstructor::
 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 QTildeReconstructor::
 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())->showerModel()->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())->showerModel()->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 QTildeReconstructor::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 QTildeReconstructor::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 QTildeReconstructor::
 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 QTildeReconstructor::
 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 QTildeReconstructor::
 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 QTildeReconstructor::
 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 QTildeReconstructor::
 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())->showerModel()->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 QTildeReconstructor::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 QTildeReconstructor::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 QTildeReconstructor::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>
 QTildeReconstructor::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>
 QTildeReconstructor::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 QTildeReconstructor::
 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 QTildeReconstructor::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/Makefile.am b/Shower/QTilde/Makefile.am
--- a/Shower/QTilde/Makefile.am
+++ b/Shower/QTilde/Makefile.am
@@ -1,27 +1,27 @@
 SUBDIRS = Matching
 pkglib_LTLIBRARIES = HwShower.la
-HwShower_la_LDFLAGS = $(AM_LDFLAGS) -module -version-info 23:0:0
+HwShower_la_LDFLAGS = $(AM_LDFLAGS) -module -version-info 24:0:0
 HwShower_la_SOURCES =  \
 Couplings/ShowerAlphaQCD.h Couplings/ShowerAlphaQCD.cc \
 Couplings/ShowerAlphaQED.h Couplings/ShowerAlphaQED.cc\
 QTildeShowerHandler.h QTildeShowerHandler.fh QTildeShowerHandler.cc \
 SplittingFunctions/HalfHalfOneSplitFn.h SplittingFunctions/HalfHalfOneSplitFn.cc\
 SplittingFunctions/OneOneOneSplitFn.h SplittingFunctions/OneOneOneSplitFn.cc\
 SplittingFunctions/ZeroZeroOneSplitFn.h SplittingFunctions/ZeroZeroOneSplitFn.cc\
 SplittingFunctions/OneHalfHalfSplitFn.h SplittingFunctions/OneHalfHalfSplitFn.cc\
 SplittingFunctions/HalfOneHalfSplitFn.h SplittingFunctions/HalfOneHalfSplitFn.cc\
 Default/QTildeSudakov.cc Default/QTildeSudakov.h\
 Default/QTildeModel.cc Default/QTildeModel.h\
 Default/Decay_QTildeShowerKinematics1to2.cc \
 Default/Decay_QTildeShowerKinematics1to2.h  \
 Default/IS_QTildeShowerKinematics1to2.cc    Default/IS_QTildeShowerKinematics1to2.h  \
 Default/FS_QTildeShowerKinematics1to2.cc    Default/FS_QTildeShowerKinematics1to2.h  \
 Default/QTildeFinder.cc Default/QTildeFinder.h\
 Default/QTildeReconstructor.cc Default/QTildeReconstructor.h Default/QTildeReconstructor.tcc \
 Base/KinematicsReconstructor.cc \
 Base/KinematicsReconstructor.h \
 Base/KinematicsReconstructor.fh \
 Base/ShowerModel.cc Base/ShowerModel.h Base/ShowerModel.fh \
 Base/PartnerFinder.h Base/PartnerFinder.fh Base/PartnerFinder.cc \
 Base/ShowerVeto.h Base/ShowerVeto.fh Base/ShowerVeto.cc \
 Base/FullShowerVeto.h Base/FullShowerVeto.fh Base/FullShowerVeto.cc
diff --git a/Shower/QTilde/Matching/Makefile.am b/Shower/QTilde/Matching/Makefile.am
--- a/Shower/QTilde/Matching/Makefile.am
+++ b/Shower/QTilde/Matching/Makefile.am
@@ -1,8 +1,8 @@
 pkglib_LTLIBRARIES = HwMatching.la
 
-HwMatching_la_LDFLAGS = $(AM_LDFLAGS) -module -version-info 3:0:0
+HwMatching_la_LDFLAGS = $(AM_LDFLAGS) -module -version-info 4:0:0
 
 HwMatching_la_SOURCES = \
 PowhegShowerHandler.h	PowhegShowerHandler.cc	\
 CKKWTree.h CKKWTree.fh CKKWTree.cc \
 ProtoTree.h ProtoBranching.h PotentialTree.h
diff --git a/Shower/ShowerHandler.cc b/Shower/ShowerHandler.cc
--- a/Shower/ShowerHandler.cc
+++ b/Shower/ShowerHandler.cc
@@ -1,1103 +1,1101 @@
 // -*- C++ -*-
 //
 // ShowerHandler.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 ShowerHandler class.
 //
 
 #include "ShowerHandler.h"
 #include "ThePEG/Interface/ClassDocumentation.h"
 #include "ThePEG/Interface/Reference.h"
 #include "ThePEG/Interface/Parameter.h"
 #include "ThePEG/Interface/ParVector.h"
 #include "ThePEG/Interface/Switch.h"
 #include "ThePEG/Interface/Command.h"
 #include "ThePEG/PDF/PartonExtractor.h"
 #include "ThePEG/PDF/PartonBinInstance.h"
 #include "Herwig/PDT/StandardMatchers.h"
 #include "ThePEG/Cuts/Cuts.h"
 #include "ThePEG/Handlers/StandardXComb.h"
 #include "ThePEG/Utilities/Throw.h"
 #include "ThePEG/Utilities/StringUtils.h"
 #include "ThePEG/Persistency/PersistentOStream.h"
 #include "ThePEG/Persistency/PersistentIStream.h"
 #include "ThePEG/Repository/EventGenerator.h"
 #include "Herwig/Utilities/EnumParticles.h"
 #include "Herwig/PDF/MPIPDF.h"
 #include "Herwig/PDF/MinBiasPDF.h"
 #include "ThePEG/Handlers/EventHandler.h"
 #include "Herwig/Shower/Core/Base/ShowerTree.h"
 #include "Herwig/PDF/HwRemDecayer.h"
 #include <cassert>
 #include "ThePEG/Utilities/DescribeClass.h"
 #include "Herwig/Decay/DecayIntegrator.h"
 #include "Herwig/Decay/DecayPhaseSpaceMode.h"
 
 using namespace Herwig;
 
 DescribeClass<ShowerHandler,CascadeHandler>
 describeShowerHandler ("Herwig::ShowerHandler","HwShower.so");
 
 ShowerHandler::~ShowerHandler() {}
 
 tShowerHandlerPtr ShowerHandler::currentHandler_ = tShowerHandlerPtr();
 
 void ShowerHandler::doinit() {
   CascadeHandler::doinit();
   // copy particles to decay before showering from input vector to the 
   // set used in the simulation
   if ( particlesDecayInShower_.empty() )
     particlesDecayInShower_.insert(inputparticlesDecayInShower_.begin(),
 				   inputparticlesDecayInShower_.end());
   ShowerTree::_vmin2 = vMin_;
   ShowerTree::_spaceTime = includeSpaceTime_;
   if ( profileScales() ) {
     if ( profileScales()->unrestrictedPhasespace() &&
 	 restrictPhasespace() ) {
       generator()->log()
 	<< "ShowerApproximation warning: The scale profile chosen requires an unrestricted phase space,\n"
 	<< "however, the phase space was set to be restricted. Will switch to unrestricted phase space.\n"
 	<< flush;
       restrictPhasespace_ = false;
     }
   }
 }
 
 IBPtr ShowerHandler::clone() const {
   return new_ptr(*this);
 }
 
 IBPtr ShowerHandler::fullclone() const {
   return new_ptr(*this);
 }
 
 ShowerHandler::ShowerHandler() : 
   maxtry_(10),maxtryMPI_(10),maxtryDP_(10),maxtryDecay_(100),
   factorizationScaleFactor_(1.0),
   renormalizationScaleFactor_(1.0),
   hardScaleFactor_(1.0),
   restrictPhasespace_(true), maxPtIsMuF_(false), 
   pdfFreezingScale_(2.5*GeV),
   doFSR_(true), doISR_(true),
   splitHardProcess_(true),
   includeSpaceTime_(false), vMin_(0.1*GeV2),
   reweight_(1.0) {
   inputparticlesDecayInShower_.push_back( 6  ); //  top 
   inputparticlesDecayInShower_.push_back( 23 ); // Z0
   inputparticlesDecayInShower_.push_back( 24 ); // W+/-
   inputparticlesDecayInShower_.push_back( 25 ); // h0
 }
 
 void ShowerHandler::doinitrun(){
   CascadeHandler::doinitrun();
   //can't use isMPIOn here, because the EventHandler is not set at that stage
   if(MPIHandler_) { 
     MPIHandler_->initialize();
     if(MPIHandler_->softInt())
       remDec_->initSoftInteractions(MPIHandler_->Ptmin(), MPIHandler_->beta());
   }
   ShowerTree::_vmin2 = vMin_;
   ShowerTree::_spaceTime = includeSpaceTime_;
 }
 
 void ShowerHandler::dofinish() {
   CascadeHandler::dofinish();
   if(MPIHandler_) MPIHandler_->finalize();
 }
 
 void ShowerHandler::persistentOutput(PersistentOStream & os) const {
   os << remDec_ << ounit(pdfFreezingScale_,GeV) << maxtry_ 
      << maxtryMPI_ << maxtryDP_ << maxtryDecay_ 
      << inputparticlesDecayInShower_
      << particlesDecayInShower_ << MPIHandler_ << PDFA_ << PDFB_
      << PDFARemnant_ << PDFBRemnant_
      << includeSpaceTime_ << ounit(vMin_,GeV2)
      << factorizationScaleFactor_ << renormalizationScaleFactor_
      << hardScaleFactor_
      << restrictPhasespace_ << maxPtIsMuF_ << hardScaleProfile_
      << showerVariations_ << doFSR_ << doISR_ << splitHardProcess_;
 }
 
 void ShowerHandler::persistentInput(PersistentIStream & is, int) {
   is >> remDec_ >> iunit(pdfFreezingScale_,GeV) >> maxtry_ 
      >> maxtryMPI_ >> maxtryDP_ >> maxtryDecay_
      >> inputparticlesDecayInShower_
      >> particlesDecayInShower_ >> MPIHandler_ >> PDFA_ >> PDFB_
      >> PDFARemnant_ >> PDFBRemnant_
      >> includeSpaceTime_ >> iunit(vMin_,GeV2)
      >> factorizationScaleFactor_ >> renormalizationScaleFactor_
      >> hardScaleFactor_
      >> restrictPhasespace_ >> maxPtIsMuF_ >> hardScaleProfile_
      >> showerVariations_ >> doFSR_ >> doISR_ >> splitHardProcess_;
 }
 
 void ShowerHandler::Init() {
 
   static ClassDocumentation<ShowerHandler> documentation
     ("Main driver class for the showering.");
 
   static Reference<ShowerHandler,HwRemDecayer> 
     interfaceRemDecayer("RemDecayer", 
 			"A reference to the Remnant Decayer object", 
 			&Herwig::ShowerHandler::remDec_,
 			false, false, true, false);
 
   static Parameter<ShowerHandler,Energy> interfacePDFFreezingScale
     ("PDFFreezingScale",
      "The PDF freezing scale",
      &ShowerHandler::pdfFreezingScale_, GeV, 2.5*GeV, 2.0*GeV, 10.0*GeV,
      false, false, Interface::limited);
 
   static Parameter<ShowerHandler,unsigned int> interfaceMaxTry
     ("MaxTry",
      "The maximum number of attempts for the main showering loop",
      &ShowerHandler::maxtry_, 10, 1, 100,
      false, false, Interface::limited);
 
   static Parameter<ShowerHandler,unsigned int> interfaceMaxTryMPI
     ("MaxTryMPI",
      "The maximum number of regeneration attempts for an additional scattering",
      &ShowerHandler::maxtryMPI_, 10, 0, 100,
      false, false, Interface::limited);
 
   static Parameter<ShowerHandler,unsigned int> interfaceMaxTryDP
     ("MaxTryDP",
      "The maximum number of regeneration attempts for an additional hard scattering",
      &ShowerHandler::maxtryDP_, 10, 0, 100,
      false, false, Interface::limited);
 
   static ParVector<ShowerHandler,long> interfaceDecayInShower
     ("DecayInShower",
      "PDG codes of the particles to be decayed in the shower",
      &ShowerHandler::inputparticlesDecayInShower_, -1, 0l, -10000000l, 10000000l,
      false, false, Interface::limited);
 
   static Reference<ShowerHandler,UEBase> interfaceMPIHandler
     ("MPIHandler",
      "The object that administers all additional scatterings.",
      &ShowerHandler::MPIHandler_, false, false, true, true);
 
   static Reference<ShowerHandler,PDFBase> interfacePDFA
     ("PDFA",
      "The PDF for beam particle A. Overrides the particle's own PDF setting."
      "By default used for both the shower and forced splitting in the remnant",
      &ShowerHandler::PDFA_, false, false, true, true, false);
 
   static Reference<ShowerHandler,PDFBase> interfacePDFB
     ("PDFB",
      "The PDF for beam particle B. Overrides the particle's own PDF setting."
      "By default used for both the shower and forced splitting in the remnant",
      &ShowerHandler::PDFB_, false, false, true, true, false);
 
   static Reference<ShowerHandler,PDFBase> interfacePDFARemnant
     ("PDFARemnant",
      "The PDF for beam particle A used to generate forced splittings of the remnant."
      " This overrides both the particle's own PDF setting and the value set by PDFA if used.",
      &ShowerHandler::PDFARemnant_, false, false, true, true, false);
 
   static Reference<ShowerHandler,PDFBase> interfacePDFBRemnant
     ("PDFBRemnant",
      "The PDF for beam particle B used to generate forced splittings of the remnant."
      " This overrides both the particle's own PDF setting and the value set by PDFB if used.",
      &ShowerHandler::PDFBRemnant_, false, false, true, true, false);
 
   static Switch<ShowerHandler,bool> interfaceIncludeSpaceTime
     ("IncludeSpaceTime",
      "Whether to include the model for the calculation of space-time distances",
      &ShowerHandler::includeSpaceTime_, false, false, false);
   static SwitchOption interfaceIncludeSpaceTimeYes
     (interfaceIncludeSpaceTime,
      "Yes",
      "Include the model",
      true);
   static SwitchOption interfaceIncludeSpaceTimeNo
     (interfaceIncludeSpaceTime,
      "No",
      "Only include the displacement from the particle-s lifetime for decaying particles",
      false);
   
   static Parameter<ShowerHandler,Energy2> interfaceMinimumVirtuality
     ("MinimumVirtuality",
      "The minimum virtuality for the space-time model",
      &ShowerHandler::vMin_, GeV2, 0.1*GeV2, 0.0*GeV2, 1000.0*GeV2,
      false, false, Interface::limited);
 
   static Parameter<ShowerHandler,double> interfaceFactorizationScaleFactor
     ("FactorizationScaleFactor",
      "The factorization scale factor.",
      &ShowerHandler::factorizationScaleFactor_, 1.0, 0.0, 0,
      false, false, Interface::lowerlim);
 
   static Parameter<ShowerHandler,double> interfaceRenormalizationScaleFactor
     ("RenormalizationScaleFactor",
      "The renormalization scale factor.",
      &ShowerHandler::renormalizationScaleFactor_, 1.0, 0.0, 0,
      false, false, Interface::lowerlim);
 
   static Parameter<ShowerHandler,double> interfaceHardScaleFactor
     ("HardScaleFactor",
      "The hard scale factor.",
      &ShowerHandler::hardScaleFactor_, 1.0, 0.0, 0,
      false, false, Interface::lowerlim);
 
   static Parameter<ShowerHandler,unsigned int> interfaceMaxTryDecay
     ("MaxTryDecay",
      "The maximum number of attempts to generate a decay",
      &ShowerHandler::maxtryDecay_, 200, 10, 0,
      false, false, Interface::lowerlim);
 
   static Reference<ShowerHandler,HardScaleProfile> interfaceHardScaleProfile
     ("HardScaleProfile",
      "The hard scale profile to use.",
      &ShowerHandler::hardScaleProfile_, false, false, true, true, false);
 
   static Switch<ShowerHandler,bool> interfaceMaxPtIsMuF
     ("MaxPtIsMuF",
      "",
      &ShowerHandler::maxPtIsMuF_, false, false, false);
   static SwitchOption interfaceMaxPtIsMuFYes
     (interfaceMaxPtIsMuF,
      "Yes",
      "",
      true);
   static SwitchOption interfaceMaxPtIsMuFNo
     (interfaceMaxPtIsMuF,
      "No",
      "",
      false);
 
   static Switch<ShowerHandler,bool> interfaceRestrictPhasespace
     ("RestrictPhasespace",
      "Switch on or off phasespace restrictions",
      &ShowerHandler::restrictPhasespace_, true, false, false);
   static SwitchOption interfaceRestrictPhasespaceYes
     (interfaceRestrictPhasespace,
      "Yes",
      "Perform phasespace restrictions",
      true);
   static SwitchOption interfaceRestrictPhasespaceNo
     (interfaceRestrictPhasespace,
      "No",
      "Do not perform phasespace restrictions",
      false);
 
   static Command<ShowerHandler> interfaceAddVariation
     ("AddVariation",
      "Add a shower variation.",
      &ShowerHandler::doAddVariation, false);
  
   static Switch<ShowerHandler,bool> interfaceDoFSR
     ("DoFSR",
      "Switch on or off final state radiation.",
      &ShowerHandler::doFSR_, true, false, false);
   static SwitchOption interfaceDoFSRYes
     (interfaceDoFSR,
      "Yes",
      "Switch on final state radiation.",
      true);
   static SwitchOption interfaceDoFSRNo
     (interfaceDoFSR,
      "No",
      "Switch off final state radiation.",
      false);
 
   static Switch<ShowerHandler,bool> interfaceDoISR
     ("DoISR",
      "Switch on or off initial state radiation.",
      &ShowerHandler::doISR_, true, false, false);
   static SwitchOption interfaceDoISRYes
     (interfaceDoISR,
      "Yes",
      "Switch on initial state radiation.",
      true);
   static SwitchOption interfaceDoISRNo
     (interfaceDoISR,
      "No",
      "Switch off initial state radiation.",
      false);
  
   static Switch<ShowerHandler,bool> interfaceSplitHardProcess
     ("SplitHardProcess",
      "Whether or not to try and split the hard process into production and decay processes",
      &ShowerHandler::splitHardProcess_, true, false, false);
   static SwitchOption interfaceSplitHardProcessYes
     (interfaceSplitHardProcess,
      "Yes",
      "Split the hard process",
      true);
   static SwitchOption interfaceSplitHardProcessNo
     (interfaceSplitHardProcess,
      "No",
      "Don't split the hard process",
      false);
 }
 
 Energy ShowerHandler::hardScale() const {
   assert(false);
 }
 
 void ShowerHandler::cascade() {
   useMe();
   // Initialise the weights in the event object
   // so that any variations are output regardless of
   // whether showering occurs for the given event
   initializeWeights();
   // get the PDF's from ThePEG (if locally overridden use the local versions)
   tcPDFPtr first  = PDFA_ ? tcPDFPtr(PDFA_) : firstPDF().pdf();
   tcPDFPtr second = PDFB_ ? tcPDFPtr(PDFB_) : secondPDF().pdf();
   resetPDFs(make_pair(first,second));
   // set the PDFs for the remnant
   if( ! rempdfs_.first)
     rempdfs_.first  = PDFARemnant_ ? PDFPtr(PDFARemnant_) : const_ptr_cast<PDFPtr>(first);
   if( ! rempdfs_.second)
     rempdfs_.second = PDFBRemnant_ ? PDFPtr(PDFBRemnant_) : const_ptr_cast<PDFPtr>(second);
   // get the incoming partons
   tPPair  incomingPartons = 
     eventHandler()->currentCollision()->primarySubProcess()->incoming();
   // and the parton bins
   PBIPair incomingBins    = 
     make_pair(lastExtractor()->partonBinInstance(incomingPartons.first),
 	      lastExtractor()->partonBinInstance(incomingPartons.second));
   // and the incoming hadrons
   tPPair incomingHadrons = 
     eventHandler()->currentCollision()->incoming();
   remnantDecayer()->setHadronContent(incomingHadrons);
   // check if incoming hadron == incoming parton
   // and get the incoming hadron if exists or parton otherwise
   incoming_ = make_pair(incomingBins.first  ? 
 			incomingBins.first ->particle() : incomingPartons.first,
 			incomingBins.second ? 
 			incomingBins.second->particle() : incomingPartons.second);
   // check the collision is of the beam particles
   // and if not boost collision to the right frame
   // i.e. the hadron-hadron CMF of the collision
   bool btotal(false);
   LorentzRotation rtotal;
   if(incoming_.first  != incomingHadrons.first ||
      incoming_.second != incomingHadrons.second ) {
     btotal = true;
     boostCollision(false);
   }
   // set the current ShowerHandler
   setCurrentHandler();
   // first shower the hard process
   try {
     SubProPtr sub = eventHandler()->currentCollision()->primarySubProcess();
     incomingPartons = cascade(sub,lastXCombPtr());
   }
   catch(ShowerTriesVeto &veto){
     throw Exception() << "Failed to generate the shower after "
                       << veto.tries
                       << " attempts in ShowerHandler::cascade()"
                       << Exception::eventerror;
   }
   if(showerHardProcessVeto()) throw Veto();
   // if a non-hadron collision return (both incoming non-hadronic)
   if( ( !incomingBins.first||
         !isResolvedHadron(incomingBins.first ->particle()))&&
       ( !incomingBins.second||
         !isResolvedHadron(incomingBins.second->particle()))) {
     // boost back to lab if needed
     if(btotal) boostCollision(true);
     // perform the reweighting for the hard process shower
     combineWeights();
     // unset the current ShowerHandler
     unSetCurrentHandler();
     return;
   }
   // get the remnants for hadronic collision
   pair<tRemPPtr,tRemPPtr> remnants(getRemnants(incomingBins));
   // set the starting scale of the forced splitting to the PDF freezing scale
   remnantDecayer()->initialize(remnants, incoming_, *currentStep(), pdfFreezingScale());
   // do the first forcedSplitting
   try {
     remnantDecayer()->doSplit(incomingPartons, make_pair(rempdfs_.first,rempdfs_.second), true);
   }
   catch (ExtraScatterVeto) {
     throw Exception() << "Remnant extraction failed in "
                       << "ShowerHandler::cascade() from primary interaction" 
                       << Exception::eventerror;   
   }
   // perform the reweighting for the hard process shower
   combineWeights();
   // if no MPI return
   if( !isMPIOn() ) {
     remnantDecayer()->finalize();
     // boost back to lab if needed
     if(btotal) boostCollision(true);
     // unset the current ShowerHandler
     unSetCurrentHandler();
     return;
   }
   // generate the multiple scatters use modified pdf's now:
   setMPIPDFs();
   // additional "hard" processes
   unsigned int tries(0);
   // This is the loop over additional hard scatters (most of the time
   // only one, but who knows...)
   for(unsigned int i=1; i <= getMPIHandler()->additionalHardProcs(); i++){
     //counter for regeneration
 	unsigned int multSecond = 0;
     // generate the additional scatters
     while( multSecond < getMPIHandler()->multiplicity(i) ) {
       // generate the hard scatter 
       tStdXCombPtr lastXC = getMPIHandler()->generate(i);
       SubProPtr sub = lastXC->construct();
       // add to the Step
       newStep()->addSubProcess(sub);
       // increment the counters
       tries++;
       multSecond++;
       if(tries == maxtryDP_)
 	throw Exception() << "Failed to establish the requested number " 
 			  << "of additional hard processes. If this error "
 			  << "occurs often, your selection of additional "
 			  << "scatter is probably unphysical"
 			  << Exception::eventerror;
       // Generate the shower. If not possible veto the event
       try {
 	incomingPartons = cascade(sub,lastXC);
       } 
       catch(ShowerTriesVeto &veto){
 	throw Exception() << "Failed to generate the shower of " 
 			  << "a secondary hard process after "
 			  << veto.tries
 			  << " attempts in Evolver::showerHardProcess()"
 			  << Exception::eventerror;
       }
       try {
 	// do the forcedSplitting
 	remnantDecayer()->doSplit(incomingPartons, make_pair(remmpipdfs_.first,remmpipdfs_.second), false);
       } 
       catch(ExtraScatterVeto){
 	//remove all particles associated with the subprocess
 	newStep()->removeParticle(incomingPartons.first);
 	newStep()->removeParticle(incomingPartons.second);
 	//remove the subprocess from the list
 	newStep()->removeSubProcess(sub);
 	//regenerate the scattering
 	multSecond--;
 	continue;
       }
       // connect with the remnants but don't set Remnant colour,
       // because that causes problems due to the multiple colour lines.
       if ( !remnants.first ->extract(incomingPartons.first , false) ||
 	   !remnants.second->extract(incomingPartons.second, false) )
 	throw Exception() << "Remnant extraction failed in "
 			  << "ShowerHandler::cascade() for additional scatter" 
 			  << Exception::runerror;
     }
     // perform the reweighting for the additional hard scatter shower
     combineWeights();
   }
   // the underlying event processes
   unsigned int ptveto(1), veto(0);
   unsigned int max(getMPIHandler()->multiplicity());
   for(unsigned int i=0; i<max; i++) {
     // check how often this scattering has been regenerated
     if(veto > maxtryMPI_) break;
     //generate PSpoint
     tStdXCombPtr lastXC = getMPIHandler()->generate();
     SubProPtr sub = lastXC->construct();
     //If Algorithm=1 additional scatters of the signal type
     // with pt > ptmin have to be vetoed
     //with probability 1/(m+1), where m is the number of occurances in this event
     if( getMPIHandler()->Algorithm() == 1 ){
       //get the pT
       Energy pt = sub->outgoing().front()->momentum().perp();
       if(pt > getMPIHandler()->PtForVeto() && UseRandom::rnd() < 1./(ptveto+1) ){
         ptveto++;
         i--;
         continue;
       } 
     }
     // add to the SubProcess to the step
     newStep()->addSubProcess(sub);
     // Run the Shower. If not possible veto the scattering
     try {
       incomingPartons = cascade(sub,lastXC);
     } 
     // discard this extra scattering, but try the next one
     catch(ShowerTriesVeto) {
       newStep()->removeSubProcess(sub);
       //regenerate the scattering
       veto++;
       i--;
       continue;      
     }
     try{
       //do the forcedSplitting
       remnantDecayer()->doSplit(incomingPartons, make_pair(remmpipdfs_.first,remmpipdfs_.second), false);
     }
     catch (ExtraScatterVeto) {
       //remove all particles associated with the subprocess
       newStep()->removeParticle(incomingPartons.first);
       newStep()->removeParticle(incomingPartons.second);
       //remove the subprocess from the list
       newStep()->removeSubProcess(sub);
       //regenerate the scattering
       veto++;
       i--;
       continue;      
     }
     //connect with the remnants but don't set Remnant colour,
     //because that causes problems due to the multiple colour lines.
     if ( !remnants.first ->extract(incomingPartons.first , false) ||
 	 !remnants.second->extract(incomingPartons.second, false) )
       throw Exception() << "Remnant extraction failed in "
 			<< "ShowerHandler::cascade() for MPI hard scattering" 
 			<< Exception::runerror;
     //reset veto counter
     veto = 0;
     // perform the reweighting for the MPI process shower
     combineWeights();
   }
   // finalize the remnants
   remnantDecayer()->finalize(getMPIHandler()->colourDisrupt(), 
 		    getMPIHandler()->softMultiplicity());
   // boost back to lab if needed
   if(btotal) boostCollision(true);
   // unset the current ShowerHandler
   unSetCurrentHandler();
   getMPIHandler()->clean();
   resetPDFs(make_pair(first,second));
 }
 
 void ShowerHandler::initializeWeights() {
   if ( !showerVariations().empty() ) {
 
     tEventPtr event = eventHandler()->currentEvent();
 
     for ( map<string,ShowerVariation>::const_iterator var =
 	    showerVariations().begin();
 	  var != showerVariations().end(); ++var ) {
 
       // Check that this is behaving as intended
       //map<string,double>::iterator wi = event->optionalWeights().find(var->first);
       //assert(wi == event->optionalWeights().end() ); 
 
       event->optionalWeights()[var->first] = 1.0;
       currentWeights_[var->first] = 1.0;
     }
   }
   reweight_ = 1.0;
 }
 
 void ShowerHandler::resetWeights() {
   for ( map<string,double>::iterator w = currentWeights_.begin();
 	w != currentWeights_.end(); ++w ) {
     w->second = 1.0;
   }
   reweight_ = 1.0;
 }
 
 void ShowerHandler::combineWeights() {
   tEventPtr event = eventHandler()->currentEvent();
   for ( map<string,double>::const_iterator w = 
 	  currentWeights_.begin(); w != currentWeights_.end(); ++w ) {
     map<string,double>::iterator ew = event->optionalWeights().find(w->first);
     if ( ew != event->optionalWeights().end() )
       ew->second *= w->second;
     else {
       assert(false && "Weight name unknown.");
       //event->optionalWeights()[w->first] = w->second;
     }
   }
   if ( reweight_ != 1.0 ) {
     Ptr<StandardEventHandler>::tptr eh = 
       dynamic_ptr_cast<Ptr<StandardEventHandler>::tptr>(eventHandler());
     if ( !eh ) {
       throw Exception() << "ShowerHandler::combineWeights() : Cross section reweighting "
 			<< "through the shower is currently only available with standard "
 			<< "event generators" << Exception::runerror;
     }
     eh->reweight(reweight_);
   }
 }
 
 string ShowerHandler::doAddVariation(string in) {
   if ( in.empty() )
     return "expecting a name and a variation specification";
   string name = StringUtils::car(in);
   ShowerVariation var;
   string res = var.fromInFile(StringUtils::cdr(in));
   if ( res.empty() ) {
     if ( !var.firstInteraction && !var.secondaryInteractions ) {
       // TODO what about decay showers?
       return "variation does not apply to any shower";
     }
     if ( var.renormalizationScaleFactor == 1.0 && 
 	 var.factorizationScaleFactor == 1.0 ) {
       return "variation does not vary anything";
     }
     /*
     Repository::clog() << "adding a variation with tag '" << name << "' using\nxir = "
 		       << var.renormalizationScaleFactor
 		       << " xif = "
 		       << var.factorizationScaleFactor
 		       << "\napplying to:\n"
 		       << "first interaction = " << var.firstInteraction << " "
 		       << "secondary interactions = " << var.secondaryInteractions << "\n"
 		       << flush;
     */
     showerVariations()[name] = var;
   }
   return res;
 }
 
 tPPair ShowerHandler::cascade(tSubProPtr, XCPtr) {
   assert(false);
 }
 
 ShowerHandler::RemPair 
 ShowerHandler::getRemnants(PBIPair incomingBins) {
   RemPair remnants;
   // first beam particle
   if(incomingBins.first&&!incomingBins.first->remnants().empty()) {
     remnants.first  =
       dynamic_ptr_cast<tRemPPtr>(incomingBins.first->remnants()[0] );
     if(remnants.first) {
       ParticleVector children=remnants.first->children();
       for(unsigned int ix=0;ix<children.size();++ix) {
 	if(children[ix]->dataPtr()==remnants.first->dataPtr()) 
 	  remnants.first = dynamic_ptr_cast<RemPPtr>(children[ix]);
       } 
       //remove existing colour lines from the remnants
       if(remnants.first->colourLine()) 
 	remnants.first->colourLine()->removeColoured(remnants.first);
       if(remnants.first->antiColourLine()) 
 	remnants.first->antiColourLine()->removeAntiColoured(remnants.first);
     }
   }
   // seconnd beam particle
   if(incomingBins.second&&!incomingBins. second->remnants().empty()) {
     remnants.second = 
       dynamic_ptr_cast<tRemPPtr>(incomingBins.second->remnants()[0] );
     if(remnants.second) {
       ParticleVector children=remnants.second->children();
       for(unsigned int ix=0;ix<children.size();++ix) {
 	if(children[ix]->dataPtr()==remnants.second->dataPtr()) 
 	  remnants.second = dynamic_ptr_cast<RemPPtr>(children[ix]);
       } 
       //remove existing colour lines from the remnants
       if(remnants.second->colourLine()) 
 	remnants.second->colourLine()->removeColoured(remnants.second);
       if(remnants.second->antiColourLine()) 
 	remnants.second->antiColourLine()->removeAntiColoured(remnants.second);
     }
   }
   assert(remnants.first || remnants.second);
   return remnants;
 }
 
 namespace {
 
 void addChildren(tPPtr in,set<tPPtr> & particles) {
   particles.insert(in);
   for(unsigned int ix=0;ix<in->children().size();++ix)
     addChildren(in->children()[ix],particles);
 }
 }
 
 void ShowerHandler::boostCollision(bool boost) {
   // calculate boost from lab to rest
   if(!boost) {
     Lorentz5Momentum ptotal=incoming_.first ->momentum()+incoming_.second->momentum();
     boost_ = LorentzRotation(-ptotal.boostVector());
     Axis axis((boost_*incoming_.first ->momentum()).vect().unit());
     if(axis.perp2()>0.) {
       double sinth(sqrt(sqr(axis.x())+sqr(axis.y())));
       boost_.rotate(-acos(axis.z()),Axis(-axis.y()/sinth,axis.x()/sinth,0.));
     }
   }
   // first call performs the boost and second inverse
   // get the particles to be boosted 
   set<tPPtr> particles;
   addChildren(incoming_.first,particles);
   addChildren(incoming_.second,particles);
   // apply the boost
   for(set<tPPtr>::const_iterator cit=particles.begin();
       cit!=particles.end();++cit) {
     (*cit)->transform(boost_);
   }
   if(!boost) boost_.invert();
 }
 
 void ShowerHandler::setMPIPDFs() {
 
   if ( !mpipdfs_.first ) {
     // first have to check for MinBiasPDF
     tcMinBiasPDFPtr first = dynamic_ptr_cast<tcMinBiasPDFPtr>(firstPDF().pdf());
     if(first)
       mpipdfs_.first = new_ptr(MPIPDF(first->originalPDF()));
     else
       mpipdfs_.first = new_ptr(MPIPDF(firstPDF().pdf()));
   }
 
   if ( !mpipdfs_.second ) {
     tcMinBiasPDFPtr second = dynamic_ptr_cast<tcMinBiasPDFPtr>(secondPDF().pdf());
     if(second)
       mpipdfs_.second = new_ptr(MPIPDF(second->originalPDF()));
     else
       mpipdfs_.second = new_ptr(MPIPDF(secondPDF().pdf()));
   }
 
   if( !remmpipdfs_.first ) {
     tcMinBiasPDFPtr first = dynamic_ptr_cast<tcMinBiasPDFPtr>(rempdfs_.first);
     if(first)
       remmpipdfs_.first = new_ptr(MPIPDF(first->originalPDF()));
     else
       remmpipdfs_.first = new_ptr(MPIPDF(rempdfs_.first));
   }
 
   if( !remmpipdfs_.second ) {
     tcMinBiasPDFPtr second = dynamic_ptr_cast<tcMinBiasPDFPtr>(rempdfs_.second);
     if(second)
       remmpipdfs_.second = new_ptr(MPIPDF(second->originalPDF()));
     else
       remmpipdfs_.second = new_ptr(MPIPDF(rempdfs_.second));
   }
   // reset the PDFs stored in the base class
   resetPDFs(mpipdfs_);
 
 }
 
 bool ShowerHandler::isResolvedHadron(tPPtr particle) {
   if(!HadronMatcher::Check(particle->data())) return false;
   for(unsigned int ix=0;ix<particle->children().size();++ix) {
     if(particle->children()[ix]->id()==ParticleID::Remnant) return true;
   }
   return false;
 }
 
 namespace {
 
 bool decayProduct(tSubProPtr subProcess,
 		  tPPtr particle) {
   // must be time-like and not incoming
   if(particle->momentum().m2()<=ZERO||
      particle == subProcess->incoming().first||
      particle == subProcess->incoming().second) return false;
   // if only 1 outgoing and this is it
   if(subProcess->outgoing().size()==1 &&
      subProcess->outgoing()[0]==particle) return true;
   // must not be the s-channel intermediate otherwise
   if(find(subProcess->incoming().first->children().begin(),
 	  subProcess->incoming().first->children().end(),particle)!=
      subProcess->incoming().first->children().end()&&
      find(subProcess->incoming().second->children().begin(),
 	  subProcess->incoming().second->children().end(),particle)!=
      subProcess->incoming().second->children().end()&&
      subProcess->incoming().first ->children().size()==1&&
      subProcess->incoming().second->children().size()==1)
     return false;
   // if non-coloured this is enough
   if(!particle->dataPtr()->coloured()) return true;
   // if coloured must be unstable
   if(particle->dataPtr()->stable()) return false;
   // must not have same particle type as a child
   int id = particle->id();
   for(unsigned int ix=0;ix<particle->children().size();++ix)
     if(particle->children()[ix]->id()==id) return false;
   // otherwise its a decaying particle
   return true;
 }
 
 PPtr findParent(PPtr original, bool & isHard, 
 			       set<PPtr> outgoingset,
 			       tSubProPtr subProcess) {
   PPtr parent=original;
   isHard |=(outgoingset.find(original) != outgoingset.end());
   if(!original->parents().empty()) {
     PPtr orig=original->parents()[0];
-    if(CurrentGenerator::current().currentEventHandler()->currentStep()->
-       find(orig)&&decayProduct(subProcess,orig)) {
+    if(decayProduct(subProcess,orig))
       parent=findParent(orig,isHard,outgoingset,subProcess);
-    }
   }
   return parent;
 }
 }
 
 void ShowerHandler::findDecayProducts(PPtr in,PerturbativeProcessPtr hard,
 				      DecayProcessMap & decay) const {
   ParticleVector children=in->children();
   for(ParticleVector::const_iterator it=children.begin(); it!=children.end();++it) {
     // if decayed or should be decayed in shower make the PerturbaitveProcess
     bool radiates = false;
     if(!(**it).children().empty()) {
       // remove d,u,s,c,b quarks and leptons other than on-shell taus
       if( StandardQCDPartonMatcher::Check((**it).id()) ||
 	  ( LeptonMatcher::Check((**it).id()) && !(abs((**it).id())==ParticleID::tauminus &&
 						   abs((**it).mass()-(**it).dataPtr()->mass())<MeV))) {
 	radiates = true;
       }
       else {
  	bool foundParticle(false),foundGauge(false);
  	for(unsigned int iy=0;iy<(**it).children().size();++iy) {
  	  if((**it).children()[iy]->id()==(**it).id()) {
 	    foundParticle = true;
 	  }
 	  else if((**it).children()[iy]->id()==ParticleID::g ||
 		  (**it).children()[iy]->id()==ParticleID::gamma) {
 	    foundGauge = true;
 	  }
  	}
  	radiates = foundParticle && foundGauge;
       }
     }
     if(radiates) {
       findDecayProducts(*it,hard,decay);
     }
     else if(!(**it).children().empty()||
  	    (decaysInShower((**it).id())&&!(**it).dataPtr()->stable())) {
       createDecayProcess(*it,hard,decay);
     }
     else {
       hard->outgoing().push_back(make_pair(*it,PerturbativeProcessPtr()));
     }
   }
 }
 
 void ShowerHandler::splitHardProcess(tPVector tagged, PerturbativeProcessPtr & hard,
 				     DecayProcessMap & decay) const {
   // temporary storage of the particles
   set<PPtr> hardParticles;
   // tagged particles in a set
   set<PPtr> outgoingset(tagged.begin(),tagged.end());
   bool isHard=false;
   // loop over the tagged particles
   for (tParticleVector::const_iterator taggedP = tagged.begin();
        taggedP != tagged.end(); ++taggedP) {
     // skip remnants
     if (eventHandler()->currentCollision()&&
         eventHandler()->currentCollision()->isRemnant(*taggedP)) continue;
     // find the parent and whether its a decaying particle
     bool isDecayProd=false;
     // check if hard
     isHard |=(outgoingset.find(*taggedP) != outgoingset.end());
     if(splitHardProcess_) {
       tPPtr parent = *taggedP;
       // check if from s channel decaying colourless particle
       while(parent&&!parent->parents().empty()&&!isDecayProd) {
 	parent = parent->parents()[0];
  	if(parent == subProcess_->incoming().first ||
  	   parent == subProcess_->incoming().second ) break;
  	isDecayProd = decayProduct(subProcess_,parent);
       }
-      if (isDecayProd) 
+      if (isDecayProd)
 	hardParticles.insert(findParent(parent,isHard,outgoingset,subProcess_));
     }
     if (!isDecayProd) 
       hardParticles.insert(*taggedP);
   }
   // there must be something to shower
   if(hardParticles.empty()) 
     throw Exception() << "No particles to shower in "
 		      << "ShowerHandler::splitHardProcess()" 
 		      << Exception::eventerror;
   // must be a hard process
   if(!isHard)
     throw Exception() << "Starting on decay not yet implemented in "
 		      << "ShowerHandler::splitHardProcess()" 
 		      << Exception::runerror;
   // create the hard process
   hard = new_ptr(PerturbativeProcess());
   // incoming particles
   hard->incoming().push_back(make_pair(subProcess_->incoming().first ,PerturbativeProcessPtr()));
   hard->incoming().push_back(make_pair(subProcess_->incoming().second,PerturbativeProcessPtr()));
   // outgoing particles
   for(set<PPtr>::const_iterator it=hardParticles.begin();it!=hardParticles.end();++it) {
     // if decayed or should be decayed in shower make the tree
     PPtr orig = *it;
     bool radiates = false;
     if(!orig->children().empty()) {
       // remove d,u,s,c,b quarks and leptons other than on-shell taus
       if( StandardQCDPartonMatcher::Check(orig->id()) ||
 	  ( LeptonMatcher::Check(orig->id()) && 
 	    !(abs(orig->id())==ParticleID::tauminus && abs(orig->mass()-orig->dataPtr()->mass())<MeV))) {
 	radiates = true;
       }
       else {
 	bool foundParticle(false),foundGauge(false);
 	for(unsigned int iy=0;iy<orig->children().size();++iy) {
 	  if(orig->children()[iy]->id()==orig->id()) {
 	    foundParticle = true;
 	  }
 	  else if(orig->children()[iy]->id()==ParticleID::g ||
 		  orig->children()[iy]->id()==ParticleID::gamma) {
 	    foundGauge = true;
 	  }
 	}
 	radiates = foundParticle && foundGauge;
       }
     }
     if(radiates) {
       findDecayProducts(orig,hard,decay);
     }
     else if(!(**it).children().empty()||
  	    (decaysInShower((**it).id())&&!(**it).dataPtr()->stable())) {
       createDecayProcess(*it,hard,decay);
     }
     else {
       hard->outgoing().push_back(make_pair(*it,PerturbativeProcessPtr()));
     }
   }
 }
 
 void ShowerHandler::createDecayProcess(PPtr in,PerturbativeProcessPtr hard, DecayProcessMap & decay) const {
   // there must be an incoming particle
   assert(in);
   // create the new process and connect with the parent
   PerturbativeProcessPtr newDecay=new_ptr(PerturbativeProcess());
   newDecay->incoming().push_back(make_pair(in,hard));
   Energy width=in->dataPtr()->generateWidth(in->mass());
   decay.insert(make_pair(width,newDecay));
   hard->outgoing().push_back(make_pair(in,newDecay));
   // we need to deal with the decay products if decayed
   ParticleVector children = in->children();
   if(!children.empty()) {
     for(ParticleVector::const_iterator it = children.begin();
 	it!= children.end(); ++it) {
       // if decayed or should be decayed in shower make the tree
       in->abandonChild(*it);
       bool radiates = false;
       if(!(**it).children().empty()) {
  	if(StandardQCDPartonMatcher::Check((**it).id())||
  	   (LeptonMatcher::Check((**it).id())&& !(abs((**it).id())==ParticleID::tauminus &&
 						  abs((**it).mass()-(**it).dataPtr()->mass())<MeV))) {
  	  radiates = true;
  	}
  	else {
  	  bool foundParticle(false),foundGauge(false);
  	  for(unsigned int iy=0;iy<(**it).children().size();++iy) {
  	    if((**it).children()[iy]->id()==(**it).id()) {
  	      foundParticle = true;
  	    }
  	    else if((**it).children()[iy]->id()==ParticleID::g ||
  		    (**it).children()[iy]->id()==ParticleID::gamma) {
  	      foundGauge = true;
  	    }
  	  }
  	  radiates = foundParticle && foundGauge;
  	}
   	// finally assume all non-decaying particles are in this class
 	// pr 27/11/15 not sure about this bit
    	// if(!radiates) {
    	//   radiates = !decaysInShower((**it).id());
    	// }
       }
       if(radiates) {
  	findDecayProducts(*it,newDecay,decay);
       }
       else if(!(**it).children().empty()||
 	      (decaysInShower((**it).id())&&!(**it).dataPtr()->stable())) {
 	createDecayProcess(*it,newDecay,decay);
       }
       else {
 	newDecay->outgoing().push_back(make_pair(*it,PerturbativeProcessPtr()));
       }
     }
   }
 }
 
 tDMPtr ShowerHandler::decay(PerturbativeProcessPtr process,
 			    DecayProcessMap & decayMap,
 			    bool radPhotons ) const {
   PPtr parent = process->incoming()[0].first;
   assert(parent);
   if(parent->spinInfo()) parent->spinInfo()->decay(true);
   unsigned int ntry = 0;
   ParticleVector children;
   tDMPtr dm = DMPtr();
   while (true) {
     // exit if fails
     if (++ntry>=maxtryDecay_)
       throw Exception() << "Failed to perform decay in ShowerHandler::decay()"
  			<< " after " << maxtryDecay_
  			<< " attempts for " << parent->PDGName() 
  			<< Exception::eventerror;
     // select decay mode
     dm = parent->data().selectMode(*parent);
 
     if(!dm) 
       throw Exception() << "Failed to select decay  mode in ShowerHandler::decay()"
 			<< "for " << parent->PDGName()
 			<< Exception::eventerror;
     if(!dm->decayer()) 
       throw Exception() << "No Decayer for selected decay mode "
  			<< " in ShowerHandler::decay()"
  			<< Exception::runerror;
     // start of try block
     try {
       children = dm->decayer()->decay(*dm, *parent);
       // if no children have another go
       if(children.empty()) continue;
 
       if(radPhotons){
 	// generate radiation in the decay
 	tDecayIntegratorPtr hwdec=dynamic_ptr_cast<tDecayIntegratorPtr>(dm->decayer());
 	if (hwdec && hwdec->canGeneratePhotons())
 	  children = hwdec->generatePhotons(*parent,children);
       }
 
       // set up parent
       parent->decayMode(dm);
       // add children
       for (unsigned int i = 0, N = children.size(); i < N; ++i ) {
   	children[i]->setLabVertex(parent->labDecayVertex());
 	//parent->addChild(children[i]);
       }
       // if succeeded break out of loop
       break;
     }
     catch(Veto) {
     }
   }
   assert(!children.empty());
   for(ParticleVector::const_iterator it = children.begin();
       it!= children.end(); ++it) {
     if(!(**it).children().empty()||
        (decaysInShower((**it).id())&&!(**it).dataPtr()->stable())) {
       createDecayProcess(*it,process,decayMap);
     }
     else {
       process->outgoing().push_back(make_pair(*it,PerturbativeProcessPtr()));
     }
   }
   return dm;
 }
 
 
 // Note: The tag must be constructed from an ordered particle container.
 tDMPtr ShowerHandler::findDecayMode(const string & tag) const {
   static map<string,DMPtr> cache;
   map<string,DMPtr>::const_iterator pos = cache.find(tag);
 
   if ( pos != cache.end() ) 
     return pos->second;
 
   tDMPtr dm = CurrentGenerator::current().findDecayMode(tag);
   cache[tag] = dm;
   return dm;
 }
 
 
 /**
  *  Operator for the particle ordering
  * @param p1 The first ParticleData object
  * @param p2 The second ParticleData object
  */
 
 bool ShowerHandler::ParticleOrdering::operator() (tcPDPtr p1, tcPDPtr p2) {
   return abs(p1->id()) > abs(p2->id()) ||
     ( abs(p1->id()) == abs(p2->id()) && p1->id() > p2->id() ) ||
     ( p1->id() == p2->id() && p1->fullName() > p2->fullName() );
 }
 
diff --git a/Tests/Makefile.am b/Tests/Makefile.am
--- a/Tests/Makefile.am
+++ b/Tests/Makefile.am
@@ -1,365 +1,365 @@
 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
 HWRUN = $(HERWIG) run
 
 tests : tests-LEP tests-DIS tests-LHC tests-Gamma
 
 if WANT_LIBFASTJET
 tests-LEP : test-LEP-VV test-LEP-VH test-LEP-VBF test-LEP-BB test-LEP-Quarks test-LEP-Leptons \
             test-LEP-default test-LEP-Powheg test-LEP-TopDecay
 else
 tests-LEP : test-LEP-VV test-LEP-VH test-LEP-VBF test-LEP-BB test-LEP-Quarks test-LEP-Leptons
 endif
 
 tests-DIS : test-DIS-Charged test-DIS-Neutral
 
 if WANT_LIBFASTJET
 tests-LHC : 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 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
 else
 tests-LHC : 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
 endif
 
 tests-Gamma : test-Gamma-FF test-Gamma-WW test-Gamma-P
 
 if WANT_LIBFASTJET 
 test-LEP-% : Inputs/LEP-%.in LeptonTest.la LeptonJetTest.la
 	$(HWREAD) $<
 	$(HWRUN) $(notdir $(subst .in,.run,$<)) -N $${NUMEVENTS:-10000}
 else
 test-LEP-% : Inputs/LEP-%.in LeptonTest.la
 	$(HWREAD) $<
 	$(HWRUN) $(notdir $(subst .in,.run,$<)) -N $${NUMEVENTS:-10000}
 endif
 
 Rivet-LHC-Matchbox-% : Rivet/LHC-Matchbox-%.in
 	if [ ! -d Rivet-$(notdir $(subst .in,,$<))  ]; then mkdir Rivet-$(notdir $(subst .in,,$<)); fi;
 	cd Rivet-$(notdir $(subst .in,,$<)); echo `pwd`; \
 	../$(HERWIG) read --repo ../$(REPO) -L ../$(top_builddir)/lib -i ../$(top_builddir)/src ../$<; \
 	../$(HERWIG) run $(notdir $(subst .in,.run,$<)) -N $${NUMEVENTS:-10000}; \
 	mv $(notdir $(subst .in,.yoda,$<)) ..; \
 	cd ..
 
 Rivet-TVT-Matchbox-% : Rivet/TVT-Matchbox-%.in
 	if [ ! -d Rivet-$(notdir $(subst .in,,$<))  ]; then mkdir Rivet-$(notdir $(subst .in,,$<)); fi;
 	cd Rivet-$(notdir $(subst .in,,$<)); echo `pwd`; \
 	../$(HERWIG) read --repo ../$(REPO) -L ../$(top_builddir)/lib -i ../$(top_builddir)/src ../$<; \
 	../$(HERWIG) run $(notdir $(subst .in,.run,$<)) -N $${NUMEVENTS:-10000}; \
 	mv $(notdir $(subst .in,.yoda,$<)) ..; \
 	cd ..
 
 Rivet-TVT-Dipole-% : Rivet/TVT-Dipole-%.in
 	if [ ! -d Rivet-$(notdir $(subst .in,,$<))  ]; then mkdir Rivet-$(notdir $(subst .in,,$<)); fi;
 	cd Rivet-$(notdir $(subst .in,,$<)); echo `pwd`; \
 	../$(HERWIG) read --repo ../$(REPO) -L ../$(top_builddir)/lib -i ../$(top_builddir)/src ../$<; \
 	../$(HERWIG) run $(notdir $(subst .in,.run,$<)) -N $${NUMEVENTS:-10000}; \
 	mv $(notdir $(subst .in,.yoda,$<)) ..; \
 	cd ..
 
 Rivet-LHC-Dipole-% : Rivet/LHC-Dipole-%.in
 	if [ ! -d Rivet-$(notdir $(subst .in,,$<))  ]; then mkdir Rivet-$(notdir $(subst .in,,$<)); fi;
 	cd Rivet-$(notdir $(subst .in,,$<)); echo `pwd`; \
 	../$(HERWIG) read --repo ../$(REPO) -L ../$(top_builddir)/lib -i ../$(top_builddir)/src ../$<; \
 	../$(HERWIG) run $(notdir $(subst .in,.run,$<)) -N $${NUMEVENTS:-10000}; \
 	mv $(notdir $(subst .in,.yoda,$<)) ..; \
 	cd ..
 
 Rivet/LEP-%.in :
 	python/make_input_files.py $(notdir $(subst .in,,$@))
 
 Rivet/DIS-%.in : 
 	python/make_input_files.py $(notdir $(subst .in,,$@))
 
 Rivet/BFactory-%.in:
 	python/make_input_files.py $(notdir $(subst .in,,$@))
 
 Rivet/TVT-%.in:
 	python/make_input_files.py $(notdir $(subst .in,,$@))
 
 Rivet/LHC-%.in:
 	python/make_input_files.py $(notdir $(subst .in,,$@))
 
 Rivet/Star-%.in:
 	python/make_input_files.py $(notdir $(subst .in,,$@))
 
 Rivet/SppS-%.in:
 	python/make_input_files.py $(notdir $(subst .in,,$@))
 
 Rivet/ISR-%.in:
 	python/make_input_files.py $(notdir $(subst .in,,$@))
 
 Rivet-LEP-Matchbox-% : Rivet/LEP-Matchbox-%.in
 	if [ ! -d Rivet-$(notdir $(subst .in,,$<))  ]; then mkdir Rivet-$(notdir $(subst .in,,$<)); fi;
 	cd Rivet-$(notdir $(subst .in,,$<)); echo `pwd`; \
 	../$(HERWIG) read --repo ../$(REPO) -L ../$(top_builddir)/lib -i ../$(top_builddir)/src ../$<; \
 	../$(HERWIG) run $(notdir $(subst .in,.run,$<)) -N $${NUMEVENTS:-10000}; \
 	mv $(notdir $(subst .in,.yoda,$<)) ..; \
 	cd ..
 
 Rivet-LEP-Dipole-% : Rivet/LEP-Dipole-%.in
 	if [ ! -d Rivet-$(notdir $(subst .in,,$<))  ]; then mkdir Rivet-$(notdir $(subst .in,,$<)); fi;
 	cd Rivet-$(notdir $(subst .in,,$<)); echo `pwd`; \
 	../$(HERWIG) read --repo ../$(REPO) -L ../$(top_builddir)/lib -i ../$(top_builddir)/src ../$<; \
 	../$(HERWIG) run $(notdir $(subst .in,.run,$<)) -N $${NUMEVENTS:-10000}; \
 	mv $(notdir $(subst .in,.yoda,$<)) ..; \
 	cd ..
 
 Rivet-BFactory-Matchbox-% : Rivet/BFactory-Matchbox-%.in
 	if [ ! -d Rivet-$(notdir $(subst .in,,$<))  ]; then mkdir Rivet-$(notdir $(subst .in,,$<)); fi;
 	cd Rivet-$(notdir $(subst .in,,$<)); echo `pwd`; \
 	../$(HERWIG) read --repo ../$(REPO) -L ../$(top_builddir)/lib -i ../$(top_builddir)/src ../$<; \
 	../$(HERWIG) run $(notdir $(subst .in,.run,$<)) -N $${NUMEVENTS:-10000}; \
 	mv $(notdir $(subst .in,.yoda,$<)) ..; \
 	cd ..
 
 Rivet-LEP-% : Rivet/LEP-%.in
 	$(HWREAD) $<
 	$(HWRUN) $(notdir $(subst .in,.run,$<)) -N $${NUMEVENTS:-10000}
 
 Rivet-BFactory-% : Rivet/BFactory-%.in
 	$(HWREAD) $<
 	$(HWRUN) $(notdir $(subst .in,.run,$<)) -N $${NUMEVENTS:-10000}
 
 Rivet-TVT-% : Rivet/TVT-%.in
 	$(HWREAD) $<
 	$(HWRUN) $(notdir $(subst .in,.run,$<)) -N $${NUMEVENTS:-10000}
 
 Rivet-DIS-% : Rivet/DIS-%.in
 	$(HWREAD) $<
 	$(HWRUN) $(notdir $(subst .in,.run,$<)) -N $${NUMEVENTS:-10000}
 
 Rivet-LHC-% : Rivet/LHC-%.in
 	$(HWREAD) $<
 	$(HWRUN) $(notdir $(subst .in,.run,$<)) -N $${NUMEVENTS:-10000}
 
 Rivet-Star-% : Rivet/Star-%.in
 	$(HWREAD) $<
 	$(HWRUN) $(notdir $(subst .in,.run,$<)) -N $${NUMEVENTS:-10000}
 
 Rivet-SppS-% : Rivet/SppS-%.in
 	$(HWREAD) $<
 	$(HWRUN) $(notdir $(subst .in,.run,$<)) -N $${NUMEVENTS:-10000}
 
 Rivet-ISR-% : Rivet/ISR-%.in
 	$(HWREAD) $<
 	$(HWRUN) $(notdir $(subst .in,.run,$<)) -N $${NUMEVENTS:-10000}
 
 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-Top-{L,SL}.in) \
 		  $(shell echo Rivet/LHC{,-Dipole,-Dipole-MCatNLO,-Dipole-Matchbox-Powheg,-Matchbox,-Matchbox-Powheg,-Merging}-{7,8,13}-Top-All.in) \
-                  $(shell echo Rivet/Star-{UE,Jets-{1..4}}.in ) \
-	          $(shell echo Rivet/SppS-{200,500,900,546}-UE.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},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-ZZ-lv,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,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,-Powheg}-7-{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}.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: $(shell echo Rivet-LEP{,-Powheg,-Matchbox,-Dipole}-{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}) \
 	   $(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) \
            $(shell echo Rivet-LEP{,-Powheg,-Matchbox-Powheg}-14.in)	
 	rm -rf Rivet-LEP
 	python/merge-LEP --with-gg LEP
 	python/merge-LEP LEP-Powheg
 	python/merge-LEP LEP-Matchbox
 	python/merge-LEP LEP-Dipole
 	rivet-mkhtml -o Rivet-LEP LEP.yoda:Hw LEP-Powheg.yoda:Hw-Powheg LEP-Matchbox.yoda:Hw-Matchbox LEP-Dipole.yoda:Hw-Dipole
 
 Rivet-BFactory: $(shell echo Rivet-BFactory{,-Powheg,-Matchbox,-Dipole}-{10.52,10.52-sym,10.54,10.45}) \
                 $(shell echo Rivet-BFactory-{Upsilon,Upsilon2,Upsilon4,Tau,10.58-res,10.58})
 	rm -rf Rivet-BFactory
 	python/merge-BFactory BFactory
 	python/merge-BFactory BFactory-Powheg
 	python/merge-BFactory BFactory-Matchbox
 	python/merge-BFactory BFactory-Dipole
 	rivet-mkhtml -o Rivet-BFactory BFactory.yoda:Hw BFactory-Powheg.yoda:Hw-Powheg BFactory-Matchbox.yoda:Hw-Matchbox BFactory-Dipole.yoda:Hw-Dipole
 
 Rivet-DIS: $(shell echo Rivet-DIS{,-NoME,-Powheg,-Matchbox,-Dipole}-{e--LowQ2,e+-LowQ2,e+-HighQ2})
 	rm -rf Rivet-DIS
 	python/merge-DIS DIS 
 	python/merge-DIS DIS-Powheg
 	python/merge-DIS DIS-NoME
 	python/merge-DIS DIS-Matchbox
 	python/merge-DIS DIS-Dipole
 	rivet-mkhtml -o Rivet-DIS DIS.yoda:Hw DIS-Powheg.yoda:Hw-Powheg DIS-NoME.yoda:Hw-NoME DIS-Matchbox.yoda:Hw-Matchbox DIS-Dipole.yoda:Hw-Dipole
 
 Rivet-TVT-WZ:  $(shell echo Rivet-TVT{,-Powheg,-Matchbox,-Dipole}-{Run-I-Z,Run-I-W,Run-I-WZ,Run-II-Z-{e,{,LowMass-,HighMass-}mu},Run-II-W})
 	rm -rf Rivet-TVT-WZ
 	python/merge-TVT-EW TVT-Run-II-W.yoda TVT-Run-II-Z-{e,{,LowMass-,HighMass-}mu}.yoda\
                             TVT-Run-I-{W,Z,WZ}.yoda -o TVT-WZ.yoda
 	python/merge-TVT-EW TVT-Powheg-Run-II-W.yoda   TVT-Powheg-Run-II-Z-{e,{,LowMass-,HighMass-}mu}.yoda\
                             TVT-Powheg-Run-I-{W,Z,WZ}.yoda -o TVT-Powheg-WZ.yoda
 	python/merge-TVT-EW TVT-Matchbox-Run-II-W.yoda   TVT-Matchbox-Run-II-Z-{e,{,LowMass-,HighMass-}mu}.yoda\
                             TVT-Matchbox-Run-I-{W,Z,WZ}.yoda -o TVT-Matchbox-WZ.yoda
 	python/merge-TVT-EW TVT-Dipole-Run-II-W.yoda   TVT-Dipole-Run-II-Z-{e,{,LowMass-,HighMass-}mu}.yoda\
                             TVT-Dipole-Run-I-{W,Z,WZ}.yoda -o TVT-Dipole-WZ.yoda
 	rivet-mkhtml -o Rivet-TVT-WZ TVT-WZ.yoda:Hw TVT-Powheg-WZ.yoda:Hw-Powheg TVT-Matchbox-WZ.yoda:Hw-Matchbox TVT-Dipole-WZ.yoda:Hw-Dipole
 
 Rivet-TVT-Photon: $(shell echo Rivet-TVT-Run-II-{DiPhoton-GammaGamma,DiPhoton-GammaJet,PromptPhoton}) \
                   $(shell echo Rivet-TVT-Powheg-Run-II-{DiPhoton-GammaGamma,DiPhoton-GammaJet})
 	rm -rf Rivet-TVT-Photon
 	python/merge-TVT-Photon TVT -o TVT-Photon.yoda
 	python/merge-TVT-Photon TVT-Powheg -o TVT-Powheg-Photon.yoda
 	rivet-mkhtml -o Rivet-TVT-Photon TVT-Photon.yoda:Hw TVT-Powheg-Photon.yoda:Hw-Powheg
 
 Rivet-TVT-Jets:  $(shell echo Rivet-TVT-{Run-II-Jets-{0..11},Run-I-Jets-{1..8}} ) \
 	         $(shell echo Rivet-TVT-{630-Jets-{1..3},300-Jets-1,900-Jets-1} ) \
                  $(shell echo Rivet-TVT-{Run-I,Run-II,300,630,900}-UE)
 	rm -rf Rivet-TVT-Jets
 	python/merge-TVT-Jets TVT
 	rivet-mkhtml -o Rivet-TVT-Jets TVT-Jets.yoda:Hw
 
 #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-LHC-Jets: $(shell echo Rivet-LHC-7-DiJets-{1..7}-{A,B,C} ) \
 	        $(shell echo Rivet-LHC-{7,8,13}-Jets-{0..10} ) \
 	        $(shell echo Rivet-LHC-{900,2360,2760,7,8,13}-UE ) \
 	        $(shell echo Rivet-LHC-{900,7,13}-UE-Long ) \
 		$(shell echo Rivet-LHC-7-Charm-{1..5}) \
 		$(shell echo Rivet-LHC-7-Bottom-{0..8}) \
 		$(shell echo Rivet-LHC-7-Top-{L,SL})\
 		$(shell echo Rivet-LHC-{7,8,13}-Top-All)
 	rm -rf Rivet-LHC-Jets
 	python/merge-LHC-Jets LHC
 	rivet-mkhtml -o Rivet-LHC-Jets LHC-Jets.yoda:Hw
 
 Rivet-Star: $(shell echo Rivet-Star-{UE,Jets-{1..4}} ) 
 	rm -rf Rivet-Star
 	python/merge-Star Star
 	rivet-mkhtml -o Rivet-Star Star.yoda
 
 Rivet-SppS: $(shell echo Rivet-ISR-{30,44,53,62}-UE ) \
 	    $(shell echo Rivet-SppS-{53,63,200,500,900,546}-UE )
 	rm -rf Rivet-SppS
 	python/merge-SppS SppS
 	rivet-mkhtml -o Rivet-SppS SppS.yoda
 
 Rivet-LHC-EW: $(shell echo Rivet-LHC{,-Matchbox,-Powheg,-Dipole}-{13-Z-{e,mu},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-ZZ-lv,W-Z-{e,mu}}) \
 	      $(shell echo Rivet-LHC{,-Matchbox,-Dipole}-{7-W-Jet-{1..3}-e,7-Z-Jet-{0..3}-e,7-Z-Jet-0-mu}) \
 	      $(shell echo Rivet-LHC{-Matchbox,-Dipole}-{Z-b,Z-bb,W-b,8-Z-jj}) \
               $(shell echo Rivet-LHC-7-{W,Z}Gamma-{e,mu}) \
 	rm -rf Rivet-LHC-EW;
 	python/merge-LHC-EW LHC-{13-Z-{e,mu},8-Z-Mass{1..4}-{e,mu},W-{e,mu},Z-{e,mu,mu-Short},Z-LowMass-{e,mu},Z-MedMass-e,W-Z-{e,mu},WW-{emu,ll},WZ,ZZ-{ll,lv},8-ZZ-lv}.yoda LHC-7-{W,Z}-Jet-{1,2,3}-e.yoda LHC-7-{W,Z}Gamma-{e,mu}.yoda -o LHC-EW.yoda;
 	python/merge-LHC-EW LHC-Matchbox-{13-Z-{e,mu},8-Z-Mass{1..4}-{e,mu},W-{e,mu},Z-{e,mu,mu-Short},Z-LowMass-{e,mu},Z-MedMass-e,W-Z-{e,mu},WW-{emu,ll},WZ,ZZ-{ll,lv},8-ZZ-lv}.yoda LHC-Matchbox-7-{W,Z}-Jet-{1,2,3}-e.yoda -o LHC-Matchbox-EW.yoda;
 	python/merge-LHC-EW LHC-Dipole-{13-Z-{e,mu},8-Z-Mass{1..4}-{e,mu},W-{e,mu},Z-{e,mu,mu-Short},Z-LowMass-{e,mu},Z-MedMass-e,W-Z-{e,mu},WW-{emu,ll},WZ,ZZ-{ll,lv},8-ZZ-lv}.yoda LHC-Dipole-7-{W,Z}-Jet-{1,2,3}-e.yoda -o LHC-Dipole-EW.yoda;
 	python/merge-LHC-EW LHC-Powheg-{W-{e,mu},Z-{e,mu},Z-LowMass-{e,mu},Z-MedMass-e,W-Z-{e,mu},WW-{emu,ll},WZ,ZZ-{ll,lv},8-ZZ-lv}.yoda -o LHC-Powheg-EW.yoda;
 	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
 Rivet-LHC-Photon: $(shell echo Rivet-LHC-{7,8}-PromptPhoton-{1..4}) Rivet-LHC-GammaGamma-7 \
 	          $(shell echo Rivet-LHC{,-Powheg}-7-{DiPhoton-GammaGamma,DiPhoton-GammaJet})
 	rm -rf Rivet-LHC-Photon
 	python/merge-LHC-Photon LHC -o LHC-Photon.yoda
 	python/merge-LHC-Photon LHC-Powheg -o LHC-Powheg-Photon.yoda
 	rivet-mkhtml -o Rivet-LHC-Photon LHC-Photon.yoda:Hw LHC-Powheg-Photon.yoda:Hw-Powheg
 
 Rivet-LHC-Higgs:  $(shell echo Rivet-LHC{,-Powheg}-{ggH,VBF,WH,ZH})\
                   $(shell echo Rivet-LHC{,-Powheg}-8-{ggH,VBF,WH,ZH}{,-GammaGamma}) Rivet-LHC-ggHJet
 	rm -rf Rivet-LHC-Higgs
 	rivet-mkhtml -o Rivet-LHC-Higgs LHC-Powheg-ggH.yoda:gg-Powheg LHC-ggH.yoda:gg LHC-ggHJet.yoda:HJet \
                         LHC-Powheg-VBF.yoda:VBF-Powheg LHC-VBF.yoda:VBF LHC-WH.yoda:WH LHC-ZH.yoda:ZH \
                         LHC-Powheg-WH.yoda:WH-Powheg LHC-Powheg-ZH.yoda:ZH-Powheg
 
 tests-Rivet : Rivet-LEP Rivet-BFactory Rivet-DIS Rivet-TVT-WZ Rivet-TVT-Photon Rivet-TVT-Jets Rivet-LHC-Jets Rivet-Star Rivet-SppS Rivet-LHC-EW Rivet-LHC-Photon Rivet-LHC-Higgs
 
 
 test-Gamma-% : Inputs/Gamma-%.in GammaTest.la
 	$(HWREAD) $<
 	$(HWRUN) $(notdir $(subst .in,.run,$<)) -N $${NUMEVENTS:-10000}
 
 test-DIS-% : Inputs/DIS-%.in DISTest.la
 	$(HWREAD) $<
 	$(HWRUN) $(notdir $(subst .in,.run,$<)) -N $${NUMEVENTS:-10000}
 
 if WANT_LIBFASTJET 
 test-LHC-% : Inputs/LHC-%.in HadronTest.la GammaTest.la HadronJetTest.la
 	$(HWREAD) $<
 	$(HWRUN) $(notdir $(subst .in,.run,$<)) -N $${NUMEVENTS:-10000}
 else
 test-LHC-% : Inputs/LHC-%.in HadronTest.la GammaTest.la
 	$(HWREAD) $<
 	$(HWRUN) $(notdir $(subst .in,.run,$<)) -N $${NUMEVENTS:-10000}
 endif
 
 clean-local:
 	rm -f *.out *.log *.tex *.top *.run *.dump *.mult *.Bmult *.yoda
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,1879 +1,1888 @@
 #! /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\n"
   res+="set /Herwig/Cuts/JetPairMass:FirstRegion /Herwig/Cuts/FirstJet\n"
   res+="set /Herwig/Cuts/JetPairMass:SecondRegion /Herwig/Cuts/SecondJet\n"
   res+="insert /Herwig/Cuts/JetCuts:JetPairRegions 0  /Herwig/Cuts/JetPairMass\n"
   res+="set /Herwig/Cuts/JetPairMass:MassMin "+minmass+".*GeV\n"
   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
 
 
 
 (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]
 
 # settings for four flavour scheme
 fourFlavour="read Matchbox/FourFlavourScheme.in\ndo /Herwig/MatrixElements/Matchbox/Factory:StartParticleGroup bjet\ninsert /Herwig/MatrixElements/Matchbox/Factory:ParticleGroup 0 /Herwig/Particles/b\ninsert /Herwig/MatrixElements/Matchbox/Factory:ParticleGroup 0 /Herwig/Particles/bbar\ninsert /Herwig/MatrixElements/Matchbox/Factory:ParticleGroup 0 /Herwig/Particles/c\ninsert /Herwig/MatrixElements/Matchbox/Factory:ParticleGroup 0 /Herwig/Particles/cbar\ninsert /Herwig/MatrixElements/Matchbox/Factory:ParticleGroup 0 /Herwig/Particles/s\ninsert /Herwig/MatrixElements/Matchbox/Factory:ParticleGroup 0 /Herwig/Particles/sbar\ninsert /Herwig/MatrixElements/Matchbox/Factory:ParticleGroup 0 /Herwig/Particles/d\ninsert /Herwig/MatrixElements/Matchbox/Factory:ParticleGroup 0 /Herwig/Particles/dbar\ninsert /Herwig/MatrixElements/Matchbox/Factory:ParticleGroup 0 /Herwig/Particles/u\ninsert /Herwig/MatrixElements/Matchbox/Factory:ParticleGroup 0 /Herwig/Particles/ubar\ninsert /Herwig/MatrixElements/Matchbox/Factory:ParticleGroup 0 /Herwig/Particles/g\ndo /Herwig/MatrixElements/Matchbox/Factory:EndParticleGroup\nset /Herwig/Cuts/MatchboxJetMatcher:Group bjet\n"
 
 collider=""
 # select the template to load
 # collider
 parameters = {}
 if(name.find("BFactory")==0) :
     collider="BFactory"
 elif(name.find("LEP")==0) :
     collider="LEP"
 elif(name.find("DIS")==0) :
     collider="DIS"
 elif(name.find("TVT")==0) :
     collider="TVT"
 elif(name.find("LHC-GammaGamma")==0) :
     collider="LHC-GammaGamma"
 elif(name.find("LHC")==0) :
     collider="LHC"
 elif(name.find("ISR")==0) :
     collider="ISR"
 elif(name.find("SppS")==0) :
     collider="SppS"
 elif(name.find("Star")==0) :
     collider="Star"
 
 thefactory="Factory"
 
 istart = 1
 print name
 
 parameters["shower"]=""
 parameters["bscheme"]=""
 
 # Dipole shower with Matchbox Powheg
 if(name.find("Dipole-Matchbox-Powheg")>0) :
     istart = 4
     simulation="Matchbox"
     parameters["shower"]  = "read Matchbox/Powheg-DipoleShower.in\n"
 
     # Dipole shower with internal Powheg - Todo: Finish modifying template files.
     '''
     elif(name.find("Dipole-Powheg")>0) :
     istart = 3
     simulation="Powheg"
     parameters["shower"]  = "set /Herwig/EventHandlers/EventHandler:CascadeHandler /Herwig/DipoleShower/DipoleShowerHandler\nread Matchbox/MCatNLO-Dipole-HardAlphaSTune.in\n"
     '''
 
 # Dipole shower with MCatNLO
 elif(name.find("Dipole-MCatNLO")>0) :
     istart = 3
     simulation="Matchbox"
     parameters["shower"]  = "read Matchbox/MCatNLO-DipoleShower.in\n" 
 
 # Dipole shower with Matchbox LO
 elif(name.find("Dipole-Matchbox-LO")>0) :
     istart = 4
     simulation="Matchbox"
     parameters["shower"]  = "read Matchbox/LO-DipoleShower.in\n" 
 
 # Dipole shower with internal LO
 elif(name.find("Dipole")>0) :
     istart = 2
     simulation=""
     parameters["shower"]  = "set /Herwig/EventHandlers/EventHandler:CascadeHandler /Herwig/DipoleShower/DipoleShowerHandler\nread Matchbox/MCatNLO-Dipole-HardAlphaSTune.in\n"
     
 # AO shower with Matchbox Powheg
 elif(name.find("Matchbox-Powheg")>0) :
     istart = 3
     simulation="Matchbox"
     parameters["shower"] = "read Matchbox/Powheg-DefaultShower.in\n"
 
 # AO shower with MCatNLO
 elif(name.find("Matchbox")>0) :
     istart = 2
     simulation="Matchbox"
     parameters["shower"] = "read Matchbox/MCatNLO-DefaultShower.in\n"
 
 # AO shower with inernal Powheg    
 elif(name.find("Powheg")>0) :
     istart = 2
     simulation="Powheg"
 
 # Dipole shower with merging    
 elif(name.find("Merging")>0) :
     istart = 2
     simulation="Merging"
     thefactory="MergingFactory"
     
 # Flavour settings for Matchbox    
 if(simulation=="Matchbox") :
     parameters["bscheme"] = "read Matchbox/FiveFlavourScheme.in\n"
     
     if(parameters["shower"].find("Dipole")>=0) :
         parameters["bscheme"] += "read Matchbox/FiveFlavourNoBMassScheme.in\n"
         
     if(collider.find("DIS")<0 and collider.find("LEP")<0 ) :
         parameters["nlo"] = "read Matchbox/MadGraph-OpenLoops.in\n"
 
 # Flavour settings for dipole shower with internal ME
 if ( simulation == "" and parameters["shower"].find("Dipole")>=0 ) :
     parameters["bscheme"] = "read snippets/DipoleShowerFiveFlavours.in"
     
 
 if(collider=="") :
     logging.error("Can\'t find collider")
     sys.exit(1)
 
 # find the template
 if(simulation=="") :
     if(collider.find("LHC-GammaGamma") >=0) :
         istart += 1
         templateName="Hadron-Gamma.in"
     elif(collider.find("TVT")>=0 or collider.find("LHC") >=0 or
        collider.find("ISR")>=0 or collider.find("SppS")>=0 or
        collider.find("Star")>=0) :
         templateName="Hadron.in"
     elif(collider.find("BFactory")<0) :
         templateName= "%s.in" % (collider)
     else :
         templateName= "LEP.in"
 else :
     if(collider.find("TVT")>=0 or collider.find("LHC") >=0 or
        collider.find("ISR")>=0 or collider.find("SppS")>=0 or
        collider.find("Star")>=0) :
         templateName= "Hadron-%s.in" % (simulation) 
     elif(collider.find("BFactory")<0) :
         templateName= "%s-%s.in" % (collider,simulation) 
     else :
         templateName= "LEP-%s.in" % (simulation) 
 with open(os.path.join("Rivet/Templates",templateName), 'r') as f:
     templateText = f.read()
 template = Template( templateText )
 # work out the name of the parameter file
 nameSplit=name.split("-")
 parameterName=nameSplit[istart]
 for i in range(istart+1,len(nameSplit)) :
     parameterName += "-%s" % nameSplit[i] 
 
 # work out the process and parameters
 process=""
 # Bfactory
 if(collider=="BFactory") :
     if(simulation=="") :
         if(parameterName=="10.58-res") :
             process += "\ncreate Herwig::MEee2VectorMeson /Herwig/MatrixElements/MEUpsilon HwMELepton.so\nset /Herwig/MatrixElements/MEUpsilon:VectorMeson /Herwig/Particles/Upsilon(4S)\nset /Herwig/MatrixElements/MEUpsilon:Coupling 0.0004151809\ninsert /Herwig/MatrixElements/SubProcess:MatrixElements 0 /Herwig/MatrixElements/MEUpsilon"
         elif(parameterName=="10.58") :
             process += "\ncreate Herwig::MEee2VectorMeson /Herwig/MatrixElements/MEUpsilon HwMELepton.so\nset /Herwig/MatrixElements/MEUpsilon:VectorMeson /Herwig/Particles/Upsilon(4S)\nset /Herwig/MatrixElements/MEUpsilon:Coupling 0.0004151809\ninsert /Herwig/MatrixElements/SubProcess:MatrixElements 0 /Herwig/MatrixElements/MEUpsilon\n"
             process += "set /Herwig/MatrixElements/MEee2gZ2qq:MaximumFlavour 4\n"
         else :
             process+="insert  /Herwig/MatrixElements/SubProcess:MatrixElements 0 /Herwig/MatrixElements/MEee2gZ2qq\n"
             process+= "set /Herwig/MatrixElements/MEee2gZ2qq:MaximumFlavour 4\n"
     elif(simulation=="Powheg") :
         process = "set /Herwig/MatrixElements/PowhegMEee2gZ2qq:MaximumFlavour 4\n"
     elif(simulation=="Matchbox" ) :
         process =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(parameterName.find("NoME")>=0) :
             process = "set /Herwig/Shower/ShowerHandler:HardEmission None"
             parameterName=parameterName.replace("NoME-","")
         else :
             process = ""
     elif(simulation=="Powheg") :
         process = ""
     elif(simulation=="Matchbox" ) :
       if(parameterName.find("e-")>=0) :
             process=addProcess(thefactory,"e- p -> e- j","0","2","",0,0)
       else :
             process=addProcess(thefactory,"e+ p -> e+ j","0","2","",0,0)
     elif(simulation=="Merging" ) :
         if(parameterName.find("e-")>=0) :
             process=addProcess(thefactory,"e- p -> e- j","0","2","",2,2)
         else :
             process=addProcess(thefactory,"e+ p -> e+ j","0","2","",2,2)
 
 # LEP
 elif(collider=="LEP") :
     if(simulation=="") :
         if(parameterName.find("gg")>=0) :
             process ="create Herwig::MEee2Higgs2SM /Herwig/MatrixElements/MEee2Higgs2SM\n"
             process+="insert /Herwig/MatrixElements/SubProcess:MatrixElements[0] /Herwig/MatrixElements/MEee2Higgs2SM\n"
             process+="set /Herwig/MatrixElements/MEee2Higgs2SM:Allowed Gluon\n"
 
         else :
             process="insert  /Herwig/MatrixElements/SubProcess:MatrixElements 0 /Herwig/MatrixElements/MEee2gZ2qq\n"
             if(parameterName=="10") :
                 process+="set /Herwig/MatrixElements/MEee2gZ2qq:MaximumFlavour 4"
     elif(simulation=="Powheg") :
         process=""
         if(parameterName=="10") :
             process="set /Herwig/MatrixElements/PowhegMEee2gZ2qq:MaximumFlavour 4"
     elif(simulation=="Matchbox" ) :
         if(parameterName=="10") :
             process =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=addProcess(thefactory,"e- e+ -> j j","0","2","",0,0)
 
     elif(simulation=="Merging" ) :
         if(parameterName=="10") :
           process=addProcess(thefactory,"e- e+ -> j j","0","2","",2,2)
           process+="read Matchbox/FourFlavourScheme.in"
         else :
           process=addProcess(thefactory,"e- e+ -> j j","0","2","",2,2)
 # TVT
 elif(collider=="TVT") :
     process="set /Herwig/Generators/EventGenerator:EventHandler:BeamB /Herwig/Particles/pbar-\n"
     if(parameterName.find("Run-II")>=0) :
         process+="set /Herwig/Generators/EventGenerator:EventHandler:LuminosityFunction:Energy 1960.0\n"
     elif(parameterName.find("Run-I")>=0) :
         process+="set /Herwig/Generators/EventGenerator:EventHandler:LuminosityFunction:Energy 1800.0\n"
     elif(parameterName.find("900")>=0) :
         process+="set /Herwig/Generators/EventGenerator:EventHandler:LuminosityFunction:Energy 900.0\n"
     elif(parameterName.find("630")>=0) :
         process+="set /Herwig/Generators/EventGenerator:EventHandler:LuminosityFunction:Energy 630.0\n"
     elif(parameterName.find("300")>=0) :
         process+="set /Herwig/Generators/EventGenerator:EventHandler:LuminosityFunction:Energy 300.0\n"
 
     if(simulation=="") :
         if(parameterName.find("PromptPhoton")>=0) :
             process+="insert SubProcess:MatrixElements[0] MEGammaJet\n"
             process+="set /Herwig/Cuts/PhotonKtCut:MinKT 15.\n"
         elif(parameterName.find("DiPhoton-GammaGamma")>=0) :
             process+="insert SubProcess:MatrixElements[0] MEGammaGamma\n"
             process+="set /Herwig/Cuts/PhotonKtCut:MinKT 5.\n"
             parameterName=parameterName.replace("-GammaGamma","")
         elif(parameterName.find("DiPhoton-GammaJet")>=0) :
             process+="insert SubProcess:MatrixElements[0] MEGammaJet\n"
             process+="set /Herwig/Cuts/PhotonKtCut:MinKT 5.\n"
             parameterName=parameterName.replace("-GammaJet","")
         elif(parameterName.find("UE")>=0) :
-            process += "insert SubProcess:MatrixElements[0] MEMinBias\n"
-            process += "set /Herwig/UnderlyingEvent/MPIHandler:IdenticalToUE 0\n"
-            process += "set /Herwig/Generators/EventGenerator:EventHandler:Cuts /Herwig/Cuts/MinBiasCuts\n"
-            process += "create Herwig::MPIXSecReweighter /Herwig/Generators/MPIXSecReweighter\n"
-            process += "insert /Herwig/Generators/EventGenerator:EventHandler:PostSubProcessHandlers 0 /Herwig/Generators/MPIXSecReweighter\n"
+            if (parameters["shower"].find("Dipole")>=0):
+                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(parameterName.find("Jets")>=0) :
             process+="insert SubProcess:MatrixElements[0] MEQCD2to2\n"
             process+="set /Herwig/UnderlyingEvent/MPIHandler:IdenticalToUE 0\n"
             if(parameterName.find("Run-II-Jets-10")>=0) :
                 process+="set /Herwig/Cuts/JetKtCut:MinKT 30.\n"
                 process+="set /Herwig/Cuts/Cuts:MHatMin 500.*GeV\n"
             elif(parameterName.find("Run-II-Jets-11")>=0) :
                 process+="set /Herwig/Cuts/JetKtCut:MinKT 30.\n"
                 process+="set /Herwig/Cuts/Cuts:MHatMin 900.*GeV\n"
             elif(parameterName.find("Run-I-Jets-1")>=0) :
                 process+="set /Herwig/Cuts/JetKtCut:MinKT 20.\n"
             elif(parameterName.find("Run-I-Jets-2")>=0) :
                 process+="set /Herwig/Cuts/JetKtCut:MinKT 40.\n"
             elif(parameterName.find("Run-I-Jets-3")>=0) :
                 process+="set /Herwig/Cuts/JetKtCut:MinKT 65.\n"
             elif(parameterName.find("Run-I-Jets-4")>=0) :
                 process+="set /Herwig/Cuts/JetKtCut:MinKT 90.\n"
             elif(parameterName.find("Run-I-Jets-5")>=0) :
                 process+="set /Herwig/Cuts/JetKtCut:MinKT 160.\n"
             elif(parameterName.find("Run-I-Jets-6")>=0) :
                 process+="set /Herwig/Cuts/JetKtCut:MinKT 30.\n"
                 process+="set /Herwig/Cuts/Cuts:MHatMin 100.*GeV\n"
             elif(parameterName.find("Run-I-Jets-7")>=0) :
                 process+="set /Herwig/Cuts/JetKtCut:MinKT 30.\n"
                 process+="set /Herwig/Cuts/Cuts:MHatMin 400.*GeV\n"
             elif(parameterName.find("Run-I-Jets-8")>=0) :
                 process+="set /Herwig/Cuts/JetKtCut:MinKT 30.\n"
                 process+="set /Herwig/Cuts/Cuts:MHatMin 700.*GeV\n"
             elif(parameterName.find("Run-II-Jets-0")>=0) :
                 process+="set /Herwig/Cuts/JetKtCut:MinKT 15.\n"
             elif(parameterName.find("Run-II-Jets-1")>=0) :
                 process+="set /Herwig/Cuts/JetKtCut:MinKT 25.\n"
             elif(parameterName.find("Run-II-Jets-2")>=0) :
                 process+="set /Herwig/Cuts/JetKtCut:MinKT 40.\n"
             elif(parameterName.find("Run-II-Jets-3")>=0) :
                 process+="set /Herwig/Cuts/JetKtCut:MinKT 60.\n"
             elif(parameterName.find("Run-II-Jets-4")>=0) :
                 process+="set /Herwig/Cuts/JetKtCut:MinKT 85.\n"
             elif(parameterName.find("Run-II-Jets-5")>=0) :
                 process+="set /Herwig/Cuts/JetKtCut:MinKT 110.\n"
             elif(parameterName.find("Run-II-Jets-6")>=0) :
                 process+="set /Herwig/Cuts/JetKtCut:MinKT 160.\n"
             elif(parameterName.find("Run-II-Jets-7")>=0) :
                 process+="set /Herwig/Cuts/JetKtCut:MinKT 250.\n"
             elif(parameterName.find("Run-II-Jets-8")>=0) :
                 process+="set /Herwig/Cuts/JetKtCut:MinKT 30.\n"
                 process+="set /Herwig/Cuts/Cuts:MHatMin 100.*GeV\n"
             elif(parameterName.find("Run-II-Jets-9")>=0) :
                 process+="set /Herwig/Cuts/JetKtCut:MinKT 30.\n"
                 process+="set /Herwig/Cuts/Cuts:MHatMin 300.*GeV\n"
             elif(parameterName.find("900-Jets-1")>=0) :
                 process+="set /Herwig/Cuts/JetKtCut:MinKT 10.\n"
             elif(parameterName.find("300-Jets-1")>=0) :
                 process+="set /Herwig/Cuts/JetKtCut:MinKT 6.\n"
             elif(parameterName.find("630-Jets-1")>=0) :
                 process+="set /Herwig/Cuts/JetKtCut:MinKT 20.\n"
             elif(parameterName.find("630-Jets-2")>=0) :
                 process+="set /Herwig/Cuts/JetKtCut:MinKT 40.\n"
             elif(parameterName.find("630-Jets-3")>=0) :
                 process+="set /Herwig/Cuts/JetKtCut:MinKT 75.\n"
             elif(parameterName.find("900-Jets-1")>=0) :
                 process+="set /Herwig/Cuts/JetKtCut:MinKT 10.\n"
         elif(parameterName.find("Run-I-WZ")>=0) :
             process+="insert SubProcess:MatrixElements[0] MEqq2W2ff\nset MEqq2W2ff:Process Electron\ninsert SubProcess:MatrixElements[0] MEqq2gZ2ff\nset MEqq2gZ2ff:Process Electron\n"
         elif(parameterName.find("Run-I-W")>=0 or parameterName.find("Run-II-W")>=0) :
             process+="insert SubProcess:MatrixElements[0] MEqq2W2ff\nset MEqq2W2ff:Process Electron\n"
         elif(parameterName.find("Run-I-Z")>=0 or parameterName.find("Run-II-Z-e")>=0) :
             process +="insert SubProcess:MatrixElements[0] MEqq2gZ2ff\nset MEqq2gZ2ff:Process Electron\n"
         elif(parameterName.find("Run-II-Z-LowMass-mu")>=0) :
             process +="insert SubProcess:MatrixElements[0] MEqq2gZ2ff\nset MEqq2gZ2ff:Process Muon\n"
             process+=addLeptonPairCut("25","70")
         elif(parameterName.find("Run-II-Z-HighMass-mu")>=0) :
             process +="insert SubProcess:MatrixElements[0] MEqq2gZ2ff\nset MEqq2gZ2ff:Process Muon\n"
             process+=addLeptonPairCut("150","600")
         elif(parameterName.find("Run-II-Z-mu")>=0) :
             process +="insert SubProcess:MatrixElements[0] MEqq2gZ2ff\nset MEqq2gZ2ff:Process Muon\n"
     elif(simulation=="Powheg") :
         if(parameterName.find("Run-I-WZ")>=0) :
             process+="insert SubProcess:MatrixElements[0] PowhegMEqq2W2ff\nset PowhegMEqq2W2ff:Process Electron\ninsert SubProcess:MatrixElements[0] PowhegMEqq2gZ2ff\nset PowhegMEqq2gZ2ff:Process Electron\n"
         elif(parameterName.find("Run-I-W")>=0 or parameterName.find("Run-II-W")>=0) :
             process+="insert SubProcess:MatrixElements[0] PowhegMEqq2W2ff\nset PowhegMEqq2W2ff:Process Electron\n"
         elif(parameterName.find("Run-I-Z")>=0 or parameterName.find("Run-II-Z-e")>=0) :
             process+="insert SubProcess:MatrixElements[0] PowhegMEqq2gZ2ff\nset PowhegMEqq2gZ2ff:Process Electron\n"
         elif(parameterName.find("Run-II-Z-LowMass-mu")>=0) :
             process+="insert SubProcess:MatrixElements[0] PowhegMEqq2gZ2ff\nset PowhegMEqq2gZ2ff:Process Muon\n"
             process+=addLeptonPairCut("25","70")
         elif(parameterName.find("Run-II-Z-HighMass-mu")>=0) :
             process+="insert SubProcess:MatrixElements[0] PowhegMEqq2gZ2ff\nset PowhegMEqq2gZ2ff:Process Muon\n"
             process+=addLeptonPairCut("150","600")
         elif(parameterName.find("Run-II-Z-mu")>=0) :
             process+="insert SubProcess:MatrixElements[0] PowhegMEqq2gZ2ff\nset PowhegMEqq2gZ2ff:Process Muon\n"
         elif(parameterName.find("DiPhoton-GammaGamma")>=0) :
             process+="insert SubProcess:MatrixElements[0] MEGammaGammaPowheg\n"
             process+="set MEGammaGammaPowheg:Process GammaGamma\n"
             process+="insert SubProcess:MatrixElements[0] MEGammaGamma\n"
             process+="set MEGammaGamma:Process gg\n"
             process+="set /Herwig/Cuts/PhotonKtCut:MinKT 5.\n"
             process+="set /Herwig/Cuts/JetKtCut:MinKT 5.\n"
             parameterName=parameterName.replace("-GammaGamma","")
         elif(parameterName.find("DiPhoton-GammaJet")>=0) :
             process+="insert SubProcess:MatrixElements[0] MEGammaGammaPowheg\n"
             process+="set MEGammaGammaPowheg:Process VJet\n"
             process+="set /Herwig/Cuts/PhotonKtCut:MinKT 5.\n"
             process+="set /Herwig/Cuts/JetKtCut:MinKT 5.\n"
             parameterName=parameterName.replace("-GammaJet","")
     elif(simulation=="Matchbox" or simulation=="Merging" ) :
         if(parameterName.find("Jets")>=0) :
             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(parameterName.find("Run-II-Jets-10")>=0) :
                 process+=addFirstJet("30")
                 process+=addSecondJet("25")
                 process+=addJetPairCut("500")
             elif(parameterName.find("Run-II-Jets-11")>=0) :
                 process+=addFirstJet("30")
                 process+=addSecondJet("25")
                 process+=addJetPairCut("900")
             elif(parameterName.find("Run-II-Jets-12")>=0) :
                 process+=addFirstJet("30")
                 process+=addSecondJet("25")
                 process+=addJetPairCut("300")
             elif(parameterName.find("Run-I-Jets-1")>=0) :
                 process+=addFirstJet("20")
             elif(parameterName.find("Run-I-Jets-2")>=0) :
                 process+=addFirstJet("40")
             elif(parameterName.find("Run-I-Jets-3")>=0) :
                 process+=addFirstJet("65")
             elif(parameterName.find("Run-I-Jets-4")>=0) :
                 process+=addFirstJet("90")
             elif(parameterName.find("Run-I-Jets-5")>=0) :
                 process+=addFirstJet("160")
             elif(parameterName.find("Run-I-Jets-6")>=0) :
                 process+=addFirstJet("30")
                 process+=addSecondJet("25")
                 process+=addJetPairCut("100")
             elif(parameterName.find("Run-I-Jets-7")>=0) :
                 process+=addFirstJet("30")
                 process+=addSecondJet("25")
                 process+=addJetPairCut("400")
             elif(parameterName.find("Run-I-Jets-8")>=0) :
                 process+=addFirstJet("30")
                 process+=addSecondJet("25")
                 process+=addJetPairCut("700")
             elif(parameterName.find("Run-II-Jets-0")>=0) :
                 process+=addFirstJet("15")
             elif(parameterName.find("Run-II-Jets-1")>=0) :
                 process+=addFirstJet("25")
             elif(parameterName.find("Run-II-Jets-2")>=0) :
                 process+=addFirstJet("40")
             elif(parameterName.find("Run-II-Jets-3")>=0) :
                 process+=addFirstJet("60")
             elif(parameterName.find("Run-II-Jets-4")>=0) :
                 process+=addFirstJet("85")
             elif(parameterName.find("Run-II-Jets-5")>=0) :
                 process+=addFirstJet("110")
             elif(parameterName.find("Run-II-Jets-6")>=0) :
                 process+=addFirstJet("160")
             elif(parameterName.find("Run-II-Jets-7")>=0) :
                 process+=addFirstJet("250")
             elif(parameterName.find("Run-II-Jets-8")>=0) :
                 process+=addFirstJet("30")
                 process+=addSecondJet("25")
                 process+=addJetPairCut("100")
             elif(parameterName.find("Run-II-Jets-9")>=0) :
                 process+=addFirstJet("30")
                 process+=addSecondJet("25")
                 process+=addJetPairCut("300")
             elif(parameterName.find("900-Jets-1")>=0) :
                 process+=addFirstJet("10")
             elif(parameterName.find("300-Jets-1")>=0) :
                 process+=addFirstJet("6")
             elif(parameterName.find("630-Jets-1")>=0) :
                 process+=addFirstJet("20")
             elif(parameterName.find("630-Jets-2")>=0) :
                 process+=addFirstJet("40")
             elif(parameterName.find("630-Jets-3")>=0) :
                 process+=addFirstJet("75")
             elif(parameterName.find("900-Jets-1")>=0) :
                 process+=addFirstJet("10")
             else :
                 logging.error("Exit 00007")
                 sys.exit(1)
         elif(parameterName.find("Run-I-WZ")>=0) :
             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+="do "+thefactory+":StartParticleGroup epm\n"
                 process+="insert "+thefactory+":ParticleGroup 0 /Herwig/Particles/e+\n"
                 process+="insert "+thefactory+":ParticleGroup 0 /Herwig/Particles/e-\n"
                 process+="do "+thefactory+":EndParticleGroup\n"
                 process+="do "+thefactory+":StartParticleGroup epmnu\n"
                 process+="insert "+thefactory+":ParticleGroup 0 /Herwig/Particles/e+\n"
                 process+="insert "+thefactory+":ParticleGroup 0 /Herwig/Particles/e-\n"
                 process+="insert "+thefactory+":ParticleGroup 0 /Herwig/Particles/nu_e\n"
                 process+="insert "+thefactory+":ParticleGroup 0 /Herwig/Particles/nu_ebar\n"
                 process+="do "+thefactory+":EndParticleGroup\n"
                 process+=addProcess(thefactory,"p pbar epm epmnu","0","2","LeptonPairMassScale",2,2)
             process+=addLeptonPairCut("60","120")
         elif(parameterName.find("Run-I-W")>=0 or parameterName.find("Run-II-W")>=0) :
             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+="do "+thefactory+":StartParticleGroup epm\n"
                 process+="insert "+thefactory+":ParticleGroup 0 /Herwig/Particles/e+\n"
                 process+="insert "+thefactory+":ParticleGroup 0 /Herwig/Particles/e-\n"
                 process+="do "+thefactory+":EndParticleGroup\n"
                 process+=addProcess(thefactory,"p pbar epm nu","0","2","LeptonPairMassScale",2,2)
             process+=addLeptonPairCut("60","120")
         elif(parameterName.find("Run-I-Z")>=0 or parameterName.find("Run-II-Z-e")>=0) :
             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(parameterName.find("Run-II-Z-LowMass-mu")>=0) :
             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(parameterName.find("Run-II-Z-HighMass-mu")>=0) :
             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(parameterName.find("Run-II-Z-mu")>=0) :
             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 = "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+= "set /Herwig/Generators/EventGenerator:EventHandler:LuminosityFunction:Energy 200.0\n"
     process+= "set /Herwig/Cuts/Cuts:X2Min 0.01\n"
     if(simulation=="") :
         if(parameterName.find("UE")>=0) :
-            process += "insert SubProcess:MatrixElements[0] MEMinBias\n"
-            process += "set /Herwig/UnderlyingEvent/MPIHandler:IdenticalToUE 0\n"
-            process += "set /Herwig/Generators/EventGenerator:EventHandler:Cuts /Herwig/Cuts/MinBiasCuts\n"
-            process += "create Herwig::MPIXSecReweighter /Herwig/Generators/MPIXSecReweighter\n"
-            process += "insert /Herwig/Generators/EventGenerator:EventHandler:PostSubProcessHandlers 0 /Herwig/Generators/MPIXSecReweighter\n"
+            if (parameters["shower"].find("Dipole")>=0):
+                process+="read snippets/MB-DipoleShower.in\n"
+            else:
+                process+="read snippets/MB.in\n"    
+            process+="read snippets/Diffraction.in\n"
+            
+            
         else :
             process+="insert SubProcess:MatrixElements[0] MEQCD2to2\n"
             process+="set /Herwig/UnderlyingEvent/MPIHandler:IdenticalToUE 0\n"
             if(parameterName.find("Jets-1")>=0) :
                 process+="set /Herwig/Cuts/JetKtCut:MinKT 2.\n"
             elif(parameterName.find("Jets-2")>=0) :
                 process+="set /Herwig/Cuts/JetKtCut:MinKT 5.\n"
             elif(parameterName.find("Jets-3")>=0) :
                 process+="set /Herwig/Cuts/JetKtCut:MinKT 20.\n"
             elif(parameterName.find("Jets-4")>=0) :
                 process+="set /Herwig/Cuts/JetKtCut:MinKT 25.\n"
     else :
         logging.error("Star not supported for %s " % simulation)
         sys.exit(1)
 # ISR and SppS
 elif(collider=="ISR" or collider =="SppS" ) :
     process="set /Herwig/Decays/DecayHandler:LifeTimeOption 0\n"
     process+="set /Herwig/Decays/DecayHandler:MaxLifeTime 10*mm\n"
     if(collider=="SppS") :
         process ="set /Herwig/Generators/EventGenerator:EventHandler:BeamB /Herwig/Particles/pbar-\n"
     if(parameterName.find("30")>=0) :
         process+="set /Herwig/Generators/EventGenerator:EventHandler:LuminosityFunction:Energy 30.4\n"
     elif(parameterName.find("44")>=0) :
         process+="set /Herwig/Generators/EventGenerator:EventHandler:LuminosityFunction:Energy 44.4\n"
     elif(parameterName.find("53")>=0) :
         process+="set /Herwig/Generators/EventGenerator:EventHandler:LuminosityFunction:Energy 53.0\n"
     elif(parameterName.find("62")>=0) :
         process+="set /Herwig/Generators/EventGenerator:EventHandler:LuminosityFunction:Energy 62.2\n"
     elif(parameterName.find("63")>=0) :
         process+="set /Herwig/Generators/EventGenerator:EventHandler:LuminosityFunction:Energy 63.0\n"
     elif(parameterName.find("200")>=0) :
         process+="set /Herwig/Generators/EventGenerator:EventHandler:LuminosityFunction:Energy 200.0\n"
     elif(parameterName.find("500")>=0) :
         process+="set /Herwig/Generators/EventGenerator:EventHandler:LuminosityFunction:Energy 500.0\n"
     elif(parameterName.find("546")>=0) :
         process+="set /Herwig/Generators/EventGenerator:EventHandler:LuminosityFunction:Energy 546.0\n"
     elif(parameterName.find("900")>=0) :
         process+="set /Herwig/Generators/EventGenerator:EventHandler:LuminosityFunction:Energy 900.0\n"
     if(simulation=="") :
-        process += "insert SubProcess:MatrixElements[0] MEMinBias\n"
-        process += "set /Herwig/UnderlyingEvent/MPIHandler:IdenticalToUE 0\n"
-        process += "set /Herwig/Generators/EventGenerator:EventHandler:Cuts /Herwig/Cuts/MinBiasCuts\n"
-        process += "create Herwig::MPIXSecReweighter /Herwig/Generators/MPIXSecReweighter\n"
-        process += "insert /Herwig/Generators/EventGenerator:EventHandler:PostSubProcessHandlers 0 /Herwig/Generators/MPIXSecReweighter\n"
+        if (parameters["shower"].find("Dipole")>=0):
+            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.find("7-")==0) :
         process="set /Herwig/Generators/EventGenerator:EventHandler:LuminosityFunction:Energy 7000.0\n"
     elif(parameterName.find("8-")==0) :
         process="set /Herwig/Generators/EventGenerator:EventHandler:LuminosityFunction:Energy 8000.0\n"
     elif(parameterName.find("13-")==0) :
         process="set /Herwig/Generators/EventGenerator:EventHandler:LuminosityFunction:Energy 13000.0\n"
     elif(parameterName.find("900")==0) :
         process="set /Herwig/Generators/EventGenerator:EventHandler:LuminosityFunction:Energy 900.0\n"
     elif(parameterName.find("2360")==0) :
         process="set /Herwig/Generators/EventGenerator:EventHandler:LuminosityFunction:Energy 2360.0\n"
     elif(parameterName.find("2760")==0) :
         process="set /Herwig/Generators/EventGenerator:EventHandler:LuminosityFunction:Energy 2760.0\n"
     else :
         process="set /Herwig/Generators/EventGenerator:EventHandler:LuminosityFunction:Energy 7000.0\n"
     if(simulation=="") :
         if(parameterName.find("8-VBF")>=0) :
             process+="insert SubProcess:MatrixElements[0] MEPP2HiggsVBF\n"
         elif(parameterName.find("VBF")>=0) :
             process+=selectDecayMode("h0",["h0->tau-,tau+;"])
             process+=addBRReweighter()
             process+="set /Herwig/Particles/tau-:Stable Stable\n"
             process+="insert SubProcess:MatrixElements[0] MEPP2HiggsVBF\n"
         elif(parameterName.find("ggHJet")>=0) :
             process+=selectDecayMode("h0",["h0->tau-,tau+;"])
             process+=addBRReweighter()
             process+="set /Herwig/Particles/tau-:Stable Stable\n"
             process+="insert SubProcess:MatrixElements[0] MEHiggsJet\n"
             process+="set /Herwig/Cuts/JetKtCut:MinKT 20.\n"
         elif(parameterName.find("8-ggH")>=0) :
             process+="insert SubProcess:MatrixElements[0] MEHiggs\n"
             process+="insert SubProcess:MatrixElements[0] MEHiggsJet\n"
             process+="set MEHiggsJet:Process qqbar\n"
             process+="set /Herwig/Cuts/JetKtCut:MinKT 0.0*GeV\n"
         elif(parameterName.find("ggH")>=0) :
             process+=selectDecayMode("h0",["h0->tau-,tau+;"])
             process+=addBRReweighter()
             process+="set /Herwig/Particles/tau-:Stable Stable\n"
             process+="insert SubProcess:MatrixElements[0] MEHiggs\n"
             process+="insert SubProcess:MatrixElements[0] MEHiggsJet\n"
             process+="set MEHiggsJet:Process qqbar\n"
             process+="set /Herwig/Cuts/JetKtCut:MinKT 0.0*GeV\n"
         elif(parameterName.find("PromptPhoton")>=0) :
             process+="insert SubProcess:MatrixElements[0] MEGammaJet\n"
             if(parameterName.find("PromptPhoton-1")>=0) :
                 process+="set /Herwig/Cuts/PhotonKtCut:MinKT 5.\n"
             elif(parameterName.find("PromptPhoton-2")>=0) :
                 process+="set /Herwig/Cuts/PhotonKtCut:MinKT 25.\n"
             elif(parameterName.find("PromptPhoton-3")>=0) :
                 process+="set /Herwig/Cuts/PhotonKtCut:MinKT 80.\n"
             elif(parameterName.find("PromptPhoton-4")>=0) :
                 process+="set /Herwig/Cuts/PhotonKtCut:MinKT 150.\n"
         elif(parameterName.find("DiPhoton-GammaGamma")>=0) :
             process+="insert SubProcess:MatrixElements[0] MEGammaGamma\n"
             process+="set /Herwig/Cuts/PhotonKtCut:MinKT 5.\n"
             parameterName=parameterName.replace("-GammaGamma","")
         elif(parameterName.find("DiPhoton-GammaJet")>=0) :
             process+="insert SubProcess:MatrixElements[0] MEGammaJet\n"
             process+="set /Herwig/Cuts/PhotonKtCut:MinKT 5.\n"
             parameterName=parameterName.replace("-GammaJet","")
         elif(parameterName.find("8-WH")>=0) :
             process+="insert SubProcess:MatrixElements[0] MEPP2WH\n"
             process+="set /Herwig/Cuts/JetKtCut:MinKT 0.0*GeV\n"
         elif(parameterName.find("8-ZH")>=0) :
             process+="insert SubProcess:MatrixElements[0] MEPP2ZH\n"
             process+="set /Herwig/Cuts/JetKtCut:MinKT 0.0*GeV\n"
         elif(parameterName.find("WH")>=0) :
             process+=selectDecayMode("h0",["h0->b,bbar;"])
             process+=selectDecayMode("W+",["W+->nu_e,e+;",
                                            "W+->nu_mu,mu+;"])
             process+=addBRReweighter()
             process+="insert SubProcess:MatrixElements[0] MEPP2WH\n"
             process+="set /Herwig/Cuts/JetKtCut:MinKT 0.0*GeV\n"
         elif(parameterName.find("ZH")>=0) :
             process+=selectDecayMode("h0",["h0->b,bbar;"])
             process+=selectDecayMode("Z0",["Z0->e-,e+;",
                                            "Z0->mu-,mu+;"])
             process+=addBRReweighter()
             process+="insert SubProcess:MatrixElements[0] MEPP2ZH\n"
             process+="set /Herwig/Cuts/JetKtCut:MinKT 0.0*GeV\n"
         elif(parameterName.find("UE")>=0) :
-            process+="set /Herwig/Shower/ShowerHandler:IntrinsicPtGaussian 2.2*GeV\n"
-            process+="read snippets/MB.in\n"
+            if (parameters["shower"].find("Dipole")>=0):
+                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(parameterName.find("Long")>=0) :
                 process += "set /Herwig/Decays/DecayHandler:MaxLifeTime 100*mm\n"
         elif(parameterName.find("7-DiJets")>=0 or parameterName.find("8-DiJets")>=0) :
             process+="insert SubProcess:MatrixElements[0] MEQCD2to2\n"
             process+="set MEQCD2to2:MaximumFlavour 5\n"
             process+="set /Herwig/UnderlyingEvent/MPIHandler:IdenticalToUE 0\n"
             if(parameterName.find("-A")>=0) :
                process+="set /Herwig/Cuts/JetKtCut:MinKT 45.\n"
                process+="set /Herwig/Cuts/JetKtCut:MinEta -3.\n"
                process+="set /Herwig/Cuts/JetKtCut:MaxEta  3.\n"
             elif(parameterName.find("-B")>=0) :
                process+="set /Herwig/Cuts/JetKtCut:MinKT 20.\n"
                process+="set /Herwig/Cuts/JetKtCut:MinEta -2.7\n"
                process+="set /Herwig/Cuts/JetKtCut:MaxEta  2.7\n"
             elif(parameterName.find("-C")>=0) :
                process+="set /Herwig/Cuts/JetKtCut:MinKT 20.\n"
                process+="set /Herwig/Cuts/JetKtCut:MinEta -4.8\n"
                process+="set /Herwig/Cuts/JetKtCut:MaxEta  4.8\n"
             if(parameterName.find("DiJets-1")>=0) :
                 process+="set /Herwig/Cuts/Cuts:MHatMin 90.*GeV\n"
             elif(parameterName.find("DiJets-2")>=0) :
                 process+="set /Herwig/Cuts/Cuts:MHatMin 200.*GeV\n"
             elif(parameterName.find("DiJets-3")>=0) :
                 process+="set /Herwig/Cuts/Cuts:MHatMin 450.*GeV\n"
             elif(parameterName.find("DiJets-4")>=0) :
                 process+="set /Herwig/Cuts/Cuts:MHatMin 750.*GeV\n"
             elif(parameterName.find("DiJets-5")>=0) :
                 process+="set /Herwig/Cuts/Cuts:MHatMin 950.*GeV\n"
             elif(parameterName.find("DiJets-6")>=0) :
                 process+="set /Herwig/Cuts/Cuts:MHatMin 1550.*GeV\n"
             elif(parameterName.find("DiJets-7")>=0) :
                 process+="set /Herwig/Cuts/Cuts:MHatMin 2150.*GeV\n"
             elif(parameterName.find("DiJets-8")>=0) :
                 process+="set /Herwig/Cuts/Cuts:MHatMin 2750.*GeV\n"
         elif(parameterName.find("7-Jets")>=0 or parameterName.find("8-Jets")>=0 or \
              parameterName.find("13-Jets")>=0) :
             process+="insert SubProcess:MatrixElements[0] MEQCD2to2\n"
             process+="set MEQCD2to2:MaximumFlavour 5\n"
             process+="set /Herwig/UnderlyingEvent/MPIHandler:IdenticalToUE 0\n"
             if(parameterName.find("Jets-10")>=0) :
                 process+="set /Herwig/Cuts/JetKtCut:MinKT 1800.\n"
             elif(parameterName.find("Jets-0")>=0) :
                 process+="set /Herwig/Cuts/JetKtCut:MinKT 5.\n"
             elif(parameterName.find("Jets-1")>=0) :
                 process+="set /Herwig/Cuts/JetKtCut:MinKT 10.\n"
             elif(parameterName.find("Jets-2")>=0) :
                 process+="set /Herwig/Cuts/JetKtCut:MinKT 20.\n"
             elif(parameterName.find("Jets-3")>=0) :
                 process+="set /Herwig/Cuts/JetKtCut:MinKT 40.\n"
             elif(parameterName.find("Jets-4")>=0) :
                 process+="set /Herwig/Cuts/JetKtCut:MinKT 70.\n"
             elif(parameterName.find("Jets-5")>=0) :
                 process+="set /Herwig/Cuts/JetKtCut:MinKT 150.\n"
             elif(parameterName.find("Jets-6")>=0) :
                 process+="set /Herwig/Cuts/JetKtCut:MinKT 200.\n"
             elif(parameterName.find("Jets-7")>=0) :
                 process+="set /Herwig/Cuts/JetKtCut:MinKT 300.\n"
             elif(parameterName.find("Jets-8")>=0) :
                 process+="set /Herwig/Cuts/JetKtCut:MinKT 500.\n"
             elif(parameterName.find("Jets-9")>=0) :
                 process+="set /Herwig/Cuts/JetKtCut:MinKT 800.\n"
         elif(parameterName.find("7-Charm")>=0 or \
              parameterName.find("7-Bottom")>=0) :
             if(parameterName.find("7-Bottom")>=0) :
                 process+="cp MEHeavyQuark MEBottom\n" 
                 process+="set MEBottom:QuarkType Bottom\n"
                 process+="insert SubProcess:MatrixElements[0] MEBottom\n"
             else : 
                 process+="cp MEHeavyQuark MECharm\n" 
                 process+="set MECharm:QuarkType Charm\n"
                 process+="insert SubProcess:MatrixElements[0] MECharm\n"
             process+="set /Herwig/UnderlyingEvent/MPIHandler:IdenticalToUE 0\n"
             if(parameterName.find("-0")>=0) :
                 if(parameterName.find("7-Bottom")>=0) :
                     process+="set MEBottom:Process Pair\n" 
                 process+="set /Herwig/Cuts/JetKtCut:MinKT 0.\n"
             elif(parameterName.find("-1")>=0) :
                 process+="set /Herwig/Cuts/JetKtCut:MinKT 5.\n"
             elif(parameterName.find("-2")>=0) :
                 process+="set /Herwig/Cuts/JetKtCut:MinKT 20.\n"
             elif(parameterName.find("-3")>=0) :
                 process+="set /Herwig/Cuts/JetKtCut:MinKT 50.\n"
             elif(parameterName.find("-4")>=0) :
                 process+="set /Herwig/Cuts/JetKtCut:MinKT 80.\n"
             elif(parameterName.find("-5")>=0) :
                 process+="set /Herwig/Cuts/JetKtCut:MinKT 110.\n"
             elif(parameterName.find("-6")>=0) :
                 process+="set /Herwig/Cuts/JetKtCut:MinKT 30.\n"
                 process+="set /Herwig/Cuts/Cuts:MHatMin 90.*GeV\n"
             elif(parameterName.find("-7")>=0) :
                 process+="set /Herwig/Cuts/JetKtCut:MinKT 30.\n"
                 process+="set /Herwig/Cuts/Cuts:MHatMin 340.*GeV\n"
             elif(parameterName.find("-8")>=0) :
                 process+="set /Herwig/Cuts/JetKtCut:MinKT 30.\n"
                 process+="set /Herwig/Cuts/Cuts:MHatMin 500.*GeV\n"
         elif(parameterName.find("Top-L")>=0) :
             process+="set MEHeavyQuark:QuarkType Top\n"
             process+="insert SubProcess:MatrixElements[0] MEHeavyQuark\n"
             process+=selectDecayMode("t",["t->nu_e,e+,b;",
                                           "t->nu_mu,mu+,b;"])
             process+=addBRReweighter()
             
         elif(parameterName.find("Top-SL")>=0) :
             process+="set MEHeavyQuark:QuarkType Top\n"
             process+="insert SubProcess:MatrixElements[0] MEHeavyQuark\n"
             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(parameterName.find("Top-All")>=0) :
             process+="set MEHeavyQuark:QuarkType Top\n"
             process+="insert SubProcess:MatrixElements[0] MEHeavyQuark\n"
         elif(parameterName.find("WZ")>=0) :
             process+="insert SubProcess:MatrixElements[0] MEPP2VV\nset MEPP2VV:Process WZ\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()
             
         elif(parameterName.find("WW-emu")>=0) :
             process+="insert SubProcess:MatrixElements[0] MEPP2VV\nset MEPP2VV:Process WW\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()
             
         elif(parameterName.find("WW-ll")>=0) :
             process+="insert SubProcess:MatrixElements[0] MEPP2VV\nset MEPP2VV:Process WW\n"
             process+=selectDecayMode("W+",["W+->nu_e,e+;","W+->nu_mu,mu+;","W+->nu_tau,tau+;"])
             process+=addBRReweighter()
             
         elif(parameterName.find("ZZ-ll")>=0) :
             process+="insert SubProcess:MatrixElements[0] MEPP2VV\nset MEPP2VV:Process ZZ\n"
             process+=selectDecayMode("Z0",["Z0->e-,e+;",
                                            "Z0->mu-,mu+;",
                                            "Z0->tau-,tau+;"])
             process+=addBRReweighter()
 
         elif(parameterName.find("ZZ-lv")>=0) :
             process+="insert SubProcess:MatrixElements[0] MEPP2VV\nset MEPP2VV:Process ZZ\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()
             
         elif(parameterName.find("W-Z-e")>=0) :
             process+="insert SubProcess:MatrixElements[0] MEqq2gZ2ff\nset MEqq2gZ2ff:Process Electron\n"
             process+="insert SubProcess:MatrixElements[0] MEqq2W2ff\nset MEqq2W2ff:Process Electron\n"
 
         elif(parameterName.find("W-Z-mu")>=0) :
             process+="insert SubProcess:MatrixElements[0] MEqq2gZ2ff\nset MEqq2gZ2ff:Process Muon\n"
             process+="insert SubProcess:MatrixElements[0] MEqq2W2ff\nset MEqq2W2ff:Process Muon\n"
         elif(parameterName.find("W-e")>=0) :
             process+="insert SubProcess:MatrixElements[0] MEqq2W2ff\nset MEqq2W2ff:Process Electron\n"
         elif(parameterName.find("W-mu")>=0) :
             process+="insert SubProcess:MatrixElements[0] MEqq2W2ff\nset MEqq2W2ff:Process Muon\n"
         elif(parameterName.find("Z-e")>=0) :
             process+="insert SubProcess:MatrixElements[0] MEqq2gZ2ff\nset MEqq2gZ2ff:Process Electron\n"
         elif(parameterName.find("Z-mu")>=0) :
             process+="insert SubProcess:MatrixElements[0] MEqq2gZ2ff\nset MEqq2gZ2ff:Process Muon\n"
         elif(parameterName.find("Z-LowMass-e")>=0) :
             process+="insert SubProcess:MatrixElements[0] MEqq2gZ2ff\nset MEqq2gZ2ff:Process Electron\n"
             process+="set /Herwig/Cuts/Cuts:MHatMin 20.*GeV\nset /Herwig/Cuts/MassCut:MinM 20.*GeV\nset /Herwig/Cuts/MassCut:MaxM 70.*GeV\n"
         elif(parameterName.find("Z-MedMass-e")>=0) :
             process+="insert SubProcess:MatrixElements[0] MEqq2gZ2ff\nset MEqq2gZ2ff:Process Electron\n"
             process+="set /Herwig/Cuts/Cuts:MHatMin 40.*GeV\nset /Herwig/Cuts/MassCut:MinM 40.*GeV\nset /Herwig/Cuts/MassCut:MaxM 130.*GeV\n"
         elif(parameterName.find("Z-LowMass-mu")>=0) :
             process+="insert SubProcess:MatrixElements[0] MEqq2gZ2ff\nset MEqq2gZ2ff:Process Muon\n"
             process+="set /Herwig/Cuts/Cuts:MHatMin 10.*GeV\nset /Herwig/Cuts/MassCut:MinM 10.*GeV\nset /Herwig/Cuts/MassCut:MaxM 70.*GeV\n"
         elif(parameterName.find("Z-Mass1")>=0) :
             process+="set /Herwig/Cuts/Cuts:MHatMin 10.*GeV\n"
             process+="set /Herwig/Cuts/MassCut:MinM 10.*GeV\n"
             process+="set /Herwig/Cuts/MassCut:MaxM 35.*GeV\n"
             if(parameterName.find("-e")>=0) :
                 process+="insert SubProcess:MatrixElements[0] MEqq2gZ2ff\nset MEqq2gZ2ff:Process Electron\n"
             else :
                 process+="insert SubProcess:MatrixElements[0] MEqq2gZ2ff\nset MEqq2gZ2ff:Process Muon\n"
         elif(parameterName.find("Z-Mass2")>=0) :
             process+="set /Herwig/Cuts/Cuts:MHatMin 25.*GeV\n"
             process+="set /Herwig/Cuts/MassCut:MinM 25.*GeV\n"
             process+="set /Herwig/Cuts/MassCut:MaxM 70.*GeV\n"
             if(parameterName.find("-e")>=0) :
                 process+="insert SubProcess:MatrixElements[0] MEqq2gZ2ff\nset MEqq2gZ2ff:Process Electron\n"
             else :
                 process+="insert SubProcess:MatrixElements[0] MEqq2gZ2ff\nset MEqq2gZ2ff:Process Muon\n"
         elif(parameterName.find("Z-Mass3")>=0) :
             process+="set /Herwig/Cuts/Cuts:MHatMin 60.*GeV\n"
             process+="set /Herwig/Cuts/MassCut:MinM 60.*GeV\n"
             process+="set /Herwig/Cuts/MassCut:MaxM 120.*GeV\n"
             if(parameterName.find("-e")>=0) :
                 process+="insert SubProcess:MatrixElements[0] MEqq2gZ2ff\nset MEqq2gZ2ff:Process Electron\n"
             else :
                 process+="insert SubProcess:MatrixElements[0] MEqq2gZ2ff\nset MEqq2gZ2ff:Process Muon\n"
         elif(parameterName.find("Z-Mass4")>=0) :
             process+="set /Herwig/Cuts/Cuts:MHatMin 110.*GeV\n"
             process+="set /Herwig/Cuts/MassCut:MinM 110.*GeV\n"
             process+="set /Herwig/Cuts/MassCut:MaxM 8000.*GeV\n"
             if(parameterName.find("-e")>=0) :
                 process+="insert SubProcess:MatrixElements[0] MEqq2gZ2ff\nset MEqq2gZ2ff:Process Electron\n"
             else :
                 process+="insert SubProcess:MatrixElements[0] MEqq2gZ2ff\nset MEqq2gZ2ff:Process Muon\n"
         elif(parameterName.find("W-Jet")>=0) :
             process+="insert SubProcess:MatrixElements[0] MEWJet\nset MEWJet:WDecay Electron\n"
             if(parameterName.find("W-Jet-1-e")>=0) :
                 process+="set /Herwig/Cuts/WBosonKtCut:MinKT 100.0*GeV\n"
                 parameterName=parameterName.replace("W-Jet-1-e","W-Jet-e")
             elif(parameterName.find("W-Jet-2-e")>=0) :
                 process+="set /Herwig/Cuts/WBosonKtCut:MinKT 190.0*GeV\n"
                 parameterName=parameterName.replace("W-Jet-2-e","W-Jet-e")
             elif(parameterName.find("W-Jet-3-e")>=0) :
                 process+="set /Herwig/Cuts/WBosonKtCut:MinKT 270.0*GeV\n"
                 parameterName=parameterName.replace("W-Jet-3-e","W-Jet-e")
         elif(parameterName.find("Z-Jet")>=0) :
             if(parameterName.find("-e")>=0) :
                 process+="insert SubProcess:MatrixElements[0] MEZJet\nset MEZJet:ZDecay Electron\n"
                 if(parameterName.find("Z-Jet-0-e")>=0) :
                     process+="set /Herwig/Cuts/ZBosonKtCut:MinKT 35.0*GeV\n"
                     parameterName=parameterName.replace("Z-Jet-0-e","Z-Jet-e")
                 elif(parameterName.find("Z-Jet-1-e")>=0) :
                     process+="set /Herwig/Cuts/ZBosonKtCut:MinKT 100.0*GeV\n"
                     parameterName=parameterName.replace("Z-Jet-1-e","Z-Jet-e")
                 elif(parameterName.find("Z-Jet-2-e")>=0) :
                     process+="set /Herwig/Cuts/ZBosonKtCut:MinKT 190.0*GeV\n"
                     parameterName=parameterName.replace("Z-Jet-2-e","Z-Jet-e")
                 elif(parameterName.find("Z-Jet-3-e")>=0) :
                     process+="set /Herwig/Cuts/ZBosonKtCut:MinKT 270.0*GeV\n"
                     parameterName=parameterName.replace("Z-Jet-3-e","Z-Jet-e")
             else :
                 process+="insert SubProcess:MatrixElements[0] MEZJet\nset MEZJet:ZDecay Muon\n"
                 process+="set /Herwig/Cuts/ZBosonKtCut:MinKT 35.0*GeV\n"
                 parameterName=parameterName.replace("Z-Jet-0-mu","Z-Jet-mu")
         elif(parameterName.find("WGamma")>=0) :
             process+="insert SubProcess:MatrixElements[0] MEPP2VGamma\nset MEPP2VGamma:Process 1\nset MEPP2VGamma:MassOption 1\n"
             process+="set /Herwig/Cuts/PhotonKtCut:MinKT 10.\n"
             
             
             if(parameterName.find("-e")>=0) :
                 process+=selectDecayMode("W+",["W+->nu_e,e+;"])
                 process+=addBRReweighter()
             else :
                 process+=selectDecayMode("W+",["W+->nu_mu,mu+;"])
                 process+=addBRReweighter()
         elif(parameterName.find("ZGamma")>=0) :
             process+="insert SubProcess:MatrixElements[0] MEPP2VGamma\nset MEPP2VGamma:Process 2\n"
             process+="set /Herwig/Cuts/PhotonKtCut:MinKT 10.\n"
             if(parameterName.find("-e")>=0) :
                 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(parameterName.find("8-VBF")>=0) :
             process+="insert SubProcess:MatrixElements[0] PowhegMEPP2HiggsVBF\n"
         elif(parameterName.find("VBF")>=0) :
             process+=selectDecayMode("h0",["h0->tau-,tau+;"])
             process+=addBRReweighter()
             process+="set /Herwig/Particles/tau-:Stable Stable\n"
             process+="insert SubProcess:MatrixElements[0] PowhegMEPP2HiggsVBF\n"
         elif(parameterName.find("ggHJet")>=0) :
             logging.error(" Process %s not supported for POWHEG matrix elements" % name)
             sys.exit(1)
         elif(parameterName.find("8-ggH")>=0) :
             process+="insert SubProcess:MatrixElements[0] PowhegMEHiggs\n"
         elif(parameterName.find("ggH")>=0) :
             process+=selectDecayMode("h0",["h0->tau-,tau+;"])
             process+=addBRReweighter()
             process+="set /Herwig/Particles/tau-:Stable Stable\n"
             process+="insert SubProcess:MatrixElements[0] PowhegMEHiggs\n"
         elif(parameterName.find("8-WH")>=0) :
             process+="insert SubProcess:MatrixElements[0] PowhegMEPP2WH\n"
             process+="set /Herwig/Cuts/JetKtCut:MinKT 0.0*GeV\n"
         elif(parameterName.find("8-ZH")>=0) :
             process+="insert SubProcess:MatrixElements[0] PowhegMEPP2ZH\n"
             process+="set /Herwig/Cuts/JetKtCut:MinKT 0.0*GeV\n"
         elif(parameterName.find("WH")>=0) :
             process+=selectDecayMode("h0",["h0->b,bbar;"])
             process+=selectDecayMode("W+",["W+->nu_e,e+;",
                                            "W+->nu_mu,mu+;"])
             process+=addBRReweighter()
             process+="insert SubProcess:MatrixElements[0] PowhegMEPP2WH\n"
             process+="set /Herwig/Cuts/JetKtCut:MinKT 0.0*GeV\n"
         elif(parameterName.find("ZH")>=0) :
             process+=selectDecayMode("h0",["h0->b,bbar;"])
             process+=selectDecayMode("Z0",["Z0->e-,e+;",
                                            "Z0->mu-,mu+;"])
             process+=addBRReweighter()
             process+="insert SubProcess:MatrixElements[0] PowhegMEPP2ZH\n"
             process+="set /Herwig/Cuts/JetKtCut:MinKT 0.0*GeV\n"
         elif(parameterName.find("UE")>=0) :
             logging.error(" Process %s not supported for powheg matrix elements" % name)
             sys.exit(1)
         elif(parameterName.find("WZ")>=0) :
             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/ZPowhegDecayer:PhotonGenerator NULL\n";
             process+="set /Herwig/Decays/WDecayer:PhotonGenerator NULL\n";
             process+="set /Herwig/Decays/WPowhegDecayer: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 SubProcess:MatrixElements[0] PowhegMEPP2VV\nset PowhegMEPP2VV:Process WZ\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()
             
         elif(parameterName.find("WW-emu")>=0) :
             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/ZPowhegDecayer:PhotonGenerator NULL\n";
             process+="set /Herwig/Decays/WDecayer:PhotonGenerator NULL\n";
             process+="set /Herwig/Decays/WPowhegDecayer: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 SubProcess:MatrixElements[0] PowhegMEPP2VV\nset PowhegMEPP2VV:Process WW\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()
             
         elif(parameterName.find("WW-ll")>=0) :
             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/ZPowhegDecayer:PhotonGenerator NULL\n";
             process+="set /Herwig/Decays/WDecayer:PhotonGenerator NULL\n";
             process+="set /Herwig/Decays/WPowhegDecayer: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 SubProcess:MatrixElements[0] PowhegMEPP2VV\nset PowhegMEPP2VV:Process WW\n"
             process+=selectDecayMode("W+",["W+->nu_e,e+;",
                                            "W+->nu_mu,mu+;",
                                            "W+->nu_tau,tau+;"])
             process+=addBRReweighter()
             
         elif(parameterName.find("ZZ-ll")>=0) :
             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/ZPowhegDecayer:PhotonGenerator NULL\n";
             process+="set /Herwig/Decays/WDecayer:PhotonGenerator NULL\n";
             process+="set /Herwig/Decays/WPowhegDecayer: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 SubProcess:MatrixElements[0] PowhegMEPP2VV\nset PowhegMEPP2VV:Process ZZ\n"
             process+=selectDecayMode("Z0",["Z0->e-,e+;",
                                            "Z0->mu-,mu+;",
                                            "Z0->tau-,tau+;"])
             process+=addBRReweighter()
             
         elif(parameterName.find("ZZ-lv")>=0) :
             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/ZPowhegDecayer:PhotonGenerator NULL\n";
             process+="set /Herwig/Decays/WDecayer:PhotonGenerator NULL\n";
             process+="set /Herwig/Decays/WPowhegDecayer: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 SubProcess:MatrixElements[0] PowhegMEPP2VV\nset PowhegMEPP2VV:Process ZZ\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()
             
         elif(parameterName.find("W-Z-e")>=0) :
             process+="insert SubProcess:MatrixElements[0] PowhegMEqq2gZ2ff\nset PowhegMEqq2gZ2ff:Process Electron\n"
             process+="insert SubProcess:MatrixElements[0] PowhegMEqq2W2ff\nset PowhegMEqq2W2ff:Process Electron\n"
         elif(parameterName.find("W-Z-mu")>=0) :
             process+="insert SubProcess:MatrixElements[0] MEqq2gZ2ff\nset MEqq2gZ2ff:Process Muon\n"
             process+="insert SubProcess:MatrixElements[0] MEqq2W2ff\nset MEqq2W2ff:Process Muon\n"
         elif(parameterName.find("W-e")>=0) :
             process+="insert SubProcess:MatrixElements[0] PowhegMEqq2W2ff\nset PowhegMEqq2W2ff:Process Electron\n"
         elif(parameterName.find("W-mu")>=0) :
             process+="insert SubProcess:MatrixElements[0] PowhegMEqq2W2ff\nset PowhegMEqq2W2ff:Process Muon\n"
         elif(parameterName.find("Z-e")>=0) :
             process+="insert SubProcess:MatrixElements[0] PowhegMEqq2gZ2ff\nset PowhegMEqq2gZ2ff:Process Electron\n"
         elif(parameterName.find("Z-mu")>=0) :
             process+="insert SubProcess:MatrixElements[0] PowhegMEqq2gZ2ff\nset PowhegMEqq2gZ2ff:Process Muon\n"
         elif(parameterName.find("Z-LowMass-e")>=0) :
             process+="insert SubProcess:MatrixElements[0] PowhegMEqq2gZ2ff\nset PowhegMEqq2gZ2ff:Process Electron\n"
             process+="set /Herwig/Cuts/Cuts:MHatMin 20.*GeV\nset /Herwig/Cuts/MassCut:MinM 20.*GeV\nset /Herwig/Cuts/MassCut:MaxM 70.*GeV\n"
         elif(parameterName.find("Z-MedMass-e")>=0) :
             process+="insert SubProcess:MatrixElements[0] PowhegMEqq2gZ2ff\nset PowhegMEqq2gZ2ff:Process Electron\n"
             process+="set /Herwig/Cuts/Cuts:MHatMin 40.*GeV\nset /Herwig/Cuts/MassCut:MinM 40.*GeV\nset /Herwig/Cuts/MassCut:MaxM 130.*GeV\n"
         elif(parameterName.find("Z-LowMass-mu")>=0) :
             process+="insert SubProcess:MatrixElements[0] PowhegMEqq2gZ2ff\nset PowhegMEqq2gZ2ff:Process Muon\n"
             process+="set /Herwig/Cuts/Cuts:MHatMin 10.*GeV\nset /Herwig/Cuts/MassCut:MinM 10.*GeV\nset /Herwig/Cuts/MassCut:MaxM 70.*GeV\n"
         elif(parameterName.find("Z-Mass1")>=0) :
             process+="set /Herwig/Cuts/Cuts:MHatMin 10.*GeV\n"
             process+="set /Herwig/Cuts/MassCut:MinM 10.*GeV\n"
             process+="set /Herwig/Cuts/MassCut:MaxM 35.*GeV\n"
             if(parameterName.find("-e")>=0) :
                 process+="insert SubProcess:MatrixElements[0] PowhegMEqq2gZ2ff\nset PowhegMEqq2gZ2ff:Process Electron\n"
             else :
                 process+="insert SubProcess:MatrixElements[0] PowhegMEqq2gZ2ff\nset PowhegMEqq2gZ2ff:Process Muon\n"
         elif(parameterName.find("Z-Mass2")>=0) :
             process+="set /Herwig/Cuts/Cuts:MHatMin 25.*GeV\n"
             process+="set /Herwig/Cuts/MassCut:MinM 25.*GeV\n"
             process+="set /Herwig/Cuts/MassCut:MaxM 70.*GeV\n"
             if(parameterName.find("-e")>=0) :
                 process+="insert SubProcess:MatrixElements[0] PowhegMEqq2gZ2ff\nset PowhegMEqq2gZ2ff:Process Electron\n"
             else :
                 process+="insert SubProcess:MatrixElements[0] PowhegMEqq2gZ2ff\nset PowhegMEqq2gZ2ff:Process Muon\n"
         elif(parameterName.find("Z-Mass3")>=0) :
             process+="set /Herwig/Cuts/Cuts:MHatMin 60.*GeV\n"
             process+="set /Herwig/Cuts/MassCut:MinM 60.*GeV\n"
             process+="set /Herwig/Cuts/MassCut:MaxM 120.*GeV\n"
             if(parameterName.find("-e")>=0) :
                 process+="insert SubProcess:MatrixElements[0] PowhegMEqq2gZ2ff\nset PowhegMEqq2gZ2ff:Process Electron\n"
             else :
                 process+="insert SubProcess:MatrixElements[0] PowhegMEqq2gZ2ff\nset PowhegMEqq2gZ2ff:Process Muon\n"
         elif(parameterName.find("Z-Mass4")>=0) :
             process+="set /Herwig/Cuts/Cuts:MHatMin 110.*GeV\n"
             process+="set /Herwig/Cuts/MassCut:MinM 110.*GeV\n"
             process+="set /Herwig/Cuts/MassCut:MaxM 8000.*GeV\n"
             if(parameterName.find("-e")>=0) :
                 process+="insert SubProcess:MatrixElements[0] PowhegMEqq2gZ2ff\nset PowhegMEqq2gZ2ff:Process Electron\n"
             else :
                 process+="insert SubProcess:MatrixElements[0] PowhegMEqq2gZ2ff\nset PowhegMEqq2gZ2ff:Process Muon\n"
         elif(parameterName.find("DiPhoton-GammaGamma")>=0) :
             process+="insert SubProcess:MatrixElements[0] MEGammaGammaPowheg\n"
             process+="set MEGammaGammaPowheg:Process GammaGamma\n"
             process+="insert SubProcess:MatrixElements[0] MEGammaGamma\n"
             process+="set MEGammaGamma:Process gg\n"
             process+="set /Herwig/Cuts/PhotonKtCut:MinKT 5.\n"
             process+="set /Herwig/Cuts/JetKtCut:MinKT 5.\n"
             parameterName=parameterName.replace("-GammaGamma","")
         elif(parameterName.find("DiPhoton-GammaJet")>=0) :
             process+="insert SubProcess:MatrixElements[0] MEGammaGammaPowheg\n"
             process+="set MEGammaGammaPowheg:Process VJet\n"
             process+="set /Herwig/Cuts/PhotonKtCut:MinKT 5.\n"
             process+="set /Herwig/Cuts/JetKtCut:MinKT 5.\n"
             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(parameterName.find("8-VBF")>=0) :
             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(parameterName.find("GammaGamma")>=0) :
                process+=selectDecayMode("h0",["h0->gamma,gamma;"])
                process+=addBRReweighter()
                
         elif(parameterName.find("VBF")>=0) :
             process+=selectDecayMode("h0",["h0->tau-,tau+;"])
             process+=addBRReweighter()
             process+="set /Herwig/Particles/tau-:Stable Stable\n"
             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"
         elif(parameterName.find("ggHJet")>=0) :
             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(parameterName.find("8-ggH")>=0) :
             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(parameterName.find("GammaGamma")>=0) :
                process+=selectDecayMode("h0",["h0->gamma,gamma;"])
                process+=addBRReweighter()
                
         elif(parameterName.find("ggH")>=0) :
             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+=selectDecayMode("h0",["h0->tau-,tau+;"])
             process+=addBRReweighter()
             process+="set /Herwig/Particles/tau-:Stable Stable\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 "+thefactory+":ScaleChoice /Herwig/MatrixElements/Matchbox/Scales/FixedScale\n"
             process+="set /Herwig/MatrixElements/Matchbox/Scales/FixedScale:FixedScale 125.7\n"
         elif(parameterName.find("8-WH")>=0) :
             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(parameterName.find("GammaGamma")>=0) :
                process+=selectDecayMode("h0",["h0->gamma,gamma;"])
                process+=addBRReweighter()
                
         elif(parameterName.find("8-ZH")>=0) :
             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(parameterName.find("GammaGamma")>=0) :
                process+=selectDecayMode("h0",["h0->gamma,gamma;"])
                process+=addBRReweighter()
                
         elif(parameterName.find("WH")>=0) :
             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(parameterName.find("ZH")>=0) :
             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(parameterName.find("UE")>=0) :
             logging.error(" Process %s not supported for Matchbox matrix elements" % name)
             sys.exit(1)
         elif(parameterName.find("7-DiJets")>=0 or parameterName.find("8-DiJets")>=0) :
             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(parameterName.find("-A")>=0) :
                  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(parameterName.find("-B")>=0) :
                  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(parameterName.find("-C")>=0) :
                  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(parameterName.find("DiJets-1")>=0) :
                 process+=addJetPairCut("90")
             elif(parameterName.find("DiJets-2")>=0) :
                 process+=addJetPairCut("200")
             elif(parameterName.find("DiJets-3")>=0) :
                 process+=addJetPairCut("450")
             elif(parameterName.find("DiJets-4")>=0) :
                 process+=addJetPairCut("750")
             elif(parameterName.find("DiJets-5")>=0) :
                 process+=addJetPairCut("950")
             elif(parameterName.find("DiJets-6")>=0) :
                 process+=addJetPairCut("1550")
             elif(parameterName.find("DiJets-7")>=0) :
                 process+=addJetPairCut("2150")
             elif(parameterName.find("DiJets-8")>=0) :
                 process+=addJetPairCut("2750")
             else :
                 logging.error("Exit 00002")
                 sys.exit(1)
 
 
         elif(parameterName.find("7-Jets")>=0 or parameterName.find("8-Jets")>=0 or \
              parameterName.find("13-Jets")>=0) :
             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(parameterName.find("Jets-10")>=0) :
                 process+=addFirstJet("1800")
             elif(parameterName.find("Jets-0")>=0) :
                 process+=addFirstJet("5")
             elif(parameterName.find("Jets-1")>=0) :
                 process+=addFirstJet("10")
             elif(parameterName.find("Jets-2")>=0) :
                 process+=addFirstJet("20")
             elif(parameterName.find("Jets-3")>=0) :
                 process+=addFirstJet("40")
             elif(parameterName.find("Jets-4")>=0) :
                 process+=addFirstJet("70")
             elif(parameterName.find("Jets-5")>=0) :
                 process+=addFirstJet("150")
             elif(parameterName.find("Jets-6")>=0) :
                 process+=addFirstJet("200")
             elif(parameterName.find("Jets-7")>=0) :
                 process+=addFirstJet("300")
             elif(parameterName.find("Jets-8")>=0) :
                 process+=addFirstJet("500")
             elif(parameterName.find("Jets-9")>=0) :
                 process+=addFirstJet("800")
             else :
                 logging.error("Exit 00003")
                 sys.exit(1)
         elif(parameterName.find("7-Charm")>=0 or \
              parameterName.find("7-Bottom")>=0) :
             parameters["bscheme"]=fourFlavour
             process+="set /Herwig/Particles/b:HardProcessMass 4.2*GeV\n"
             process+="set /Herwig/Particles/bbar:HardProcessMass 4.2*GeV\n"
             
             
             if(parameterName.find("7-Bottom")>=0) :
                 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(parameterName.find("-0")>=0) :
                 process+=addFirstJet("0")
             elif(parameterName.find("-1")>=0) :
                 process+=addFirstJet("5")
             elif(parameterName.find("-2")>=0) :
                 process+=addFirstJet("20")
             elif(parameterName.find("-3")>=0) :
                 process+=addFirstJet("50")
             elif(parameterName.find("-4")>=0) :
                 process+=addFirstJet("80")
             elif(parameterName.find("-5")>=0) :
                 process+=addFirstJet("110")
             elif(parameterName.find("-6")>=0) :
                 process+=addFirstJet("30")
                 process+=addSecondJet("25")
                 process+=addJetPairCut("90")
             elif(parameterName.find("-7")>=0) :
                 process+=addFirstJet("30")
                 process+=addSecondJet("25")
                 process+=addJetPairCut("340")
             elif(parameterName.find("-8")>=0) :
                 process+=addFirstJet("30")
                 process+=addSecondJet("25")
                 process+=addJetPairCut("500")
             else :
                 logging.error("Exit 00004")
                 sys.exit(1)
                   
         elif(parameterName.find("Top-L")>=0) :
             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(parameterName.find("Top-SL")>=0) :
             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(parameterName.find("Top-All")>=0) :
             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(parameterName.find("WZ")>=0) :
             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(parameterName.find("WW-emu")>=0) :
             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(parameterName.find("WW-ll")>=0) :
             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(parameterName.find("ZZ-ll")>=0) :
             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(parameterName.find("ZZ-lv")>=0) :
             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(parameterName.find("W-Z-e")>=0) :
             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+="do "+thefactory+":StartParticleGroup epm\n"
               process+="insert "+thefactory+":ParticleGroup 0 /Herwig/Particles/e+\n"
               process+="insert "+thefactory+":ParticleGroup 0 /Herwig/Particles/e-\n"
               process+="do "+thefactory+":EndParticleGroup\n"
               process+="do "+thefactory+":StartParticleGroup epmnu\n"
               process+="insert "+thefactory+":ParticleGroup 0 /Herwig/Particles/e+\n"
               process+="insert "+thefactory+":ParticleGroup 0 /Herwig/Particles/e-\n"
               process+="insert "+thefactory+":ParticleGroup 0 /Herwig/Particles/nu_e\n"
               process+="insert "+thefactory+":ParticleGroup 0 /Herwig/Particles/nu_ebar\n"
               process+="do "+thefactory+":EndParticleGroup\n"
               process+=addProcess(thefactory,"p p epm epmnu","0","2","LeptonPairMassScale",2,2)
             process+=addLeptonPairCut("60","120")
         elif(parameterName.find("W-Z-mu")>=0) :
             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+="do "+thefactory+":StartParticleGroup mupm\n"
               process+="insert "+thefactory+":ParticleGroup 0 /Herwig/Particles/mu+\n"
               process+="insert "+thefactory+":ParticleGroup 0 /Herwig/Particles/mu-\n"
               process+="do "+thefactory+":EndParticleGroup\n"
               process+="do "+thefactory+":StartParticleGroup mupmnu\n"
               process+="insert "+thefactory+":ParticleGroup 0 /Herwig/Particles/mu+\n"
               process+="insert "+thefactory+":ParticleGroup 0 /Herwig/Particles/mu-\n"
               process+="insert "+thefactory+":ParticleGroup 0 /Herwig/Particles/nu_mu\n"
               process+="insert "+thefactory+":ParticleGroup 0 /Herwig/Particles/nu_mubar\n"
               process+="do "+thefactory+":EndParticleGroup\n"
               process+=addProcess(thefactory,"p p mupm mupmnu","0","2","LeptonPairMassScale",2,2)
             process+=addLeptonPairCut("60","120")
         elif(parameterName.find("W-e")>=0) :
             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+="do "+thefactory+":StartParticleGroup epm\n"
                 process+="insert "+thefactory+":ParticleGroup 0 /Herwig/Particles/e+\n"
                 process+="insert "+thefactory+":ParticleGroup 0 /Herwig/Particles/e-\n"
                 process+="do "+thefactory+":EndParticleGroup\n"
                 process+=addProcess(thefactory,"p p epm nu","0","2","LeptonPairMassScale",2,2)
             process+=addLeptonPairCut("60","120")
 
         elif(parameterName.find("W-mu")>=0) :
             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+="do "+thefactory+":StartParticleGroup mupm\n"
                 process+="insert "+thefactory+":ParticleGroup 0 /Herwig/Particles/mu+\n"
                 process+="insert "+thefactory+":ParticleGroup 0 /Herwig/Particles/mu-\n"
                 process+="do "+thefactory+":EndParticleGroup\n"
                 process+=addProcess(thefactory,"p p mupm nu","0","2","LeptonPairMassScale",2,2)
             process+=addLeptonPairCut("60","120")
 
         elif(parameterName.find("Z-e")>=0) :
             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(parameterName.find("Z-mu")>=0) :
             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(parameterName.find("Z-jj")>=0) :
             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(parameterName.find("Z-LowMass-e")>=0) :
             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(parameterName.find("Z-MedMass-e")>=0) :
             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(parameterName.find("Z-LowMass-mu")>=0) :
             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(parameterName.find("Z-Mass1")>=0) :
             process+=addLeptonPairCut("10","35")
             if(parameterName.find("-e")>=0) :
                 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(parameterName.find("Z-Mass2")>=0) :
             process+=addLeptonPairCut("25","70")
             if(parameterName.find("-e")>=0) :
                 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(parameterName.find("Z-Mass3")>=0) :
             process+=addLeptonPairCut("60","120")
             if(parameterName.find("-e")>=0) :
                 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(parameterName.find("Z-Mass4")>=0) :
             process+=addLeptonPairCut("115","8000")
             if(parameterName.find("-e")>=0) :
                 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(parameterName.find("W-Jet")>=0) :
             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(parameterName.find("W-Jet-1-e")>=0) :
                 process+=addFirstJet("100")
                 parameterName=parameterName.replace("W-Jet-1-e","W-Jet-e")
             elif(parameterName.find("W-Jet-2-e")>=0) :
                 process+=addFirstJet("190")
                 parameterName=parameterName.replace("W-Jet-2-e","W-Jet-e")
             elif(parameterName.find("W-Jet-3-e")>=0) :
                 process+=addFirstJet("270")
                 parameterName=parameterName.replace("W-Jet-3-e","W-Jet-e")
             else :
                 logging.error("Exit 00005")
                 sys.exit(1)
         elif(parameterName.find("Z-Jet")>=0) :
             if(simulation=="Merging"):
               logging.warning("Z-Jet not explicitly tested for %s " % simulation)
               sys.exit(0)
             
             
             if(parameterName.find("-e")>=0) :
                 process+=addProcess(thefactory,"p p e+ e- j","1","2","HTScale",0,0)
                 if(parameterName.find("Z-Jet-0-e")>=0) :
                     process+=addFirstJet("35")
                     parameterName=parameterName.replace("Z-Jet-0-e","Z-Jet-e")
                 elif(parameterName.find("Z-Jet-1-e")>=0) :
                     process+=addFirstJet("100")
                     parameterName=parameterName.replace("Z-Jet-1-e","Z-Jet-e")
                 elif(parameterName.find("Z-Jet-2-e")>=0) :
                     process+=addFirstJet("190")
                     parameterName=parameterName.replace("Z-Jet-2-e","Z-Jet-e")
                 elif(parameterName.find("Z-Jet-3-e")>=0) :
                     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(parameterName.find("Z-bb")>=0) :
             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(parameterName.find("Z-b")>=0) :
             if(simulation=="Merging"):
               logging.warning("Z-b not explicitly tested for %s " % simulation)
               sys.exit(0)
             process+="do "+thefactory+":StartParticleGroup bjet\n"
             process+="insert "+thefactory+":ParticleGroup 0 /Herwig/Particles/b\n"
             process+="insert "+thefactory+":ParticleGroup 0 /Herwig/Particles/bbar\n"
             process+="do "+thefactory+":EndParticleGroup\n"
             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(parameterName.find("W-b")>=0) :
             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(parameterName.find("-7-")>=0) :
         process="set /Herwig/Generators/EventGenerator:EventHandler:LuminosityFunction:Energy 7000.0\n"
     elif(parameterName.find("-8-")>=0) :
         process="set /Herwig/Generators/EventGenerator:EventHandler:LuminosityFunction:Energy 8000.0\n"
     else :
         process="set /Herwig/Generators/EventGenerator:EventHandler:LuminosityFunction:Energy 7000.0\n"
     if(simulation=="") :
         if(parameterName.find("7")>=0) :
             process += "insert SubProcess:MatrixElements 0 /Herwig/MatrixElements/MEgg2ff\n"
             process += "set /Herwig/MatrixElements/MEgg2ff:Process Muon\n"
         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,collider+"-"+parameterName+".in")
 parameters['runname'] = name
 parameters['process'] = 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)
 
 # write the file
 
 with open(os.path.join("Rivet",name+".in") ,'w') as f:
         f.write( template.substitute(parameters))
 
 
 
 
 
 
diff --git a/Tests/python/merge-SppS b/Tests/python/merge-SppS
--- a/Tests/python/merge-SppS
+++ b/Tests/python/merge-SppS
@@ -1,163 +1,163 @@
 #! /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","SppS-63-UE.yoda","ISR-30-UE.yoda", \
-           "ISR-53-UE.yoda","SppS-200-UE.yoda","SppS-500-UE.yoda","SppS-900-UE.yoda", \
-           "SppS-546-UE.yoda","SppS-53-UE.yoda"]
+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:
     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(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/UnderlyingEvent/MPIHandler.cc b/UnderlyingEvent/MPIHandler.cc
--- a/UnderlyingEvent/MPIHandler.cc
+++ b/UnderlyingEvent/MPIHandler.cc
@@ -1,841 +1,855 @@
 // -*- C++ -*-
 //
 // MPIHandler.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 MPIHandler class.
 //
 
 #include "MPIHandler.h"
 
 #include "ThePEG/Handlers/StandardXComb.h"
 #include "ThePEG/Handlers/SubProcessHandler.h"
 #include "ThePEG/Interface/ClassDocumentation.h"
 #include "ThePEG/Interface/Parameter.h"
 #include "ThePEG/Interface/Reference.h"
 #include "ThePEG/Interface/RefVector.h"
 #include "ThePEG/Interface/ParVector.h"
 #include "ThePEG/Interface/Switch.h"
 #include "ThePEG/MatrixElement/MEBase.h"
 #include "ThePEG/Handlers/CascadeHandler.h"
 #include "ThePEG/Cuts/Cuts.h"
 #include "ThePEG/Cuts/JetCuts.h"
 #include "ThePEG/Cuts/SimpleKTCut.h"
 #include "ThePEG/PDF/PartonExtractor.h"
 
 #include "gsl/gsl_sf_bessel.h"
 
 #include "ThePEG/Persistency/PersistentOStream.h"
 #include "ThePEG/Persistency/PersistentIStream.h"
 
 using namespace Herwig;
 
 MPIHandler * MPIHandler::currentHandler_ = 0;
 
 bool MPIHandler::beamOK() const {
   return (HadronMatcher::Check(*eventHandler()->incoming().first)  &&
 	  HadronMatcher::Check(*eventHandler()->incoming().second) );
 }
 
 
 tStdXCombPtr MPIHandler::generate(unsigned int sel) {
   //generate a certain process
   if(sel+1 > processHandlers().size())
     throw Exception() << "MPIHandler::generate called with argument out of range"
                       << Exception::runerror;
 
   return processHandlers()[sel]->generate();
 }
 
 IBPtr MPIHandler::clone() const {
   return new_ptr(*this);
 }
 
 IBPtr MPIHandler::fullclone() const {
   return new_ptr(*this);
 }
 
 void MPIHandler::finalize() {
   if( beamOK() ){
     statistics();
   }
 }
 
 void MPIHandler::initialize() {
   currentHandler_ = this;
   useMe();
   theHandler = generator()->currentEventHandler(); 
   //stop if the EventHandler is not present:
   assert(theHandler);
 
   //check if MPI is wanted
   if( !beamOK() ){
     throw Exception()  << "You have requested multiple parton-parton scattering,\n"
 		       << "but the model is not forseen for the beam setup you chose.\n" 
 		       << "You should therefore disable that by setting XXXGenerator:EventHandler:"
 		       << "CascadeHandler:MPIHandler to NULL"
                        << Exception::runerror;
   }
 
   numSubProcs_ = subProcesses().size();
 
   if( numSubProcs_ != cuts().size() ) 
     throw Exception() << "MPIHandler::each SubProcess needs a Cuts Object"
 		      << "ReferenceVectors are not equal in size"
 		      << Exception::runerror;
 
   if( additionalMultiplicities_.size()+1 != numSubProcs_ )
     throw Exception() << "MPIHandler: each additional SubProcess needs "
 		      << "a multiplicity assigned. This can be done in with "
 		      << "insert MPIHandler:additionalMultiplicities 0 1"
 		      << Exception::runerror;
 
   //identicalToUE_ = 0 hard process is identical to ue, -1 no one
   if( identicalToUE_ > (int)numSubProcs_ || identicalToUE_ < -1 )
     throw Exception() << "MPIHandler:identicalToUE has disallowed value"
 		      << Exception::runerror;
 
   // override the cuts for the additional scatters if energyExtrapolation_ is
   // set
   if (energyExtrapolation_ != 0 ) {
     overrideUECuts();
   }
 
   tcPDPtr gluon=getParticleData(ParticleID::g);
   //determine ptmin
   Ptmin_ = cuts()[0]->minKT(gluon);
 
   if(identicalToUE_ == -1){
     algorithm_ = 2;
   }else{
     if(identicalToUE_ == 0){
       //Need to work a bit, in case of LesHouches events for QCD2to2
       Ptr<StandardEventHandler>::pointer eH =
 	dynamic_ptr_cast<Ptr<StandardEventHandler>::pointer>(eventHandler());
 
       if( eH ) {
 	PtOfQCDProc_ = eH->cuts()->minKT(gluon);
 	// find the jet cut in the new style cuts
 	for(unsigned int ix=0;ix<eH->cuts()->multiCuts().size();++ix) {
 	  Ptr<JetCuts>::pointer jetCuts =
 	    dynamic_ptr_cast<Ptr<JetCuts>::pointer>(eH->cuts()->multiCuts()[ix]);
 	  if(jetCuts) {
 	    Energy ptMin=1e30*GeV;
 	    for(unsigned int iy=0;iy<jetCuts->jetRegions().size();++iy) {
 	      ptMin = min(ptMin,jetCuts->jetRegions()[iy]->ptMin());
 	    }
 	    if(ptMin<1e29*GeV&&ptMin>PtOfQCDProc_) PtOfQCDProc_ = ptMin;
 	  }
 	}
       }
       else {
 	if(PtOfQCDProc_ == -1.0*GeV)
 	  throw Exception() << "MPIHandler: You need to specify the pt cutoff "
 			    << "used to in the LesHouches file for QCD2to2 events"
 			    << Exception::runerror;
       }
     }
     else {
       PtOfQCDProc_ = cuts()[identicalToUE_]->minKT(gluon);
     }
 
     if(PtOfQCDProc_ > 2*Ptmin_)
       algorithm_ = 1;
     else
       algorithm_ = 0;
 
     if(PtOfQCDProc_ == ZERO)//pure MinBias mode
       algorithm_ = -1;
   }
 
   //Init all subprocesses
   for(unsigned int i=0; i<numSubProcs_; i++){
     theProcessHandlers.push_back(new_ptr(ProcessHandler()));
     processHandlers().back()->initialize(subProcesses()[i], 
 					 cuts()[i], eventHandler());
     processHandlers().back()->initrun();
   }
 
   //now calculate the individual Probabilities
   XSVector UEXSecs;
   UEXSecs.push_back(processHandlers()[0]->integratedXSec());
   //save the hard cross section
   hardXSec_ = UEXSecs.front();
 
   //determine sigma_soft and beta
   if(softInt_){//check that soft ints are requested
     GSLBisection rootFinder;
 
     if(twoComp_){
       //two component model
       /*
       GSLMultiRoot eqSolver;
       slopeAndTotalXSec eq(this);
       pair<CrossSection, Energy2> res = eqSolver.value(eq, 10*millibarn, 0.6*GeV2);
       softXSec_ = res.first;
       softMu2_ = res.second;
       */
       slopeBisection fs(this);
       try{
 	softMu2_ = rootFinder.value(fs, 0.3*GeV2, 1.*GeV2);
 	softXSec_ = fs.softXSec();
       }catch(GSLBisection::IntervalError){
+        try{
+	// Very low energies (e.g. 200 GeV) need this.
+	// Very high energies (e.g. 100 TeV) produce issues with
+	// this choice. This is a temp. fix.  
+          softMu2_ = rootFinder.value(fs, 0.25*GeV2, 1.3*GeV2);
+          softXSec_ = fs.softXSec();
+        }catch(GSLBisection::IntervalError){
 	throw Exception() <<
-        "\n**********************************************************\n"
-	  "* Inconsistent MPI parameter choice for this beam energy *\n"
+        "\n**********************************************************\n"	  "* Inconsistent MPI parameter choice for this beam energy *\n"
 	  "**********************************************************\n"
 	  "MPIHandler parameter choice is unable to reproduce\n"
 	  "the total cross section. Please check arXiv:0806.2949\n"
 	  "for the allowed parameter space."
 			  << Exception::runerror;
+        }
       }
 
     }else{
       //single component model
       TotalXSecBisection fn(this);
       try{
 	softXSec_ = rootFinder.value(fn, 0*millibarn, 5000*millibarn);
       }catch(GSLBisection::IntervalError){
 	throw Exception() <<
 	"\n**********************************************************\n"
 	  "* Inconsistent MPI parameter choice for this beam energy *\n"
 	  "**********************************************************\n"
 	  "MPIHandler parameter choice is unable to reproduce\n"
 	  "the total cross section. Please check arXiv:0806.2949\n"
 	  "for the allowed parameter space."
 			  << Exception::runerror;      
       }
     }
 
     //now get the differential cross section at ptmin
     ProHdlPtr qcd = new_ptr(ProcessHandler());
     Energy eps = 0.1*GeV;
     Energy ptminPlus = Ptmin_ + eps;
     
     Ptr<SimpleKTCut>::pointer ktCut = new_ptr(SimpleKTCut(ptminPlus));
     ktCut->init();
     ktCut->initrun();
 
     CutsPtr qcdCut = new_ptr(Cuts(2*ptminPlus));
     qcdCut->add(dynamic_ptr_cast<tOneCutPtr>(ktCut));
     qcdCut->init();
     qcdCut->initrun();
       
     qcd->initialize(subProcesses()[0], qcdCut, eventHandler());
     qcd->initrun();
     
     // ds/dp_T^2 = 1/2/p_T ds/dp_T
     DiffXSec hardPlus = (hardXSec_-qcd->integratedXSec())/(2*Ptmin_*eps);
     
     betaBisection fn2(softXSec_, hardPlus, Ptmin_);
     try{
       beta_ = rootFinder.value(fn2, -10/GeV2, 2/GeV2);
     }catch(GSLBisection::IntervalError){
+      try{
+	// Very low energies (e.g. 200 GeV) need this.
+	// Very high energies (e.g. 100 TeV) produce issues with
+	// this choice. This is a temp. fix.
+        beta_ = rootFinder.value(fn2, -5/GeV2, 8./GeV2);
+      }catch(GSLBisection::IntervalError){
       throw Exception() << "MPIHandler: slope of soft pt spectrum couldn't be "
 			<< "determined."
 			<< Exception::runerror;    
+      }
     }
   }
 
   Probs(UEXSecs);
   //MultDistribution("probs.test");
 
   UEXSecs.clear();
 }
 
 void MPIHandler::MultDistribution(string filename) const {
   ofstream file;
   double p(0.0), pold(0.0);
   file.open(filename.c_str());
   //theMultiplicities  
   Selector<MPair>::const_iterator it = theMultiplicities.begin();
 
   while(it != theMultiplicities.end()){
     p = it->first;
     file << it->second.first << " " << it->second.second
 	 << " " << p-pold << '\n';
     it++;
     pold = p;
   }
 
   file << "sum of all probabilities: " << theMultiplicities.sum() 
        << endl;
 
   file.close();
 }
 
 void MPIHandler::statistics() const {
   ostream & file = generator()->misc();
   
   string line = "======================================="
     "=======================================\n";
 
   for(unsigned int i=0; i<cuts().size(); i++){
     Stat tot;
     if(i == 0)
       file << "Statistics for the UE process: \n";
     else
       file << "Statistics for additional hard Process " << i << ": \n";
 
     processHandlers()[i]->statistics(file, tot);
     file << "\n";
   }
 
   if(softInt_){
     file << line
 	 << "Eikonalized and soft cross sections:\n\n"
 	 << "Model parameters:                    "
 	 << "ptmin:   " << Ptmin_/GeV << " GeV"
       	 << ", mu2: " << invRadius_/sqr(1.*GeV) << " GeV2\n"
 	 << "                                     "
 	 << "DL mode: " << DLmode_
 	 << ", CMenergy: " << generator()->maximumCMEnergy()/GeV
 	 << " GeV" << '\n'
 	 << "hard inclusive cross section (mb):   "
 	 << hardXSec_/millibarn << '\n'
 	 << "soft inclusive cross section (mb):   "
 	 << softXSec_/millibarn << '\n'
 	 << "total cross section (mb):            "
 	 << totalXSecExp()/millibarn << '\n'
 	 << "inelastic cross section (mb):        "
 	 << inelXSec_/millibarn << '\n'
 	 << "soft inv radius (GeV2):              "
 	 << softMu2_/GeV2 << '\n'
 	 << "slope of soft pt spectrum (1/GeV2):  "
 	 << beta_*sqr(1.*GeV) << '\n'
 	 << "Average hard multiplicity:           "
 	 << avgNhard_ << '\n'
 	 << "Average soft multiplicity:           "
 	 << avgNsoft_ << '\n' << line << endl;
   }else{
     file << line
 	 << "Eikonalized and soft cross sections:\n\n"
 	 << "Model parameters:                    "
 	 << "ptmin:   " << Ptmin_/GeV << " GeV"
       	 << ", mu2: " << invRadius_/sqr(1.*GeV) << " GeV2\n"
 	 << "                                     "
 	 << ", CMenergy: " << generator()->maximumCMEnergy()/GeV
 	 << " GeV" << '\n'
 	 << "hard inclusive cross section (mb):   "
 	 << hardXSec_/millibarn << '\n'
 	 << "Average hard multiplicity:           "
 	 << avgNhard_ << '\n' << line << endl;
   }
 }
 
 unsigned int MPIHandler::multiplicity(unsigned int sel){
   if(sel==0){//draw from the pretabulated distribution
     MPair m = theMultiplicities.select(UseRandom::rnd());
     softMult_ = m.second;
     return m.first;
   } else{ //fixed multiplicities for the additional hard scatters
     if(additionalMultiplicities_.size() < sel)
       throw Exception() << "MPIHandler::multiplicity: process index "
 			<< "is out of range"
 			<< Exception::runerror;
 
     return additionalMultiplicities_[sel-1];
   }
 }
 
 
 void MPIHandler::Probs(XSVector UEXSecs) {
   GSLIntegrator integrator;
   unsigned int iH(1), iS(0);
   double P(0.0);
   double P0(0.0);//the probability for i hard and zero soft scatters
   Length bmax(500.0*sqrt(millibarn));
   //only one UE process will be drawn from a probability distribution,
   //so check that.
   assert(UEXSecs.size() == 1);
 
   for ( XSVector::const_iterator it = UEXSecs.begin();
         it != UEXSecs.end(); ++it ) {
 
     iH = 0; 
 
     //get the inel xsec
     Eikonalization inelint(this, -1, *it, softXSec_, softMu2_);
     inelXSec_ = integrator.value(inelint, ZERO, bmax);
 
     avgNhard_ = 0.0;
     avgNsoft_ = 0.0;
     bmax = 10.0*sqrt(millibarn);
     do{//loop over hard ints
       if(Algorithm()>-1 && iH==0){
 	iH++;
 	continue;
       }
       iS = 0;
       do{//loop over soft ints
 	if( ( Algorithm() == -1 && iS==0 && iH==0 ) ){
 	  iS++;
 	  continue;
 	}
 
 	Eikonalization integrand(this, iH*100+iS, *it, softXSec_, softMu2_);
       
 	if(Algorithm() > 0){
 	  P = integrator.value(integrand, ZERO, bmax) / *it;
 	}else{
 	  P = integrator.value(integrand, ZERO, bmax) / inelXSec_;
 	}
 	//store the probability
 	if(Algorithm()>-1){
 	  theMultiplicities.insert(P, make_pair(iH-1, iS));
 	  avgNhard_ += P*(iH-1);
 	}else{
 	  theMultiplicities.insert(P, make_pair(iH, iS));
 	  avgNhard_ += P*(iH);
 	}
 	avgNsoft_ += P*iS;
 	if(iS==0)
 	  P0 = P;
 
 	iS++;
       } while ( (iS < maxScatters_) && (iS < 5 || P > 1.e-15 ) && softInt_ );
       iH++;
     } while ( (iH < maxScatters_) && (iH < 5 || P0 > 1.e-15) );
   }
 }
 
 
 // calculate the integrand
 Length Eikonalization::operator() (Length b) const {
   unsigned int Nhard(0), Nsoft(0);
   //fac is just: d^2b=fac*db despite that large number
   Length fac(Constants::twopi*b);
   
   double chiTot(( theHandler->OverlapFunction(b)*hardXSec_ + 
 		  theHandler->OverlapFunction(b, softMu2_)*softXSec_ ) / 2.0);
 
   //total cross section wanted
   if(theoption == -2) return 2 * fac * ( 1 - exp(-chiTot) );
   //inelastic cross section
   if(theoption == -1) return fac * ( 1 - exp(- 2.0 * chiTot) );
 
   if(theoption >= 0){
     //encode multiplicities as: N_hard*100 + N_soft   
     Nhard = theoption/100;
     Nsoft = theoption%100;
 
     if(theHandler->Algorithm() > 0){
       //P_n*sigma_hard: n-1 extra scatters + 1 hard scatterer != hardXSec_
       return fac * Nhard * theHandler->poisson(b, hardXSec_, Nhard) *
 	theHandler->poisson(b, softXSec_, Nsoft, softMu2_);
     }else{
       //P_n*sigma_inel: n extra scatters
       return fac * theHandler->poisson(b, hardXSec_, Nhard) *
 	theHandler->poisson(b, softXSec_, Nsoft, softMu2_);
     }
 
   }else{
     throw Exception() << "Parameter theoption in Struct Eikonalization in " 
 		      << "MPIHandler.cc has not allowed value"
                       << Exception::runerror;
     return 0.0*meter;
   }
 }
 
 InvEnergy2 slopeBisection::operator() (Energy2 softMu2) const {
   GSLBisection root;
   //single component model
   TotalXSecBisection fn(handler_, softMu2);
   try{
     softXSec_ = root.value(fn, 0*millibarn, 5000*millibarn);
   }catch(GSLBisection::IntervalError){
     throw Exception() << "MPIHandler 2-Component model didn't work out."
 		      << Exception::runerror;
   }
   return handler_->slopeDiff(softXSec_, softMu2);
 }
 
 LengthDiff slopeInt::operator() (Length b) const {
   //fac is just: d^2b=fac*db
   Length fac(Constants::twopi*b);
   
   double chiTot(( handler_->OverlapFunction(b)*hardXSec_ + 
 		  handler_->OverlapFunction(b, softMu2_)*softXSec_ ) / 2.0);
 
   InvEnergy2 b2 = sqr(b/hbarc);
   //B*sigma_tot
   return fac * b2 * ( 1 - exp(-chiTot) );
 }
 
 double MPIHandler::factorial (unsigned int n) const {
 
   static double f[] = {1.,1.,2.,6.,24.,120.,720.,5040.,40320.,362880.,3.6288e6,
 		3.99168e7,4.790016e8,6.2270208e9,8.71782912e10,1.307674368e12,
 		2.0922789888e13,3.55687428096e14,6.402373705728e15,1.21645100408832e17,
 		2.43290200817664e18,5.10909421717094e19,1.12400072777761e21,
 		2.5852016738885e22,6.20448401733239e23,1.5511210043331e25,
 		4.03291461126606e26,1.08888694504184e28,3.04888344611714e29,
 		8.8417619937397e30,2.65252859812191e32,8.22283865417792e33,
 		2.63130836933694e35,8.68331761881189e36,2.95232799039604e38,
 		1.03331479663861e40,3.71993326789901e41,1.37637530912263e43,
 		5.23022617466601e44,2.03978820811974e46,8.15915283247898e47,
 		3.34525266131638e49,1.40500611775288e51,6.04152630633738e52,
 		2.65827157478845e54,1.1962222086548e56,5.50262215981209e57,
 		2.58623241511168e59,1.24139155925361e61,6.08281864034268e62,
 		3.04140932017134e64,1.55111875328738e66,8.06581751709439e67,
 		4.27488328406003e69,2.30843697339241e71,1.26964033536583e73,
 		7.10998587804863e74,4.05269195048772e76,2.35056133128288e78,
 		1.3868311854569e80,8.32098711274139e81,5.07580213877225e83,
 		3.14699732603879e85,1.98260831540444e87,1.26886932185884e89,
 		8.24765059208247e90,5.44344939077443e92,3.64711109181887e94,
 		2.48003554243683e96,1.71122452428141e98,1.19785716699699e100,
 		8.50478588567862e101,6.12344583768861e103,4.47011546151268e105,
 		3.30788544151939e107,2.48091408113954e109,1.88549470166605e111,
 		1.45183092028286e113,1.13242811782063e115,8.94618213078298e116,
 		7.15694570462638e118,5.79712602074737e120,4.75364333701284e122,
 		3.94552396972066e124,3.31424013456535e126,2.81710411438055e128,
 		2.42270953836727e130,2.10775729837953e132,1.85482642257398e134,
 		1.65079551609085e136,1.48571596448176e138,1.3520015276784e140,
 		1.24384140546413e142,1.15677250708164e144,1.08736615665674e146,
 		1.03299784882391e148,9.9167793487095e149,9.61927596824821e151,
 		9.42689044888325e153,9.33262154439442e155,9.33262154439442e157};
 
   if(n > maxScatters_) 
         throw Exception() << "MPIHandler::factorial called with too large argument"
                       << Exception::runerror;
   else
     return f[n];
 }
 
 InvArea MPIHandler::OverlapFunction(Length b, Energy2 mu2) const {
   if(mu2 == ZERO)
     mu2 = invRadius_;
 
   InvLength mu = sqrt(mu2)/hbarc;
   return (sqr(mu)/96/Constants::pi)*pow(mu*b, 3)*(gsl_sf_bessel_Kn(3, mu*b));
 }
 
 double MPIHandler::poisson(Length b, CrossSection sigma, unsigned int N, Energy2 mu2) const {
   if(sigma > 0*millibarn){
     return pow(OverlapFunction(b, mu2)*sigma, (double)N)/factorial(N)
       *exp(-OverlapFunction(b, mu2)*sigma);
   }else{
     return (N==0) ? 1.0 : 0.0;
   }
 }
 
 CrossSection MPIHandler::totalXSecDiff(CrossSection softXSec, 
 				       Energy2 softMu2) const {
   GSLIntegrator integrator;
   Eikonalization integrand(this, -2, hardXSec_, softXSec, softMu2);
   Length bmax = 500.0*sqrt(millibarn);
 
   CrossSection tot = integrator.value(integrand, ZERO, bmax);
   return (tot-totalXSecExp());
 }
 
 InvEnergy2 MPIHandler::slopeDiff(CrossSection softXSec, 
 				 Energy2 softMu2) const {
   GSLIntegrator integrator;
   Eikonalization integrand(this, -2, hardXSec_, softXSec, softMu2);
   Length bmax = 500.0*sqrt(millibarn);
 
   CrossSection tot = integrator.value(integrand, ZERO, bmax);
   
   slopeInt integrand2(this, hardXSec_, softXSec, softMu2);
   
   return integrator.value(integrand2, ZERO, bmax)/tot - slopeExp();
 }
 
 CrossSection MPIHandler::totalXSecExp() const {
   if(totalXSecExp_ != 0*millibarn)
     return totalXSecExp_;
 
   double pom_old = 0.0808;
   CrossSection coef_old = 21.7*millibarn;
   double pom_new_hard = 0.452;
   CrossSection coef_new_hard = 0.0139*millibarn;
   double pom_new_soft = 0.0667;
   CrossSection coef_new_soft = 24.22*millibarn;
 
   Energy energy(generator()->maximumCMEnergy());
 
   switch(DLmode_){
   case 1://old DL extrapolation
     return coef_old * pow(energy/GeV, 2*pom_old);
     break;
 
   case 2://old DL extrapolation fixed to CDF
     return 81.8*millibarn * pow(energy/1800.0/GeV, 2*pom_old);
     break;
     
   case 3://new DL extrapolation
     return coef_new_hard * pow(energy/GeV, 2*pom_new_hard) + 
       coef_new_soft * pow(energy/GeV, 2*pom_new_soft);
     break;
     
   default:
     throw Exception() << "MPIHandler::totalXSecExp non-existing mode selected"
                       << Exception::runerror;   
   }
 }
 
 InvEnergy2 MPIHandler::slopeExp() const{
   //Currently return the slope as calculated in the pomeron fit by
   //Donnachie & Landshoff
   Energy energy(generator()->maximumCMEnergy());
   //slope at
   Energy e_0 = 1800*GeV;
   InvEnergy2 b_0 = 17/GeV2;
   return b_0 + log(energy/e_0)/GeV2;
 }
 
 void MPIHandler::overrideUECuts() {
   if(energyExtrapolation_==1)
     Ptmin_ = EEparamA_ * log(generator()->maximumCMEnergy() / EEparamB_);
   else if(energyExtrapolation_==2)
     Ptmin_ = pT0_*pow(double(generator()->maximumCMEnergy()/refScale_),b_);
   else
     assert(false);
   // create a new SimpleKTCut object with the calculated ptmin value
   Ptr<SimpleKTCut>::pointer newUEktCut = new_ptr(SimpleKTCut(Ptmin_));
   newUEktCut->init();
   newUEktCut->initrun();
 
   // create a new Cuts object with MHatMin = 2 * Ptmin_
   CutsPtr newUEcuts = new_ptr(Cuts(2*Ptmin_));
   newUEcuts->add(dynamic_ptr_cast<tOneCutPtr>(newUEktCut));
   newUEcuts->init();
   newUEcuts->initrun();
 
   // replace the old Cuts object
   cuts()[0] = newUEcuts;
 }
 
 void MPIHandler::persistentOutput(PersistentOStream & os) const {
   os << theMultiplicities << theHandler
      << theSubProcesses << theCuts << theProcessHandlers
      << additionalMultiplicities_ << identicalToUE_ 
      << ounit(PtOfQCDProc_, GeV) << ounit(Ptmin_, GeV) 
      << ounit(hardXSec_, millibarn) << ounit(softXSec_, millibarn)
      << ounit(beta_, 1/GeV2)
      << algorithm_ << ounit(invRadius_, GeV2)
      << numSubProcs_ << colourDisrupt_ << softInt_ << twoComp_ 
      << DLmode_ << ounit(totalXSecExp_, millibarn)
      << energyExtrapolation_ << ounit(EEparamA_, GeV) << ounit(EEparamB_, GeV)
      << ounit(refScale_,GeV) << ounit(pT0_,GeV) << b_
      << avgNhard_ << avgNsoft_ << softMult_ 
      << ounit(inelXSec_, millibarn) 
      << ounit(softMu2_, GeV2);
 }
 
 void MPIHandler::persistentInput(PersistentIStream & is, int) {
   is >> theMultiplicities >> theHandler
      >> theSubProcesses >> theCuts >> theProcessHandlers
      >> additionalMultiplicities_ >> identicalToUE_ 
      >> iunit(PtOfQCDProc_, GeV) >> iunit(Ptmin_, GeV)
      >> iunit(hardXSec_, millibarn) >> iunit(softXSec_, millibarn)
      >> iunit(beta_, 1/GeV2)
      >> algorithm_ >> iunit(invRadius_, GeV2)
      >> numSubProcs_ >> colourDisrupt_ >> softInt_ >> twoComp_ 
      >> DLmode_ >> iunit(totalXSecExp_, millibarn)
      >> energyExtrapolation_ >> iunit(EEparamA_, GeV) >> iunit(EEparamB_, GeV)
      >> iunit(refScale_,GeV) >> iunit(pT0_,GeV) >> b_
      >> avgNhard_ >> avgNsoft_ >> softMult_ 
      >> iunit(inelXSec_, millibarn) 
      >> iunit(softMu2_, GeV2);
   currentHandler_ = this;
 }
 
 void MPIHandler::clean() {
   // ThePEG's event handler's usual event cleanup doesn't reach these
   // XCombs. Need to do it by hand here.
   for ( size_t i = 0; i < theSubProcesses.size(); ++i ) {
     theSubProcesses[i]->pExtractor()->lastXCombPtr()->clean();
   }
 }
 
 
 ClassDescription<MPIHandler> MPIHandler::initMPIHandler;
 // Definition of the static class description member.
 
 void MPIHandler::Init() {
 
   static ClassDocumentation<MPIHandler> documentation
     ("The MPIHandler class is the main administrator of the multiple interaction model", 
      "The underlying event was simulated with an eikonal model for multiple partonic interactions."
      "Details can be found in Ref.~\\cite{Bahr:2008dy,Bahr:2009ek}.", 
      "%\\cite{Bahr:2008dy}\n"
      "\\bibitem{Bahr:2008dy}\n"
      "  M.~Bahr, S.~Gieseke and M.~H.~Seymour,\n"
      "  ``Simulation of multiple partonic interactions in Herwig,''\n"
      "  JHEP {\\bf 0807}, 076 (2008)\n"
      "  [arXiv:0803.3633 [hep-ph]].\n"
      "  %%CITATION = JHEPA,0807,076;%%\n"
     "\\bibitem{Bahr:2009ek}\n"
      "  M.~Bahr, J.~M.~Butterworth, S.~Gieseke and M.~H.~Seymour,\n"
      "  ``Soft interactions in Herwig,''\n"
      "  arXiv:0905.4671 [hep-ph].\n"
      "  %%CITATION = ARXIV:0905.4671;%%\n"
      );
   
   static RefVector<MPIHandler,SubProcessHandler> interfaceSubhandlers
     ("SubProcessHandlers",
      "The list of sub-process handlers used in this EventHandler. ",
      &MPIHandler::theSubProcesses, -1, false, false, true, false, false);
 
   static RefVector<MPIHandler,Cuts> interfaceCuts
     ("Cuts",
      "List of cuts used for the corresponding list of subprocesses. These cuts "
      "should not be overidden in individual sub-process handlers.",
      &MPIHandler::theCuts, -1, false, false, true, false, false);
 
   static Parameter<MPIHandler,Energy2> interfaceInvRadius
     ("InvRadius",
      "The inverse hadron radius squared used in the overlap function",
      &MPIHandler::invRadius_, GeV2, 2.0*GeV2, 0.2*GeV2, 4.0*GeV2,
      true, false, Interface::limited);
 
   static ParVector<MPIHandler,int> interfaceadditionalMultiplicities
     ("additionalMultiplicities",
      "specify the multiplicities of secondary hard processes (multiple parton scattering)",
      &MPIHandler::additionalMultiplicities_, 
      -1, 0, 0, 3,
      false, false, true);
 
   static Parameter<MPIHandler,int> interfaceIdenticalToUE
     ("IdenticalToUE",
      "Specify which of the hard processes is identical to the UE one (QCD dijets)",
      &MPIHandler::identicalToUE_, -1, 0, 0,
      false, false, Interface::nolimits);
 
   static Parameter<MPIHandler,Energy> interfacePtOfQCDProc
     ("PtOfQCDProc",
      "Specify the value of the pt cutoff for the process that is identical to the UE one",
      &MPIHandler::PtOfQCDProc_, GeV, -1.0*GeV, ZERO, ZERO,
      false, false, Interface::nolimits);
 
   static Parameter<MPIHandler,double> interfacecolourDisrupt
     ("colourDisrupt",
      "Fraction of connections to additional subprocesses, which are colour disrupted.",
      &MPIHandler::colourDisrupt_, 
      0.0, 0.0, 1.0, 
      false, false, Interface::limited);
 
   
   static Switch<MPIHandler,bool> interfacesoftInt
     ("softInt",
      "Switch to enable soft interactions",
      &MPIHandler::softInt_, true, false, false);
 
   static SwitchOption interfacesoftIntYes
     (interfacesoftInt,
      "Yes",
      "enable the two component model",
      true);
   static SwitchOption interfacesoftIntNo
     (interfacesoftInt,
      "No",
      "disable the model",
      false);
 
 
   static Switch<MPIHandler,unsigned int> interEnergyExtrapolation
     ("EnergyExtrapolation",
      "Switch to ignore the cuts object at MPIHandler:Cuts[0]. "
      "Instead, extrapolate the pt cut.",
      &MPIHandler::energyExtrapolation_, 2, false, false);
   static SwitchOption interEnergyExtrapolationLog
     (interEnergyExtrapolation,
      "Log",
      "Use logarithmic dependence, ptmin = A * log (sqrt(s) / B).",
      1);
   static SwitchOption interEnergyExtrapolationPower
     (interEnergyExtrapolation,
      "Power",
      "Use power law, ptmin = pt_0 * (sqrt(s) / E_0)^b.",
      2);
   static SwitchOption interEnergyExtrapolationNo
     (interEnergyExtrapolation,
      "No",
      "Use manually set value for the minimal pt, "
      "specified in MPIHandler:Cuts[0]:OneCuts[0]:MinKT.",
      0);
 
   static Parameter<MPIHandler,Energy> interfaceEEparamA
     ("EEparamA",
      "Parameter A in the empirical parametrization "
      "ptmin = A * log (sqrt(s) / B)",
      &MPIHandler::EEparamA_, GeV, 0.6*GeV, ZERO, Constants::MaxEnergy,
      false, false, Interface::limited);
 
   static Parameter<MPIHandler,Energy> interfaceEEparamB
     ("EEparamB",
      "Parameter B in the empirical parametrization "
      "ptmin = A * log (sqrt(s) / B)",
      &MPIHandler::EEparamB_, GeV, 39.0*GeV, ZERO, Constants::MaxEnergy,
      false, false, Interface::limited);
 
   static Switch<MPIHandler,bool> interfacetwoComp
     ("twoComp",
      "switch to enable the model with a different radius for soft interactions",
      &MPIHandler::twoComp_, true, false, false);
 
   static SwitchOption interfacetwoCompYes
     (interfacetwoComp,
      "Yes",
      "enable the two component model",
      true);
   static SwitchOption interfacetwoCompNo
     (interfacetwoComp,
      "No",
      "disable the model",
      false);
 
 
   static Parameter<MPIHandler,CrossSection> interfaceMeasuredTotalXSec
     ("MeasuredTotalXSec",
      "Value for the total cross section (assuming rho=0). If non-zero, this "
      "overwrites the Donnachie-Landshoff parametrizations.",
      &MPIHandler::totalXSecExp_, millibarn, 0.0*millibarn, 0.0*millibarn, 0*millibarn,
      false, false, Interface::lowerlim);
 
   
   static Switch<MPIHandler,unsigned int> interfaceDLmode
     ("DLmode",
      "Choice of Donnachie-Landshoff parametrization for the total cross section.",
      &MPIHandler::DLmode_, 2, false, false);
   static SwitchOption interfaceDLmodeStandard
     (interfaceDLmode,
      "Standard",
      "Standard parametrization with s**0.08",
      1);
   static SwitchOption interfaceDLmodeCDF
     (interfaceDLmode,
      "CDF",
      "Standard parametrization but normalization fixed to CDF's measured value",
      2);
   static SwitchOption interfaceDLmodeNew
     (interfaceDLmode,
      "New",
      "Parametrization taking hard and soft pomeron contributions into account",
      3);
 
   static Parameter<MPIHandler,Energy> interfaceReferenceScale
     ("ReferenceScale",
      "The reference energy for power law energy extrapolation of pTmin",
      &MPIHandler::refScale_, GeV, 7000.0*GeV, 0.0*GeV, 20000.*GeV,
      false, false, Interface::limited);
 
   static Parameter<MPIHandler,Energy> interfacepTmin0
     ("pTmin0",
      "The pTmin at the reference scale for power law extrapolation of pTmin.",
      &MPIHandler::pT0_, GeV, 3.11*GeV, 0.0*GeV, 10.0*GeV,
      false, false, Interface::limited);
 
   static Parameter<MPIHandler,double> interfacePower
     ("Power",
      "The power for power law extrapolation of the pTmin cut-off.",
      &MPIHandler::b_, 0.21, 0.0, 10.0,
      false, false, Interface::limited);
 }
diff --git a/UnderlyingEvent/Makefile.am b/UnderlyingEvent/Makefile.am
--- a/UnderlyingEvent/Makefile.am
+++ b/UnderlyingEvent/Makefile.am
@@ -1,15 +1,15 @@
 pkglib_LTLIBRARIES = HwUA5.la
 HwUA5_la_SOURCES = UA5Handler.cc  UA5Handler.h UA5Handler.icc
-HwUA5_la_LDFLAGS= $(AM_LDFLAGS) -module -version-info 5:1:0
+HwUA5_la_LDFLAGS= $(AM_LDFLAGS) -module -version-info 6:0:0
 
 pkglib_LTLIBRARIES += HwMPI.la
 HwMPI_la_SOURCES = MPISampler.cc MPISampler.h MPISampler.icc \
 	MPISampler.fh MPIHandler.cc \
 	MPIHandler.fh MPIHandler.h \
 	ProcessHandler.cc ProcessHandler.icc \
 	ProcessHandler.fh ProcessHandler.h \
 	MPIXSecReweighter.h MPIXSecReweighter.cc \
 	stat.h
-HwMPI_la_LDFLAGS= $(AM_LDFLAGS) -module -version-info 13:0:0
+HwMPI_la_LDFLAGS= $(AM_LDFLAGS) -module -version-info 14:0:0
 HwMPI_la_LIBADD= $(GSLLIBS)
 HwMPI_la_CPPFLAGS= $(AM_CPPFLAGS) $(GSLINCLUDE)
diff --git a/configure.ac b/configure.ac
--- a/configure.ac
+++ b/configure.ac
@@ -1,240 +1,240 @@
 dnl Process this file with autoconf to produce a configure script.
 
 AC_PREREQ([2.63])
-AC_INIT([Herwig],[trunk],[herwig@projects.hepforge.org],[Herwig])
+AC_INIT([Herwig],[devel],[herwig@projects.hepforge.org],[Herwig])
 AC_CONFIG_SRCDIR([Utilities/HerwigStrategy.cc])
 AC_CONFIG_AUX_DIR([Config])
 AC_CONFIG_MACRO_DIR([m4])
 AC_CONFIG_HEADERS([Config/config.h])
 dnl AC_PRESERVE_HELP_ORDER
 AC_CANONICAL_HOST
 
 dnl === disable debug symbols by default =====
 if test "x$CXXFLAGS" = "x"; then
    CXXFLAGS=-O2
 fi
 if test "x$CFLAGS" = "x"; then
    CFLAGS=-O2
 fi
 
 AC_LANG([C++])
 
 AM_INIT_AUTOMAKE([1.11 subdir-objects gnu dist-bzip2 no-dist-gzip -Wall -Wno-portability])
 m4_ifdef([AM_SILENT_RULES], [AM_SILENT_RULES([yes])])
 m4_ifdef([AM_PROG_AR], [AM_PROG_AR])
 
 dnl Checks for C++ compiler. Handle C++11 flags.
 AC_PROG_CXX
 AX_CXX_COMPILE_STDCXX([11],[noext],[mandatory])
 
 dnl check for POSIX
 AC_CHECK_HEADER([unistd.h],[],
       [AC_MSG_ERROR([Herwig needs "unistd.h". Non-POSIX systems are not supported.])])
 
 dnl Checks for programs.
 AC_PROG_INSTALL
 AC_PROG_MAKE_SET
 AC_PROG_LN_S
 
 dnl modified search order
 AC_PROG_FC([gfortran g95 g77]) 
 dnl xlf95 f95 fort ifort ifc efc pgf95 lf95 ftn xlf90 f90 pgf90 pghpf epcf90 xlf f77 frt pgf77 cf77 fort77 fl32 af77])
 AC_LANG_PUSH([Fortran])
 AC_MSG_CHECKING([if the Fortran compiler ($FC) works])
 AC_COMPILE_IFELSE(
    	AC_LANG_PROGRAM([],[      print *[,]"Hello"]),
 	[AC_MSG_RESULT([yes])],
 	[AC_MSG_RESULT([no])
 	 AC_MSG_ERROR([A Fortran compiler is required to build Herwig.])
 	]
 )
 AC_LANG_POP([Fortran])
 
 
 LT_PREREQ([2.2.6])
 LT_INIT([disable-static dlopen pic-only])
 
 dnl ####################################
 dnl ####################################
 
 dnl for Doc/fixinterfaces.pl
 AC_PATH_PROG(PERL, perl)
 
 dnl for Models/Feynrules
 AM_PATH_PYTHON([2.6],, [:])
 AM_CONDITIONAL([HAVE_PYTHON], [test "x$PYTHON" != "x:"])
 
 HERWIG_CHECK_GSL
 
 HERWIG_CHECK_THEPEG
 
 BOOST_REQUIRE([1.41])
 BOOST_FIND_HEADER([boost/numeric/ublas/io.hpp])
 BOOST_FIND_HEADER([boost/numeric/ublas/matrix.hpp])
 BOOST_FIND_HEADER([boost/numeric/ublas/matrix_proxy.hpp])
 BOOST_FIND_HEADER([boost/numeric/ublas/matrix_sparse.hpp])
 BOOST_FIND_HEADER([boost/numeric/ublas/symmetric.hpp])
 BOOST_FIND_HEADER([boost/numeric/ublas/vector.hpp])
 BOOST_FIND_HEADER([boost/operators.hpp])
 BOOST_FIND_HEADER([boost/progress.hpp])
 BOOST_FILESYSTEM([mt])
 BOOST_TEST()
 
 HERWIG_CHECK_VBFNLO
 
 HERWIG_CHECK_NJET
 
 HERWIG_CHECK_GOSAM
 
 HERWIG_CHECK_GOSAM_CONTRIB
 
 HERWIG_CHECK_OPENLOOPS
 
 HERWIG_CHECK_MADGRAPH
 
 HERWIG_CHECK_EVTGEN
 HERWIG_CHECK_PYTHIA
 
 HERWIG_COMPILERFLAGS
 
 HERWIG_LOOPTOOLS
 
 FASTJET_CHECK_FASTJET
 
 HERWIG_ENABLE_MODELS
 
 SHARED_FLAG=-shared
 AM_CONDITIONAL(NEED_APPLE_FIXES,
 		[test "xx${host/darwin/foundit}xx" != "xx${host}xx"])
 if test "xx${host/darwin/foundit}xx" != "xx${host}xx"; then
    APPLE_DSO_FLAGS=-Wl,-undefined,dynamic_lookup
    SHARED_FLAG=-bundle
 fi
 AC_SUBST([APPLE_DSO_FLAGS])
 AC_SUBST([SHARED_FLAG])
 
 AC_CONFIG_FILES([UnderlyingEvent/Makefile
 		Models/Makefile
 		Models/StandardModel/Makefile
 		Models/RSModel/Makefile
 		Models/General/Makefile
 		Models/Susy/Makefile
 		Models/Susy/NMSSM/Makefile
 		Models/Susy/RPV/Makefile
 		Models/UED/Makefile
 		Models/LH/Makefile
 		Models/LHTP/Makefile
 		Models/Transplanckian/Makefile
 		Models/Leptoquarks/Makefile
 		Models/Zprime/Makefile
 		Models/TTbAsymm/Makefile
 		Models/Feynrules/Makefile
 		Models/Feynrules/python/Makefile-FR
 		Models/ADD/Makefile
 		Models/Sextet/Makefile
 		Decay/Makefile
 		Decay/FormFactors/Makefile
 		Decay/Tau/Makefile
 		Decay/Baryon/Makefile
 		Decay/VectorMeson/Makefile
 		Decay/Perturbative/Makefile
 		Decay/ScalarMeson/Makefile
 		Decay/TensorMeson/Makefile
 		Decay/WeakCurrents/Makefile
 		Decay/Partonic/Makefile
 		Decay/General/Makefile	
 		Decay/Radiation/Makefile
 		Decay/EvtGen/Makefile
 		Doc/refman.conf
 		Doc/refman.h
 		PDT/Makefile
 		PDF/Makefile
 		MatrixElement/Makefile
 		MatrixElement/General/Makefile
 		MatrixElement/Lepton/Makefile
 		MatrixElement/Hadron/Makefile
 		MatrixElement/DIS/Makefile
 		MatrixElement/Powheg/Makefile
 		MatrixElement/Gamma/Makefile
 		MatrixElement/Reweighters/Makefile
 		MatrixElement/Matchbox/Makefile
 		MatrixElement/Matchbox/Base/Makefile
 		MatrixElement/Matchbox/Utility/Makefile
 		MatrixElement/Matchbox/Phasespace/Makefile
 		MatrixElement/Matchbox/Dipoles/Makefile
 		MatrixElement/Matchbox/InsertionOperators/Makefile
 		MatrixElement/Matchbox/Matching/Makefile
 		MatrixElement/Matchbox/Cuts/Makefile
 		MatrixElement/Matchbox/Scales/Makefile
 		MatrixElement/Matchbox/ColorFull/Makefile
 		MatrixElement/Matchbox/CVolver/Makefile
 		MatrixElement/Matchbox/Builtin/Makefile
 		MatrixElement/Matchbox/Builtin/Amplitudes/Makefile
 		MatrixElement/Matchbox/Tests/Makefile
 		MatrixElement/Matchbox/External/Makefile
 		MatrixElement/Matchbox/External/BLHAGeneric/Makefile
 		MatrixElement/Matchbox/External/VBFNLO/Makefile
 		MatrixElement/Matchbox/External/NJet/Makefile
 		MatrixElement/Matchbox/External/GoSam/Makefile
 		MatrixElement/Matchbox/External/OpenLoops/Makefile
 		MatrixElement/Matchbox/External/MadGraph/Makefile
 		MatrixElement/Matchbox/External/MadGraph/mg2herwig.py
 		Sampling/Makefile
 		Sampling/CellGrids/Makefile
 		Shower/Makefile
 		Shower/QTilde/Makefile
 		Shower/QTilde/Matching/Makefile
 		Shower/Dipole/Makefile
 		Shower/Dipole/Base/Makefile
 		Shower/Dipole/Kernels/Makefile
 		Shower/Dipole/Kinematics/Makefile
 		Shower/Dipole/Utility/Makefile
 		Shower/Dipole/AlphaS/Makefile
 		Utilities/Makefile
 		Utilities/XML/Makefile
 		Utilities/Statistics/Makefile
 		Hadronization/Makefile
 		lib/Makefile
 		include/Makefile
 		src/Makefile
 		src/defaults/Makefile
 		src/snippets/Makefile
 		src/Matchbox/Makefile
 		src/herwig-config
 		Doc/Makefile
 		Doc/HerwigDefaults.in
 		Looptools/Makefile
 		Analysis/Makefile
 		API/Makefile
 		src/Makefile-UserModules
 		src/defaults/Analysis.in
 		src/defaults/MatchboxDefaults.in
 		src/defaults/Decays.in
 		src/defaults/decayers.in
 		src/defaults/setup.gosam.in
 		src/Matchbox/LO-DefaultShower.in
 		src/Matchbox/LO-DipoleShower.in
 		src/Matchbox/MCatLO-DefaultShower.in
 		src/Matchbox/MCatLO-DipoleShower.in
 		src/Matchbox/LO-NoShower.in
 		src/Matchbox/MCatNLO-DefaultShower.in
 		src/Matchbox/MCatNLO-DipoleShower.in
 		src/Matchbox/NLO-NoShower.in
 		src/Matchbox/Powheg-DefaultShower.in
 		src/Matchbox/Powheg-DipoleShower.in
 		src/Merging/Makefile
 		Shower/Dipole/Merging/Makefile
 		src/defaults/MatchboxMergingDefaults.in
 		Contrib/Makefile
 		Contrib/make_makefiles.sh
 		Tests/Makefile
 		Makefile])
 
 AC_CONFIG_LINKS([Doc/BSMlibs.in:Doc/BSMlibs.in])
 AC_CONFIG_FILES([Doc/fixinterfaces.pl],[chmod +x Doc/fixinterfaces.pl])
 
 HERWIG_OVERVIEW
 
 AC_CONFIG_COMMANDS([summary],[cat config.herwig])
 
 AC_OUTPUT
diff --git a/lib/Makefile.am b/lib/Makefile.am
--- a/lib/Makefile.am
+++ b/lib/Makefile.am
@@ -1,49 +1,49 @@
 pkglib_LTLIBRARIES = Herwig.la
 Herwig_la_SOURCES =
 Herwig_la_LIBTOOLFLAGS = --tag=CXX
-Herwig_la_LDFLAGS = $(AM_LDFLAGS) -module -version-info 20:0:0
+Herwig_la_LDFLAGS = $(AM_LDFLAGS) -module -version-info 21:0:0
 Herwig_la_LDFLAGS += $(THEPEGLDFLAGS) $(BOOST_SYSTEM_LDFLAGS) $(BOOST_FILESYSTEM_LDFLAGS) $(FCLIBS)
 Herwig_la_LIBADD = \
 $(top_builddir)/Hadronization/libHwHadronization.la \
 $(top_builddir)/Models/libHwStandardModel.la \
 $(top_builddir)/Decay/libHwDecay.la \
 $(top_builddir)/Decay/libHwFormFactor.la \
 $(top_builddir)/Decay/libHwDecRad.la \
 $(top_builddir)/Utilities/libHwUtils.la \
 $(top_builddir)/Models/libHwModelGenerator.la \
 $(top_builddir)/Decay/General/libHwGeneralDecay.la \
 $(top_builddir)/MatrixElement/General/libHwGeneralME.la \
 $(top_builddir)/MatrixElement/libHwME.la \
 $(top_builddir)/MatrixElement/Reweighters/libHwReweighters.la \
 $(top_builddir)/MatrixElement/Matchbox/libHwMatchbox.la \
 $(top_builddir)/Decay/libHwWeakCurrent.la \
 $(top_builddir)/Looptools/libHwLooptools.la \
 $(top_builddir)/Shower/libHwShower.la \
 $(THEPEGLIB) $(BOOST_SYSTEM_LIBS) $(BOOST_FILESYSTEM_LIBS) -ldl
 
 dist_noinst_SCRIPTS = fix-osx-path
 
 
 POSTPROCESSING = done-all-links
 
 if NEED_APPLE_FIXES
 POSTPROCESSING += apple-fixes
 endif
 
 
 
 all-local: $(POSTPROCESSING)
 
 done-all-links: Herwig.la
 	find $(top_builddir) \( -name '*.so.*' -or -name '*.so' \) \
   -not -name 'lib*' -not -path '$(top_builddir)/lib/*' \
   -not -path '$(top_builddir)/.hg/*' -exec $(LN_S) -f \{\} \;
 	$(LN_S) -f .libs/Herwig*so* .
 	echo "stamp" > $@
 
 apple-fixes: fix-osx-path done-all-links
 	./$<
 	echo "stamp" > $@
 
 clean-local:
 	rm -f *.so *.so.* done-all-links apple-fixes
diff --git a/m4/ax_compare_version.m4 b/m4/ax_compare_version.m4
new file mode 100644
--- /dev/null
+++ b/m4/ax_compare_version.m4
@@ -0,0 +1,177 @@
+# ===========================================================================
+#    https://www.gnu.org/software/autoconf-archive/ax_compare_version.html
+# ===========================================================================
+#
+# SYNOPSIS
+#
+#   AX_COMPARE_VERSION(VERSION_A, OP, VERSION_B, [ACTION-IF-TRUE], [ACTION-IF-FALSE])
+#
+# DESCRIPTION
+#
+#   This macro compares two version strings. Due to the various number of
+#   minor-version numbers that can exist, and the fact that string
+#   comparisons are not compatible with numeric comparisons, this is not
+#   necessarily trivial to do in a autoconf script. This macro makes doing
+#   these comparisons easy.
+#
+#   The six basic comparisons are available, as well as checking equality
+#   limited to a certain number of minor-version levels.
+#
+#   The operator OP determines what type of comparison to do, and can be one
+#   of:
+#
+#    eq  - equal (test A == B)
+#    ne  - not equal (test A != B)
+#    le  - less than or equal (test A <= B)
+#    ge  - greater than or equal (test A >= B)
+#    lt  - less than (test A < B)
+#    gt  - greater than (test A > B)
+#
+#   Additionally, the eq and ne operator can have a number after it to limit
+#   the test to that number of minor versions.
+#
+#    eq0 - equal up to the length of the shorter version
+#    ne0 - not equal up to the length of the shorter version
+#    eqN - equal up to N sub-version levels
+#    neN - not equal up to N sub-version levels
+#
+#   When the condition is true, shell commands ACTION-IF-TRUE are run,
+#   otherwise shell commands ACTION-IF-FALSE are run. The environment
+#   variable 'ax_compare_version' is always set to either 'true' or 'false'
+#   as well.
+#
+#   Examples:
+#
+#     AX_COMPARE_VERSION([3.15.7],[lt],[3.15.8])
+#     AX_COMPARE_VERSION([3.15],[lt],[3.15.8])
+#
+#   would both be true.
+#
+#     AX_COMPARE_VERSION([3.15.7],[eq],[3.15.8])
+#     AX_COMPARE_VERSION([3.15],[gt],[3.15.8])
+#
+#   would both be false.
+#
+#     AX_COMPARE_VERSION([3.15.7],[eq2],[3.15.8])
+#
+#   would be true because it is only comparing two minor versions.
+#
+#     AX_COMPARE_VERSION([3.15.7],[eq0],[3.15])
+#
+#   would be true because it is only comparing the lesser number of minor
+#   versions of the two values.
+#
+#   Note: The characters that separate the version numbers do not matter. An
+#   empty string is the same as version 0. OP is evaluated by autoconf, not
+#   configure, so must be a string, not a variable.
+#
+#   The author would like to acknowledge Guido Draheim whose advice about
+#   the m4_case and m4_ifvaln functions make this macro only include the
+#   portions necessary to perform the specific comparison specified by the
+#   OP argument in the final configure script.
+#
+# LICENSE
+#
+#   Copyright (c) 2008 Tim Toolan <toolan@ele.uri.edu>
+#
+#   Copying and distribution of this file, with or without modification, are
+#   permitted in any medium without royalty provided the copyright notice
+#   and this notice are preserved. This file is offered as-is, without any
+#   warranty.
+
+#serial 12
+
+dnl #########################################################################
+AC_DEFUN([AX_COMPARE_VERSION], [
+  AC_REQUIRE([AC_PROG_AWK])
+
+  # Used to indicate true or false condition
+  ax_compare_version=false
+
+  # Convert the two version strings to be compared into a format that
+  # allows a simple string comparison.  The end result is that a version
+  # string of the form 1.12.5-r617 will be converted to the form
+  # 0001001200050617.  In other words, each number is zero padded to four
+  # digits, and non digits are removed.
+  AS_VAR_PUSHDEF([A],[ax_compare_version_A])
+  A=`echo "$1" | sed -e 's/\([[0-9]]*\)/Z\1Z/g' \
+                     -e 's/Z\([[0-9]]\)Z/Z0\1Z/g' \
+                     -e 's/Z\([[0-9]][[0-9]]\)Z/Z0\1Z/g' \
+                     -e 's/Z\([[0-9]][[0-9]][[0-9]]\)Z/Z0\1Z/g' \
+                     -e 's/[[^0-9]]//g'`
+
+  AS_VAR_PUSHDEF([B],[ax_compare_version_B])
+  B=`echo "$3" | sed -e 's/\([[0-9]]*\)/Z\1Z/g' \
+                     -e 's/Z\([[0-9]]\)Z/Z0\1Z/g' \
+                     -e 's/Z\([[0-9]][[0-9]]\)Z/Z0\1Z/g' \
+                     -e 's/Z\([[0-9]][[0-9]][[0-9]]\)Z/Z0\1Z/g' \
+                     -e 's/[[^0-9]]//g'`
+
+  dnl # In the case of le, ge, lt, and gt, the strings are sorted as necessary
+  dnl # then the first line is used to determine if the condition is true.
+  dnl # The sed right after the echo is to remove any indented white space.
+  m4_case(m4_tolower($2),
+  [lt],[
+    ax_compare_version=`echo "x$A
+x$B" | sed 's/^ *//' | sort -r | sed "s/x${A}/false/;s/x${B}/true/;1q"`
+  ],
+  [gt],[
+    ax_compare_version=`echo "x$A
+x$B" | sed 's/^ *//' | sort | sed "s/x${A}/false/;s/x${B}/true/;1q"`
+  ],
+  [le],[
+    ax_compare_version=`echo "x$A
+x$B" | sed 's/^ *//' | sort | sed "s/x${A}/true/;s/x${B}/false/;1q"`
+  ],
+  [ge],[
+    ax_compare_version=`echo "x$A
+x$B" | sed 's/^ *//' | sort -r | sed "s/x${A}/true/;s/x${B}/false/;1q"`
+  ],[
+    dnl Split the operator from the subversion count if present.
+    m4_bmatch(m4_substr($2,2),
+    [0],[
+      # A count of zero means use the length of the shorter version.
+      # Determine the number of characters in A and B.
+      ax_compare_version_len_A=`echo "$A" | $AWK '{print(length)}'`
+      ax_compare_version_len_B=`echo "$B" | $AWK '{print(length)}'`
+
+      # Set A to no more than B's length and B to no more than A's length.
+      A=`echo "$A" | sed "s/\(.\{$ax_compare_version_len_B\}\).*/\1/"`
+      B=`echo "$B" | sed "s/\(.\{$ax_compare_version_len_A\}\).*/\1/"`
+    ],
+    [[0-9]+],[
+      # A count greater than zero means use only that many subversions
+      A=`echo "$A" | sed "s/\(\([[0-9]]\{4\}\)\{m4_substr($2,2)\}\).*/\1/"`
+      B=`echo "$B" | sed "s/\(\([[0-9]]\{4\}\)\{m4_substr($2,2)\}\).*/\1/"`
+    ],
+    [.+],[
+      AC_WARNING(
+        [illegal OP numeric parameter: $2])
+    ],[])
+
+    # Pad zeros at end of numbers to make same length.
+    ax_compare_version_tmp_A="$A`echo $B | sed 's/./0/g'`"
+    B="$B`echo $A | sed 's/./0/g'`"
+    A="$ax_compare_version_tmp_A"
+
+    # Check for equality or inequality as necessary.
+    m4_case(m4_tolower(m4_substr($2,0,2)),
+    [eq],[
+      test "x$A" = "x$B" && ax_compare_version=true
+    ],
+    [ne],[
+      test "x$A" != "x$B" && ax_compare_version=true
+    ],[
+      AC_WARNING([illegal OP parameter: $2])
+    ])
+  ])
+
+  AS_VAR_POPDEF([A])dnl
+  AS_VAR_POPDEF([B])dnl
+
+  dnl # Execute ACTION-IF-TRUE / ACTION-IF-FALSE.
+  if test "$ax_compare_version" = "true" ; then
+    m4_ifvaln([$4],[$4],[:])dnl
+    m4_ifvaln([$5],[else $5])dnl
+  fi
+]) dnl AX_COMPARE_VERSION
diff --git a/m4/boost.m4 b/m4/boost.m4
--- a/m4/boost.m4
+++ b/m4/boost.m4
@@ -1,1576 +1,1578 @@
 # boost.m4: Locate Boost headers and libraries for autoconf-based projects.
 # Copyright (C) 2007-2011, 2014  Benoit Sigoure <tsuna@lrde.epita.fr>
 #
 # This program is free software: you can redistribute it and/or modify
 # it under the terms of the GNU General Public License as published by
 # the Free Software Foundation, either version 3 of the License, or
 # (at your option) any later version.
 #
 # Additional permission under section 7 of the GNU General Public
 # License, version 3 ("GPLv3"):
 #
 # If you convey this file as part of a work that contains a
 # configuration script generated by Autoconf, you may do so under
 # terms of your choice.
 #
 # This program is distributed in the hope that it will be useful,
 # but WITHOUT ANY WARRANTY; without even the implied warranty of
 # MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
 # GNU General Public License for more details.
 #
 # You should have received a copy of the GNU General Public License
 # along with this program.  If not, see <http://www.gnu.org/licenses/>.
 
 m4_define([_BOOST_SERIAL], [m4_translit([
 # serial 26
 ], [#
 ], [])])
 
 # Original sources can be found at http://github.com/tsuna/boost.m4
 # You can fetch the latest version of the script by doing:
 #   wget http://github.com/tsuna/boost.m4/raw/master/build-aux/boost.m4
 
 # ------ #
 # README #
 # ------ #
 
 # This file provides several macros to use the various Boost libraries.
 # The first macro is BOOST_REQUIRE.  It will simply check if it's possible to
 # find the Boost headers of a given (optional) minimum version and it will
 # define BOOST_CPPFLAGS accordingly.  It will add an option --with-boost to
 # your configure so that users can specify non standard locations.
 # If the user's environment contains BOOST_ROOT and --with-boost was not
 # specified, --with-boost=$BOOST_ROOT is implicitly used.
 # For more README and documentation, go to http://github.com/tsuna/boost.m4
 # Note: THESE MACROS ASSUME THAT YOU USE LIBTOOL.  If you don't, don't worry,
 # simply read the README, it will show you what to do step by step.
 
 m4_pattern_forbid([^_?(BOOST|Boost)_])
 
 
 # _BOOST_SED_CPP(SED-PROGRAM, PROGRAM,
 #                [ACTION-IF-FOUND], [ACTION-IF-NOT-FOUND])
 # --------------------------------------------------------
 # Same as AC_EGREP_CPP, but leave the result in conftest.i.
 #
 # SED-PROGRAM is *not* overquoted, as in AC_EGREP_CPP.  It is expanded
 # in double-quotes, so escape your double quotes.
 #
 # It could be useful to turn this into a macro which extracts the
 # value of any macro.
 m4_define([_BOOST_SED_CPP],
 [AC_LANG_PUSH([C++])dnl
 AC_LANG_PREPROC_REQUIRE()dnl
 AC_REQUIRE([AC_PROG_SED])dnl
 AC_LANG_CONFTEST([AC_LANG_SOURCE([[$2]])])
 AS_IF([dnl eval is necessary to expand ac_cpp.
 dnl Ultrix and Pyramid sh refuse to redirect output of eval, so use subshell.
 dnl Beware of Windows end-of-lines, for instance if we are running
 dnl some Windows programs under Wine.  In that case, boost/version.hpp
 dnl is certainly using "\r\n", but the regular Unix shell will only
 dnl strip `\n' with backquotes, not the `\r'.  This results in
 dnl boost_cv_lib_version='1_37\r' for instance, which breaks
 dnl everything else.
 dnl Cannot use 'dnl' after [$4] because a trailing dnl may break AC_CACHE_CHECK
 dnl
 dnl Beware that GCC 5, when expanding macros, may embed # line directives
 dnl a within single line:
 dnl
 dnl # 1 "conftest.cc"
 dnl # 1 "<built-in>"
 dnl # 1 "<command-line>"
 dnl # 1 "conftest.cc"
 dnl # 1 "/opt/local/include/boost/version.hpp" 1 3
 dnl # 2 "conftest.cc" 2
 dnl boost-lib-version =
 dnl # 2 "conftest.cc" 3
 dnl                    "1_56"
 dnl
 dnl So get rid of the # and empty lines, and glue the remaining ones together.
 (eval "$ac_cpp conftest.$ac_ext") 2>&AS_MESSAGE_LOG_FD |
   grep -v '#' |
   grep -v '^[[[:space:]]]*$' |
   tr -d '\r' |
   tr -s '\n' ' ' |
   $SED -n -e "$1" >conftest.i 2>&1],
   [$3],
   [$4])
 rm -rf conftest*
 AC_LANG_POP([C++])dnl
 ])# _BOOST_SED_CPP
 
 
 
 # BOOST_REQUIRE([VERSION], [ACTION-IF-NOT-FOUND])
 # -----------------------------------------------
 # Look for Boost.  If version is given, it must either be a literal of the form
 # "X.Y.Z" where X, Y and Z are integers (the ".Z" part being optional) or a
 # variable "$var".
 # Defines the value BOOST_CPPFLAGS.  This macro only checks for headers with
 # the required version, it does not check for any of the Boost libraries.
 # On # success, defines HAVE_BOOST.  On failure, calls the optional
 # ACTION-IF-NOT-FOUND action if one was supplied.
 # Otherwise aborts with an error message.
 AC_DEFUN_ONCE([BOOST_REQUIRE],
 [AC_REQUIRE([AC_PROG_CXX])dnl
 AC_REQUIRE([AC_PROG_GREP])dnl
 echo "$as_me: this is boost.m4[]_BOOST_SERIAL" >&AS_MESSAGE_LOG_FD
 boost_save_IFS=$IFS
 boost_version_req=$1
 IFS=.
 set x $boost_version_req 0 0 0
 IFS=$boost_save_IFS
 shift
 boost_version_req=`expr "$[1]" '*' 100000 + "$[2]" '*' 100 + "$[3]"`
 boost_version_req_string=$[1].$[2].$[3]
 AC_ARG_WITH([boost],
    [AS_HELP_STRING([--with-boost=DIR],
                    [prefix of Boost $1 @<:@guess@:>@])])dnl
 AC_ARG_VAR([BOOST_ROOT],[Location of Boost installation])dnl
 # If BOOST_ROOT is set and the user has not provided a value to
 # --with-boost, then treat BOOST_ROOT as if it the user supplied it.
 if test x"$BOOST_ROOT" != x; then
   if test x"$with_boost" = x; then
     AC_MSG_NOTICE([Detected BOOST_ROOT; continuing with --with-boost=$BOOST_ROOT])
     with_boost=$BOOST_ROOT
   else
     AC_MSG_NOTICE([Detected BOOST_ROOT=$BOOST_ROOT, but overridden by --with-boost=$with_boost])
   fi
 fi
 dnl AC_SUBST([DISTCHECK_CONFIGURE_FLAGS],
 dnl          ["$DISTCHECK_CONFIGURE_FLAGS '--with-boost=$with_boost'"])dnl
 boost_save_CPPFLAGS=$CPPFLAGS
   AC_CACHE_CHECK([for Boost headers version >= $boost_version_req_string],
     [boost_cv_inc_path],
     [boost_cv_inc_path=no
 AC_LANG_PUSH([C++])dnl
 m4_pattern_allow([^BOOST_VERSION$])dnl
     AC_LANG_CONFTEST([AC_LANG_PROGRAM([[#include <boost/version.hpp>
 #if !defined BOOST_VERSION
 # error BOOST_VERSION is not defined
 #elif BOOST_VERSION < $boost_version_req
 # error Boost headers version < $boost_version_req
 #endif
 ]])])
     # If the user provided a value to --with-boost, use it and only it.
     case $with_boost in #(
       ''|yes) set x '' /opt/local/include /usr/local/include /opt/include \
                  /usr/include C:/Boost/include;; #(
       *)      set x "$with_boost/include" "$with_boost";;
     esac
     shift
     for boost_dir
     do
     # Without --layout=system, Boost (or at least some versions) installs
     # itself in <prefix>/include/boost-<version>.  This inner loop helps to
     # find headers in such directories.
     #
     # Any ${boost_dir}/boost-x_xx directories are searched in reverse version
     # order followed by ${boost_dir}.  The final '.' is a sentinel for
     # searching $boost_dir" itself.  Entries are whitespace separated.
     #
     # I didn't indent this loop on purpose (to avoid over-indented code)
     boost_layout_system_search_list=`cd "$boost_dir" 2>/dev/null \
         && ls -1 | "${GREP}" '^boost-' | sort -rn -t- -k2 \
         && echo .`
     for boost_inc in $boost_layout_system_search_list
     do
       if test x"$boost_inc" != x.; then
         boost_inc="$boost_dir/$boost_inc"
       else
         boost_inc="$boost_dir" # Uses sentinel in boost_layout_system_search_list
       fi
       if test x"$boost_inc" != x; then
         # We are going to check whether the version of Boost installed
         # in $boost_inc is usable by running a compilation that
         # #includes it.  But if we pass a -I/some/path in which Boost
         # is not installed, the compiler will just skip this -I and
         # use other locations (either from CPPFLAGS, or from its list
         # of system include directories).  As a result we would use
         # header installed on the machine instead of the /some/path
         # specified by the user.  So in that precise case (trying
         # $boost_inc), make sure the version.hpp exists.
         #
         # Use test -e as there can be symlinks.
         test -e "$boost_inc/boost/version.hpp" || continue
         CPPFLAGS="$CPPFLAGS -I$boost_inc"
       fi
       AC_COMPILE_IFELSE([], [boost_cv_inc_path=yes], [boost_cv_version=no])
       if test x"$boost_cv_inc_path" = xyes; then
         if test x"$boost_inc" != x; then
           boost_cv_inc_path=$boost_inc
         fi
         break 2
       fi
     done
     done
 AC_LANG_POP([C++])dnl
     ])
     case $boost_cv_inc_path in #(
       no)
         boost_errmsg="cannot find Boost headers version >= $boost_version_req_string"
         m4_if([$2], [],  [AC_MSG_ERROR([$boost_errmsg])],
                         [AC_MSG_NOTICE([$boost_errmsg])])
         $2
         ;;#(
       yes)
         BOOST_CPPFLAGS=
         ;;#(
       *)
         AC_SUBST([BOOST_CPPFLAGS], ["-I$boost_cv_inc_path"])dnl
         ;;
     esac
   if test x"$boost_cv_inc_path" != xno; then
   AC_DEFINE([HAVE_BOOST], [1],
             [Defined if the requested minimum BOOST version is satisfied])
   AC_CACHE_CHECK([for Boost's header version],
     [boost_cv_lib_version],
     [m4_pattern_allow([^BOOST_LIB_VERSION$])dnl
      _BOOST_SED_CPP([[/^boost-lib-version = /{s///;s/[\" ]//g;p;q;}]],
                     [#include <boost/version.hpp>
 boost-lib-version = BOOST_LIB_VERSION],
     [boost_cv_lib_version=`cat conftest.i`])])
     # e.g. "134" for 1_34_1 or "135" for 1_35
     boost_major_version=`echo "$boost_cv_lib_version" | sed 's/_//;s/_.*//'`
     case $boost_major_version in #(
       '' | *[[!0-9]]*)
         AC_MSG_ERROR([invalid value: boost_major_version='$boost_major_version'])
         ;;
     esac
 fi
 CPPFLAGS=$boost_save_CPPFLAGS
 ])# BOOST_REQUIRE
 
 
 # BOOST_STATIC()
 # --------------
 # Add the "--enable-static-boost" configure argument. If this argument is given
 # on the command line, static versions of the libraries will be looked up.
 AC_DEFUN([BOOST_STATIC],
   [AC_ARG_ENABLE([static-boost],
      [AS_HELP_STRING([--enable-static-boost],
                [Prefer the static boost libraries over the shared ones [no]])],
      [enable_static_boost=yes],
      [enable_static_boost=no])])# BOOST_STATIC
 
 
 # BOOST_FIND_HEADER([HEADER-NAME], [ACTION-IF-NOT-FOUND], [ACTION-IF-FOUND])
 # --------------------------------------------------------------------------
 # Wrapper around AC_CHECK_HEADER for Boost headers.  Useful to check for
 # some parts of the Boost library which are only made of headers and don't
 # require linking (such as Boost.Foreach).
 #
 # Default ACTION-IF-NOT-FOUND: Fail with a fatal error unless Boost couldn't be
 # found in the first place, in which case by default a notice is issued to the
 # user.  Presumably if we haven't died already it's because it's OK to not have
 # Boost, which is why only a notice is issued instead of a hard error.
 #
 # Default ACTION-IF-FOUND: define the preprocessor symbol HAVE_<HEADER-NAME> in
 # case of success # (where HEADER-NAME is written LIKE_THIS, e.g.,
 # HAVE_BOOST_FOREACH_HPP).
 AC_DEFUN([BOOST_FIND_HEADER],
 [AC_REQUIRE([BOOST_REQUIRE])dnl
 if test x"$boost_cv_inc_path" = xno; then
   m4_default([$2], [AC_MSG_NOTICE([Boost not available, not searching for $1])])
 else
 AC_LANG_PUSH([C++])dnl
 boost_save_CPPFLAGS=$CPPFLAGS
 CPPFLAGS="$CPPFLAGS $BOOST_CPPFLAGS"
 AC_CHECK_HEADER([$1],
   [m4_default([$3], [AC_DEFINE(AS_TR_CPP([HAVE_$1]), [1],
                                [Define to 1 if you have <$1>])])],
   [m4_default([$2], [AC_MSG_ERROR([cannot find $1])])])
 CPPFLAGS=$boost_save_CPPFLAGS
 AC_LANG_POP([C++])dnl
 fi
 ])# BOOST_FIND_HEADER
 
 
 # BOOST_FIND_LIBS([COMPONENT-NAME], [CANDIDATE-LIB-NAMES],
 #                 [PREFERRED-RT-OPT], [HEADER-NAME], [CXX-TEST],
 #                 [CXX-PROLOGUE])
 # --------------------------------------------------------------
 # Look for the Boost library COMPONENT-NAME (e.g., `thread', for
 # libboost_thread) under the possible CANDIDATE-LIB-NAMES (e.g.,
 # "thread_win32 thread").  Check that HEADER-NAME works and check that
 # libboost_LIB-NAME can link with the code CXX-TEST.  The optional
 # argument CXX-PROLOGUE can be used to include some C++ code before
 # the `main' function.
 #
 # Invokes BOOST_FIND_HEADER([HEADER-NAME]) (see above).
 #
 # Boost libraries typically come compiled with several flavors (with different
 # runtime options) so PREFERRED-RT-OPT is the preferred suffix.  A suffix is one
 # or more of the following letters: sgdpn (in that order).  s = static
 # runtime, d = debug build, g = debug/diagnostic runtime, p = STLPort build,
 # n = (unsure) STLPort build without iostreams from STLPort (it looks like `n'
 # must always be used along with `p').  Additionally, PREFERRED-RT-OPT can
 # start with `mt-' to indicate that there is a preference for multi-thread
 # builds.  Some sample values for PREFERRED-RT-OPT: (nothing), mt, d, mt-d, gdp
 # ...  If you want to make sure you have a specific version of Boost
 # (eg, >= 1.33) you *must* invoke BOOST_REQUIRE before this macro.
 AC_DEFUN([BOOST_FIND_LIBS],
 [AC_REQUIRE([BOOST_REQUIRE])dnl
 AC_REQUIRE([_BOOST_FIND_COMPILER_TAG])dnl
 AC_REQUIRE([BOOST_STATIC])dnl
 AC_REQUIRE([_BOOST_GUESS_WHETHER_TO_USE_MT])dnl
 if test x"$boost_cv_inc_path" = xno; then
   AC_MSG_NOTICE([Boost not available, not searching for the Boost $1 library])
 else
 dnl The else branch is huge and wasn't intended on purpose.
 AC_LANG_PUSH([C++])dnl
 AS_VAR_PUSHDEF([Boost_lib], [boost_cv_lib_$1])dnl
 AS_VAR_PUSHDEF([Boost_lib_LDFLAGS], [boost_cv_lib_$1_LDFLAGS])dnl
 AS_VAR_PUSHDEF([Boost_lib_LDPATH], [boost_cv_lib_$1_LDPATH])dnl
 AS_VAR_PUSHDEF([Boost_lib_LIBS], [boost_cv_lib_$1_LIBS])dnl
 BOOST_FIND_HEADER([$4])
 boost_save_CPPFLAGS=$CPPFLAGS
 CPPFLAGS="$CPPFLAGS $BOOST_CPPFLAGS"
 AC_CACHE_CHECK([for the Boost $1 library], [Boost_lib],
                [_BOOST_FIND_LIBS($@)])
 case $Boost_lib in #(
   (no) _AC_MSG_LOG_CONFTEST
     AC_MSG_ERROR([cannot find the flags to link with Boost $1])
     ;;
 esac
 AC_SUBST(AS_TR_CPP([BOOST_$1_LDFLAGS]), [$Boost_lib_LDFLAGS])dnl
 AC_SUBST(AS_TR_CPP([BOOST_$1_LDPATH]), [$Boost_lib_LDPATH])dnl
 AC_SUBST([BOOST_LDPATH], [$Boost_lib_LDPATH])dnl
 AC_SUBST(AS_TR_CPP([BOOST_$1_LIBS]), [$Boost_lib_LIBS])dnl
 CPPFLAGS=$boost_save_CPPFLAGS
 AS_VAR_POPDEF([Boost_lib])dnl
 AS_VAR_POPDEF([Boost_lib_LDFLAGS])dnl
 AS_VAR_POPDEF([Boost_lib_LDPATH])dnl
 AS_VAR_POPDEF([Boost_lib_LIBS])dnl
 AC_LANG_POP([C++])dnl
 fi
 ])
 
 
 # BOOST_FIND_LIB([LIB-NAME],
 #                [PREFERRED-RT-OPT], [HEADER-NAME], [CXX-TEST],
 #                [CXX-PROLOGUE])
 # --------------------------------------------------------------
 # Backward compatibility wrapper for BOOST_FIND_LIBS.
 AC_DEFUN([BOOST_FIND_LIB],
 [BOOST_FIND_LIBS([$1], $@)])
 
 
 # _BOOST_FIND_LIBS([LIB-NAME], [CANDIDATE-LIB-NAMES],
 #                 [PREFERRED-RT-OPT], [HEADER-NAME], [CXX-TEST],
 #                 [CXX-PROLOGUE])
 # --------------------------------------------------------------
 # Real implementation of BOOST_FIND_LIBS: rely on these local macros:
 # Boost_lib, Boost_lib_LDFLAGS, Boost_lib_LDPATH, Boost_lib_LIBS
 #
 # The algorithm is as follows: first look for a given library name
 # according to the user's PREFERRED-RT-OPT.  For each library name, we
 # prefer to use the ones that carry the tag (toolset name).  Each
 # library is searched through the various standard paths were Boost is
 # usually installed.  If we can't find the standard variants, we try
 # to enforce -mt (for instance on MacOSX, libboost_thread.dylib
 # doesn't exist but there's -obviously- libboost_thread-mt.dylib).
 AC_DEFUN([_BOOST_FIND_LIBS],
 [Boost_lib=no
   case "$3" in #(
     (mt | mt-) boost_mt=-mt; boost_rtopt=;; #(
     (mt* | mt-*) boost_mt=-mt; boost_rtopt=`expr "X$3" : 'Xmt-*\(.*\)'`;; #(
     (*) boost_mt=; boost_rtopt=$3;;
   esac
   if test $enable_static_boost = yes; then
     boost_rtopt="s$boost_rtopt"
   fi
   # Find the proper debug variant depending on what we've been asked to find.
   case $boost_rtopt in #(
     (*d*) boost_rt_d=$boost_rtopt;; #(
     (*[[sgpn]]*) # Insert the `d' at the right place (in between `sg' and `pn')
       boost_rt_d=`echo "$boost_rtopt" | sed 's/\(s*g*\)\(p*n*\)/\1\2/'`;; #(
     (*) boost_rt_d='-d';;
   esac
   # If the PREFERRED-RT-OPT are not empty, prepend a `-'.
   test -n "$boost_rtopt" && boost_rtopt="-$boost_rtopt"
   $boost_guess_use_mt && boost_mt=-mt
   # Look for the abs path the static archive.
   # $libext is computed by Libtool but let's make sure it's non empty.
   test -z "$libext" &&
     AC_MSG_ERROR([the libext variable is empty, did you invoke Libtool?])
   boost_save_ac_objext=$ac_objext
   # Generate the test file.
   AC_LANG_CONFTEST([AC_LANG_PROGRAM([#include <$4>
 $6], [$5])])
 dnl Optimization hacks: compiling C++ is slow, especially with Boost.  What
 dnl we're trying to do here is guess the right combination of link flags
 dnl (LIBS / LDFLAGS) to use a given library.  This can take several
 dnl iterations before it succeeds and is thus *very* slow.  So what we do
 dnl instead is that we compile the code first (and thus get an object file,
 dnl typically conftest.o).  Then we try various combinations of link flags
 dnl until we succeed to link conftest.o in an executable.  The problem is
 dnl that the various TRY_LINK / COMPILE_IFELSE macros of Autoconf always
 dnl remove all the temporary files including conftest.o.  So the trick here
 dnl is to temporarily change the value of ac_objext so that conftest.o is
 dnl preserved accross tests.  This is obviously fragile and I will burn in
 dnl hell for not respecting Autoconf's documented interfaces, but in the
 dnl mean time, it optimizes the macro by a factor of 5 to 30.
 dnl Another small optimization: the first argument of AC_COMPILE_IFELSE left
 dnl empty because the test file is generated only once above (before we
 dnl start the for loops).
   AC_COMPILE_IFELSE([],
     [ac_objext=do_not_rm_me_plz],
     [AC_MSG_ERROR([cannot compile a test that uses Boost $1])])
   ac_objext=$boost_save_ac_objext
   boost_failed_libs=
 # Don't bother to ident the following nested for loops, only the 2
 # innermost ones matter.
 for boost_lib_ in $2; do
 for boost_tag_ in -$boost_cv_lib_tag ''; do
 for boost_ver_ in -$boost_cv_lib_version ''; do
 for boost_mt_ in $boost_mt -mt ''; do
 for boost_rtopt_ in $boost_rtopt '' -d; do
   for boost_lib in \
     boost_$boost_lib_$boost_tag_$boost_mt_$boost_rtopt_$boost_ver_ \
     boost_$boost_lib_$boost_tag_$boost_rtopt_$boost_ver_ \
     boost_$boost_lib_$boost_tag_$boost_mt_$boost_ver_ \
     boost_$boost_lib_$boost_tag_$boost_ver_
   do
     # Avoid testing twice the same lib
     case $boost_failed_libs in #(
       (*@$boost_lib@*) continue;;
     esac
     # If with_boost is empty, we'll search in /lib first, which is not quite
     # right so instead we'll try to a location based on where the headers are.
     boost_tmp_lib=$with_boost
     test x"$with_boost" = x && boost_tmp_lib=${boost_cv_inc_path%/include}
     for boost_ldpath in "$boost_tmp_lib/lib" '' \
              /opt/local/lib* /usr/local/lib* /opt/lib* /usr/lib* \
              "$with_boost" C:/Boost/lib /lib*
     do
       # Don't waste time with directories that don't exist.
       if test x"$boost_ldpath" != x && test ! -e "$boost_ldpath"; then
         continue
       fi
       boost_save_LDFLAGS=$LDFLAGS
       # Are we looking for a static library?
       case $boost_ldpath:$boost_rtopt_ in #(
         (*?*:*s*) # Yes (Non empty boost_ldpath + s in rt opt)
           Boost_lib_LIBS="$boost_ldpath/lib$boost_lib.$libext"
           test -e "$Boost_lib_LIBS" || continue;; #(
         (*) # No: use -lboost_foo to find the shared library.
           Boost_lib_LIBS="-l$boost_lib";;
       esac
       boost_save_LIBS=$LIBS
       LIBS="$Boost_lib_LIBS $LIBS"
       test x"$boost_ldpath" != x && LDFLAGS="$LDFLAGS -L$boost_ldpath"
 dnl First argument of AC_LINK_IFELSE left empty because the test file is
 dnl generated only once above (before we start the for loops).
       _BOOST_AC_LINK_IFELSE([],
                             [Boost_lib=yes], [Boost_lib=no])
       ac_objext=$boost_save_ac_objext
       LDFLAGS=$boost_save_LDFLAGS
       LIBS=$boost_save_LIBS
       if test x"$Boost_lib" = xyes; then
         # Check or used cached result of whether or not using -R or
         # -rpath makes sense.  Some implementations of ld, such as for
         # Mac OSX, require -rpath but -R is the flag known to work on
         # other systems.  https://github.com/tsuna/boost.m4/issues/19
         AC_CACHE_VAL([boost_cv_rpath_link_ldflag],
           [case $boost_ldpath in
            '') # Nothing to do.
              boost_cv_rpath_link_ldflag=
              boost_rpath_link_ldflag_found=yes;;
            *)
             for boost_cv_rpath_link_ldflag in -Wl,-R, -Wl,-rpath,; do
               LDFLAGS="$boost_save_LDFLAGS -L$boost_ldpath $boost_cv_rpath_link_ldflag$boost_ldpath"
               LIBS="$boost_save_LIBS $Boost_lib_LIBS"
               _BOOST_AC_LINK_IFELSE([],
                 [boost_rpath_link_ldflag_found=yes
                 break],
                 [boost_rpath_link_ldflag_found=no])
             done
             ;;
           esac
           AS_IF([test "x$boost_rpath_link_ldflag_found" != "xyes"],
             [AC_MSG_ERROR([Unable to determine whether to use -R or -rpath])])
           LDFLAGS=$boost_save_LDFLAGS
           LIBS=$boost_save_LIBS
           ])
         test x"$boost_ldpath" != x &&
           Boost_lib_LDFLAGS="-L$boost_ldpath $boost_cv_rpath_link_ldflag$boost_ldpath"
         Boost_lib_LDPATH="$boost_ldpath"
         break 7
       else
         boost_failed_libs="$boost_failed_libs@$boost_lib@"
       fi
     done
   done
 done
 done
 done
 done
 done # boost_lib_
 rm -f conftest.$ac_objext
 ])
 
 
 
 # --------------------------------------- #
 # Checks for the various Boost libraries. #
 # --------------------------------------- #
 
 # List of boost libraries: http://www.boost.org/libs/libraries.htm
 # The page http://beta.boost.org/doc/libs is useful: it gives the first release
 # version of each library (among other things).
 
 # BOOST_DEFUN(LIBRARY, CODE)
 # --------------------------
 # Define BOOST_<LIBRARY-UPPERCASE> as a macro that runs CODE.
 #
 # Use indir to avoid the warning on underquoted macro name given to AC_DEFUN.
 m4_define([BOOST_DEFUN],
 [m4_indir([AC_DEFUN],
           m4_toupper([BOOST_$1]),
 [m4_pushdef([BOOST_Library], [$1])dnl
 $2
 m4_popdef([BOOST_Library])dnl
 ])
 ])
 
 # BOOST_ARRAY()
 # -------------
 # Look for Boost.Array
 BOOST_DEFUN([Array],
 [BOOST_FIND_HEADER([boost/array.hpp])])
 
 
 # BOOST_ASIO()
 # ------------
 # Look for Boost.Asio (new in Boost 1.35).
 BOOST_DEFUN([Asio],
 [AC_REQUIRE([BOOST_SYSTEM])dnl
 BOOST_FIND_HEADER([boost/asio.hpp])])
 
 
 # BOOST_ASSIGN()
 # -------------
 # Look for Boost.Assign
 BOOST_DEFUN([Assign],
 [BOOST_FIND_HEADER([boost/assign.hpp])])
 
 
 # BOOST_BIND()
 # ------------
 # Look for Boost.Bind.
 BOOST_DEFUN([Bind],
 [BOOST_FIND_HEADER([boost/bind.hpp])])
 
 
 # BOOST_CHRONO()
 # --------------
 # Look for Boost.Chrono.
 BOOST_DEFUN([Chrono],
 [# Do we have to check for Boost.System?  This link-time dependency was
 # added as of 1.35.0.  If we have a version <1.35, we must not attempt to
 # find Boost.System as it didn't exist by then.
 if test $boost_major_version -ge 135; then
   BOOST_SYSTEM([$1])
 fi # end of the Boost.System check.
 boost_filesystem_save_LIBS=$LIBS
 boost_filesystem_save_LDFLAGS=$LDFLAGS
 m4_pattern_allow([^BOOST_SYSTEM_(LIBS|LDFLAGS)$])dnl
 LIBS="$LIBS $BOOST_SYSTEM_LIBS"
 LDFLAGS="$LDFLAGS $BOOST_SYSTEM_LDFLAGS"
 BOOST_FIND_LIB([chrono], [$1],
                 [boost/chrono.hpp],
                 [boost::chrono::thread_clock d;])
 if test $enable_static_boost = yes && test $boost_major_version -ge 135; then
   BOOST_CHRONO_LIBS="$BOOST_CHRONO_LIBS $BOOST_SYSTEM_LIBS"
 fi
 LIBS=$boost_filesystem_save_LIBS
 LDFLAGS=$boost_filesystem_save_LDFLAGS
 ])# BOOST_CHRONO
 
 
 # BOOST_CONTEXT([PREFERRED-RT-OPT])
 # -----------------------------------
 # Look for Boost.Context.  For the documentation of PREFERRED-RT-OPT, see the
 # documentation of BOOST_FIND_LIB above.
 #
 # * This library was introduced in Boost 1.51.0
 # * The signatures of make_fcontext() and jump_fcontext were changed in 1.56.0
 # * A dependency on boost_thread appears in 1.57.0
 BOOST_DEFUN([Context],
 [boost_context_save_LIBS=$LIBS
  boost_context_save_LDFLAGS=$LDFLAGS
 if test $boost_major_version -ge 157; then
   BOOST_THREAD([$1])
   m4_pattern_allow([^BOOST_THREAD_(LIBS|LDFLAGS)$])dnl
   LIBS="$LIBS $BOOST_THREAD_LIBS"
   LDFLAGS="$LDFLAGS $BOOST_THREAD_LDFLAGS"
 fi
 BOOST_FIND_LIB([context], [$1],
                 [boost/context/all.hpp],[[
 
 // creates a stack
 void * stack_pointer = new void*[4096];
 std::size_t const size = sizeof(void*[4096]);
 
 #if BOOST_VERSION <= 105100
 ctx::make_fcontext(&fc, f);
 return ctx::jump_fcontext(&fcm, &fc, 3) == 6;
 
 #else
 
 fc = ctx::make_fcontext(stack_pointer, size, f);
 return ctx::jump_fcontext(&fcm, fc, 3) == 6;
 
 #endif
 
 
 ]],[dnl
 
 #include <boost/version.hpp>
 #if BOOST_VERSION <= 105100
 
 namespace ctx = boost::ctx;
 
 static ctx::fcontext_t fcm, fc;
 
 static void f(intptr_t i) {
     ctx::jump_fcontext(&fc, &fcm, i * 2);
 }
 
 #elif BOOST_VERSION <= 105500
 
 namespace ctx = boost::context;
 
 // context
 static ctx::fcontext_t fcm, *fc;
 
 // context-function
 static void f(intptr_t i) {
     ctx::jump_fcontext(fc, &fcm, i * 2);
 }
 
 #else
 
 namespace ctx = boost::context;
 
 // context
 static ctx::fcontext_t fcm, fc;
 
 // context-function
 static void f(intptr_t i) {
     ctx::jump_fcontext(&fc, fcm, i * 2);
 }
 #endif
 ])
 LIBS=$boost_context_save_LIBS
 LDFLAGS=$boost_context_save_LDFLAGS
 ])# BOOST_CONTEXT
 
 
 # BOOST_CONVERSION()
 # ------------------
 # Look for Boost.Conversion (cast / lexical_cast)
 BOOST_DEFUN([Conversion],
 [BOOST_FIND_HEADER([boost/cast.hpp])
 BOOST_FIND_HEADER([boost/lexical_cast.hpp])
 ])# BOOST_CONVERSION
 
 
 # BOOST_COROUTINE([PREFERRED-RT-OPT])
 # -----------------------------------
 # Look for Boost.Coroutine.  For the documentation of PREFERRED-RT-OPT, see the
 # documentation of BOOST_FIND_LIB above.  This library was introduced in Boost
 # 1.53.0
 BOOST_DEFUN([Coroutine],
 [
 boost_coroutine_save_LIBS=$LIBS
 boost_coroutine_save_LDFLAGS=$LDFLAGS
 # Link-time dependency from coroutine to context
 BOOST_CONTEXT([$1])
 # Starting from Boost 1.55 a dependency on Boost.System is added
 if test $boost_major_version -ge 155; then
   BOOST_SYSTEM([$1])
 fi
 m4_pattern_allow([^BOOST_(CONTEXT|SYSTEM)_(LIBS|LDFLAGS)])
 LIBS="$LIBS $BOOST_CONTEXT_LIBS $BOOST_SYSTEM_LIBS"
 LDFLAGS="$LDFLAGS $BOOST_CONTEXT_LDFLAGS"
 
 # in 1.53 coroutine was a header only library
 if test $boost_major_version -eq 153; then
   BOOST_FIND_HEADER([boost/coroutine/coroutine.hpp])
 else
   BOOST_FIND_LIB([coroutine], [$1],
 		  [boost/coroutine/coroutine.hpp],
 		  [
   #include <boost/version.hpp>
   #if   BOOST_VERSION <= 105500
   boost::coroutines::coroutine<int(int)> coro; coro.get();
   #else
   boost::coroutines::asymmetric_coroutine<int>::pull_type coro; coro.get();
   #endif
   ])
 fi
 # Link-time dependency from coroutine to context, existed only in 1.53, in 1.54
 # coroutine doesn't use context from its headers but from its library.
 if test $boost_major_version -eq 153 || test $enable_static_boost = yes && test $boost_major_version -ge 154; then
   BOOST_COROUTINE_LIBS="$BOOST_COROUTINE_LIBS $BOOST_CONTEXT_LIBS"
   BOOST_COROUTINE_LDFLAGS="$BOOST_COROUTINE_LDFLAGS $BOOST_CONTEXT_LDFLAGS"
 fi
 if test $enable_static_boost = yes && test $boost_major_version -ge 155; then
   BOOST_COROUTINE_LIBS="$BOOST_COROUTINE_LIBS $BOOST_SYSTEM_LIBS"
   BOOST_COROUTINE_LDFLAGS="$BOOST_COROUTINE_LDFLAGS $BOOST_SYSTEM_LDFLAGS"
 fi
 LIBS=$boost_coroutine_save_LIBS
 LDFLAGS=$boost_coroutine_save_LDFLAGS
 ])# BOOST_COROUTINE
 
 
 # BOOST_CRC()
 # -----------
 # Look for Boost.CRC
 BOOST_DEFUN([CRC],
 [BOOST_FIND_HEADER([boost/crc.hpp])
 ])# BOOST_CRC
 
 
 # BOOST_DATE_TIME([PREFERRED-RT-OPT])
 # -----------------------------------
 # Look for Boost.Date_Time.  For the documentation of PREFERRED-RT-OPT, see the
 # documentation of BOOST_FIND_LIB above.
 BOOST_DEFUN([Date_Time],
 [BOOST_FIND_LIB([date_time], [$1],
                 [boost/date_time/posix_time/posix_time.hpp],
                 [boost::posix_time::ptime t;])
 ])# BOOST_DATE_TIME
 
 
 # BOOST_FILESYSTEM([PREFERRED-RT-OPT])
 # ------------------------------------
 # Look for Boost.Filesystem.  For the documentation of PREFERRED-RT-OPT, see
 # the documentation of BOOST_FIND_LIB above.
 # Do not check for boost/filesystem.hpp because this file was introduced in
 # 1.34.
 BOOST_DEFUN([Filesystem],
 [# Do we have to check for Boost.System?  This link-time dependency was
 # added as of 1.35.0.  If we have a version <1.35, we must not attempt to
 # find Boost.System as it didn't exist by then.
 if test $boost_major_version -ge 135; then
   BOOST_SYSTEM([$1])
 fi # end of the Boost.System check.
 boost_filesystem_save_LIBS=$LIBS
 boost_filesystem_save_LDFLAGS=$LDFLAGS
 m4_pattern_allow([^BOOST_SYSTEM_(LIBS|LDFLAGS)$])dnl
 LIBS="$LIBS $BOOST_SYSTEM_LIBS"
 LDFLAGS="$LDFLAGS $BOOST_SYSTEM_LDFLAGS"
 BOOST_FIND_LIB([filesystem], [$1],
                 [boost/filesystem/path.hpp], [boost::filesystem::path p;])
 if test $enable_static_boost = yes && test $boost_major_version -ge 135; then
   BOOST_FILESYSTEM_LIBS="$BOOST_FILESYSTEM_LIBS $BOOST_SYSTEM_LIBS"
 fi
 LIBS=$boost_filesystem_save_LIBS
 LDFLAGS=$boost_filesystem_save_LDFLAGS
 ])# BOOST_FILESYSTEM
 
 
 # BOOST_FLYWEIGHT()
 # -----------------
 # Look for Boost.Flyweight.
 BOOST_DEFUN([Flyweight],
 [dnl There's a hidden dependency on pthreads.
 AC_REQUIRE([_BOOST_PTHREAD_FLAG])dnl
 BOOST_FIND_HEADER([boost/flyweight.hpp])
 AC_SUBST([BOOST_FLYWEIGHT_LIBS], [$boost_cv_pthread_flag])
 ])
 
 
 # BOOST_FOREACH()
 # ---------------
 # Look for Boost.Foreach.
 BOOST_DEFUN([Foreach],
 [BOOST_FIND_HEADER([boost/foreach.hpp])])
 
 
 # BOOST_FORMAT()
 # --------------
 # Look for Boost.Format.
 # Note: we can't check for boost/format/format_fwd.hpp because the header isn't
 # standalone.  It can't be compiled because it triggers the following error:
 # boost/format/detail/config_macros.hpp:88: error: 'locale' in namespace 'std'
 #                                                  does not name a type
 BOOST_DEFUN([Format],
 [BOOST_FIND_HEADER([boost/format.hpp])])
 
 
 # BOOST_FUNCTION()
 # ----------------
 # Look for Boost.Function
 BOOST_DEFUN([Function],
 [BOOST_FIND_HEADER([boost/function.hpp])])
 
 
 # BOOST_GEOMETRY()
 # ----------------
 # Look for Boost.Geometry (new since 1.47.0).
 BOOST_DEFUN([Geometry],
 [BOOST_FIND_HEADER([boost/geometry.hpp])
 ])# BOOST_GEOMETRY
 
 
 # BOOST_GRAPH([PREFERRED-RT-OPT])
 # -------------------------------
 # Look for Boost.Graphs.  For the documentation of PREFERRED-RT-OPT, see the
 # documentation of BOOST_FIND_LIB above.
 BOOST_DEFUN([Graph],
 [boost_graph_save_LIBS=$LIBS
 boost_graph_save_LDFLAGS=$LDFLAGS
 # Link-time dependency from graph to regex was added as of 1.40.0.
 if test $boost_major_version -ge 140; then
   BOOST_REGEX([$1])
   m4_pattern_allow([^BOOST_REGEX_(LIBS|LDFLAGS)$])dnl
   LIBS="$LIBS $BOOST_REGEX_LIBS"
   LDFLAGS="$LDFLAGS $BOOST_REGEX_LDFLAGS"
 fi
 BOOST_FIND_LIB([graph], [$1],
                 [boost/graph/adjacency_list.hpp], [boost::adjacency_list<> g;])
 LIBS=$boost_graph_save_LIBS
 LDFLAGS=$boost_graph_save_LDFLAGS
 ])# BOOST_GRAPH
 
 
 # BOOST_IOSTREAMS([PREFERRED-RT-OPT])
 # -----------------------------------
 # Look for Boost.IOStreams.  For the documentation of PREFERRED-RT-OPT, see the
 # documentation of BOOST_FIND_LIB above.
 BOOST_DEFUN([IOStreams],
 [BOOST_FIND_LIB([iostreams], [$1],
                 [boost/iostreams/device/file_descriptor.hpp],
                 [boost::iostreams::file_descriptor fd; fd.close();])
 ])# BOOST_IOSTREAMS
 
 
 # BOOST_HASH()
 # ------------
 # Look for Boost.Functional/Hash
 BOOST_DEFUN([Hash],
 [BOOST_FIND_HEADER([boost/functional/hash.hpp])])
 
 
 # BOOST_LAMBDA()
 # --------------
 # Look for Boost.Lambda
 BOOST_DEFUN([Lambda],
 [BOOST_FIND_HEADER([boost/lambda/lambda.hpp])])
 
 
 # BOOST_LOCALE()
 # --------------
 # Look for Boost.Locale
 BOOST_DEFUN([Locale],
 [
 boost_locale_save_LIBS=$LIBS
 boost_locale_save_LDFLAGS=$LDFLAGS
 # require SYSTEM for boost-1.50.0 and up
 if test $boost_major_version -ge 150; then
   BOOST_SYSTEM([$1])
   m4_pattern_allow([^BOOST_SYSTEM_(LIBS|LDFLAGS)$])dnl
   LIBS="$LIBS $BOOST_SYSTEM_LIBS"
   LDFLAGS="$LDFLAGS $BOOST_SYSTEM_LDFLAGS"
 fi # end of the Boost.System check.
 BOOST_FIND_LIB([locale], [$1],
     [boost/locale.hpp],
     [[boost::locale::generator gen; std::locale::global(gen(""));]])
 LIBS=$boost_locale_save_LIBS
 LDFLAGS=$boost_locale_save_LDFLAGS
 ])# BOOST_LOCALE
 
 # BOOST_LOG([PREFERRED-RT-OPT])
 # -----------------------------
 # Look for Boost.Log.  For the documentation of PREFERRED-RT-OPT, see the
 # documentation of BOOST_FIND_LIB above.
 BOOST_DEFUN([Log],
 [boost_log_save_LIBS=$LIBS
 boost_log_save_LDFLAGS=$LDFLAGS
 BOOST_SYSTEM([$1])
 BOOST_FILESYSTEM([$1])
 BOOST_DATE_TIME([$1])
 m4_pattern_allow([^BOOST_(SYSTEM|FILESYSTEM|DATE_TIME)_(LIBS|LDFLAGS)$])dnl
 LIBS="$LIBS $BOOST_DATE_TIME_LIBS $BOOST_FILESYSTEM_LIBS $BOOST_SYSTEM_LIBS"
 LDFLAGS="$LDFLAGS $BOOST_DATE_TIME_LDFLAGS $BOOST_FILESYSTEM_LDFLAGS $BOOST_SYSTEM_LDFLAGS"
 BOOST_FIND_LIB([log], [$1],
     [boost/log/core/core.hpp],
     [boost::log::attribute a; a.get_value();])
 LIBS=$boost_log_save_LIBS
 LDFLAGS=$boost_log_save_LDFLAGS
 ])# BOOST_LOG
 
 
 # BOOST_LOG_SETUP([PREFERRED-RT-OPT])
 # -----------------------------------
 # Look for Boost.Log.  For the documentation of PREFERRED-RT-OPT, see the
 # documentation of BOOST_FIND_LIB above.
 BOOST_DEFUN([Log_Setup],
 [boost_log_setup_save_LIBS=$LIBS
 boost_log_setup_save_LDFLAGS=$LDFLAGS
 BOOST_LOG([$1])
 m4_pattern_allow([^BOOST_LOG_(LIBS|LDFLAGS)$])dnl
 LIBS="$LIBS $BOOST_LOG_LIBS"
 LDFLAGS="$LDFLAGS $BOOST_LOG_LDFLAGS"
 BOOST_FIND_LIB([log_setup], [$1],
     [boost/log/utility/setup/from_settings.hpp],
     [boost::log::basic_settings<char> bs; bs.empty();])
 LIBS=$boost_log_setup_save_LIBS
 LDFLAGS=$boost_log_setup_save_LDFLAGS
 ])# BOOST_LOG_SETUP
 
 
 # BOOST_MATH()
 # ------------
 # Look for Boost.Math
 # TODO: This library isn't header-only but it comes in multiple different
 # flavors that don't play well with BOOST_FIND_LIB (e.g, libboost_math_c99,
 # libboost_math_c99f, libboost_math_c99l, libboost_math_tr1,
 # libboost_math_tr1f, libboost_math_tr1l).  This macro must be fixed to do the
 # right thing anyway.
 BOOST_DEFUN([Math],
 [BOOST_FIND_HEADER([boost/math/special_functions.hpp])])
 
 
 # BOOST_MPI([PREFERRED-RT-OPT])
 # -------------------------------
 # Look for Boost MPI.  For the documentation of PREFERRED-RT-OPT, see the
 # documentation of BOOST_FIND_LIB above.  Uses MPICXX variable if it is
 # set, otherwise tries CXX
 #
 BOOST_DEFUN([MPI],
 [boost_save_CXX=${CXX}
 boost_save_CXXCPP=${CXXCPP}
 if test x"${MPICXX}" != x; then
   CXX=${MPICXX}
   CXXCPP="${MPICXX} -E"
 fi
 BOOST_FIND_LIB([mpi], [$1],
                [boost/mpi.hpp],
                [int argc = 0;
                 char **argv = 0;
                 boost::mpi::environment env(argc,argv);])
 CXX=${boost_save_CXX}
 CXXCPP=${boost_save_CXXCPP}
 ])# BOOST_MPI
 
 
 # BOOST_MULTIARRAY()
 # ------------------
 # Look for Boost.MultiArray
 BOOST_DEFUN([MultiArray],
 [BOOST_FIND_HEADER([boost/multi_array.hpp])])
 
 
 # BOOST_NUMERIC_UBLAS()
 # --------------------------
 # Look for Boost.NumericUblas (Basic Linear Algebra)
 BOOST_DEFUN([Numeric_Ublas],
 [BOOST_FIND_HEADER([boost/numeric/ublas/vector.hpp])
 ])# BOOST_NUMERIC_UBLAS
 
 
 # BOOST_NUMERIC_CONVERSION()
 # --------------------------
 # Look for Boost.NumericConversion (policy-based numeric conversion)
 BOOST_DEFUN([Numeric_Conversion],
 [BOOST_FIND_HEADER([boost/numeric/conversion/converter.hpp])
 ])# BOOST_NUMERIC_CONVERSION
 
 
 # BOOST_OPTIONAL()
 # ----------------
 # Look for Boost.Optional
 BOOST_DEFUN([Optional],
 [BOOST_FIND_HEADER([boost/optional.hpp])])
 
 
 # BOOST_PREPROCESSOR()
 # --------------------
 # Look for Boost.Preprocessor
 BOOST_DEFUN([Preprocessor],
 [BOOST_FIND_HEADER([boost/preprocessor/repeat.hpp])])
 
 
 # BOOST_RANGE()
 # --------------------
 # Look for Boost.Range
 BOOST_DEFUN([Range],
 [BOOST_FIND_HEADER([boost/range/adaptors.hpp])])
 
 # BOOST_UNORDERED()
 # -----------------
 # Look for Boost.Unordered
 BOOST_DEFUN([Unordered],
 [BOOST_FIND_HEADER([boost/unordered_map.hpp])])
 
 
 # BOOST_UUID()
 # ------------
 # Look for Boost.Uuid
 BOOST_DEFUN([Uuid],
 [BOOST_FIND_HEADER([boost/uuid/uuid.hpp])])
 
 
 # BOOST_PROGRAM_OPTIONS([PREFERRED-RT-OPT])
 # -----------------------------------------
 # Look for Boost.Program_options.  For the documentation of PREFERRED-RT-OPT,
 # see the documentation of BOOST_FIND_LIB above.
 BOOST_DEFUN([Program_Options],
 [BOOST_FIND_LIB([program_options], [$1],
                 [boost/program_options.hpp],
                 [boost::program_options::options_description d("test");])
 ])# BOOST_PROGRAM_OPTIONS
 
 
 
 # _BOOST_PYTHON_CONFIG(VARIABLE, FLAG)
 # ------------------------------------
 # Save VARIABLE, and define it via `python-config --FLAG`.
 # Substitute BOOST_PYTHON_VARIABLE.
 m4_define([_BOOST_PYTHON_CONFIG],
 [AC_SUBST([BOOST_PYTHON_$1],
           [`python-config --$2 2>/dev/null`])dnl
 boost_python_save_$1=$$1
 $1="$$1 $BOOST_PYTHON_$1"])
 
 
 # BOOST_PYTHON([PREFERRED-RT-OPT])
 # --------------------------------
 # Look for Boost.Python.  For the documentation of PREFERRED-RT-OPT,
 # see the documentation of BOOST_FIND_LIB above.
 BOOST_DEFUN([Python],
 [_BOOST_PYTHON_CONFIG([CPPFLAGS], [includes])
 _BOOST_PYTHON_CONFIG([LDFLAGS],   [ldflags])
 _BOOST_PYTHON_CONFIG([LIBS],      [libs])
 m4_pattern_allow([^BOOST_PYTHON_MODULE$])dnl
 BOOST_FIND_LIBS([python], [python python3], [$1],
                 [boost/python.hpp],
                 [], [BOOST_PYTHON_MODULE(empty) {}])
 CPPFLAGS=$boost_python_save_CPPFLAGS
 LDFLAGS=$boost_python_save_LDFLAGS
 LIBS=$boost_python_save_LIBS
 ])# BOOST_PYTHON
 
 
 # BOOST_REF()
 # -----------
 # Look for Boost.Ref
 BOOST_DEFUN([Ref],
 [BOOST_FIND_HEADER([boost/ref.hpp])])
 
 
 # BOOST_REGEX([PREFERRED-RT-OPT])
 # -------------------------------
 # Look for Boost.Regex.  For the documentation of PREFERRED-RT-OPT, see the
 # documentation of BOOST_FIND_LIB above.
 BOOST_DEFUN([Regex],
 [BOOST_FIND_LIB([regex], [$1],
                 [boost/regex.hpp],
                 [boost::regex exp("*"); boost::regex_match("foo", exp);])
 ])# BOOST_REGEX
 
 
 # BOOST_SERIALIZATION([PREFERRED-RT-OPT])
 # ---------------------------------------
 # Look for Boost.Serialization.  For the documentation of PREFERRED-RT-OPT, see
 # the documentation of BOOST_FIND_LIB above.
 BOOST_DEFUN([Serialization],
 [BOOST_FIND_LIB([serialization], [$1],
                 [boost/archive/text_oarchive.hpp],
                 [std::ostream* o = 0; // Cheap way to get an ostream...
                 boost::archive::text_oarchive t(*o);])
 ])# BOOST_SERIALIZATION
 
 
 # BOOST_SIGNALS([PREFERRED-RT-OPT])
 # ---------------------------------
 # Look for Boost.Signals.  For the documentation of PREFERRED-RT-OPT, see the
 # documentation of BOOST_FIND_LIB above.
 BOOST_DEFUN([Signals],
 [BOOST_FIND_LIB([signals], [$1],
                 [boost/signal.hpp],
                 [boost::signal<void ()> s;])
 ])# BOOST_SIGNALS
 
 
 # BOOST_SIGNALS2()
 # ----------------
 # Look for Boost.Signals2 (new since 1.39.0).
 BOOST_DEFUN([Signals2],
 [BOOST_FIND_HEADER([boost/signals2.hpp])
 ])# BOOST_SIGNALS2
 
 
 # BOOST_SMART_PTR()
 # -----------------
 # Look for Boost.SmartPtr
 BOOST_DEFUN([Smart_Ptr],
 [BOOST_FIND_HEADER([boost/scoped_ptr.hpp])
 BOOST_FIND_HEADER([boost/shared_ptr.hpp])
 ])
 
 
 # BOOST_STATICASSERT()
 # --------------------
 # Look for Boost.StaticAssert
 BOOST_DEFUN([StaticAssert],
 [BOOST_FIND_HEADER([boost/static_assert.hpp])])
 
 
 # BOOST_STRING_ALGO()
 # -------------------
 # Look for Boost.StringAlgo
 BOOST_DEFUN([String_Algo],
 [BOOST_FIND_HEADER([boost/algorithm/string.hpp])
 ])
 
 
 # BOOST_SYSTEM([PREFERRED-RT-OPT])
 # --------------------------------
 # Look for Boost.System.  For the documentation of PREFERRED-RT-OPT, see the
 # documentation of BOOST_FIND_LIB above.  This library was introduced in Boost
 # 1.35.0.
 BOOST_DEFUN([System],
 [BOOST_FIND_LIB([system], [$1],
                 [boost/system/error_code.hpp],
                 [boost::system::error_code e; e.clear();])
 ])# BOOST_SYSTEM
 
 
 # BOOST_TEST([PREFERRED-RT-OPT])
 # ------------------------------
 # Look for Boost.Test.  For the documentation of PREFERRED-RT-OPT, see the
 # documentation of BOOST_FIND_LIB above.
 BOOST_DEFUN([Test],
 [m4_pattern_allow([^BOOST_CHECK$])dnl
 BOOST_FIND_LIB([unit_test_framework], [$1],
                [boost/test/unit_test.hpp], [BOOST_CHECK(2 == 2);],
                [using boost::unit_test::test_suite;
                test_suite* init_unit_test_suite(int argc, char ** argv)
                { return NULL; }])
 ])# BOOST_TEST
 
 
 # BOOST_THREAD([PREFERRED-RT-OPT])
 # ---------------------------------
 # Look for Boost.Thread.  For the documentation of PREFERRED-RT-OPT, see the
 # documentation of BOOST_FIND_LIB above.
 BOOST_DEFUN([Thread],
 [dnl Having the pthread flag is required at least on GCC3 where
 dnl boost/thread.hpp would complain if we try to compile without
 dnl -pthread on GNU/Linux.
 AC_REQUIRE([_BOOST_PTHREAD_FLAG])dnl
 boost_thread_save_LIBS=$LIBS
 boost_thread_save_LDFLAGS=$LDFLAGS
 boost_thread_save_CPPFLAGS=$CPPFLAGS
 # Link-time dependency from thread to system was added as of 1.49.0.
 if test $boost_major_version -ge 149; then
 BOOST_SYSTEM([$1])
 fi # end of the Boost.System check.
 m4_pattern_allow([^BOOST_SYSTEM_(LIBS|LDFLAGS)$])dnl
 LIBS="$LIBS $BOOST_SYSTEM_LIBS $boost_cv_pthread_flag"
 LDFLAGS="$LDFLAGS $BOOST_SYSTEM_LDFLAGS"
 CPPFLAGS="$CPPFLAGS $boost_cv_pthread_flag"
 
 # When compiling for the Windows platform, the threads library is named
 # differently.  This suffix doesn't exist in new versions of Boost, or
 # possibly new versions of GCC on mingw I am assuming it's Boost's change for
 # now and I am setting version to 1.48, for lack of knowledge as to when this
 # change occurred.
 if test $boost_major_version -lt 148; then
   case $host_os in
     (*mingw*) boost_thread_lib_ext=_win32;;
   esac
 fi
 BOOST_FIND_LIBS([thread], [thread$boost_thread_lib_ext],
                 [$1],
                 [boost/thread.hpp], [boost::thread t; boost::mutex m;])
 
 case $host_os in
   (*mingw*) boost_thread_w32_socket_link=-lws2_32;;
 esac
 
 BOOST_THREAD_LIBS="$BOOST_THREAD_LIBS $BOOST_SYSTEM_LIBS $boost_cv_pthread_flag $boost_thread_w32_socket_link"
 BOOST_THREAD_LDFLAGS="$BOOST_SYSTEM_LDFLAGS"
 BOOST_CPPFLAGS="$BOOST_CPPFLAGS $boost_cv_pthread_flag"
 LIBS=$boost_thread_save_LIBS
 LDFLAGS=$boost_thread_save_LDFLAGS
 CPPFLAGS=$boost_thread_save_CPPFLAGS
 ])# BOOST_THREAD
 
 AU_ALIAS([BOOST_THREADS], [BOOST_THREAD])
 
 
 # BOOST_TOKENIZER()
 # -----------------
 # Look for Boost.Tokenizer
 BOOST_DEFUN([Tokenizer],
 [BOOST_FIND_HEADER([boost/tokenizer.hpp])])
 
 
 # BOOST_TRIBOOL()
 # ---------------
 # Look for Boost.Tribool
 BOOST_DEFUN([Tribool],
 [BOOST_FIND_HEADER([boost/logic/tribool_fwd.hpp])
 BOOST_FIND_HEADER([boost/logic/tribool.hpp])
 ])
 
 
 # BOOST_TUPLE()
 # -------------
 # Look for Boost.Tuple
 BOOST_DEFUN([Tuple],
 [BOOST_FIND_HEADER([boost/tuple/tuple.hpp])])
 
 
 # BOOST_TYPETRAITS()
 # --------------------
 # Look for Boost.TypeTraits
 BOOST_DEFUN([TypeTraits],
 [BOOST_FIND_HEADER([boost/type_traits.hpp])])
 
 
 # BOOST_UTILITY()
 # ---------------
 # Look for Boost.Utility (noncopyable, result_of, base-from-member idiom,
 # etc.)
 BOOST_DEFUN([Utility],
 [BOOST_FIND_HEADER([boost/utility.hpp])])
 
 
 # BOOST_VARIANT()
 # ---------------
 # Look for Boost.Variant.
 BOOST_DEFUN([Variant],
 [BOOST_FIND_HEADER([boost/variant/variant_fwd.hpp])
 BOOST_FIND_HEADER([boost/variant.hpp])])
 
 
 # BOOST_POINTER_CONTAINER()
 # ------------------------
 # Look for Boost.PointerContainer
 BOOST_DEFUN([Pointer_Container],
 [BOOST_FIND_HEADER([boost/ptr_container/ptr_deque.hpp])
 BOOST_FIND_HEADER([boost/ptr_container/ptr_list.hpp])
 BOOST_FIND_HEADER([boost/ptr_container/ptr_vector.hpp])
 BOOST_FIND_HEADER([boost/ptr_container/ptr_array.hpp])
 BOOST_FIND_HEADER([boost/ptr_container/ptr_set.hpp])
 BOOST_FIND_HEADER([boost/ptr_container/ptr_map.hpp])
 ])# BOOST_POINTER_CONTAINER
 
 
 # BOOST_WAVE([PREFERRED-RT-OPT])
 # ------------------------------
 # NOTE: If you intend to use Wave/Spirit with thread support, make sure you
 # call BOOST_THREAD first.
 # Look for Boost.Wave.  For the documentation of PREFERRED-RT-OPT, see the
 # documentation of BOOST_FIND_LIB above.
 BOOST_DEFUN([Wave],
 [AC_REQUIRE([BOOST_FILESYSTEM])dnl
 AC_REQUIRE([BOOST_DATE_TIME])dnl
 boost_wave_save_LIBS=$LIBS
 boost_wave_save_LDFLAGS=$LDFLAGS
 m4_pattern_allow([^BOOST_((FILE)?SYSTEM|DATE_TIME|THREAD)_(LIBS|LDFLAGS)$])dnl
 LIBS="$LIBS $BOOST_SYSTEM_LIBS $BOOST_FILESYSTEM_LIBS $BOOST_DATE_TIME_LIBS \
 $BOOST_THREAD_LIBS"
 LDFLAGS="$LDFLAGS $BOOST_SYSTEM_LDFLAGS $BOOST_FILESYSTEM_LDFLAGS \
 $BOOST_DATE_TIME_LDFLAGS $BOOST_THREAD_LDFLAGS"
 BOOST_FIND_LIB([wave], [$1],
                 [boost/wave.hpp],
                 [boost::wave::token_id id; get_token_name(id);])
 LIBS=$boost_wave_save_LIBS
 LDFLAGS=$boost_wave_save_LDFLAGS
 ])# BOOST_WAVE
 
 
 # BOOST_XPRESSIVE()
 # -----------------
 # Look for Boost.Xpressive (new since 1.36.0).
 BOOST_DEFUN([Xpressive],
 [BOOST_FIND_HEADER([boost/xpressive/xpressive.hpp])])
 
 
 # ----------------- #
 # Internal helpers. #
 # ----------------- #
 
 
 # _BOOST_PTHREAD_FLAG()
 # ---------------------
 # Internal helper for BOOST_THREAD.  Computes boost_cv_pthread_flag
 # which must be used in CPPFLAGS and LIBS.
 #
 # Yes, we *need* to put the -pthread thing in CPPFLAGS because with GCC3,
 # boost/thread.hpp will trigger a #error if -pthread isn't used:
 #   boost/config/requires_threads.hpp:47:5: #error "Compiler threading support
 #   is not turned on. Please set the correct command line options for
 #   threading: -pthread (Linux), -pthreads (Solaris) or -mthreads (Mingw32)"
 #
 # Based on ACX_PTHREAD: http://autoconf-archive.cryp.to/acx_pthread.html
 AC_DEFUN([_BOOST_PTHREAD_FLAG],
 [AC_REQUIRE([AC_PROG_CXX])dnl
 AC_REQUIRE([AC_CANONICAL_HOST])dnl
 AC_LANG_PUSH([C++])dnl
 AC_CACHE_CHECK([for the flags needed to use pthreads], [boost_cv_pthread_flag],
 [ boost_cv_pthread_flag=
   # The ordering *is* (sometimes) important.  Some notes on the
   # individual items follow:
   # (none): in case threads are in libc; should be tried before -Kthread and
   #       other compiler flags to prevent continual compiler warnings
   # -lpthreads: AIX (must check this before -lpthread)
   # -Kthread: Sequent (threads in libc, but -Kthread needed for pthread.h)
   # -kthread: FreeBSD kernel threads (preferred to -pthread since SMP-able)
   # -llthread: LinuxThreads port on FreeBSD (also preferred to -pthread)
   # -pthread: GNU Linux/GCC (kernel threads), BSD/GCC (userland threads)
   # -pthreads: Solaris/GCC
   # -mthreads: MinGW32/GCC, Lynx/GCC
   # -mt: Sun Workshop C (may only link SunOS threads [-lthread], but it
   #      doesn't hurt to check since this sometimes defines pthreads too;
   #      also defines -D_REENTRANT)
   #      ... -mt is also the pthreads flag for HP/aCC
   # -lpthread: GNU Linux, etc.
   # --thread-safe: KAI C++
   case $host_os in #(
     *solaris*)
       # On Solaris (at least, for some versions), libc contains stubbed
       # (non-functional) versions of the pthreads routines, so link-based
       # tests will erroneously succeed.  (We need to link with -pthreads/-mt/
       # -lpthread.)  (The stubs are missing pthread_cleanup_push, or rather
       # a function called by this macro, so we could check for that, but
       # who knows whether they'll stub that too in a future libc.)  So,
       # we'll just look for -pthreads and -lpthread first:
       boost_pthread_flags="-pthreads -lpthread -mt -pthread";; #(
     *)
       boost_pthread_flags="-lpthreads -Kthread -kthread -llthread -pthread \
                            -pthreads -mthreads -lpthread --thread-safe -mt";;
   esac
   # Generate the test file.
   AC_LANG_CONFTEST([AC_LANG_PROGRAM([#include <pthread.h>],
     [pthread_t th; pthread_join(th, 0);
     pthread_attr_init(0); pthread_cleanup_push(0, 0);
     pthread_create(0,0,0,0); pthread_cleanup_pop(0);])])
   for boost_pthread_flag in '' $boost_pthread_flags; do
     boost_pthread_ok=false
 dnl Re-use the test file already generated.
     boost_pthreads__save_LIBS=$LIBS
     LIBS="$LIBS $boost_pthread_flag"
     AC_LINK_IFELSE([],
       [if grep ".*$boost_pthread_flag" conftest.err; then
          echo "This flag seems to have triggered warnings" >&AS_MESSAGE_LOG_FD
        else
          boost_pthread_ok=:; boost_cv_pthread_flag=$boost_pthread_flag
        fi])
     LIBS=$boost_pthreads__save_LIBS
     $boost_pthread_ok && break
   done
 ])
 AC_LANG_POP([C++])dnl
 ])# _BOOST_PTHREAD_FLAG
 
 
 # _BOOST_gcc_test(MAJOR, MINOR)
 # -----------------------------
 # Internal helper for _BOOST_FIND_COMPILER_TAG.
 m4_define([_BOOST_gcc_test],
 ["defined __GNUC__ && __GNUC__ == $1 && __GNUC_MINOR__ == $2 && !defined __ICC @ gcc$1$2"])dnl
 
 # _BOOST_mingw_test(MAJOR, MINOR)
 # -----------------------------
 # Internal helper for _BOOST_FIND_COMPILER_TAG.
 m4_define([_BOOST_mingw_test],
 ["defined __GNUC__ && __GNUC__ == $1 && __GNUC_MINOR__ == $2 && !defined __ICC && \
   (defined WIN32 || defined WINNT || defined _WIN32 || defined __WIN32 \
          || defined __WIN32__ || defined __WINNT || defined __WINNT__) @ mgw$1$2"])dnl
 
 
 # _BOOST_FIND_COMPILER_TAG()
 # --------------------------
 # Internal.  When Boost is installed without --layout=system, each library
 # filename will hold a suffix that encodes the compiler used during the
 # build.  The Boost build system seems to call this a `tag'.
 AC_DEFUN([_BOOST_FIND_COMPILER_TAG],
 [AC_REQUIRE([AC_PROG_CXX])dnl
 AC_REQUIRE([AC_CANONICAL_HOST])dnl
 AC_CACHE_CHECK([for the toolset name used by Boost for $CXX],
                [boost_cv_lib_tag],
 [boost_cv_lib_tag=unknown
 if test x$boost_cv_inc_path != xno; then
   AC_LANG_PUSH([C++])dnl
   # The following tests are mostly inspired by boost/config/auto_link.hpp
   # The list is sorted to most recent/common to oldest compiler (in order
   # to increase the likelihood of finding the right compiler with the
   # least number of compilation attempt).
   # Beware that some tests are sensible to the order (for instance, we must
   # look for MinGW before looking for GCC3).
   # I used one compilation test per compiler with a #error to recognize
   # each compiler so that it works even when cross-compiling (let me know
   # if you know a better approach).
   # Known missing tags (known from Boost's tools/build/v2/tools/common.jam):
   #   como, edg, kcc, bck, mp, sw, tru, xlc
   # I'm not sure about my test for `il' (be careful: Intel's ICC pre-defines
   # the same defines as GCC's).
   for i in \
     _BOOST_mingw_test(7, 1) \
     _BOOST_gcc_test(7, 1) \
+    _BOOST_mingw_test(6, 3) \
+    _BOOST_gcc_test(6, 3) \
     _BOOST_mingw_test(6, 2) \
     _BOOST_gcc_test(6, 2) \
     _BOOST_mingw_test(6, 1) \
     _BOOST_gcc_test(6, 1) \
     _BOOST_mingw_test(5, 4) \
     _BOOST_gcc_test(5, 4) \
     _BOOST_mingw_test(5, 3) \
     _BOOST_gcc_test(5, 3) \
     _BOOST_mingw_test(5, 2) \
     _BOOST_gcc_test(5, 2) \
     _BOOST_mingw_test(5, 1) \
     _BOOST_gcc_test(5, 1) \
     _BOOST_mingw_test(5, 0) \
     _BOOST_gcc_test(5, 0) \
     _BOOST_mingw_test(4, 10) \
     _BOOST_gcc_test(4, 10) \
     _BOOST_mingw_test(4, 9) \
     _BOOST_gcc_test(4, 9) \
     _BOOST_mingw_test(4, 8) \
     _BOOST_gcc_test(4, 8) \
     _BOOST_mingw_test(4, 7) \
     _BOOST_gcc_test(4, 7) \
     _BOOST_mingw_test(4, 6) \
     _BOOST_gcc_test(4, 6) \
     _BOOST_mingw_test(4, 5) \
     _BOOST_gcc_test(4, 5) \
     _BOOST_mingw_test(4, 4) \
     _BOOST_gcc_test(4, 4) \
     _BOOST_mingw_test(4, 3) \
     _BOOST_gcc_test(4, 3) \
     _BOOST_mingw_test(4, 2) \
     _BOOST_gcc_test(4, 2) \
     _BOOST_mingw_test(4, 1) \
     _BOOST_gcc_test(4, 1) \
     _BOOST_mingw_test(4, 0) \
     _BOOST_gcc_test(4, 0) \
     "defined __GNUC__ && __GNUC__ == 3 && !defined __ICC \
      && (defined WIN32 || defined WINNT || defined _WIN32 || defined __WIN32 \
          || defined __WIN32__ || defined __WINNT || defined __WINNT__) @ mgw" \
     _BOOST_gcc_test(3, 4) \
     _BOOST_gcc_test(3, 3) \
     "defined _MSC_VER && _MSC_VER >= 1500 @ vc90" \
     "defined _MSC_VER && _MSC_VER == 1400 @ vc80" \
     _BOOST_gcc_test(3, 2) \
     "defined _MSC_VER && _MSC_VER == 1310 @ vc71" \
     _BOOST_gcc_test(3, 1) \
     _BOOST_gcc_test(3, 0) \
     "defined __BORLANDC__ @ bcb" \
     "defined __ICC && (defined __unix || defined __unix__) @ il" \
     "defined __ICL @ iw" \
     "defined _MSC_VER && _MSC_VER == 1300 @ vc7" \
     _BOOST_gcc_test(2, 95) \
     "defined __MWERKS__ && __MWERKS__ <= 0x32FF @ cw9" \
     "defined _MSC_VER && _MSC_VER < 1300 && !defined UNDER_CE @ vc6" \
     "defined _MSC_VER && _MSC_VER < 1300 && defined UNDER_CE @ evc4" \
     "defined __MWERKS__ && __MWERKS__ <= 0x31FF @ cw8"
   do
     boost_tag_test=`expr "X$i" : 'X\([[^@]]*\) @ '`
     boost_tag=`expr "X$i" : 'X[[^@]]* @ \(.*\)'`
     AC_COMPILE_IFELSE([AC_LANG_PROGRAM([[
 #if $boost_tag_test
 /* OK */
 #else
 # error $boost_tag_test
 #endif
 ]])], [boost_cv_lib_tag=$boost_tag; break], [])
   done
 AC_LANG_POP([C++])dnl
   case $boost_cv_lib_tag in #(
     # Some newer (>= 1.35?) versions of Boost seem to only use "gcc" as opposed
     # to "gcc41" for instance.
     *-gcc | *'-gcc ') :;; #(  Don't re-add -gcc: it's already in there.
     gcc*)
       boost_tag_x=
       case $host_os in #(
         darwin*)
           if test $boost_major_version -ge 136; then
             # The `x' added in r46793 of Boost.
             boost_tag_x=x
           fi;;
       esac
       # We can specify multiple tags in this variable because it's used by
       # BOOST_FIND_LIB that does a `for tag in -$boost_cv_lib_tag' ...
       boost_cv_lib_tag="$boost_tag_x$boost_cv_lib_tag -${boost_tag_x}gcc"
       ;; #(
     unknown)
       AC_MSG_WARN([[could not figure out which toolset name to use for $CXX]])
       boost_cv_lib_tag=
       ;;
   esac
 fi])dnl end of AC_CACHE_CHECK
 ])# _BOOST_FIND_COMPILER_TAG
 
 
 # _BOOST_GUESS_WHETHER_TO_USE_MT()
 # --------------------------------
 # Compile a small test to try to guess whether we should favor MT (Multi
 # Thread) flavors of Boost.  Sets boost_guess_use_mt accordingly.
 AC_DEFUN([_BOOST_GUESS_WHETHER_TO_USE_MT],
 [# Check whether we do better use `mt' even though we weren't ask to.
 AC_LANG_PUSH([C++])dnl
 AC_COMPILE_IFELSE([AC_LANG_PROGRAM([[
 #if defined _REENTRANT || defined _MT || defined __MT__
 /* use -mt */
 #else
 # error MT not needed
 #endif
 ]])], [boost_guess_use_mt=:], [boost_guess_use_mt=false])
 AC_LANG_POP([C++])dnl
 ])
 
 # _BOOST_AC_LINK_IFELSE(PROGRAM, [ACTION-IF-TRUE], [ACTION-IF-FALSE])
 # -------------------------------------------------------------------
 # Fork of _AC_LINK_IFELSE that preserves conftest.o across calls.  Fragile,
 # will break when Autoconf changes its internals.  Requires that you manually
 # rm -f conftest.$ac_objext in between to really different tests, otherwise
 # you will try to link a conftest.o left behind by a previous test.
 # Used to aggressively optimize BOOST_FIND_LIB (see the big comment in this
 # macro).
 #
 # Don't use "break" in the actions, as it would short-circuit some code
 # this macro runs after the actions.
 m4_define([_BOOST_AC_LINK_IFELSE],
 [m4_ifvaln([$1], [AC_LANG_CONFTEST([$1])])dnl
 rm -f conftest$ac_exeext
 boost_save_ac_ext=$ac_ext
 boost_use_source=:
 # If we already have a .o, re-use it.  We change $ac_ext so that $ac_link
 # tries to link the existing object file instead of compiling from source.
 test -f conftest.$ac_objext && ac_ext=$ac_objext && boost_use_source=false &&
   _AS_ECHO_LOG([re-using the existing conftest.$ac_objext])
 AS_IF([_AC_DO_STDERR($ac_link) && {
          test -z "$ac_[]_AC_LANG_ABBREV[]_werror_flag" ||
          test ! -s conftest.err
        } && test -s conftest$ac_exeext && {
          test "$cross_compiling" = yes ||
          $as_executable_p conftest$ac_exeext
 dnl FIXME: use AS_TEST_X instead when 2.61 is widespread enough.
        }],
       [$2],
       [if $boost_use_source; then
          _AC_MSG_LOG_CONFTEST
        fi
        $3])
 ac_objext=$boost_save_ac_objext
 ac_ext=$boost_save_ac_ext
 dnl Delete also the IPA/IPO (Inter Procedural Analysis/Optimization)
 dnl information created by the PGI compiler (conftest_ipa8_conftest.oo),
 dnl as it would interfere with the next link command.
 rm -f core conftest.err conftest_ipa8_conftest.oo \
       conftest$ac_exeext m4_ifval([$1], [conftest.$ac_ext])[]dnl
 ])# _BOOST_AC_LINK_IFELSE
 
 # Local Variables:
 # mode: autoconf
 # End:
diff --git a/m4/herwig.m4 b/m4/herwig.m4
--- a/m4/herwig.m4
+++ b/m4/herwig.m4
@@ -1,892 +1,900 @@
 dnl ##### THEPEG #####
 AC_DEFUN([HERWIG_CHECK_THEPEG],
 [
 defaultlocation="${prefix}"
 test "x$defaultlocation" = xNONE && defaultlocation="${ac_default_prefix}"
 AC_MSG_CHECKING([for libThePEG in])
 AC_ARG_WITH(thepeg,
         AC_HELP_STRING([--with-thepeg=DIR],[location of ThePEG installation]),
         [],
 	[with_thepeg="${defaultlocation}"])
 AC_MSG_RESULT([$with_thepeg])
 
 if test "x$with_thepeg" = "xno"; then
 	AC_MSG_ERROR([Cannot build Herwig without ThePEG. Please set --with-thepeg.])
 fi
 
 THEPEGLDFLAGS="-L${with_thepeg}/lib/ThePEG"
 
 THEPEGHASLHAPDF="no"
 if test -e ${with_thepeg}/lib/ThePEG/ThePEGLHAPDF.so ; then
    THEPEGHASLHAPDF="yes"
 fi
 if test "${host_cpu}" == "x86_64" -a -e ${with_thepeg}/lib64/ThePEG/libThePEG.so ; then
   THEPEGLDFLAGS="-L${with_thepeg}/lib64/ThePEG"
   if test -e ${with_thepeg}/lib64/ThePEG/ThePEGLHAPDF.so ; then
       THEPEGHASLHAPDF="yes"
   fi
 fi
 
 if test "x$THEPEGHASLHAPDF" == "xno" ; then
    AC_MSG_ERROR([Herwig requires ThePEG to be build with lhapdf.])
 fi
 
 THEPEGHASFASTJET="no"
 if test -e ${with_thepeg}/lib/ThePEG/FastJetFinder.so ; then
    THEPEGHASFASTJET="yes"
 fi
 if test "${host_cpu}" == "x86_64" -a -e ${with_thepeg}/lib64/ThePEG/libThePEG.so ; then
   THEPEGLDFLAGS="-L${with_thepeg}/lib64/ThePEG"
   if test -e ${with_thepeg}/lib64/ThePEG/FastJetFinder.so ; then
       THEPEGHASFASTJET="yes"
   fi
 fi
 
 if test "x$THEPEGHASFASTJET" == "xno" ; then
    AC_MSG_ERROR([Herwig requires ThePEG to be build with FastJet.])
 fi
 
 THEPEGPATH="${with_thepeg}"
 
 oldldflags="$LDFLAGS"
 oldlibs="$LIBS"
 
 LDFLAGS="$LDFLAGS $THEPEGLDFLAGS"
 AC_CHECK_LIB([ThePEG],[debugThePEG],[],
 	[AC_MSG_ERROR([No ThePEG libraries in $THEPEGLDFLAGS. Please set --with-thepeg.])])
 
 AC_SUBST([THEPEGLIB],[-lThePEG])
 AC_SUBST(THEPEGLDFLAGS)
 AC_SUBST(THEPEGPATH)
 AC_SUBST(THEPEGHASLHAPDF)
 AC_SUBST(THEPEGHASFASTJET)
 
 LIBS="$oldlibs"
 LDFLAGS="$oldldflags"
 
 AC_MSG_CHECKING([for ThePEG headers in])
 AC_ARG_WITH([thepeg-headers],
         AC_HELP_STRING([--with-thepeg-headers=DIR],[location of ThePEG include directory]),
         [],
 	[with_thepeg_headers="${with_thepeg}/include"])
 AC_MSG_RESULT([$with_thepeg_headers])
 
 if test "x$with_thepeg_headers" = "xno"; then
 	AC_MSG_ERROR([Cannot build Herwig without ThePEG headers. Please set --with-thepeg-headers.])
 fi
 
 THEPEGINCLUDE="-I$with_thepeg_headers"
 
 oldcppflags="$CPPFLAGS"
 CPPFLAGS="$CPPFLAGS $THEPEGINCLUDE"
 AC_CHECK_HEADER([ThePEG/Config/ThePEG.h],[],
 	[AC_MSG_ERROR([No ThePEG headers in $with_thepeg_headers. Please set --with-thepeg-headers.])])
 CPPFLAGS="$oldcppflags"
 
 AC_SUBST(THEPEGINCLUDE)
 
 AC_MSG_CHECKING([for HepMCAnalysis.so in ThePEG])
 
 THEPEGHASHEPMC="no"
 if test -e ${with_thepeg}/lib/ThePEG/HepMCAnalysis.so ; then
    THEPEGHASHEPMC="yes"
 fi
 if test "${host_cpu}" == "x86_64" -a -e ${with_thepeg}/lib64/ThePEG/libThePEG.so ; then
   THEPEGLDFLAGS="-L${with_thepeg}/lib64/ThePEG"
   if test -e ${with_thepeg}/lib64/ThePEG/HepMCAnalysis.so ; then
     THEPEGHASHEPMC="yes"
   fi
 fi
 
 if test "x$THEPEGHASHEPMC" == "xno" ; then
   CREATE_HEPMC="# create"
   AC_MSG_RESULT([not found])
 else
   CREATE_HEPMC="create"
   AC_MSG_RESULT([found])
 fi
 
 AC_SUBST([CREATE_HEPMC])
 
 AC_MSG_CHECKING([for RivetAnalysis.so in ThePEG])
 
 THEPEGHASRIVET="no"
 if test -e ${with_thepeg}/lib/ThePEG/RivetAnalysis.so ; then
    THEPEGHASRIVET="yes"
 fi
 if test "${host_cpu}" == "x86_64" -a -e ${with_thepeg}/lib64/ThePEG/libThePEG.so ; then
   THEPEGLDFLAGS="-L${with_thepeg}/lib64/ThePEG"
   if test -e ${with_thepeg}/lib64/ThePEG/RivetAnalysis.so ; then
     THEPEGHASRIVET="yes"
   fi
 fi
 
 if test "x$THEPEGHASRIVET" == "xno" ; then
   CREATE_RIVET="# create"
   AC_MSG_RESULT([not found])
 else
   CREATE_RIVET="create"
   AC_MSG_RESULT([found])
 fi
 
 AC_SUBST([CREATE_RIVET])
 ])
 
 dnl ##### LOOPTOOLS #####
 AC_DEFUN([HERWIG_LOOPTOOLS],
 [
 AC_REQUIRE([AC_PROG_FC])
 AC_REQUIRE([AC_FC_LIBRARY_LDFLAGS])
 AC_REQUIRE([AC_PROG_CC])
 AC_REQUIRE([HERWIG_COMPILERFLAGS])
 
 AC_MSG_CHECKING([if Looptools build works])
 enable_looptools=yes
 
 if test "x$GCC" = "xyes"; then
    case "${host}" in
       x86_64-*|*-darwin1*)
 	AM_FCFLAGS="$AM_FCFLAGS -fdefault-integer-8"
       	;;
    esac
 
    AC_LANG_PUSH([Fortran])
    	oldFCFLAGS="$FCFLAGS"
    	FCFLAGS="$AM_FCFLAGS"
    	AC_COMPILE_IFELSE(
 	   	AC_LANG_PROGRAM([],[      print *[,]"Hello"]),
 		[],
 		[AC_MSG_RESULT([no])
  		 AC_MSG_ERROR([needs gfortran on 64bit machines])]
 	)
 	FCFLAGS="$oldFCFLAGS"
   AC_LANG_POP([Fortran])
 fi
 AC_MSG_RESULT([$enable_looptools])
 
 AC_SUBST([F77],[$FC])
 AC_SUBST([FFLAGS],[$FCFLAGS])
 AC_SUBST([AM_FFLAGS],[$AM_FCFLAGS])
 AC_SUBST([FLIBS],[$FCLIBS])
 ])
 
 dnl ##### VBFNLO #####
 AC_DEFUN([HERWIG_CHECK_VBFNLO],
 [
 AC_MSG_CHECKING([for VBFNLO])
 
 AC_ARG_WITH([vbfnlo],
     AS_HELP_STRING([--with-vbfnlo=DIR], [Installation path of VBFNLO]),
     [],
     [with_vbfnlo=no]
 
 )
 
 AC_MSG_RESULT([$with_vbfnlo])
 
 AS_IF([test "x$with_vbfnlo" != "xno"],
       [AC_CHECK_FILES(
       ${with_vbfnlo}/lib/VBFNLO/libVBFNLO.so,
       [have_vbfnlo=lib], [have_vbfnlo=no])],
       [have_vbfnlo=no])
 
 AS_IF([test "x$with_vbfnlo" != "xno" -a "x$have_vbfnlo" = "xno" ],
       [AC_CHECK_FILES(
       ${with_vbfnlo}/lib64/VBFNLO/libVBFNLO.so,
       [have_vbfnlo=lib64], [have_vbfnlo=no])])
 
 AS_IF([test "x$with_vbfnlo" != "xno" -a "x$have_vbfnlo" = "xno" ],
       [AC_CHECK_FILES(
       ${with_vbfnlo}/lib/VBFNLO/libVBFNLO.dylib,
       [have_vbfnlo=lib], [have_vbfnlo=no])])
 
 AS_IF([test "x$with_vbfnlo" != "xno" -a "x$have_vbfnlo" = "xno" ],
       [AC_CHECK_FILES(
       ${with_vbfnlo}/lib64/VBFNLO/libVBFNLO.dylib,
       [have_vbfnlo=lib64], [have_vbfnlo=no])])
 
 AS_IF([test "x$have_vbfnlo" = "xlib"],
       [VBFNLOLIBS=${with_vbfnlo}/lib/VBFNLO
       AC_SUBST(VBFNLOLIBS)
       ])
 
 AS_IF([test "x$have_vbfnlo" = "xlib64"],
       [VBFNLOLIBS=${with_vbfnlo}/lib64/VBFNLO
       AC_SUBST(VBFNLOLIBS)
       ])
 
 AS_IF([test "x$with_vbfnlo" != "xno" -a "x$have_vbfnlo" = "xno"],
       [AC_MSG_ERROR([vbfnlo requested but not found])])
 
 AM_CONDITIONAL(HAVE_VBFNLO,[test "x$have_vbfnlo" = "xlib" -o "x$have_vbfnlo" = "xlib64"])
 
 if test "x$have_vbfnlo" = "xlib" -o "x$have_vbfnlo" = "xlib64" ; then
         AC_REQUIRE([AC_PROG_SED])
         VBFNLOINCLUDE=${with_vbfnlo}/include
 	AC_SUBST(VBFNLOINCLUDE)
         VBFNLOLIB=$(echo ${with_vbfnlo}/${have_vbfnlo}/VBFNLO | $SED -e 's%/\+%/%g')
         AC_SUBST(VBFNLOLIB)
      	LOAD_VBFNLO="library"
      	CREATE_VBFNLO="create"
      	INSERT_VBFNLO="insert"
      	SET_VBFNLO="set"
      	DO_VBFNLO="do"
      	MKDIR_VBFNLO="mkdir"
 else
      	LOAD_VBFNLO="# library"
 	CREATE_VBFNLO="# create"
      	INSERT_VBFNLO="# insert"
      	SET_VBFNLO="# set"
      	DO_VBFNLO="# do"
      	MKDIR_VBFNLO="# mkdir"
 fi
 
 AC_SUBST([LOAD_VBFNLO])
 AC_SUBST([CREATE_VBFNLO])
 AC_SUBST([INSERT_VBFNLO])
 AC_SUBST([SET_VBFNLO])
 AC_SUBST([DO_VBFNLO])
 AC_SUBST([MKDIR_VBFNLO])
 
 ])
 
 dnl ##### njet #####
 AC_DEFUN([HERWIG_CHECK_NJET],
 [
 AC_MSG_CHECKING([for njet])
 
 AC_ARG_WITH([njet],
     AS_HELP_STRING([--with-njet=DIR], [Installation path of njet]),
     [],
     [with_njet=no]
 
 )
 
 AC_MSG_RESULT([$with_njet])
 
 AS_IF([test "x$with_njet" != "xno"],
       [AC_CHECK_FILES(
       ${with_njet}/lib/libnjet2.so,
       [have_njet=lib], [have_njet=no])],
       [have_njet=no])
 
 AS_IF([test "x$with_njet" != "xno" -a "x$have_njet" = "xno" ],
       [AC_CHECK_FILES(
       ${with_njet}/lib64/libnjet2.so,
       [have_njet=lib64], [have_njet=no])])
 
 AS_IF([test "x$with_njet" != "xno" -a "x$have_njet" = "xno" ],
       [AC_CHECK_FILES(
       ${with_njet}/lib/libnjet2.dylib,
       [have_njet=lib], [have_njet=no])])
 
 AS_IF([test "x$have_njet" = "xlib"],
       [NJETLIBPATH=${with_njet}/lib
       AC_SUBST(NJETLIBPATH)
       NJETINCLUDEPATH=${with_njet}/include
       AC_SUBST(NJETINCLUDEPATH)
       NJETPREFIX=${with_njet}
       AC_SUBST(NJETPREFIX)
       ])
 
 AS_IF([test "x$have_njet" = "xlib64"],
       [NJETLIBPATH=${with_njet}/lib64
       AC_SUBST(NJETLIBPATH)
       NJETINCLUDEPATH=${with_njet}/include
       AC_SUBST(NJETINCLUDEPATH)
       NJETPREFIX=${with_njet}
       AC_SUBST(NJETPREFIX)
       ])
 
 AS_IF([test "x$with_njet" != "xno"  -a "x$have_njet" = "xno"],
       [AC_MSG_ERROR([njet requested but not found])])
 
 AM_CONDITIONAL(HAVE_NJET,[test "x$have_njet" = "xlib" -o "x$have_njet" = "xlib64"])
 
 if test "x$have_njet" = "xlib" -o "x$have_njet" = "xlib64" ; then
      	LOAD_NJET="library"
      	CREATE_NJET="create"
      	INSERT_NJET="insert"
      	DO_NJET="do"
 else
      	LOAD_NJET="# library"
 	CREATE_NJET="# create"
      	INSERT_NJET="# insert"
      	DO_NJET="# do"
 fi
 
 AC_SUBST([LOAD_NJET])
 AC_SUBST([CREATE_NJET])
 AC_SUBST([INSERT_NJET])
 AC_SUBST([DO_NJET])
 
 ])
 
 
 
 dnl ##### gosam #####
 AC_DEFUN([HERWIG_CHECK_GOSAM],
 [
-AC_MSG_CHECKING([for gosam])
+AC_MSG_CHECKING([for GoSam])
 
 AC_ARG_WITH([gosam],
-    AS_HELP_STRING([--with-gosam=DIR], [Installation path of gosam]),
+    AS_HELP_STRING([--with-gosam=DIR], [Installation path of GoSam]),
     [],
     [with_gosam=no]
 )
 
 AC_MSG_RESULT([$with_gosam])
 
 AS_IF([test "x$with_gosam" != "xno"],
       [AC_CHECK_FILES(
       ${with_gosam}/bin/gosam.py,
       [have_gosam=lib], [have_gosam=no])],
       [have_gosam=no])
 
 AS_IF([test "x$have_gosam" = "xlib"],
       [GOSAMPREFIX=${with_gosam}
       AC_SUBST(GOSAMPREFIX)
       ])
 
 AS_IF([test "x$with_gosam" != "xno"  -a "x$have_gosam" = "xno"],
       [AC_MSG_ERROR([GoSam requested but not found])])
 
+AS_IF([test "x$with_gosam" != "xno"],
+[AC_MSG_CHECKING([for GoSam version >= 2.0.4])
+tmp_gosamversion=[$(${with_gosam}/bin/gosam.py --version | grep 'GoSam.*rev' | cut -d' ' -f2)]
+AX_COMPARE_VERSION([${tmp_gosamversion}],[lt],[2.0.4],
+                   [AC_MSG_RESULT([no])
+                    AC_MSG_ERROR([Herwig requires GoSam 2.0.4 or later, found ${tmp_gosamversion}])],
+                   [AC_MSG_RESULT([yes])])])
+
 AM_CONDITIONAL(HAVE_GOSAM,[test "x$have_gosam" = "xlib" ])
 
 if test "x$have_gosam" = "xlib"  ; then
      	LOAD_GOSAM="library"
      	CREATE_GOSAM="create"
      	INSERT_GOSAM="insert"
      	DO_GOSAM="do"
 else
      	LOAD_GOSAM="# library"
 	CREATE_GOSAM="# create"
      	INSERT_GOSAM="# insert"
      	DO_GOSAM="# do"
 fi
 
 AC_SUBST([LOAD_GOSAM])
 AC_SUBST([CREATE_GOSAM])
 AC_SUBST([INSERT_GOSAM])
 AC_SUBST([DO_GOSAM])
 
 
 ])
 
 
 dnl ##### gosam-contrib #####
 AC_DEFUN([HERWIG_CHECK_GOSAM_CONTRIB],
 [
 AC_MSG_CHECKING([for gosam-contrib])
 
 AC_ARG_WITH([gosam-contrib],
     AS_HELP_STRING([--with-gosam-contrib=DIR], [Installation path of gosam-contrib]),
     [],
     [with_gosam_contrib=no]
 )
 
 AC_MSG_RESULT([$with_gosam_contrib])
 
 AS_IF([test "x$with_gosam_contrib" = "xno" -a "x$with_gosam" != "xno"],
       [AC_CHECK_FILES(
       ${with_gosam}/lib/libsamurai.so,
       [with_gosam_contrib=${with_gosam}], [])
 ])
 
 AS_IF([test "x$with_gosam_contrib" = "xno" -a "x$with_gosam" != "xno"],
       [AC_CHECK_FILES(
       ${with_gosam}/lib64/libsamurai.so,
       [with_gosam_contrib=${with_gosam}], [])
 ])
 
 AS_IF([test "x$with_gosam_contrib" = "xno" -a "x$with_gosam" != "xno"],
       [AC_CHECK_FILES(
       ${with_gosam}/lib/libsamurai.dylib,
       [with_gosam_contrib=${with_gosam}], [])
 ])
 
 AS_IF([test "x$with_gosam_contrib" = "xno" -a "x$with_gosam" != "xno"],
       [AC_CHECK_FILES(
       ${with_gosam}/lib64/libsamurai.dylib,
       [with_gosam_contrib=${with_gosam}], [])
 ])
 
 AS_IF([test "x$with_gosam_contrib" = "xno" -a "x$with_gosam" != "xno"],
       [AC_MSG_ERROR([GoSam requested without requesting GoSam-Contrib])])
 
 AS_IF([test "x$with_gosam_contrib" != "xno"],
       [AC_CHECK_FILES(
       ${with_gosam_contrib}/lib/libsamurai.so,
       [have_gosam_contrib=lib], [have_gosam_contrib=no])],
       [have_gosam_contrib=no])
 
 AS_IF([test "x$with_gosam_contrib" != "xno" -a "x$have_gosam_contrib" = "xno" ],
       [AC_CHECK_FILES(
       ${with_gosam_contrib}/lib64/libsamurai.so,
       [have_gosam_contrib=lib64], [have_gosam_contrib=no])])
 
 AS_IF([test "x$with_gosam_contrib" != "xno" -a "x$have_gosam_contrib" = "xno" ],
       [AC_CHECK_FILES(
       ${with_gosam_contrib}/lib/libsamurai.dylib,
       [have_gosam_contrib=lib], [have_gosam_contrib=no])])
 
 AS_IF([test "x$with_gosam_contrib" != "xno" -a "x$have_gosam_contrib" = "xno" ],
       [AC_CHECK_FILES(
       ${with_gosam_contrib}/lib64/libsamurai.dylib,
       [have_gosam_contrib=lib64], [have_gosam_contrib=no])])
 
 
 
 
 
 
 
 AS_IF([test "x$have_gosam_contrib" != "xno"],
       [GOSAMCONTRIBPREFIX=${with_gosam_contrib}
       AC_SUBST(GOSAMCONTRIBPREFIX)
       ])
 
 AS_IF([test "x$have_gosam_contrib" = "xlib"],
       [GOSAMCONTRIBLIBS=${with_gosam_contrib}/lib
       AC_SUBST(GOSAMCONTRIBLIBS)
       ])
 
 AS_IF([test "x$have_gosam_contrib" = "xlib64"],
       [GOSAMCONTRIBLIBS=${with_gosam_contrib}/lib64
       AC_SUBST(GOSAMCONTRIBLIBS)
       ])
 
 AS_IF([test "x$with_gosam_contrib" != "xno"  -a "x$have_gosam_contrib" = "xno"],
       [AC_MSG_ERROR([GoSam-Contrib requested but not found])])
 
 AM_CONDITIONAL(HAVE_GOSAM_CONTRIB,[test "x$have_gosam_contrib" = "xlib" -o "x$have_gosam_contrib" = "xlib64"])
 
 if test "x$have_gosam_contrib" = "xlib" -o "x$have_gosam_contrib" = "xlib64" ; then
         LOAD_GOSAM_CONTRIB="library"
         CREATE_GOSAM_CONTRIB="create"
         INSERT_GOSAM_CONTRIB="insert"
 else
         LOAD_GOSAM_CONTRIB="# library"
         CREATE_GOSAM_CONTRIB="# create"
         INSERT_GOSAM_CONTRIB="# insert"
 fi
 
 AC_SUBST([LOAD_GOSAM_CONTRIB])
 AC_SUBST([CREATE_GOSAM_CONTRIB])
 AC_SUBST([INSERT_GOSAM_CONTRIB])
 
 
 ])
 
 
 dnl ##### OpenLoops #####
 AC_DEFUN([HERWIG_CHECK_OPENLOOPS],
 [
 AC_MSG_CHECKING([for OpenLoops])
 
 AC_ARG_WITH([openloops],
     AS_HELP_STRING([--with-openloops=DIR], [Installation path of OpenLoops]),
     [],
     [with_openloops=no]
 
 )
 
 AC_MSG_RESULT([$with_openloops])
 
 AS_IF([test "x$with_openloops" != "xno"],
       [AC_CHECK_FILES(
       ${with_openloops}/lib/libopenloops.so,
       [have_openloops=lib], [have_openloops=no])],
       [have_openloops=no])
 
 AS_IF([test "x$with_openloops" != "xno" -a "x$have_openloops" = "xno" ],
       [AC_CHECK_FILES(
       ${with_openloops}/lib/libopenloops.dylib,
       [have_openloops=lib], [have_openloops=no])])
 
 AS_IF([test "x$with_openloops" != "xno" -a "x$have_openloops" = "xno" ],
       [AC_CHECK_FILES(
       ${with_openloops}/lib64/libopenloops.so,
       [have_openloops=lib64], [have_openloops=no])])
 
 
 AS_IF([test "x$with_openloops" != "xno" -a "x$have_openloops" = "xno" ],
       [AC_CHECK_FILES(
       ${with_openloops}/lib64/libopenloops.dylib,
       [have_openloops=lib64], [have_openloops=no])])
 
 
 
 
 
 AS_IF([test "x$have_openloops" = "xlib"],
       [OPENLOOPSLIBS=${with_openloops}/lib
       AC_SUBST(OPENLOOPSLIBS)
       ])
 
 AS_IF([test "x$have_openloops" = "xlib64"],
       [OPENLOOPSLIBS=${with_openloops}/lib64
       AC_SUBST(OPENLOOPSLIBS)
       ])
 
 AS_IF([test "x$with_openloops" != "xno" -a "x$have_openloops" = "xno"],
       [AC_MSG_ERROR([OpenLoops requested but not found])])
 
 AM_CONDITIONAL(HAVE_OPENLOOPS,[test "x$have_openloops" = "xlib" -o "x$have_openloops" = "xlib64"])
 
 if test "x$have_openloops" = "xlib" -o "x$have_openloops" = "xlib64" ; then
         OPENLOOPSPREFIX=${with_openloops}
      	LOAD_OPENLOOPS="library"
      	CREATE_OPENLOOPS="create"
      	INSERT_OPENLOOPS="insert"
      	SET_OPENLOOPS="set"
      	DO_OPENLOOPS="do"
      	MKDIR_OPENLOOPS="mkdir"
 else
      	LOAD_OPENLOOPS="# library"
 	CREATE_OPENLOOPS="# create"
      	INSERT_OPENLOOPS="# insert"
      	SET_OPENLOOPS="# set"
      	DO_OPENLOOPS="# do"
      	MKDIR_OPENLOOPS="# mkdir"
 fi
 
 AC_SUBST([OPENLOOPSPREFIX])
 AC_SUBST([LOAD_OPENLOOPS])
 AC_SUBST([CREATE_OPENLOOPS])
 AC_SUBST([INSERT_OPENLOOPS])
 AC_SUBST([SET_OPENLOOPS])
 AC_SUBST([DO_OPENLOOPS])
 AC_SUBST([MKDIR_OPENLOOPS])
 
 ])
 
 #########################################
 
 dnl ##### madgraph #####
 AC_DEFUN([HERWIG_CHECK_MADGRAPH],
 [
 AC_MSG_CHECKING([for MadGraph])
 
 AC_ARG_WITH([madgraph],
     AS_HELP_STRING([--with-madgraph=DIR], [Installation path of MadGraph]),
     [],
     [with_madgraph=no]
 )
 
 AC_MSG_RESULT([$with_madgraph])
 
 AS_IF([test "x$with_madgraph" != "xno"],
       [AC_CHECK_FILES(
       ${with_madgraph}/bin/mg5_aMC,
       [have_madgraph=yes], [have_madgraph=no])],
       [have_madgraph=no])
 
 AS_IF([test "x$have_madgraph" = "xyes"],
       [MADGRAPHPREFIX=${with_madgraph}
       AC_SUBST(MADGRAPHPREFIX)
       ])
 
 AS_IF([test "x$with_madgraph" != "xno"  -a "x$have_madgraph" = "xno"],
       [AC_MSG_ERROR([MadGraph requested but not found])])
 
 AM_CONDITIONAL(HAVE_MADGRAPH,[test "x$have_madgraph" = "xyes" ])
 
 if test "x$have_madgraph" = "xyes"  ; then
      	LOAD_MADGRAPH="library"
      	CREATE_MADGRAPH="create"
      	INSERT_MADGRAPH="insert"
      	SET_MADGRAPH="set"
      	DO_MADGRAPH="do"
 else
      	LOAD_MADGRAPH="# library"
 	CREATE_MADGRAPH="# create"
      	INSERT_MADGRAPH="# insert"
      	SET_MADGRAPH="# set"
      	DO_MADGRAPH="# do"
 fi
 
 AC_SUBST([LOAD_MADGRAPH])
 AC_SUBST([CREATE_MADGRAPH])
 AC_SUBST([INSERT_MADGRAPH])
 AC_SUBST([SET_MADGRAPH])
 AC_SUBST([DO_MADGRAPH])
 
 ])
 
 
 dnl ##### EvtGen #####
 AC_DEFUN([HERWIG_CHECK_EVTGEN],
 [
 AC_MSG_CHECKING([for evtgen])
 
 AC_ARG_WITH([evtgen],
     AS_HELP_STRING([--with-evtgen=DIR], [Installation path of EvtGen]),
     [],
     [with_evtgen=no]
 )
 
 AC_MSG_RESULT([$with_evtgen])
 
 AS_IF([test "x$with_evtgen" != "xno"],
       [AC_CHECK_FILES(
       ${with_evtgen}/lib/libEvtGenExternal.so,
       [have_evtgen=lib], [have_evtgen=no])],
       [have_evtgen=no])
 
 AS_IF([test "x$with_evtgen" != "xno" -a "x$have_evtgen" = "xno"],
       [AC_CHECK_FILES(
       ${with_evtgen}/lib64/libEvtGenExternal.so,
       [have_evtgen=lib64], [have_evtgen=no])])
 
 AS_IF([test "x$with_evtgen" != "xno" -a "x$have_evtgen" = "xno" ],
       [AC_CHECK_FILES(
       ${with_evtgen}/lib/libEvtGenExternal.dylib,
       [have_evtgen=lib], [have_evtgen=no])])
 
 AS_IF([test "x$have_evtgen" = "xlib" -o "x$have_evtgen" = "xlib64" ],
       [EVTGENPREFIX=${with_evtgen}
       AC_SUBST(EVTGENPREFIX)
       ])
 
 AS_IF([test "x$with_evtgen" != "xno"  -a "x$have_evtgen" = "xno"],
       [AC_MSG_ERROR([EvtGen requested but not found])])
 
 AC_SUBST([EVTGENINCLUDE],[-I$EVTGENPREFIX/include])
 
 AM_CONDITIONAL(HAVE_EVTGEN,[test "x$have_evtgen" = "xlib" ])
 
 if test "x$have_evtgen" = "xlib"  ; then
      	LOAD_EVTGEN_DECAYS="read EvtGenBDecays.in"
      	LOAD_EVTGEN_DECAYER="read EvtGenDecayer.in"
 	EVTGENLIBS="-L$with_evtgen/lib -lEvtGen -lEvtGenExternal"
 elif test "x$have_evtgen" = "xlib64"  ; then
       LOAD_EVTGEN_DECAYS="read EvtGenBDecays.in"
       LOAD_EVTGEN_DECAYER="read EvtGenDecayer.in"
   EVTGENLIBS="-L$with_evtgen/lib64 -lEvtGen -lEvtGenExternal"
 else
      	LOAD_EVTGEN_DECAYS="read HerwigBDecays.in"
      	LOAD_EVTGEN_DECAYER="#read EvtGenDecayer.in"
 	EVTGENLIBS=""
 fi
 
 AC_SUBST([LOAD_EVTGEN_DECAYS])
 AC_SUBST([LOAD_EVTGEN_DECAYER])
 AC_SUBST([EVTGENLIBS])
 
 
 ])
 
 AC_DEFUN([HERWIG_CHECK_PYTHIA],
 [
 dnl check if a directory is specified for Pythia
 AC_ARG_WITH(pythia,
             [AC_HELP_STRING([--with-pythia=dir], 
                             [Assume the given directory for Pythia])])
 
 dnl search for the pythia-config script
 if test "$with_pythia" = ""; then
    AC_PATH_PROG(pythiaconfig, pythia8-config, no)
 else
    AC_PATH_PROG(pythiaconfig, pythia8-config, no, ${with_pythia}/bin)
 fi
 
 if test "${pythiaconfig}" = "no"; then
    AC_MSG_CHECKING(Pythia)
    AC_MSG_RESULT(no);
 #   $2
 else
 
    PYTHIA8DATA=`${pythiaconfig} --datadir`/xmldoc
 
 fi
 
 AC_SUBST(PYTHIA8DATA)
 
 ])
 
 dnl CHECK PYTHIA END
 
 dnl ###### GSL ######
 AC_DEFUN([HERWIG_CHECK_GSL],
 [
 AC_MSG_CHECKING([for gsl location])
 GSLINCLUDE=""
 GSLLIBS=""
 
 AC_ARG_WITH(gsl,
         AC_HELP_STRING([--with-gsl=DIR],[location of gsl installation @<:@default=system libs@:>@]),
         [],
 	[with_gsl=system])
 
 if test "x$with_gsl" = "xno"; then
 AC_MSG_ERROR([libgsl is required. Please install the GNU scientific library and header files.])
 fi
 
 if test "x$with_gsl" = "xsystem"; then
 	AC_MSG_RESULT([in system libraries])
 	oldlibs="$LIBS"
 	AC_CHECK_LIB(m,main)
 	AC_CHECK_LIB(gslcblas,main)
 	AC_CHECK_LIB(gsl,main,[],
 			[
 			AC_MSG_ERROR([Cannot find libgsl. Please install the GNU scientific library and header files or use --with-gsl=.])
 			]
 		     )
 	GSLLIBS="$LIBS"
 	GSLPATH="$with_gsl"
 	LIBS=$oldlibs
 else
 	if test "`uname -m`" = "x86_64" -a -e "$with_gsl/lib64/libgsl.a" -a -d "$with_gsl/include/gsl"; then
 		AC_MSG_RESULT([found in $with_gsl])
 		GSLLIBS="-L$with_gsl/lib64 -R$with_gsl/lib64 -lgslcblas -lgsl"
 		GSLINCLUDE="-I$with_gsl/include"
 		GSLPATH="$with_gsl"
 	elif test -e "$with_gsl/lib/libgsl.a" -a -d "$with_gsl/include/gsl"; then
 		AC_MSG_RESULT([found in $with_gsl])
 		GSLLIBS="-L$with_gsl/lib -R$with_gsl/lib -lgslcblas -lgsl"
 		GSLINCLUDE="-I$with_gsl/include"
 		GSLPATH="$with_gsl"
 	else
 		AC_MSG_RESULT([not found])
 		AC_MSG_ERROR([Can't find $with_gsl/lib/libgsl.a or the headers in $with_gsl/include])
 	fi
 fi
 
 AC_SUBST(GSLINCLUDE)
 AC_SUBST(GSLLIBS)
 AC_SUBST(GSLPATH)
 ])
 
 dnl ##### COMPILERFLAGS #####
 AC_DEFUN([HERWIG_COMPILERFLAGS],
 [
 AC_REQUIRE([HERWIG_CHECK_GSL])
 AC_REQUIRE([HERWIG_CHECK_THEPEG])
 AC_REQUIRE([BOOST_REQUIRE])
 AC_REQUIRE([AX_COMPILER_VENDOR])
 
 AM_CPPFLAGS="-I\$(top_builddir)/include $THEPEGINCLUDE \$(GSLINCLUDE) \$(BOOST_CPPFLAGS)"
 
 AC_MSG_CHECKING([for debugging mode])
 AC_ARG_ENABLE(debug,
         AC_HELP_STRING([--enable-debug],[debug mode, use --enable-debug=slow for additional options that slow down the run.]),
         [],
         [enable_debug=no]
         )
 AC_MSG_RESULT([$enable_debug])
 
 if test "x$enable_debug" = "xno"; then
 	debugflags=""
 else
 	debugflags="-g"
 fi
 
 dnl -Wfloat-equal -fvisibility-inlines-hidden -Wctor-dtor-privacy -Weffc++
 if test -n "$GCC"; then
 	warnflags="-pedantic -Wall -Wextra -Wno-overloaded-virtual"
 
 	if test "x$enable_debug" = "xslow"; then
 		debugflags="$debugflags -fno-inline"
 		AM_CPPFLAGS="$AM_CPPFLAGS -D_GLIBCXX_DEBUG"
 	fi
 fi
 
 dnl do an actual capability check on ld instead of this workaround
 case "${host}" in
   *-darwin*)
      ;;
   *)
      AM_LDFLAGS="-Wl,--enable-new-dtags"
      ;;
 esac
 
 case "${ax_cv_cxx_compiler_vendor}" in
      gnu)
         AM_CXXFLAGS="-pedantic -Wall -W"
         ;;
      clang)
         AM_CXXFLAGS="-pedantic -Wall -Wno-overloaded-virtual -Wno-unused-function -Wno-unused-parameter"
 dnl  -Wno-unneeded-internal-declaration
         ;;
      intel)
         AM_CXXFLAGS="-strict-ansi -Wall -wd13000,1418,981,444,383,1599,1572,2259,980"
         ;;
 esac
 
 
 
 AC_SUBST(AM_CPPFLAGS)
 AC_SUBST(AM_CFLAGS,  ["$warnflags $debugflags"])
 AC_SUBST(AM_CXXFLAGS,["$AM_CXXFLAGS $warnflags $debugflags"])
 AC_SUBST(AM_FCFLAGS,  ["$debugflags"])
 AC_SUBST(AM_LDFLAGS)
 ])
 
 AC_DEFUN([HERWIG_ENABLE_MODELS],
 [
 AC_MSG_CHECKING([if BSM models should be built])
 
 AC_ARG_ENABLE(models,
         AC_HELP_STRING([--disable-models],[Turn off compilation of BSM models.]),
         [],
         [enable_models=yes]
         )
 AC_MSG_RESULT([$enable_models])
 
 LOAD_BSM=""
 if test "$enable_models" = "yes"; then
 LOAD_BSM="read BSMlibs.in"
 fi
 AC_SUBST(LOAD_BSM)
 
 AM_CONDITIONAL(WANT_BSM,[test "$enable_models" = "yes"])
 ])
 
 AC_DEFUN([HERWIG_OVERVIEW],
 [
 FCSTRING=`$FC --version | head -1`
 CXXSTRING=`$CXX --version | head -1`
 CCSTRING=`$CC --version | head -1`
 if test "x$PYTHON" != "x:"
 then
    python_was_found="yes, using Python $PYTHON_VERSION"
 else
    python_was_found="no, requires Python >= 2.6"
 fi
 cat << _HW_EOF_ > config.herwig
 *****************************************************
 *** $PACKAGE_STRING configuration summary
 *** Please include this information in bug reports!
 ***--------------------------------------------------
 *** Prefix:		$prefix
 ***
 *** BSM models:		$enable_models
 *** UFO converter:	${python_was_found}
 ***
 *** Herwig debug mode:	$enable_debug
 ***
 *** ThePEG:		$with_thepeg
 *** ThePEG headers:	$with_thepeg_headers
 ***
 *** GoSam:		$with_gosam
 *** GoSam-Contrib:      $with_gosam_contrib
 *** MadGraph:        	$with_madgraph
 *** njet:		$with_njet
 *** OpenLoops:		$with_openloops
 *** VBFNLO:		$with_vbfnlo
 ***
 *** EvtGen:		$with_evtgen
 *** GSL:		$with_gsl
 *** boost:              ${BOOST_CPPFLAGS:-system}
 *** Fastjet:		${fjconfig}
 ***
 *** Host:		$host
 *** CC:			$CCSTRING
 *** CXX:		$CXXSTRING
 *** FC:			$FCSTRING
 ***
 *** CXXFLAGS:		$CXXFLAGS
 *****************************************************
 _HW_EOF_
 ])
diff --git a/src/LEP.in b/src/LEP.in
--- a/src/LEP.in
+++ b/src/LEP.in
@@ -1,111 +1,85 @@
 # -*- ThePEG-repository -*-
 
 ##################################################
 # Example generator based on LEP parameters
 # usage: Herwig read LEP.in
 ##################################################
 
 read snippets/EECollider.in
 
 ##################################################
 # Change settings for the ee->Z->qq matrix element
 # to avoid producing top quarks
 #
 # 'set' lines like this can be omitted if the 
 # default value is already okay.
 #
 # Any repository setting can be modified here
 ##################################################
 
 ##################################################
 # Selected the hard process 
 ##################################################
 # leading-order processes
 ##################################################
 cd /Herwig/MatrixElements
 # default e+e- > q qbar (5 flavours d,u,s,c,b)
 insert SubProcess:MatrixElements 0 MEee2gZ2qq
 # e+e- > l+l-
 # insert SubProcess:MatrixElements[0] MEee2gZ2ll
 # e+e- > W+W- ZZ
 # insert SubProcess:MatrixElements[0] MEee2VV
 # higgs+Z
 # insert SubProcess:MatrixElements[0] MEee2ZH
 # higgs+e+e-/nu_enu_ebar via VBF
 # insert SubProcess:MatrixElements[0] MEee2HiggsVBF
 ##################################################
 # NLO powheg processes
 ##################################################
 #set /Herwig/Shower/ShowerHandler:HardEmission POWHEG
 #read Matchbox/Powheg-Default-ShowerAlphaSTune.in
 #insert SubProcess:MatrixElements 0 PowhegMEee2gZ2qq
 #insert SubProcess:MatrixElements 0 PowhegMEee2gZ2ll
 
 
 ##################################################
 # LEP physics parameters (override defaults) 
 ##################################################
 cd /Herwig/Generators
 set EventGenerator:EventHandler:LuminosityFunction:Energy 91.2
 
 cd /Herwig/Generators
 ##################################################
-#  Useful analysis handlers for LEP physics
-##################################################
-# particle multiplicities
-# insert EventGenerator:AnalysisHandlers 0 /Herwig/Analysis/LEPMultiplicity
-# b multiplicities
-# insert EventGenerator:AnalysisHandlers 0 /Herwig/Analysis/BMultiplicity
-# b fragmentation functions
-# insert EventGenerator:AnalysisHandlers 0 /Herwig/Analysis/BFrag
-# event shapes and single particle spectra
-# insert EventGenerator:AnalysisHandlers 0 /Herwig/Analysis/Shapes
-# identified particle spectra
-# insert EventGenerator:AnalysisHandlers 0 /Herwig/Analysis/LEPIdent
-# four jet analysis (needs Fastjet installed)
-# insert EventGenerator:AnalysisHandlers 0 /Herwig/Analysis/LEPFourJet
-# general jet analysis (needs Fastjet installed)
-# insert EventGenerator:AnalysisHandlers 0 /Herwig/Analysis/LEPJet
-
-##################################################
-#  Useful analysis handlers for B-factory physics
-##################################################
-# BELLE data on charm hadron spetra
-# insert EventGenerator:AnalysisHandlers 0 /Herwig/Analysis/BELLECharm
-# CLEO  data on charm meson spectra
-# insert EventGenerator:AnalysisHandlers 0 /Herwig/Analysis/CLEOCharm
-
-##################################################
 ## prepare for Rivet analysis or HepMC output
 ## when running with parton shower
 ##################################################
 #read snippets/Rivet.in
 #insert Rivet:Analyses 0 XXX_2015_ABC123
 #read snippets/HepMC.in
 #set HepMC:PrintEvent NNN
 
 ##################################################
 ## prepare for Rivet analysis or HepMC output
 ## when running at fixed order (NO shower)
 ##################################################
 #read snippets/RivetFixedOrder.in
 #insert RivetFixedOrder:Analyses 0 XXX_2015_ABC123
 #read snippets/HepMCFixedOrder.in
 #set HepMCFixedOrder:PrintEvent NNN
 
 ###################################################
 # Save run for later usage with 'Herwig run'
 ##################################################
 saverun LEP EventGenerator
 
 ##################################################
 # uncomment this section for an example batch run
 # of two repeats with different parameters
 #
 # Note that a separate call of 'Herwig run' 
 # is not required
 ##################################################
 # set EventGenerator:NumberOfEvents 100
 # run LEP-Zpole EventGenerator
 # set EventGenerator:EventHandler:LuminosityFunction:Energy 208.0
 # run LEP-maxE EventGenerator
diff --git a/src/LHC-MB.in b/src/LHC-MB.in
--- a/src/LHC-MB.in
+++ b/src/LHC-MB.in
@@ -1,91 +1,62 @@
 # -*- ThePEG-repository -*-
 
 ################################################################################
 # This file contains our best tune to UE data from ATLAS at 7 TeV. More recent
 # tunes and tunes for other centre-of-mass energies as well as more usage
 # instructions can be obtained from this Herwig wiki page:
 # http://projects.hepforge.org/herwig/trac/wiki/MB_UE_tunes
 # The model for soft interactions and diffractions is explained in
 # [S. Gieseke, P. Kirchgaesser, F. Loshaj, arXiv:1612.04701]
 ################################################################################
 
 read snippets/PPCollider.in
 
 ##################################################
 # Technical parameters for this run
 ##################################################
 cd /Herwig/Generators
 ##################################################
 # LHC physics parameters (override defaults here) 
 ##################################################
 set EventGenerator:EventHandler:LuminosityFunction:Energy 7000.0
 
 # Intrinsic pT tune extrapolated to LHC energy
 set /Herwig/Shower/ShowerHandler:IntrinsicPtGaussian 2.2*GeV
 
 # Minimum Bias
 read snippets/MB.in
 
+# Read in parameters of the soft model recommended for MB/UE simulations
+read snippets/SoftTune.in
+
 # Diffraction model
 read snippets/Diffraction.in
 
+##################################################
 # Analyses
-cd /Herwig/Analysis
-create ThePEG::RivetAnalysis RivetAnalysis RivetAnalysis.so
+##################################################
 
-cd /Herwig/Generators
-insert EventGenerator:AnalysisHandlers 0 /Herwig/Analysis/RivetAnalysis
+# cd /Herwig/Analysis
+# create ThePEG::RivetAnalysis RivetAnalysis RivetAnalysis.so
 
-# ATLAS
-insert /Herwig/Analysis/RivetAnalysis:Analyses 0 ATLAS_2012_I1084540
-insert /Herwig/Analysis/RivetAnalysis:Analyses 0 ATLAS_2010_S8591806
-insert /Herwig/Analysis/RivetAnalysis:Analyses 0 ATLAS_2010_S8894728
-insert /Herwig/Analysis/RivetAnalysis:Analyses 0 ATLAS_2011_S8994773
-insert /Herwig/Analysis/RivetAnalysis:Analyses 0 ATLAS_2010_S8918562
-insert /Herwig/Analysis/RivetAnalysis:Analyses 0 ATLAS_2011_I894867
-insert /Herwig/Analysis/RivetAnalysis:Analyses 0 ATLAS_2012_I1124167
-insert /Herwig/Analysis/RivetAnalysis:Analyses 0 ATLAS_2014_I1298811
-insert /Herwig/Analysis/RivetAnalysis:Analyses 0 ATLAS_2012_I1091481
-insert /Herwig/Analysis/RivetAnalysis:Analyses 0 ATLAS_2016_I1426695
+# cd /Herwig/Generators
+# insert EventGenerator:AnalysisHandlers 0 /Herwig/Analysis/RivetAnalysis
 
-# ATLAS 13 TeV
-insert /Herwig/Analysis/RivetAnalysis:Analyses 0 ATLAS_2016_I1467230
-insert /Herwig/Analysis/RivetAnalysis:Analyses 0 ATLAS_2016_I1419652
+# insert /Herwig/Analysis/RivetAnalysis:Analyses 0 ATLAS_20XX_XXXXXXX
 
 
-# CMS
-insert /Herwig/Analysis/RivetAnalysis:Analyses 0 CMS_2015_I1356998
-insert /Herwig/Analysis/RivetAnalysis:Analyses 0 CMS_2010_S8656010
-insert /Herwig/Analysis/RivetAnalysis:Analyses 0 CMS_2011_S8884919
-insert /Herwig/Analysis/RivetAnalysis:Analyses 0 CMS_2011_S8978280
-insert /Herwig/Analysis/RivetAnalysis:Analyses 0 CMS_2012_I1193338
-insert /Herwig/Analysis/RivetAnalysis:Analyses 0 CMS_2013_I1218372
-
-
-# Alice
-insert /Herwig/Analysis/RivetAnalysis:Analyses 0 ALICE_2010_S8624100
-insert /Herwig/Analysis/RivetAnalysis:Analyses 0 ALICE_2010_S8625980
-insert /Herwig/Analysis/RivetAnalysis:Analyses 0 ALICE_2010_S8706239
-insert /Herwig/Analysis/RivetAnalysis:Analyses 0 ALICE_2011_S8909580
-insert /Herwig/Analysis/RivetAnalysis:Analyses 0 ALICE_2011_S8945144
-insert /Herwig/Analysis/RivetAnalysis:Analyses 0 ALICE_2012_I1181770
-insert /Herwig/Analysis/RivetAnalysis:Analyses 0 ALICE_2014_I1300380
-
-# LHCb
-insert /Herwig/Analysis/RivetAnalysis:Analyses 0 LHCB_2014_I1281685
-
 #set /Herwig/Analysis/Plot:EventNumber 54
 #cd /Herwig/Generators
 #insert EventGenerator:AnalysisHandlers 0 /Herwig/Analysis/Plot
 
 #insert EventGenerator:AnalysisHandlers 0 /Herwig/Analysis/HepMCFile
 #set /Herwig/Analysis/HepMCFile:PrintEvent 1000000
 #set /Herwig/Analysis/HepMCFile:Format GenEvent
 #set /Herwig/Analysis/HepMCFile:Units GeV_mm
 #set /Herwig/Analysis/HepMCFile:Filename events.fifo
 
 ##################################################
 # Save run for later usage with 'Herwig run'
 ##################################################
 saverun LHC-MB EventGenerator
 
diff --git a/src/Matchbox/KrkNLO-DipoleShower.in b/src/Matchbox/KrkNLO-DipoleShower.in
new file mode 100644
--- /dev/null
+++ b/src/Matchbox/KrkNLO-DipoleShower.in
@@ -0,0 +1,43 @@
+# LO + Dipole Shower
+read Matchbox/LO-DipoleShower.in
+
+# KrkNLO Event Reweighter
+cd /Herwig/DipoleShower
+create Herwig::KrknloEventReweight KrkNLOEventReweight HwKrknloEventReweight.so
+set DipoleShowerHandler:EventReweight KrkNLOEventReweight
+
+set DipoleShowerHandler:RestrictPhasespace No
+set DipoleShowerHandler:MaxPtIsMuF No
+set DipoleShowerHandler:HardScaleProfile NULL
+set DipoleShowerHandler:IntrinsicPtGenerator NULL
+
+set DipoleShowerHandler:GlobalAlphaS /Herwig/Couplings/NLOAlphaS
+set /Herwig/Generators/EventGenerator:StandardModelParameters:QCD/RunningAlphaS /Herwig/Couplings/NLOAlphaS
+
+# Use pT for Dipole Kernels
+cd Kernels
+set FFgx2ddxDipoleKernel:VirtualitySplittingScale No
+set FFgx2uuxDipoleKernel:VirtualitySplittingScale No
+set FFgx2ccxDipoleKernel:VirtualitySplittingScale No
+set FFgx2ssxDipoleKernel:VirtualitySplittingScale No
+set FFgx2bbxDipoleKernel:VirtualitySplittingScale No
+
+set FIgx2ddxDipoleKernel:VirtualitySplittingScale No
+set FIgx2uuxDipoleKernel:VirtualitySplittingScale No
+set FIgx2ccxDipoleKernel:VirtualitySplittingScale No
+set FIgx2ssxDipoleKernel:VirtualitySplittingScale No
+set FIgx2bbxDipoleKernel:VirtualitySplittingScale No
+
+set IFgx2ggxDipoleKernel:VirtualitySplittingScale No
+set IFqx2gqxDipoleKernel:VirtualitySplittingScale No
+
+set IIgx2ggxDipoleKernel:VirtualitySplittingScale No
+set IIqx2gqxDipoleKernel:VirtualitySplittingScale No
+
+set FFMgx2ddxDipoleKernel:VirtualitySplittingScale No
+set FFMgx2uuxDipoleKernel:VirtualitySplittingScale No
+set FFMgx2ccxDipoleKernel:VirtualitySplittingScale No
+set FFMgx2ssxDipoleKernel:VirtualitySplittingScale No
+set FFMgx2bbxDipoleKernel:VirtualitySplittingScale No
+
+cd /
\ No newline at end of file
diff --git a/src/Matchbox/MCatNLO-DefaultShower.in.in b/src/Matchbox/MCatNLO-DefaultShower.in.in
--- a/src/Matchbox/MCatNLO-DefaultShower.in.in
+++ b/src/Matchbox/MCatNLO-DefaultShower.in.in
@@ -1,29 +1,30 @@
 # -*- ThePEG-repository -*-
 
 set /Herwig/Shower/ShowerHandler:HardVetoReadOption PrimaryCollision
 set /Herwig/Shower/ShowerHandler:SpinCorrelations No
 set /Herwig/Shower/ShowerHandler:HardEmission MECorrection
 set /Herwig/Shower/KinematicsReconstructor:InitialStateReconOption SofterFraction
 set /Herwig/Shower/PartnerFinder:PartnerMethod 0
 set /Herwig/Shower/PartnerFinder:ScaleChoice 0
 
 set /Herwig/Shower/ShowerHandler:RestrictPhasespace Yes
 set /Herwig/Shower/ShowerHandler:MaxPtIsMuF Yes
 set /Herwig/Shower/ShowerHandler:HardScaleProfile /Herwig/MatrixElements/Matchbox/HardScaleProfile
 
 cd /Herwig/EventHandlers
 
 set EventHandler:CascadeHandler /Herwig/Shower/ShowerHandler
 
 cd /Herwig/MatrixElements/Matchbox
 
 set Factory:ShowerApproximation QTildeMatching
 
 # tunes
-read Matchbox/MCatNLO-Default-HardAlphaSTune.in
+# As of release 7.1 we are using the default tune
+#read Matchbox/MCatNLO-Default-HardAlphaSTune.in
 
 cd /Herwig/Analysis
 
 @CREATE_RIVET@ ThePEG::RivetAnalysis Rivet RivetAnalysis.so
 @CREATE_HEPMC@ ThePEG::HepMCFile HepMC HepMCAnalysis.so
 
diff --git a/src/Matchbox/MCatNLO-Dipole-HardAlphaSTune.in b/src/Matchbox/MCatNLO-Dipole-HardAlphaSTune.in
--- a/src/Matchbox/MCatNLO-Dipole-HardAlphaSTune.in
+++ b/src/Matchbox/MCatNLO-Dipole-HardAlphaSTune.in
@@ -1,121 +1,124 @@
 # -*- ThePEG-repository -*-
 # tune where the world average perutbative alphaS is used for the hard me
 # and matching and the shower alpha_S tuned seperately
 
 ##################################################
 ## special scale choices
 ##################################################
 
 cd /Herwig/DipoleShower/Kernels
 
 # set FFgx2ddxDipoleKernel:VirtualitySplittingScale Yes
 # set FFgx2uuxDipoleKernel:VirtualitySplittingScale Yes
 # set FFgx2ccxDipoleKernel:VirtualitySplittingScale Yes
 # set FFgx2ssxDipoleKernel:VirtualitySplittingScale Yes
 # set FFgx2bbxDipoleKernel:VirtualitySplittingScale Yes
 
 # set FIgx2ddxDipoleKernel:VirtualitySplittingScale Yes
 # set FIgx2uuxDipoleKernel:VirtualitySplittingScale Yes
 # set FIgx2ccxDipoleKernel:VirtualitySplittingScale Yes
 # set FIgx2ssxDipoleKernel:VirtualitySplittingScale Yes
 # set FIgx2bbxDipoleKernel:VirtualitySplittingScale Yes
 
 # set IFqx2gqxDipoleKernel:VirtualitySplittingScale Yes
 # set IIqx2gqxDipoleKernel:VirtualitySplittingScale Yes
 
 # Massive
 # set FFMgx2ddxDipoleKernel:VirtualitySplittingScale Yes
 # set FFMgx2uuxDipoleKernel:VirtualitySplittingScale Yes
 # set FFMgx2ccxDipoleKernel:VirtualitySplittingScale Yes
 # set FFMgx2ssxDipoleKernel:VirtualitySplittingScale Yes
 # set FFMgx2bbxDipoleKernel:VirtualitySplittingScale Yes
 
 # set FIMgx2ddxDipoleKernel:VirtualitySplittingScale Yes
 # set FIMgx2uuxDipoleKernel:VirtualitySplittingScale Yes
 # set FIMgx2ccxDipoleKernel:VirtualitySplittingScale Yes
 # set FIMgx2ssxDipoleKernel:VirtualitySplittingScale Yes
 # set FIMgx2bbxDipoleKernel:VirtualitySplittingScale Yes
 
 # set FIMDecaygx2ddxDipoleKernel:VirtualitySplittingScale Yes
 # set FIMDecaygx2uuxDipoleKernel:VirtualitySplittingScale Yes
 # set FIMDecaygx2ccxDipoleKernel:VirtualitySplittingScale Yes
 # set FIMDecaygx2ssxDipoleKernel:VirtualitySplittingScale Yes
 # set FIMDecaygx2bbxDipoleKernel:VirtualitySplittingScale Yes
 
 # set IFMqx2gqxDipoleKernel:VirtualitySplittingScale Yes
 
 ##################################################
 ## intrinsic pt
 ##################################################
 set /Herwig/DipoleShower/IntrinsicPtGenerator:ValenceIntrinsicPtScale 2.0*GeV
 set /Herwig/DipoleShower/IntrinsicPtGenerator:SeaIntrinsicPtScale 2.0*GeV
 
 ##################################################
 ## Dipole shower tune settings
 ##################################################
 
 set /Herwig/Particles/g:ConstituentMass 0.7899848*GeV
 
 ##################################################
 ## (two-loop) alpha_s
 ##################################################
 set /Herwig/DipoleShower/NLOAlphaS:input_alpha_s 0.125
 set /Herwig/DipoleShower/NLOAlphaS:input_scale 91.18*GeV
 
 ##################################################
 ## cutoffs
 ##################################################
 set /Herwig/DipoleShower/Kinematics/FFLightKinematics:IRCutoff 0.45*GeV
 set /Herwig/DipoleShower/Kinematics/FFMassiveKinematics:IRCutoff 0.45*GeV
 
 set /Herwig/DipoleShower/Kinematics/FILightKinematics:IRCutoff 0.45*GeV
 set /Herwig/DipoleShower/Kinematics/FIMassiveKinematics:IRCutoff 0.45*GeV
 
 set /Herwig/DipoleShower/Kinematics/IFLightKinematics:IRCutoff 0.45*GeV
 set /Herwig/DipoleShower/Kinematics/IFMassiveKinematics:IRCutoff 0.45*GeV
 
 set /Herwig/DipoleShower/Kinematics/IILightKinematics:IRCutoff  0.45*GeV
 
 set /Herwig/DipoleShower/Kinematics/FIMassiveDecayKinematics:IRCutoff 0.45*GeV
 
 ## needs to be synchronized with settings above
 set /Herwig/MatrixElements/Matchbox/DipoleMatching:FFPtCut 0.45*GeV
 set /Herwig/MatrixElements/Matchbox/DipoleMatching:FIPtCut 0.45*GeV
 set /Herwig/MatrixElements/Matchbox/DipoleMatching:IIPtCut 0.45*GeV
 
 ##################################################
 ## hadronization parameters -- complete?
 ##################################################
 cd /Herwig/Hadronization
 
 set ClusterFissioner:ClMaxLight                  3.30
 set ClusterFissioner:ClPowLight                  2.50
 set ClusterFissioner:PSplitLight                 1.29
 set ClusterDecayer:ClDirLight                    1
 set ClusterDecayer:ClSmrLight                    3.118342
 
 set ClusterFissioner:ClMaxCharm                  3.11*GeV
 set ClusterFissioner:ClPowCharm                  1.62
 set ClusterFissioner:PSplitCharm                 2.54
 set ClusterDecayer:ClDirCharm                    1
 set ClusterDecayer:ClSmrCharm                    0.
 set HadronSelector:SingleHadronLimitCharm   0.0
 
 set ClusterFissioner:ClMaxBottom                 1.38*GeV
 set ClusterFissioner:ClPowBottom                 0.62
 set ClusterFissioner:PSplitBottom                0.20
 set ClusterDecayer:ClDirBottom                   1
 set ClusterDecayer:ClSmrBottom                   0.
 set HadronSelector:SingleHadronLimitBottom  0.12
 
 set HadronSelector:PwtUquark                     1.0
 set HadronSelector:PwtDquark                     1.0
 set HadronSelector:PwtSquark                     1.09
 set HadronSelector:PwtCquark                     1.0
 set HadronSelector:PwtBquark                     1.0
 set HadronSelector:PwtDIquark                    0.66
 set HadronSelector:SngWt                         1.0
 set HadronSelector:DecWt                         1.0
 
+# These two options will be updated in the 7.1.1 tune
+set ColourReconnector:OctetTreatment 0
+set HadronSelector:BelowThreshold 0
 
 cd /
diff --git a/src/Matchbox/MCatNLO-Dipole-ShowerAlphaSTune.in b/src/Matchbox/MCatNLO-Dipole-ShowerAlphaSTune.in
--- a/src/Matchbox/MCatNLO-Dipole-ShowerAlphaSTune.in
+++ b/src/Matchbox/MCatNLO-Dipole-ShowerAlphaSTune.in
@@ -1,123 +1,127 @@
 # -*- ThePEG-repository -*-
 # tune wherre the alphaS used for the hard me
 # and matching and the shower alpha_S are the same
 
 ##################################################
 ## special scale choices
 ##################################################
 
 cd /Herwig/DipoleShower/Kernels
 
 # set FFgx2ddxDipoleKernel:VirtualitySplittingScale Yes
 # set FFgx2uuxDipoleKernel:VirtualitySplittingScale Yes
 # set FFgx2ccxDipoleKernel:VirtualitySplittingScale Yes
 # set FFgx2ssxDipoleKernel:VirtualitySplittingScale Yes
 # set FFgx2bbxDipoleKernel:VirtualitySplittingScale Yes
 
 # set FIgx2ddxDipoleKernel:VirtualitySplittingScale Yes
 # set FIgx2uuxDipoleKernel:VirtualitySplittingScale Yes
 # set FIgx2ccxDipoleKernel:VirtualitySplittingScale Yes
 # set FIgx2ssxDipoleKernel:VirtualitySplittingScale Yes
 # set FIgx2bbxDipoleKernel:VirtualitySplittingScale Yes
 
 # set IFqx2gqxDipoleKernel:VirtualitySplittingScale Yes
 # set IIqx2gqxDipoleKernel:VirtualitySplittingScale Yes
 
 # Massive
 # set FFMgx2ddxDipoleKernel:VirtualitySplittingScale Yes
 # set FFMgx2uuxDipoleKernel:VirtualitySplittingScale Yes
 # set FFMgx2ccxDipoleKernel:VirtualitySplittingScale Yes
 # set FFMgx2ssxDipoleKernel:VirtualitySplittingScale Yes
 # set FFMgx2bbxDipoleKernel:VirtualitySplittingScale Yes
 
 # set FIMgx2ddxDipoleKernel:VirtualitySplittingScale Yes
 # set FIMgx2uuxDipoleKernel:VirtualitySplittingScale Yes
 # set FIMgx2ccxDipoleKernel:VirtualitySplittingScale Yes
 # set FIMgx2ssxDipoleKernel:VirtualitySplittingScale Yes
 # set FIMgx2bbxDipoleKernel:VirtualitySplittingScale Yes
 
 # set FIMDecaygx2ddxDipoleKernel:VirtualitySplittingScale Yes
 # set FIMDecaygx2uuxDipoleKernel:VirtualitySplittingScale Yes
 # set FIMDecaygx2ccxDipoleKernel:VirtualitySplittingScale Yes
 # set FIMDecaygx2ssxDipoleKernel:VirtualitySplittingScale Yes
 # set FIMDecaygx2bbxDipoleKernel:VirtualitySplittingScale Yes
 
 # set IFMqx2gqxDipoleKernel:VirtualitySplittingScale Yes
 
 ##################################################
 ## intrinsic pt
 ##################################################
 set /Herwig/DipoleShower/IntrinsicPtGenerator:ValenceIntrinsicPtScale 2.0*GeV
 set /Herwig/DipoleShower/IntrinsicPtGenerator:SeaIntrinsicPtScale 2.0*GeV
 
 ##################################################
 ## Dipole shower tune settings
 ##################################################
 
 set /Herwig/Particles/g:ConstituentMass 0.7899848*GeV
 
 ##################################################
 ## (two-loop) alpha_s
 ##################################################
 set /Herwig/DipoleShower/NLOAlphaS:input_alpha_s 0.139
 set /Herwig/DipoleShower/NLOAlphaS:input_scale 91.18*GeV
 set /Herwig/Couplings/NLOAlphaS:input_alpha_s 0.139
 set /Herwig/Couplings/NLOAlphaS:input_scale 91.18*GeV
 
 
 ##################################################
 ## cutoffs
 ##################################################
 set /Herwig/DipoleShower/Kinematics/FFLightKinematics:IRCutoff 1.12*GeV
 set /Herwig/DipoleShower/Kinematics/FFMassiveKinematics:IRCutoff 1.12*GeV
 
 set /Herwig/DipoleShower/Kinematics/FILightKinematics:IRCutoff 1.12*GeV
 set /Herwig/DipoleShower/Kinematics/FIMassiveKinematics:IRCutoff 1.12*GeV
 
 set /Herwig/DipoleShower/Kinematics/IFLightKinematics:IRCutoff 1.12*GeV
 set /Herwig/DipoleShower/Kinematics/IFMassiveKinematics:IRCutoff 1.12*GeV
 
 set /Herwig/DipoleShower/Kinematics/IILightKinematics:IRCutoff  1.12*GeV
 
 set /Herwig/DipoleShower/Kinematics/FIMassiveDecayKinematics:IRCutoff 1.12*GeV
 
 ## needs to be synchronized with settings above
 set /Herwig/MatrixElements/Matchbox/DipoleMatching:FFPtCut 1.12*GeV
 set /Herwig/MatrixElements/Matchbox/DipoleMatching:FIPtCut 1.12*GeV
 set /Herwig/MatrixElements/Matchbox/DipoleMatching:IIPtCut 1.12*GeV
 
 ##################################################
 ## hadronization parameters -- complete?
 ##################################################
 cd /Herwig/Hadronization
 
 set ClusterFissioner:ClMaxLight                  3.03
 set ClusterFissioner:ClPowLight                  0.92
 set ClusterFissioner:PSplitLight                 0.57
 set ClusterDecayer:ClDirLight                    1
 set ClusterDecayer:ClSmrLight                    3.118342
 
 set ClusterFissioner:ClMaxCharm                  3.58*GeV
 set ClusterFissioner:ClPowCharm                  2.36
 set ClusterFissioner:PSplitCharm                 1.08
 set ClusterDecayer:ClDirCharm                    1
 set ClusterDecayer:ClSmrCharm                    0.
 set HadronSelector:SingleHadronLimitCharm   0.0
 
 set ClusterFissioner:ClMaxBottom                 2.03*GeV
 set ClusterFissioner:ClPowBottom                 0.67
 set ClusterFissioner:PSplitBottom                0.01
 set ClusterDecayer:ClDirBottom                   1
 set ClusterDecayer:ClSmrBottom                   0.
 set HadronSelector:SingleHadronLimitBottom  0.12
 
 set HadronSelector:PwtUquark                     1.0
 set HadronSelector:PwtDquark                     1.0
 set HadronSelector:PwtSquark                     0.61
 set HadronSelector:PwtCquark                     1.0
 set HadronSelector:PwtBquark                     1.0
 set HadronSelector:PwtDIquark                    0.46
 set HadronSelector:SngWt                         1.0
 set HadronSelector:DecWt                         1.0
 
+# These two options will be updated in the 7.1.1 tune
+set ColourReconnector:OctetTreatment 0
+set HadronSelector:BelowThreshold 0
+
 cd /
diff --git a/src/Matchbox/Powheg-DefaultShower.in.in b/src/Matchbox/Powheg-DefaultShower.in.in
--- a/src/Matchbox/Powheg-DefaultShower.in.in
+++ b/src/Matchbox/Powheg-DefaultShower.in.in
@@ -1,31 +1,32 @@
 # -*- ThePEG-repository -*-
 
 read Matchbox/Powheg.in
 
 set /Herwig/Shower/PowhegShowerHandler:HardVetoReadOption PrimaryCollision
 set /Herwig/Shower/PowhegShowerHandler:SpinCorrelations No
 set /Herwig/Shower/KinematicsReconstructor:InitialStateReconOption SofterFraction
 set /Herwig/Shower/PartnerFinder:PartnerMethod 0
 set /Herwig/Shower/PartnerFinder:ScaleChoice 0
 
 set /Herwig/Shower/PowhegShowerHandler:RestrictPhasespace Yes
 set /Herwig/Shower/PowhegShowerHandler:MaxPtIsMuF Yes
 set /Herwig/Shower/PowhegShowerHandler:HardScaleProfile NULL
 
 cd /Herwig/EventHandlers
 
 set EventHandler:CascadeHandler /Herwig/Shower/PowhegShowerHandler
 
 cd /Herwig/Shower
 
 set PowhegShowerHandler:Factory /Herwig/MatrixElements/Matchbox/Factory
 
 set PowhegShowerHandler:HardEmission POWHEG
 
 # tunes
-read Matchbox/Powheg-Default-HardAlphaSTune.in
+# As of release 7.1 we are using the default tune
+#read Matchbox/Powheg-Default-HardAlphaSTune.in
 
 cd /Herwig/Analysis
 
 @CREATE_RIVET@ ThePEG::RivetAnalysis Rivet RivetAnalysis.so
 @CREATE_HEPMC@ ThePEG::HepMCFile HepMC HepMCAnalysis.so
diff --git a/src/Merging/LEP-Merging.in b/src/Merging/LEP-Merging.in
--- a/src/Merging/LEP-Merging.in
+++ b/src/Merging/LEP-Merging.in
@@ -1,153 +1,151 @@
 # -*- ThePEG-repository -*-
 
 ##################################################
 ## Herwig/Merging example input file
 ##################################################
 
 ##################################################
 ## Collider type
 ##################################################
 
 
 read snippets/DipoleMerging.in
 read snippets/EECollider.in
 read snippets/MonacoSampler.in
 
 ##################################################
 ## Beam energy sqrt(s)
 ##################################################
 
 cd /Herwig/EventHandlers
 set EventHandler:LuminosityFunction:Energy 91.2*GeV
 
 ##################################################
 ## Process selection
 ##################################################
 
 ## Note that event generation may fail if no matching matrix element has
 ## been found.  Coupling orders are with respect to the Born process,
 ## i.e. NLO QCD does not require an additional power of alphas.
 
 ## Model assumptions
 read Matchbox/StandardModelLike.in
 read Matchbox/DiagonalCKM.in
 
 ## Set the order of the couplings
 cd /Herwig/Merging
 set MergingFactory:OrderInAlphaS 0
 set MergingFactory:OrderInAlphaEW 2
 
 ## Select the process
 ## You may use identifiers such as p, pbar, j, l, mu+, h0 etc.
 
 do MergingFactory:Process e- e+ -> j j [ j  j ]
 
 set MergingFactory:NLOProcesses 2
 
 set Merger:MergingScale 4.*GeV
 set Merger:MergingScaleSmearing 0.1
 
 cd /Herwig/MatrixElements/Matchbox/Utility
 insert DiagramGenerator:ExcludeInternal 0 /Herwig/Particles/gamma
 
 ## Special settings required for on-shell production of unstable particles
 ## enable for on-shell top production
 # read Matchbox/OnShellTopProduction.in
 ## enable for on-shell W, Z or h production
 # read Matchbox/OnShellWProduction.in
 # read Matchbox/OnShellZProduction.in
 # read Matchbox/OnShellHProduction.in
 
 ##################################################
 ## Matrix element library selection
 ##################################################
 
 ## Select a generic tree/loop combination or a
 ## specialized NLO package
+## As massive b-quarks are currently not supported by the 
+## build in ME an external ME-Provider is needed (e.g. MG+OL).
 
 # read Matchbox/MadGraph-GoSam.in
 # read Matchbox/MadGraph-MadGraph.in
 # read Matchbox/MadGraph-NJet.in
-# read Matchbox/MadGraph-OpenLoops.in
+read Matchbox/MadGraph-OpenLoops.in
 
-## Uncomment this to use ggh effective couplings
-## currently only supported by MadGraph-GoSam and MadGraph-OpenLoops
-
-# read Matchbox/HiggsEffective.in
 
 ##################################################
 ## Cut selection
 ## See the documentation for more options
 ##################################################
 
 ## cuts on additional jets
 
 # read Matchbox/DefaultEEJets.in
 # set NJetsCut:NJetsMin 3
 
 ##################################################
 ## Scale choice
 ## See the documentation for more options
 ##################################################
 
 cd /Herwig/MatrixElements/Matchbox/Scales/
 set /Herwig/Merging/MergingFactory:ScaleChoice SHatScale
 
 ##################################################
 ## Scale uncertainties
 ##################################################
 
 # read Matchbox/MuDown.in
 # read Matchbox/MuUp.in
 
 ##################################################
 ## Shower scale uncertainties
 ##################################################
 
 # read Matchbox/MuQDown.in
 # read Matchbox/MuQUp.in
 
 ##################################################
 ## CMW - Scheme
 ##################################################
 
 read Merging/Merging-Dipole-FactorCMWSchemeTune.in
 
 ### Use factor in alpha_s argument: alpha_s(q) -> alpha_s(fac*q)
 ### with fac=exp(-(67-3pi^2-10/3*Nf)/(33-2Nf))
 read Merging/FactorCMWScheme.in
 
 ### Linear CMW multiplication:
 ### alpha_s(q) -> alpha_s(q)(1+K_g*alpha_s(q)/2pi )
 # read Merging/LinearCMWScheme.in
 
 ##################################################
 ## Analyses
 ##################################################
 
 cd /Herwig/Analysis
 insert /Herwig/Generators/EventGenerator:AnalysisHandlers 0 Rivet
 # insert /Herwig/Generators/EventGenerator:AnalysisHandlers 0 HepMC
 
 
 # Here we collected a various Rivet analysis for LEP
 # at the Z Mass. (The collection might not be complete.)
 read Merging/LEP91-Analysis.in
 
 
 ##################################################
 ## Do not apply profile scales for LEP as hard
 ## scale coincides with kinematic limit
 ##################################################
 
 set /Herwig/Shower/ShowerHandler:HardScaleProfile NULL
 set /Herwig/DipoleShower/DipoleShowerHandler:HardScaleProfile NULL
 
 ##################################################
 ## Save the generator
 ##################################################
 
 do /Herwig/Merging/MergingFactory:ProductionMode
 
 cd /Herwig/Generators
 saverun LEP-Merging EventGenerator
diff --git a/src/defaults/Analysis.in.in b/src/defaults/Analysis.in.in
--- a/src/defaults/Analysis.in.in
+++ b/src/defaults/Analysis.in.in
@@ -1,90 +1,46 @@
 # -*- ThePEG-repository -*-
 # @configure_input@
 
 #########################################################
 # Analysis handler setup
 #
 # By default, only 'Basics' is active. Add the commented
 # lines to your input file to switch on other analyses.
 #########################################################
 
 mkdir /Herwig/Analysis
 cd /Herwig/Analysis
 
 library HwAnalysis.so
 
 #
 # basic analysis to check consistency of events
 # (only analysis handler switched on by default)
 #
 create Herwig::BasicConsistency Basics
 insert /Herwig/Generators/EventGenerator:AnalysisHandlers 0 Basics
 
 #
 #  Analysis Handlers for hadron-hadron collisions
 #  (switched off by default)
 #
 # simple analysis of W/Z events
 create Herwig::SimpleLHCAnalysis DrellYan
 # simple analysis of top-antitop events
 create Herwig::TTbarAnalysis TTbar
 # simple analysis of gamma+jet events
 create Herwig::GammaJetAnalysis  GammaJet
 # simple analysis of gamma-gamma events
 create Herwig::GammaGammaAnalysis GammaGamma
 # simple analysis of higgs+jet events
 create Herwig::HiggsJetAnalysis  HiggsJet
 
-#
-#  Analysis Handlers for LEP 91.2 GeV collisions
-#  (switched off by default)
-#
-# hadron multiplicities compared to LEP data
-create Herwig::LEPMultiplicityCount LEPMultiplicity HwLEPAnalysis.so
-# b fractions in specific hadrons
-create Herwig::LEPBMultiplicity BMultiplicity HwLEPAnalysis.so
-# b fragmentation functions
-create Herwig::BFragmentationAnalysisHandler BFrag HwLEPAnalysis.so
-# master LEP event shape analysis and object which does the work
-create Herwig::EventShapesMasterAnalysis Shapes
-create Herwig::EventShapes LEPShapes
-newdef Shapes:EventShapes LEPShapes
-# LEP event shapes
-create Herwig::LEPEventShapes LEPEvent
-newdef LEPEvent:EventShapes LEPShapes
-insert Shapes:Slaves 0 LEPEvent
-# LEP identified particles
-create Herwig::IdentifiedParticleAnalysis LEPIdent
-# LEP single particle analysis
-create Herwig::SingleParticleAnalysis LEPSingle
-newdef LEPSingle:EventShapes LEPShapes
-insert Shapes:Slaves 0 LEPSingle
-
-# 
-#  Analysis Handlers for Belle and CLEO data below the Upsilon(4S)
-#  (switched off by default)
-#
-# BELLE data on charm hadron spetra
-create Herwig::BELLECharmAnalysis BELLECharm HwLEPAnalysis.so
-# CLEO  data on charm meson spectra
-create Herwig::CLEOCharmAnalysis  CLEOCharm HwLEPAnalysis.so
-
-
 # Schematic overview of an event
 # (requires the graphviz program 'dot' to produce a plot)
 create ThePEG::GraphvizPlot Plot GraphvizPlot.so
 
-
-#
-#  Handlers which depend on Fastjet for LEP data
-#  (switched off by default)
-#
-# four jet analysis
-@CREATE_FASTJET@ Herwig::LEPFourJetsAnalysis LEPFourJet HwLEPJetAnalysis.so
-# general jet analysis
-@CREATE_FASTJET@ Herwig::LEPJetAnalysis LEPJet HwLEPJetAnalysis.so
 #
 #  Handlers which depend on HepMC
 #  (switched off by default)
 # A HepMC dump file (requires --with-hepmc to be set at configure time)
 @CREATE_HEPMC@ ThePEG::HepMCFile HepMCFile HepMCAnalysis.so
diff --git a/src/defaults/Hadronization.in b/src/defaults/Hadronization.in
--- a/src/defaults/Hadronization.in
+++ b/src/defaults/Hadronization.in
@@ -1,103 +1,105 @@
 # -*- 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
 
 ##################################################
 # The UA5 soft underlying event model
 # (disabled by default)
 ##################################################
 create Herwig::UA5Handler UA5 HwUA5.so
 newdef UA5:ClusterFissioner ClusterFissioner
 newdef UA5:ClusterDecayer ClusterDecayer
 #set ClusterHadHandler:UnderlyingEventHandler UA5
 ##################################################
 
 newdef ClusterFissioner:HadronSelector HadronSelector 
 newdef LightClusterDecayer:HadronSelector HadronSelector
 newdef ClusterDecayer:HadronSelector HadronSelector
 
 newdef ColourReconnector:ColourReconnection Yes
-newdef ColourReconnector:ReconnectionProbability 0.4276
+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.26*GeV
-newdef ClusterFissioner:ClPowLight  1.61
-newdef ClusterFissioner:PSplitLight 0.81
+newdef ClusterFissioner:ClMaxLight  3.002538
+newdef ClusterFissioner:ClPowLight  1.424265
+newdef ClusterFissioner:PSplitLight 0.847541
 newdef ClusterDecayer:ClDirLight 1
 newdef ClusterDecayer:ClSmrLight 0.78
 
 # Clustering parameters for b-quarks
-newdef ClusterFissioner:ClMaxBottom  3.75*GeV
-newdef ClusterFissioner:ClPowBottom  0.70
-newdef ClusterFissioner:PSplitBottom 0.92
+newdef ClusterFissioner:ClMaxBottom  3.91100
+newdef ClusterFissioner:ClPowBottom  .63750
+newdef ClusterFissioner:PSplitBottom .5306
 newdef ClusterDecayer:ClDirBottom 1
-newdef ClusterDecayer:ClSmrBottom 0.00
-newdef HadronSelector:SingleHadronLimitBottom 0.34
+newdef ClusterDecayer:ClSmrBottom 0.0204
+newdef HadronSelector:SingleHadronLimitBottom 0.0
 
 # Clustering parameters for c-quarks
-newdef ClusterFissioner:ClMaxCharm  3.55*GeV
-newdef ClusterFissioner:ClPowCharm  2.11
-newdef ClusterFissioner:PSplitCharm 1.20
+newdef ClusterFissioner:ClMaxCharm  3.638218
+newdef ClusterFissioner:ClPowCharm  2.331856
+newdef ClusterFissioner:PSplitCharm 1.233994
 newdef ClusterDecayer:ClDirCharm 1
 newdef ClusterDecayer:ClSmrCharm 0.
-newdef HadronSelector:SingleHadronLimitCharm 0.0
+newdef HadronSelector:SingleHadronLimitCharm 0.000000
 
 # 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.78
-newdef HadronSelector:SingleHadronLimitExotic 0.1
+newdef ClusterDecayer:ClSmrExotic 0.
+newdef HadronSelector:SingleHadronLimitExotic 0.
 
 # 
 newdef HadronSelector:PwtDquark  1.0
 newdef HadronSelector:PwtUquark  1.0
-newdef HadronSelector:PwtSquark  0.58
+newdef HadronSelector:PwtSquark  0.665563
 newdef HadronSelector:PwtCquark  1.0
 newdef HadronSelector:PwtBquark  1.0
-newdef HadronSelector:PwtDIquark 0.38
+newdef HadronSelector:PwtDIquark 0.439018
 newdef HadronSelector:SngWt      0.74
 newdef HadronSelector:DecWt      0.62
 newdef HadronSelector:Mode 1
+newdef HadronSelector:BelowThreshold All
diff --git a/src/defaults/Partons.in b/src/defaults/Partons.in
--- a/src/defaults/Partons.in
+++ b/src/defaults/Partons.in
@@ -1,34 +1,36 @@
 # -*- ThePEG-repository -*-
 
 mkdir /Herwig/Partons
 cd /Herwig/Partons
 
 create ThePEG::NoRemnants NoRemnants
 create ThePEG::NoPDF NoPDF
 newdef NoPDF:RemnantHandler NoRemnants
 
 create ThePEG::UnResolvedRemnant LeptonRemnants UnResolvedRemnant.so
 
 create Herwig::HwRemDecayer RemnantDecayer HwShower.so
 newdef RemnantDecayer:PomeronStructure Gluon
 newdef RemnantDecayer:colourDisrupt 0.7983
+newdef RemnantDecayer:ladderPower -0.088983
+newdef RemnantDecayer:ladderNorm 1.086029
 
 create ThePEG::SoftRemnantHandler HadronRemnants
 newdef HadronRemnants:RemnantDecayer RemnantDecayer
 
 
 read PDF.in
 
 # Make particle extractors
 create ThePEG::PartonExtractor EEExtractor
 newdef EEExtractor:NoPDF NoPDF
 cp EEExtractor PPExtractor
 newdef PPExtractor:FlatSHatY 1
 newdef PPExtractor:FirstPDF HardLOPDF
 newdef PPExtractor:SecondPDF HardLOPDF
 cp EEExtractor EPExtractor
 newdef EPExtractor:FlatSHatY 1
 
 newdef PPExtractor:FirstPDF HardLOPDF
 newdef PPExtractor:SecondPDF HardLOPDF
 newdef EPExtractor:SecondPDF HardLOPDF
diff --git a/src/defaults/Shower.in b/src/defaults/Shower.in
--- a/src/defaults/Shower.in
+++ b/src/defaults/Shower.in
@@ -1,297 +1,297 @@
 # -*- 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
 create Herwig::QTildeModel ShowerModel
 create Herwig::QTildeFinder PartnerFinder
 newdef PartnerFinder:PartnerMethod 1
 newdef PartnerFinder:ScaleChoice 1
 create Herwig::QTildeReconstructor KinematicsReconstructor
 newdef KinematicsReconstructor:ReconstructionOption Colour3
 newdef KinematicsReconstructor:InitialStateReconOption SofterFraction
 newdef KinematicsReconstructor:InitialInitialBoostOption LongTransBoost
 
 newdef /Herwig/Partons/RemnantDecayer:AlphaS  AlphaQCD
 newdef /Herwig/Partons/RemnantDecayer:AlphaEM AlphaQED
 
 newdef ShowerModel:PartnerFinder PartnerFinder
 newdef ShowerModel:KinematicsReconstructor KinematicsReconstructor
 newdef ShowerHandler:ShowerModel ShowerModel
 newdef ShowerHandler:SplittingGenerator SplittingGenerator
 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:ShowerModel ShowerModel
 newdef PowhegShowerHandler:SplittingGenerator SplittingGenerator
 newdef PowhegShowerHandler:Interactions QCDandQED
 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 OffShell3
+newdef PowhegShowerHandler:ReconstructionOption OffShell5
 
 #############################################################
 # 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 OffShell3
+newdef ShowerHandler:ReconstructionOption OffShell5
 newdef AlphaQCD:ScaleFactor 1.0
 newdef AlphaQCD:NPAlphaS 2
 newdef AlphaQCD:Qmin 0.935
 newdef AlphaQCD:NumberOfLoops 2
 newdef AlphaQCD:InputOption 1
-newdef AlphaQCD:AlphaMZ 0.134
+newdef AlphaQCD:AlphaMZ 0.126234
 #
 #
 # Lets set up all the splittings
 create Herwig::HalfHalfOneSplitFn QtoQGammaSplitFn
 set QtoQGammaSplitFn:InteractionType QED
 set QtoQGammaSplitFn:ColourStructure ChargedChargedNeutral
 set QtoQGammaSplitFn:AngularOrdered Yes
 
 create Herwig::HalfHalfOneSplitFn QtoQGSplitFn
 newdef QtoQGSplitFn:InteractionType QCD
 newdef QtoQGSplitFn:ColourStructure TripletTripletOctet
 set QtoQGSplitFn:AngularOrdered Yes
 
 create Herwig::OneOneOneSplitFn GtoGGSplitFn
 newdef GtoGGSplitFn:InteractionType QCD
 newdef GtoGGSplitFn:ColourStructure OctetOctetOctet
 set GtoGGSplitFn:AngularOrdered Yes
 
 create Herwig::OneHalfHalfSplitFn GtoQQbarSplitFn
 newdef GtoQQbarSplitFn:InteractionType QCD
 newdef GtoQQbarSplitFn:ColourStructure OctetTripletTriplet
 set GtoQQbarSplitFn:AngularOrdered Yes
 
 create Herwig::OneHalfHalfSplitFn GammatoQQbarSplitFn
 newdef GammatoQQbarSplitFn:InteractionType QED
 newdef GammatoQQbarSplitFn:ColourStructure NeutralChargedCharged
 set GammatoQQbarSplitFn:AngularOrdered Yes
 
 create Herwig::HalfOneHalfSplitFn QtoGQSplitFn
 newdef QtoGQSplitFn:InteractionType QCD
 newdef QtoGQSplitFn:ColourStructure TripletOctetTriplet
 set QtoGQSplitFn:AngularOrdered Yes
 
 create Herwig::HalfOneHalfSplitFn QtoGammaQSplitFn
 newdef QtoGammaQSplitFn:InteractionType QED
 newdef QtoGammaQSplitFn:ColourStructure ChargedNeutralCharged
 set QtoGammaQSplitFn:AngularOrdered Yes
 #
 # Now the Sudakovs
 create Herwig::QTildeSudakov SudakovCommon
 newdef SudakovCommon:Alpha AlphaQCD
 newdef SudakovCommon:cutoffKinScale 0.0*GeV
 newdef SudakovCommon:PDFmax 1.0
 newdef SudakovCommon:CutOffOption pT
-newdef SudakovCommon:pTmin 1.67*GeV
+newdef SudakovCommon:pTmin 1.222798*GeV
 
 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 SudakovCommon GtoGGSudakov
 newdef GtoGGSudakov:SplittingFunction GtoGGSplitFn
 newdef GtoGGSudakov:PDFmax 2.0
 
 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
 
 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
 #
 # 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
diff --git a/src/defaults/UnderlyingEvent.in b/src/defaults/UnderlyingEvent.in
--- a/src/defaults/UnderlyingEvent.in
+++ b/src/defaults/UnderlyingEvent.in
@@ -1,75 +1,75 @@
 # -*- ThePEG-repository -*-
 
 ################################################
 # Set up the handler for the underlying event. 
 ################################################
 
 mkdir /Herwig/UnderlyingEvent
 cd /Herwig/UnderlyingEvent
 
 ######## cuts #################################################
 library SimpleKTCut.so
 
 # cut on pt. Without a specific matcher object, it works on all
 # particles
 create ThePEG::SimpleKTCut KtCut
 newdef KtCut:MinKT 3.06
 
 # create the cuts object for the Underlying Event
 create ThePEG::Cuts UECuts
 # This should always be 2*MinKT!!
 newdef UECuts:MHatMin 6.12
 
 insert UECuts:OneCuts 0 KtCut
 
 ######## subprocess ###########################################
 create ThePEG::SubProcessHandler FastQCD
 
 create Herwig::MEQCD2to2Fast MEQCD2to2Fast HwMEHadronFast.so
 insert FastQCD:MatrixElements 0 MEQCD2to2Fast
 cp /Herwig/Partons/PPExtractor /Herwig/Partons/MPIExtractor
 newdef /Herwig/Partons/MPIExtractor:FlatSHatY 1
 newdef FastQCD:PartonExtractor /Herwig/Partons/MPIExtractor
 
 # always use LO PDF for MPI and remnants
 newdef /Herwig/Partons/MPIExtractor:FirstPDF /Herwig/Partons/MPIPDF
 newdef /Herwig/Partons/MPIExtractor:SecondPDF /Herwig/Partons/MPIPDF
 
 ######## MPI Handler ##########################################
 library JetCuts.so
 library HwMPI.so
 create Herwig::MPIHandler MPIHandler
 
 # set the subprocesses and corresponding cuts
 insert MPIHandler:SubProcessHandlers 0 FastQCD
 insert MPIHandler:Cuts 0 UECuts
 
 # energy extrapolation for the MinKT cut
 newdef MPIHandler:EnergyExtrapolation Power
-newdef MPIHandler:Power 0.3663
-newdef MPIHandler:pTmin0  4.39*GeV
+newdef MPIHandler:Power 0.420445
+newdef MPIHandler:pTmin0  3.568157
 newdef MPIHandler:ReferenceScale 7000.*GeV
 newdef MPIHandler:EEparamA 0.585*GeV
 newdef MPIHandler:EEparamB 37.45*GeV
 
 # The inverse hadron radius
-newdef MPIHandler:InvRadius 2.3
+newdef MPIHandler:InvRadius 1.489997
 
 # Set the details of the soft model
 
 # Flag to decide whether additional soft interactions (i.e. pt < ptmin)
 # should be simulated at all
 
 newdef MPIHandler:softInt Yes
 
 # Flag to decide whether to use the 2 component model. In this model,
 # the hadron radius (or better: mean parton-parton separation) can be
 # different for hard and soft scatters. The radius for the soft scatters
 # is computed during the run startup so that the elastic t-slope, B_el,
 # coincides with current measurements (for CMenergy < 1.8 TeV) or
 # Donnachie-Landshoff pomeron fit (CMenergy > 1.8 TeV). If this model is
 # disabled one has to take care that this observable is correctly
 # described by adjusting InvRadius properly.
 
 newdef MPIHandler:twoComp Yes
 newdef MPIHandler:DLmode 2
diff --git a/src/snippets/MB-DipoleShower.in b/src/snippets/MB-DipoleShower.in
new file mode 100644
--- /dev/null
+++ b/src/snippets/MB-DipoleShower.in
@@ -0,0 +1,47 @@
+##################################################
+# MEMinBias Matrix Element
+##################################################
+
+### Note to users - Release 7.1:
+### This currently uses parameters tuned for the
+### default shower.
+
+# MPI model settings
+set /Herwig/UnderlyingEvent/MPIHandler:IdenticalToUE 0
+
+## Report the correct cross section
+cd /Herwig/Generators
+create Herwig::MPIXSecReweighter MPIXSecReweighter
+insert EventGenerator:EventHandler:PostSubProcessHandlers 0 MPIXSecReweighter
+set EventGenerator:EventHandler:CascadeHandler NULL
+
+clear EventGenerator:EventHandler:SubProcessHandlers[0]
+
+##################################################
+# Create separate SubProcessHandler for MinBias
+##################################################
+cd /Herwig/MatrixElements/
+cp SubProcess QCDMinBias
+
+set QCDMinBias:CascadeHandler /Herwig/DipoleShower/DipoleShowerHandler
+set QCDMinBias:CascadeHandler:MPIHandler /Herwig/UnderlyingEvent/MPIHandler
+set QCDMinBias:DecayHandler /Herwig/Decays/DecayHandler
+
+# Due to numerics the pomeron could be seen as timelike.
+set /Herwig/Shower/ShowerHandler:SplitHardProcess No
+set /Herwig/DipoleShower/DipoleShowerHandler:SplitHardProcess No
+
+insert QCDMinBias:MatrixElements[0] MEMinBias
+
+cd /Herwig/Generators
+# MinBias parameters used for the new kinematics of soft MPI
+set /Herwig/Cuts/MinBiasCuts:X1Min 0.11
+set /Herwig/Cuts/MinBiasCuts:X2Min 0.11
+
+# Needed to get the correct fraction of diffractive events
+set /Herwig/MatrixElements/MEMinBias:csNorm 4.5584
+
+set EventGenerator:EventHandler:Cuts /Herwig/Cuts/MinBiasCuts
+
+cd /Herwig/MatrixElements/
+insert /Herwig/Generators/EventGenerator:EventHandler:SubProcessHandlers[0] QCDMinBias
diff --git a/src/snippets/Makefile.am b/src/snippets/Makefile.am
--- a/src/snippets/Makefile.am
+++ b/src/snippets/Makefile.am
@@ -1,28 +1,30 @@
 BUILT_SOURCES = done-all-links
 
 snippetsdir = ${pkgdatadir}/snippets
 
 INPUTFILES = \
 DipoleShowerFiveFlavours.in \
 DipoleShowerFourFlavours.in \
 Particles-SetLonglivedParticlesStable.in \
 PDF-CT10.in \
 PDF-NNPDF30NLO.in \
 Matchbox.in \
 MonacoSampler.in \
 DipoleMerging.in \
 EECollider.in EPCollider.in PPCollider.in \
 MB.in \
+MB-DipoleShower.in \
 SoftModel.in \
-Diffraction.in
+Diffraction.in \
+SoftTune.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/SoftTune.in b/src/snippets/SoftTune.in
new file mode 100644
--- /dev/null
+++ b/src/snippets/SoftTune.in
@@ -0,0 +1,8 @@
+# Recommended set of parameters for MB/UE runs
+
+set /Herwig/Hadronization/ColourReconnector:ReconnectionProbability 0.5
+set /Herwig/UnderlyingEvent/MPIHandler:pTmin0 3.502683
+set /Herwig/UnderlyingEvent/MPIHandler:InvRadius 1.402055
+set /Herwig/UnderlyingEvent/MPIHandler:Power 0.416852
+set /Herwig/Partons/RemnantDecayer:ladderPower -0.08
+set /Herwig/Partons/RemnantDecayer:ladderNorm 0.95