diff --git a/Handlers/SamplerBase.h b/Handlers/SamplerBase.h
--- a/Handlers/SamplerBase.h
+++ b/Handlers/SamplerBase.h
@@ -1,233 +1,255 @@
 // -*- C++ -*-
 //
 // SamplerBase.h is a part of ThePEG - Toolkit for HEP Event Generation
 // Copyright (C) 1999-2011 Leif Lonnblad
 //
 // ThePEG is licenced under version 2 of the GPL, see COPYING for details.
 // Please respect the MCnet academic guidelines, see GUIDELINES for details.
 //
 #ifndef ThePEG_SamplerBase_H
 #define ThePEG_SamplerBase_H
 // This is the declaration of the SamplerBase class.
 
 #include "ThePEG/Interface/Interfaced.h"
 #include "SamplerBase.fh"
 #include "ThePEG/Handlers/StandardEventHandler.fh"
 // #include "SamplerBase.xh"
 
 namespace ThePEG {
 
 /**
  * This is the base class for all phase space sampler classes to be
  * used by the EventHandler class to sample the phase space according
  * to the cross sections for the processes in the EventHandler. The
  * class should be able to sample a unit hyper-cube in arbitrary
  * dimensions. The points need not necessarily be sampled with unit
  * weight.
  *
  * The virtual methods to be implemented by concrete sub-classes are
  * initialize(), generate() and rejectLast().
  *
  * @see \ref SamplerBaseInterfaces "The interfaces"
  * defined for SamplerBase.
  * @see EventHandler
  */
 class SamplerBase: public Interfaced {
 
 public:
 
   /** @name Standard constructors and destructors. */
   //@{
+
+  /**
+   * Constructor
+   */
+  SamplerBase()
+    : Interfaced(), theIntegrationList("") {}
+
   /**
    * Destructor.
    */
   virtual ~SamplerBase();
   //@}
 
 public:
 
   /**
    * Set the event handler for which the function
    * StandardEventHandler::dSigDR(const vector<double> &) function
    * returns the cross section for the chosen phase space point.
    */
   void setEventHandler(tStdEHPtr eh) { theEventHandler = eh; }
 
   /** @name Virtual functions to be overridden by sub-classes. */
   //@{
   /**
    * Initialize the the sampler, possibly doing presampling of the
    * phase space.
    */
   virtual void initialize() = 0;
 
   /**
    * Generarate a new phase space point and return a weight associated
    * with it. This weight should preferably be 1.
    */
   virtual double generate() = 0;
 
   /**
    * Reject the last chosen phase space point.
    */
   virtual void rejectLast() = 0;
 
   /**
    * Return the last generated phase space point.
    */
   const vector<double> & lastPoint() const { return theLastPoint; }
 
   /**
    * 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 0; }
 
   /**
    * Return the total integrated cross section determined from the
    * Monte Carlo sampling so far.
    */
   virtual CrossSection integratedXSec() const = 0;
 
   /**
    * Return the error on the total integrated cross section determined
    * from the Monte Carlo sampling so far.
    */
   virtual CrossSection integratedXSecErr() const = 0;
 
   /**
    * Return the reference cross section, a.k.a. maximum weight. When
    * not provided directly, this will be determined effectively from
    * the sum of weights and sum of weights squared to match up the
    * standard definition of a Monte Carlo cross section along with the
    * cross section and error quoted.
    */
   virtual CrossSection maxXSec() const {
     if ( sumWeights2() <= 0.0 ) return ZERO;
     return integratedXSec()*attempts()/sumWeights();
   }
 
   /**
    * Return the number of attempts. When not provided directly, this
    * will be determined effectively from the sum of weights and sum of
    * weights squared to match up the standard definition of a Monte
    * Carlo cross section along with the cross section and error
    * quoted.
    */
   virtual double attempts() const {
     CrossSection sigma = integratedXSec();
     CrossSection esigma = integratedXSecErr();
     double sw = sumWeights(); double sw2 = sumWeights2();
     if ( sw2 <= 0.0 ) return 0.0;
     return 
       sqr(sw)*(sqr(esigma)-sqr(sigma))/(sqr(sw)*sqr(esigma) - sw2*sqr(sigma));
   }
 
   /**
    * Return the sum of the weights returned by generate() so far (of
    * the events that were not rejeted).
    */
   virtual double sumWeights() const = 0;
 
   /**
    * Return the sum of the weights squared returned by generate() so
    * far (of the events that were not rejeted).
    */
   virtual double sumWeights2() const = 0;
   //@}
 
+  /**
+   * Set a file containing a list of subprocesses to integrate
+   */
+  void integrationList(const string& newIntegrationList) { theIntegrationList = newIntegrationList; }
+
+  /**
+   * Return a file containing a list of subprocesses to integrate
+   */
+  const string& integrationList() const { return theIntegrationList; }
+
 protected:
 
   /**
    * Return the last generated phase space point.
    */
   vector<double> & lastPoint() { return theLastPoint; }
 
   /**
    * Return the associated event handler.
    */
   tStdEHPtr eventHandler() const { return theEventHandler; }
 
 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);
   //@}
 
   /**
    * Standard Init function used to initialize the interfaces.
    */
   static void Init();
 
 private:
 
   /**
    * The associated event handler.
    */
   tStdEHPtr theEventHandler;
 
   /**
    * The last generated phase space point.
    */
   vector<double> theLastPoint;
 
+  /**
+   * A file containing a list of subprocesses to integrate
+   */
+ string theIntegrationList;
+
 private:
 
   /**
    * Describe an abstract base class with persistent data.
    */
   static AbstractClassDescription<SamplerBase> initSamplerBase;
 
   /**
    *  Private and non-existent assignment operator.
    */
   SamplerBase & operator=(const SamplerBase &);
 
 };
 
 }
 
 
 namespace ThePEG {
 
 /** @cond TRAITSPECIALIZATIONS */
 
 /**
  * This template specialization informs ThePEG about the base class of
  * SamplerBase.
  */
 template <>
 struct BaseClassTrait<SamplerBase,1>: public ClassTraitsType {
   /** Typedef of the base class of SamplerBase. */
   typedef Interfaced NthBase;
 };
 
 /**
  * This template specialization informs ThePEG about the name of the
  * SamplerBase class.
  */
 template <>
 struct ClassTraits<SamplerBase>: public ClassTraitsBase<SamplerBase> {
   /** Return the class name. */
   static string className() { return "ThePEG::SamplerBase"; }
 
 };
 
 /** @endcond */
 
 }
 
 #endif /* ThePEG_SamplerBase_H */
diff --git a/Repository/EventGenerator.cc b/Repository/EventGenerator.cc
--- a/Repository/EventGenerator.cc
+++ b/Repository/EventGenerator.cc
@@ -1,1358 +1,1361 @@
 // -*- C++ -*-
 //
 // EventGenerator.cc is a part of ThePEG - Toolkit for HEP Event Generation
 // Copyright (C) 1999-2011 Leif Lonnblad
 //
 // ThePEG is licenced under version 2 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 EventGenerator class.
 //
 
 #include "EventGenerator.h"
 #include "EventGenerator.xh"
 #include "ThePEG/Handlers/EventHandler.h"
 #include "Repository.h"
 #include "ThePEG/Utilities/HoldFlag.h"
 #include "ThePEG/Utilities/Debug.h"
 #include "ThePEG/Utilities/DebugItem.h"
 #include "ThePEG/Interface/Interfaced.h"
 #include "ThePEG/Interface/Reference.h"
 #include "ThePEG/Interface/RefVector.h"
 #include "ThePEG/Interface/Parameter.h"
 #include "ThePEG/Interface/Switch.h"
 #include "ThePEG/Interface/Command.h"
 #include "ThePEG/Interface/ClassDocumentation.h"
 #include "ThePEG/PDT/ParticleData.h"
 #include "ThePEG/PDT/MatcherBase.h"
 #include "ThePEG/PDT/DecayMode.h"
 #include "ThePEG/StandardModel/StandardModelBase.h"
 #include "ThePEG/Repository/Strategy.h"
 #include "ThePEG/Repository/CurrentGenerator.h"
 #include "ThePEG/Handlers/AnalysisHandler.h"
 #include "ThePEG/Analysis/FactoryBase.h"
 #include "ThePEG/Handlers/EventManipulator.h"
 #include "ThePEG/Handlers/LuminosityFunction.h"
 #include "ThePEG/MatrixElement/MEBase.h"
 #include "ThePEG/EventRecord/Event.h"
 #include "ThePEG/Handlers/SubProcessHandler.h"
 #include "ThePEG/Handlers/CascadeHandler.h"
 #include "ThePEG/Handlers/HadronizationHandler.h"
 #include "ThePEG/Persistency/PersistentOStream.h"
 #include "ThePEG/Persistency/PersistentIStream.h"
 #include "ThePEG/Config/algorithm.h"
 #include "ThePEG/Utilities/DynamicLoader.h"
 #include <cstdlib>
 #include "ThePEG/Repository/Main.h"
 #include <csignal>
 
 #ifdef ThePEG_TEMPLATES_IN_CC_FILE
 #include "EventGenerator.tcc"
 #endif
 
 using namespace ThePEG;
 
 namespace {
   volatile sig_atomic_t THEPEG_SIGNAL_STATE = 0;
 }
 
 // signal handler function
 // very restricted in what it is allowed do
 // without causing undefined behaviour
 extern "C" {
   void thepegSignalHandler(int id) {
     THEPEG_SIGNAL_STATE=id;
     signal(id,SIG_DFL);
   }
 }
 
 void EventGenerator::checkSignalState() {
   if (THEPEG_SIGNAL_STATE) {
     finalize();
     exit(0);
   }
 }
 
 EventGenerator::EventGenerator()
   : thePath("."), theNumberOfEvents(1000), theQuickSize(7000),
     preinitializing(false), ieve(0), weightSum(0.0),
     theDebugLevel(0), logNonDefault(-1), printEvent(0), dumpPeriod(0),
     keepAllDumps(false),
     debugEvent(0), maxWarnings(10), maxErrors(10), theCurrentRandom(0),
     theCurrentGenerator(0), useStdout(false) {}
 
 EventGenerator::EventGenerator(const EventGenerator & eg)
   : Interfaced(eg), theDefaultObjects(eg.theDefaultObjects),
     theLocalParticles(eg.theLocalParticles),
     theStandardModel(eg.theStandardModel),
     theStrategy(eg.theStrategy), theRandom(eg.theRandom),
     theEventHandler(eg.theEventHandler),
     theAnalysisHandlers(eg.theAnalysisHandlers),
     theHistogramFactory(eg.theHistogramFactory),
     theEventManipulator(eg.theEventManipulator),
     thePath(eg.thePath), theRunName(eg.theRunName),
     theNumberOfEvents(eg.theNumberOfEvents), theObjects(eg.theObjects),
     theObjectMap(eg.theObjectMap),
     theParticles(eg.theParticles), theQuickParticles(eg.theQuickParticles),
     theQuickSize(eg.theQuickSize), preinitializing(false),
     theMatchers(eg.theMatchers),
     usedObjects(eg.usedObjects), ieve(eg.ieve), weightSum(eg.weightSum),
     theDebugLevel(eg.theDebugLevel), logNonDefault(eg.logNonDefault),
     printEvent(eg.printEvent), dumpPeriod(eg.dumpPeriod),
     keepAllDumps(eg.keepAllDumps),
     debugEvent(eg.debugEvent),
     maxWarnings(eg.maxWarnings), maxErrors(eg.maxErrors), theCurrentRandom(0),
     theCurrentGenerator(0),
     theCurrentEventHandler(eg.theCurrentEventHandler),
     theCurrentStepHandler(eg.theCurrentStepHandler),
     useStdout(eg.useStdout) {}
 
 EventGenerator::~EventGenerator() {
   if ( theCurrentRandom ) delete theCurrentRandom;
   if ( theCurrentGenerator ) delete theCurrentGenerator;
 }
 
 IBPtr EventGenerator::clone() const {
   return new_ptr(*this);
 }
 
 IBPtr EventGenerator::fullclone() const {
   return new_ptr(*this);
 }
 
 tcEventPtr EventGenerator::currentEvent() const {
   return eventHandler()->currentEvent();
 }
 
 CrossSection EventGenerator::histogramScale() const {
   return eventHandler()->histogramScale();
 }
 
 CrossSection EventGenerator::integratedXSec() const {
   return eventHandler()->integratedXSec();
 }
 
 CrossSection EventGenerator::integratedXSecErr() const {
   return eventHandler()->integratedXSecErr();
 }
 
 void EventGenerator::setSeed(long seed) {
   random().setSeed(seed);
   ostringstream s;
   s << seed;
   const InterfaceBase * ifb = BaseRepository::FindInterface(theRandom, "Seed");
   ifb->exec(*theRandom, "set", s.str());
 }
 
 void
 EventGenerator::setup(string newRunName,
 		      ObjectSet & newObjects,
 		      ParticleMap & newParticles,
 		      MatcherSet & newMatchers) {
   HoldFlag<int> debug(Debug::level, Debug::isset? Debug::level: theDebugLevel);
   theRunName = newRunName;
   theObjects.swap(newObjects);
   theParticles.swap(newParticles);
   theMatchers.swap(newMatchers);
   theObjectMap.clear();
   for ( ObjectSet::const_iterator it = objects().begin();
 	it != objects().end(); ++it ) theObjectMap[(**it).fullName()] = *it;
   UseRandom currentRandom(theRandom);
   CurrentGenerator currentGenerator(this);
 
   // Force update of all objects and then reset.
   touch();
   for_each(theObjects, mem_fun(&InterfacedBase::touch));
   update();
   for_each(theObjects, mem_fun(&InterfacedBase::update));
   clear();
   BaseRepository::clearAll(theObjects);
 
   init();
 
 }
 
 IBPtr EventGenerator::getPointer(string name) const {
   ObjectMap::const_iterator it = objectMap().find(name);
   if ( it == objectMap().end() ) return IBPtr();
   else return it->second;
 }
 
 void EventGenerator::openOutputFiles() {
   if ( !useStdout ) {
     logfile().open((filename() + ".log").c_str());
     theOutFileName = filename() + ".out";
     outfile().open(theOutFileName.c_str());
     outfile().close();
     theOutStream.str("");
   }
   out() << Repository::banner() << endl;
   log() << Repository::banner() << endl;
 }
 
 void EventGenerator::closeOutputFiles() {
   flushOutputFile();
   if ( !useStdout ) logfile().close();
 }
 
 void EventGenerator::flushOutputFile() {
   if ( !useStdout ) {
     outfile().open(theOutFileName.c_str(), ios::out|ios::app);
     outfile() << theOutStream.str();
     outfile().close();
   } else
     BaseRepository::cout() << theOutStream.str();
   theOutStream.str("");
 }
 
 void EventGenerator::doinit() {
 
   HoldFlag<int> debug(Debug::level, Debug::isset? Debug::level: theDebugLevel);
 
   // First initialize base class and random number generator.
   Interfaced::doinit();
   random().init();
 
   // Make random generator and this available in standard static
   // classes.
   UseRandom useRandom(theRandom);
   CurrentGenerator currentGenerator(this);
 
   // First initialize all objects which have requested this by
   // implementing a InterfacedBase::preInitialize() function which
   // returns true.
   while ( true ) {
     HoldFlag<bool> hold(preinitializing, true);
     ObjectSet preinits;
     for ( ObjectSet::iterator it = objects().begin();
 	  it != objects().end(); ++it )
       if ( (**it).preInitialize() &&
 	   (**it).state() == InterfacedBase::uninitialized )
 	preinits.insert(*it);
     if ( preinits.empty() ) break;
     for_each(preinits, mem_fun(&InterfacedBase::init));
   }
 
   // Initialize the quick access to particles.
   theQuickParticles.clear();
   theQuickParticles.resize(2*theQuickSize);
   for ( ParticleMap::const_iterator pit = theParticles.begin();
 	pit != theParticles.end(); ++pit )
     if ( abs(pit->second->id()) < theQuickSize )
       theQuickParticles[pit->second->id()+theQuickSize] = pit->second;
 
   // Then call the init method for all objects. Start with the
   // standard model and the strategy.
   standardModel()->init();
   if ( strategy() ) strategy()->init();
   eventHandler()->init();
 
   // initialize particles first
   for(ParticleMap::const_iterator pit = particles().begin();
       pit != particles().end(); ++pit) pit->second->init();
   
   for_each(objects(), mem_fun(&InterfacedBase::init));
 
   // Then initialize the Event Handler calculating initial cross
   // sections and stuff.
   eventHandler()->initialize();
 }
 
 void EventGenerator::doinitrun() {
 
   HoldFlag<int> debug(Debug::level, Debug::isset? Debug::level: theDebugLevel);
 
   signal(SIGHUP, thepegSignalHandler);
   signal(SIGINT, thepegSignalHandler);
   signal(SIGTERM,thepegSignalHandler);
 
   currentEventHandler(eventHandler());
 
   Interfaced::doinitrun();
   random().initrun();
 
   // Then call the init method for all objects. Start with the
   // standard model and the strategy.
   standardModel()->initrun();
   if ( strategy() ) strategy()->initrun();
   // initialize particles first
   for(ParticleMap::const_iterator pit = particles().begin();
       pit != particles().end(); ++pit) {
     pit->second->initrun();
   }
   eventHandler()->initrun();
 
   
   for_each(objects(), mem_fun(&InterfacedBase::initrun));
 
   if ( logNonDefault > 0 || ( ThePEG_DEBUG_LEVEL && logNonDefault == 0 ) ) {
     vector< pair<IBPtr, const InterfaceBase *> > changed =
       Repository::getNonDefaultInterfaces(objects());
     if ( changed.size() ) {
       log() << string(78, '=') << endl
 	    << "The following interfaces have non-default values (default):"
 	    << endl << string(78, '-') << endl;
       for ( int i = 0, N = changed.size(); i < N; ++i ) {
 	log() << changed[i].first->fullName() << ":"
 	      << changed[i].second->name() << " = "
 	      << changed[i].second->exec(*changed[i].first, "notdef", "")
 	      << endl;
       }
       log() << string(78,'=') << endl;
     }
   }
 
   weightSum = 0.0;
 
 }
 
 PDPtr EventGenerator::getParticleData(PID id) const {
   long newId = id;
   if ( abs(newId) < theQuickSize && theQuickParticles.size() )
     return theQuickParticles[newId+theQuickSize];
   ParticleMap::const_iterator it = theParticles.find(newId);
   if ( it == theParticles.end() ) return PDPtr();
   return it->second;
 }
 
 PPtr EventGenerator::getParticle(PID newId) const {
   tcPDPtr pd = getParticleData(newId);
   if ( !pd ) return PPtr();
   return pd->produceParticle();
 }
 
 void EventGenerator::finalize() {
   UseRandom currentRandom(theRandom);
   CurrentGenerator currentGenerator(this);
   finish();
   finally();
 }
 
 void EventGenerator::dofinish() {
 
   HoldFlag<int> debug(Debug::level, Debug::isset? Debug::level: theDebugLevel);
 
   // first write out statistics from the event handler.
   eventHandler()->statistics(out());
 
   // Call the finish method for all other objects.
   for_each(objects(), mem_fun(&InterfacedBase::finish));
 
   if ( theExceptions.empty() ) {
     log() << "No exceptions reported in this run.\n";
   } else {
 
     log() << "\nThe following exception classes were reported in this run:\n";
 
     for ( ExceptionMap::iterator it = theExceptions.begin();
 	  it != theExceptions.end(); ++it ) {
       string severity;
       switch ( it->first.second ) {
       case Exception::info       : severity="info"; break;
       case Exception::warning    : severity="warning"; break;
       case Exception::setuperror : severity="setuperror"; break;
       case Exception::eventerror : severity="eventerror"; break;
       case Exception::runerror   : severity="runerror"; break;
       case Exception::maybeabort : severity="maybeabort"; break;
       case Exception::abortnow   : severity="abortnow"; break;
       default                    : severity="unknown";
       }
       log() << it->first.first << ' ' << severity
 	    << " (" << it->second << " times)\n";
     }
   }
 
   theExceptions.clear();
 
   const string & msg = theMiscStream.str();
   if ( ! msg.empty() ) {
     log() << endl 
 	  << "Miscellaneous output from modules to the standard output:\n\n"
 	  << msg;
     theMiscStream.str("");
   }
 
   flushOutputFile();
 
 }
 
 void EventGenerator::finally() {
 
   generateReferences();
 
   closeOutputFiles();
 
   if ( theCurrentRandom ) delete theCurrentRandom;
   if ( theCurrentGenerator ) delete theCurrentGenerator;
   theCurrentRandom = 0;
   theCurrentGenerator = 0;
 
 }
 
-void EventGenerator::initialize() {
+void EventGenerator::initialize(bool initOnly) {
   UseRandom currentRandom(theRandom);
   CurrentGenerator currentGenerator(this);
-  doInitialize();
+  doInitialize(initOnly);
 }
 
 bool EventGenerator::loadMain(string file) {
   initialize();
   UseRandom currentRandom(theRandom);
   CurrentGenerator currentGenerator(this);
   Main::eventGenerator(this);
   bool ok = DynamicLoader::load(file);
   finish();
   finally();
   return ok;
 }
 
 
 void EventGenerator::go(long next, long maxevent, bool tics) {
   UseRandom currentRandom(theRandom);
   CurrentGenerator currentGenerator(this);
   doGo(next, maxevent, tics);
 }
 
 EventPtr EventGenerator::shoot() {
   static DebugItem debugfpu("ThePEG::FPU", 1);
   if ( debugfpu ) Debug::unmaskFpuErrors();
   UseRandom currentRandom(theRandom);
   CurrentGenerator currentGenerator(this);
   checkSignalState();
   EventPtr event = doShoot();
   if ( event ) weightSum += event->weight();
   DebugItem::tic();
   return event;
 }
 
 EventPtr EventGenerator::doShoot() {
   EventPtr event;
   if ( N() >= 0 && ++ieve > N() ) return event;
   HoldFlag<int> debug(Debug::level, Debug::isset? Debug::level: theDebugLevel);
   do { 
     int state = 0;
     int loop = 1;
     eventHandler()->clearEvent();
     try {
       do {
 	// Generate a full event or part of an event
 	if ( eventHandler()->empty() ) event = eventHandler()->generateEvent();
 	else event = eventHandler()->continueEvent();
 
 	if ( eventHandler()->empty() ) loop = -loop;
 	
 	// Analyze the possibly uncomplete event
 	for ( AnalysisVector::iterator it = analysisHandlers().begin();
 	      it != analysisHandlers().end(); ++it )
 	  (**it).analyze(event, ieve, loop, state);
 	
 	// Manipulate the current event, possibly deleting some steps
 	// and telling the event handler to redo them.
 	if ( manipulator() )
 	  state = manipulator()->manipulate(eventHandler(), event);
 	
 	// If the event was not completed, continue generation and continue.
 	loop = abs(loop) + 1;
       } while ( !eventHandler()->empty() );
     }
     catch (Exception & ex) {
       if ( logException(ex, eventHandler()->currentEvent()) ) throw;
     }
     catch (...) {
       event = eventHandler()->currentEvent();
       if ( event )
 	log() << *event;
       else
 	log() << "An exception occurred before any event object was created!";
       log() << endl;
       dump();
       throw;
     }
     if ( ThePEG_DEBUG_LEVEL ) {
       if ( ( ThePEG_DEBUG_LEVEL == Debug::printEveryEvent ||
 	     ieve < printEvent ) && event ) log() << *event;
       if ( debugEvent > 0 && ieve + 1 >= debugEvent )
 	Debug::level = Debug::full;
     }
   } while ( !event );
 
   // If scheduled, dump a clean state between events
   if ( ThePEG_DEBUG_LEVEL && dumpPeriod > 0 && ieve%dumpPeriod == 0 ) {
     eventHandler()->clearEvent();
     eventHandler()->clean();
     dump();
   }
 
   return event;
 }
 
 EventPtr EventGenerator::doGenerateEvent(tEventPtr e) {
   if ( N() >= 0 && ++ieve > N() ) return EventPtr();
   EventPtr event = e;
   try {
     event = eventHandler()->generateEvent(e);
   }
   catch (Exception & ex) {
     if ( logException(ex, eventHandler()->currentEvent()) ) throw;
   }
   catch (...) {
     event = eventHandler()->currentEvent();
     if ( !event ) event = e;
     log() << *event << endl;
     dump();
     throw;
   }
   return event;
 }
 
 EventPtr EventGenerator::doGenerateEvent(tStepPtr s) {
   if ( N() >= 0 && ++ieve > N() ) return EventPtr();
   EventPtr event;
   try {
     event = eventHandler()->generateEvent(s);
   }
   catch (Exception & ex) {
     if ( logException(ex, eventHandler()->currentEvent()) ) throw;
   }
   catch (...) {
     event = eventHandler()->currentEvent();
     if ( event ) log() << *event << endl;
     dump();
     throw;
   }
   return event;
 }
 
 EventPtr EventGenerator::generateEvent(Event & e) {
   UseRandom currentRandom(theRandom);
   CurrentGenerator currentGenerator(this);
   EventPtr event = doGenerateEvent(tEventPtr(&e));
   if ( event ) weightSum += event->weight();
   return event;
 }
 
 EventPtr EventGenerator::generateEvent(Step & s) {
   UseRandom currentRandom(theRandom);
   CurrentGenerator currentGenerator(this);
   EventPtr event = doGenerateEvent(tStepPtr(&s));
   if ( event ) weightSum += event->weight();
   return event;
 }
 
 Energy EventGenerator::maximumCMEnergy() const {
   tcEHPtr eh = eventHandler();
   return eh->lumiFnPtr()? eh->lumiFn().maximumCMEnergy(): ZERO;
 }
 
-void EventGenerator::doInitialize() {
+void EventGenerator::doInitialize(bool initOnly) {
 
-  openOutputFiles();
+  if ( !initOnly )
+    openOutputFiles();
 
   init();
-  initrun();
+
+  if ( !initOnly )
+    initrun();
 
   if ( !ThePEG_DEBUG_LEVEL ) Exception::noabort = true;
 
 }
 
 void EventGenerator::doGo(long next, long maxevent, bool tics) {
 
   if ( maxevent >= 0 ) N(maxevent);
 
   if ( next >= 0 ) {
     if ( tics ) 
       cerr << "event> " << setw(9) << "init\r" << flush;
     initialize();
     ieve = next-1;
   } else {
     openOutputFiles();
   }
 
   if ( tics ) tic();
   try {
     while ( shoot() ) {
       if ( tics ) tic();
     }
   }
   catch ( ... ) {
     finish();
     throw;
   }
 
   finish();
 
   finally();
 
 }
 
 void EventGenerator::tic(long currev, long totev) const {
   if ( !currev ) currev = ieve;
   if ( !totev ) totev = N();
   long i = currev;
   long n = totev;
   bool skip = currev%(max(totev/100, 1L));
   if ( i > n/2 ) i = n-i;
   while ( skip && i >= 10 && !(i%10) ) i /= 10;
   if ( i == 1 || i == 2 || i == 5 ) skip = false;
   if ( skip ) return;
   cerr << "event> " << setw(8) << currev << " " << setw(8) << totev << "\r";
   cerr.flush();
   if ( currev == totev ) cerr << endl;
 }
   
 
 void EventGenerator::dump() const {
   if ( dumpPeriod > -1 ) {
     string dumpfile;
     if ( keepAllDumps ) {
       ostringstream number;
       number << ieve;
       dumpfile = filename() + "-" + number.str() + ".dump";
     }
     else
       dumpfile = filename() + ".dump";
     PersistentOStream file(dumpfile, globalLibraries());
     file << tcEGPtr(this);
   }
 }
 
 void EventGenerator::use(const Interfaced & i) {
   IBPtr ip = getPtr(i);
   if ( ip ) usedObjects.insert(ip);
 }
 
 void EventGenerator::generateReferences() {
   typedef map<string,string> StringMap;
   StringMap references;
 
   // First get all model descriptions and model references from the
   // used objects. Put them in a map indexed by the description to
   // avoid duplicates.
   for ( ObjectSet::iterator it = usedObjects.begin();
 	it != usedObjects.end(); ++it ) {
     if ( *it == strategy() ) continue;
     string desc = Repository::getModelDescription(*it);
     if ( desc.empty() ) continue;
     if ( dynamic_ptr_cast<cEHPtr>(*it) ) desc = "A " + desc;
     else if ( dynamic_ptr_cast<cSMPtr>(*it) ) desc = "B " + desc;
     else if ( dynamic_ptr_cast<cMEPtr>(*it) ) desc = "C " + desc;
     else if ( dynamic_ptr_cast<cCascHdlPtr>(*it) ) desc = "D " + desc;
     else if ( dynamic_ptr_cast<cHadrHdlPtr>(*it) ) desc = "E " + desc;
     else if ( dynamic_ptr_cast<cStepHdlPtr>(*it) ) desc = "F " + desc;
     else if ( dynamic_ptr_cast<cDecayerPtr>(*it) ) desc = "Y " + desc;
     else if ( dynamic_ptr_cast<cAnalysisHdlPtr>(*it) ) desc = "Z " + desc;
     else if ( dynamic_ptr_cast<Ptr<HandlerBase>::const_pointer>(*it) )
       desc = "G " + desc;
     else  desc = "H " + desc;
     references[desc] = Repository::getModelReferences(*it);
   }
 
   // Now get the main strategy description which should put first and
   // remove it from the map.
   string stratdesc;
   string stratref;
   if ( strategy() ) {
     stratdesc = Repository::getModelDescription(strategy());
     stratref = Repository::getModelReferences(strategy());
     references.erase(stratdesc);
   }
 
   // Open the file and write out an appendix header
   if ( !useStdout )
     reffile().open((filename() + ".tex").c_str());
   ref() << "\\documentclass{article}\n"
 	<< "\\usepackage{graphics}\n"
 	<< "\\begin{document}\n"
 	<< "\\appendix\n"
 	<< "\\section[xxx]{\\textsc{ThePEG} version " << Repository::version()
 	<< " \\cite{ThePEG} Run Information}\n"
 	<< "Run name: \\textbf{" << runName()
 	<< "}:\\\\\n";
   if ( !stratdesc.empty() )
     ref() << "This run was generated using " << stratdesc 
 	  << " and the following models:\n";
   else
     ref() << "The following models were used:\n";
 
     ref() << "\\begin{itemize}\n";
 
   // Write out all descriptions.
   for ( StringMap::iterator it = references.begin();
 	it != references.end(); ++it )
     ref() << "\\item " << it->first.substr(2) << endl;
 
   // Write out thebibliography header and all references.
   ref() << "\\end{itemize}\n\n"
 	    << "\\begin{thebibliography}{99}\n"
 	    << "\\bibitem{ThePEG} L.~L\\\"onnblad, "
 	    << "Comput.~Phys.~Commun.\\ {\\bf 118} (1999) 213.\n";
   if ( !stratref.empty() ) ref() << stratref << '\n';
   for ( StringMap::iterator it = references.begin();
 	it != references.end(); ++it )
     ref() << it->second << '\n';
   ref() << "\\end{thebibliography}\n"
 	    << "\\end{document}" << endl;
   if ( !useStdout )
     reffile().close();
 }
 
 void EventGenerator::strategy(StrategyPtr s) {
   theStrategy = s;
 }
 
 int EventGenerator::count(const Exception & ex) {
   return ++theExceptions[make_pair(StringUtils::typeName(typeid(ex)),
 				   ex.severity())];
 }
 
 void EventGenerator::printException(const Exception & ex) {
   switch ( ex.severity() ) {
   case Exception::info:
     log() << "* An information";
         break;
   case Exception::warning:
     log() << "* A warning";
     break;
   case Exception::setuperror:
     log() << "** A setup";
     break;
   case Exception::eventerror:
     log() << "** An event";
     break;
   case Exception::runerror:
     log() << "*** An run";
     break;
   case Exception::maybeabort:
   case Exception::abortnow:
     log() << "**** A serious";
     break;
   default:
     log() << "**** An unknown";
     break;
   }
   if ( ieve > 0 )
     log() << " exception of type " << StringUtils::typeName(typeid(ex))
 	  << " occurred while generating event number "
 	  << ieve << ": \n" << ex.message() << endl;
   else
     log() << " exception occurred in the initialization of "
 	  << name() << ": \n" << ex.message() << endl;
   if ( ex.severity() == Exception::eventerror )
     log() << "The event will be discarded." << endl;
 }
 
 void EventGenerator::logWarning(const Exception & ex) {
   if ( ex.severity() != Exception::info &&
        ex.severity() != Exception::warning ) throw ex;
   ex.handle();  
   int c = count(ex);
   if ( c > maxWarnings ) return;
   printException(ex);
   if ( c == maxWarnings )
     log() << "No more warnings of this kind will be reported." << endl;
 }
  
 bool EventGenerator::
 logException(const Exception & ex, tcEventPtr event) {
   bool noEvent = !event;
   ex.handle();
   int c = count(ex);
   if ( c <= maxWarnings ) {
     printException(ex);
     if ( c == maxWarnings )
       log() << "No more warnings of this kind will be reported." << endl;
   }
   if ( ex.severity() == Exception::info ||
        ex.severity() == Exception::warning ) {
     ex.handle();
     return false;
   }
   if ( ex.severity() == Exception::eventerror ) {
     if ( c < maxErrors || maxErrors <= 0 ) {
       ex.handle();
       if ( ThePEG_DEBUG_LEVEL > 0 && !noEvent ) log() << *event;
       return false;
     }
     if ( c > maxErrors ) printException(ex);
     log() << "Too many (" << c << ") exceptions of this kind has occurred. "
       "Execution will be stopped.\n";
   } else {
     log() << "This exception is too serious. Execution will be stopped.\n";
   }
   if ( !noEvent ) log() << *event;
   else log()
     << "An exception occurred before any event object was created!\n";
   dump();
   return true;
 }
 
 struct MatcherOrdering {
   bool operator()(tcPMPtr m1, tcPMPtr m2) {
     return m1->name() < m2->name() ||
       ( m1->name() == m2->name() && m1->fullName() < m2->fullName() );
   }
 };
 
 struct ObjectOrdering {
   bool operator()(tcIBPtr i1, tcIBPtr i2) {
     return i1->fullName() < i2->fullName();
   }
 };
 
 void EventGenerator::persistentOutput(PersistentOStream & os) const {
   set<tcPMPtr,MatcherOrdering> match(theMatchers.begin(), theMatchers.end());
   set<tcIBPtr,ObjectOrdering> usedset(usedObjects.begin(), usedObjects.end());
   os << theDefaultObjects << theLocalParticles << theStandardModel
      << theStrategy << theRandom << theEventHandler << theAnalysisHandlers
      << theHistogramFactory << theEventManipulator << thePath << theRunName
      << theNumberOfEvents << theObjectMap << theParticles
      << theQuickParticles << theQuickSize << match << usedset
      << ieve << weightSum << theDebugLevel << logNonDefault << printEvent
      << dumpPeriod << keepAllDumps << debugEvent
      << maxWarnings << maxErrors << theCurrentEventHandler
      << theCurrentStepHandler << useStdout << theMiscStream.str();
 }
 
 void EventGenerator::persistentInput(PersistentIStream & is, int) {
   string dummy;
   theGlobalLibraries = is.globalLibraries();
   is >> theDefaultObjects >> theLocalParticles >> theStandardModel
      >> theStrategy >> theRandom >> theEventHandler >> theAnalysisHandlers
      >> theHistogramFactory >> theEventManipulator >> thePath >> theRunName
      >> theNumberOfEvents >> theObjectMap >> theParticles
      >> theQuickParticles >> theQuickSize >> theMatchers >> usedObjects
      >> ieve >> weightSum >> theDebugLevel >> logNonDefault >> printEvent
      >> dumpPeriod >> keepAllDumps >> debugEvent
      >> maxWarnings >> maxErrors >> theCurrentEventHandler
      >> theCurrentStepHandler >> useStdout >> dummy;
   theMiscStream.str(dummy);
   theMiscStream.seekp(0, std::ios::end);
   theObjects.clear();
   for ( ObjectMap::iterator it = theObjectMap.begin();
 	it != theObjectMap.end(); ++it ) theObjects.insert(it->second);
 }
 
 void EventGenerator::setLocalParticles(PDPtr pd, int) {
   localParticles()[pd->id()] = pd;
 }
   
 void EventGenerator::insLocalParticles(PDPtr pd, int) {
   localParticles()[pd->id()] = pd;
 }
   
 void EventGenerator::delLocalParticles(int place) {
   ParticleMap::iterator it = localParticles().begin();
   while ( place-- && it != localParticles().end() ) ++it;
   if ( it != localParticles().end() ) localParticles().erase(it);
 }
 
 vector<PDPtr> EventGenerator::getLocalParticles() const {
   vector<PDPtr> ret;
   for ( ParticleMap::const_iterator it = localParticles().begin();
  	it != localParticles().end(); ++it ) ret.push_back(it->second);
   return ret;
 }
 
 void EventGenerator::setPath(string newPath) {
   if ( std::system(("mkdir -p " + newPath).c_str()) ) throw EGNoPath(newPath);
   if ( std::system(("touch " + newPath + "/.ThePEG").c_str()) )
     throw EGNoPath(newPath);
   if ( std::system(("rm -f " + newPath + "/.ThePEG").c_str()) )
     throw EGNoPath(newPath);
   thePath = newPath;
 }
 
 string EventGenerator::defPath() const {
   char * env = std::getenv("ThePEG_RUN_DIR");
   if ( env ) return string(env);
   return string(".");
 }
 
 ostream & EventGenerator::out() {
   return theOutStream;
 }
 
 ostream & EventGenerator::log() {
   return logfile().is_open()? logfile(): BaseRepository::cout();
 }
 
 ostream & EventGenerator::ref() {
   return reffile().is_open()? reffile(): BaseRepository::cout();
 }
 
 string EventGenerator::doSaveRun(string runname) {
   runname = StringUtils::car(runname);
   if ( runname.empty() ) runname = theRunName;
   if ( runname.empty() ) runname = name();
   EGPtr eg = Repository::makeRun(this, runname);
   string file =  eg->filename() + ".run";
   PersistentOStream os(file);
   os << eg;
   if ( !os ) return "Error: Save failed! (I/O error)";
   return "";
 }
 
 string EventGenerator::doMakeRun(string runname) {
   runname = StringUtils::car(runname);
   if ( runname.empty() ) runname = theRunName;
   if ( runname.empty() ) runname = name();
   Repository::makeRun(this, runname);
   return "";
 }
 
 bool EventGenerator::preinitRegister(IPtr obj, string fullname) {
   if ( !preinitializing ) throw InitException()
     << "Tried to register a new object in the initialization of an "
     << "EventGenerator outside of the pre-initialization face. "
     << "The preinitRegister() can only be called from a doinit() function "
     << "in an object for which preInitialize() returns true.";
   if ( objectMap().find(fullname) != objectMap().end() ) return false;
   obj->name(fullname);
   objectMap()[fullname] = obj;
   objects().insert(obj);
   obj->theGenerator = this;
   PDPtr pd = dynamic_ptr_cast<PDPtr>(obj);
   if ( pd ) theParticles[pd->id()] = pd;
   PMPtr pm = dynamic_ptr_cast<PMPtr>(obj);
   if ( pm ) theMatchers.insert(pm);
   return true;
 }
 
 IPtr EventGenerator::
 preinitCreate(string classname, string fullname, string libraries) {
   if ( !preinitializing ) throw InitException()
     << "Tried to create a new object in the initialization of an "
     << "EventGenerator outside of the pre-initialization face. "
     << "The preinitCreate() can only be called from a doinit() function "
     << "in an object for which preInitialize() returns true.";
   if ( objectMap().find(fullname) != objectMap().end() ) return IPtr();
   const ClassDescriptionBase * db = DescriptionList::find(classname);
   while ( !db && libraries.length() ) {
     string library = StringUtils::car(libraries);
     libraries = StringUtils::cdr(libraries);
     DynamicLoader::load(library);
     db = DescriptionList::find(classname);
   }
   if ( !db ) return IPtr();
   IPtr obj = dynamic_ptr_cast<IPtr>(db->create());
   if ( !obj ) return IPtr();
   if ( !preinitRegister(obj, fullname) ) return IPtr();
   return obj;
 }
 
 string EventGenerator::
 preinitInterface(IPtr obj, string ifcname, string cmd, string value) {
   if ( !preinitializing ) throw InitException()
     << "Tried to manipulate an external object in the initialization of an "
     << "EventGenerator outside of the pre-initialization face. "
     << "The preinitSet() can only be called from a doinit() function "
     << "in an object for which preInitialize() returns true.";
   if ( !obj ) return "Error: No object found.";
   const InterfaceBase * ifc = Repository::FindInterface(obj, ifcname);
   if ( !ifc ) return "Error: No such interface found.";
   try {
     return ifc->exec(*obj, cmd, value);
   }
   catch ( const InterfaceException & ex) {
     ex.handle();
     return "Error: " + ex.message();
   }
 }
 
 string EventGenerator::
 preinitInterface(IPtr obj, string ifcname, int index,
 		 string cmd, string value) {
   ostringstream os;
   os << index;
   return preinitInterface(obj, ifcname, cmd, os.str() + " " + value);
 }
 
 string EventGenerator::
 preinitInterface(string fullname, string ifcname, string cmd, string value) {
   return preinitInterface(getObject<Interfaced>(fullname), ifcname, cmd, value);
 }
 
 string EventGenerator::
 preinitInterface(string fullname, string ifcname, int index,
 		 string cmd, string value) {
   return preinitInterface(getObject<Interfaced>(fullname), ifcname, index,
 			  cmd, value);
 }
 
 tDMPtr EventGenerator::findDecayMode(string tag) const {
   for ( ObjectSet::const_iterator it = objects().begin();
 	it != objects().end(); ++it ) {
     tDMPtr dm = dynamic_ptr_cast<tDMPtr>(*it);
     if ( dm && dm->tag() == tag ) return dm;
   }
   return tDMPtr();
 }
 
 tDMPtr EventGenerator::preinitCreateDecayMode(string tag) {
   return constructDecayMode(tag);
 }
 
 DMPtr EventGenerator::constructDecayMode(string & tag) {
   DMPtr rdm;
   DMPtr adm;
   int level = 0;
   string::size_type end = 0;
   while ( end < tag.size() && ( tag[end] != ']' || level ) ) {
     switch ( tag[end++] ) {
     case '[':
       ++level;
       break;
     case ']':
       --level;
       break;
     }
   }
   rdm = findDecayMode(tag.substr(0,end));
   if ( rdm ) return rdm;
 
   string::size_type next = tag.find("->");
   if ( next == string::npos ) return rdm;
   if ( tag.find(';') == string::npos ) return rdm;
   tPDPtr pd = getObject<ParticleData>(tag.substr(0,next));
   if ( !pd ) pd = findParticle(tag.substr(0,next));
   if ( !pd ) return rdm;
   rdm = ptr_new<DMPtr>();
   rdm->parent(pd);
   if ( pd->CC() ) {
     adm = ptr_new<DMPtr>();
     adm->parent(pd->CC());
     rdm->theAntiPartner = adm;
     adm->theAntiPartner = rdm;
   }
   bool error = false;
   tag = tag.substr(next+2);
   tPDPtr lastprod;
   bool dolink = false;
   do {
     switch ( tag[0] ) {
     case '[':
       {
 	tag = tag.substr(1);
 	tDMPtr cdm = constructDecayMode(tag);
 	if ( cdm ) rdm->addCascadeProduct(cdm);
 	else error = true;
       } break;
     case '=':
       dolink = true;
     case ',':
     case ']':
       tag = tag.substr(1);
       break;
     case '?':
       {
 	next = min(tag.find(','), tag.find(';'));
 	tPMPtr pm = findMatcher(tag.substr(1,next-1));
 	if ( pm ) rdm->addProductMatcher(pm);
 	else error = true;
 	tag = tag.substr(next);
       } break;
     case '!':
       {
 	next = min(tag.find(','), tag.find(';'));
 	tPDPtr pd = findParticle(tag.substr(1,next-1));
 	if ( pd ) rdm->addExcluded(pd);
 	else error = true;
 	tag = tag.substr(next);
       } break;
     case '*':
       {
 	next = min(tag.find(','), tag.find(';'));
 	tPMPtr pm = findMatcher(tag.substr(1,next-1));
 	if ( pm ) rdm->setWildMatcher(pm);
 	else error = true;
 	tag = tag.substr(next);
       } break;
     default:
       {
 	next = min(tag.find('='), min(tag.find(','), tag.find(';')));
 	tPDPtr pdp = findParticle(tag.substr(0,next));
 	if ( pdp ) rdm->addProduct(pdp);
 	else error = true;
 	tag = tag.substr(next);
 	if ( dolink && lastprod ) {
 	  rdm->addLink(lastprod, pdp);
 	  dolink = false;
 	}
 	lastprod = pdp;
       } break;
     }
   } while ( tag[0] != ';' && tag.size() );
   if ( tag[0] != ';' || error ) {
     return DMPtr();
   }
 
   tag = tag.substr(1);
   
   DMPtr ndm = findDecayMode(rdm->tag());
   if ( ndm ) return ndm;
   pd->addDecayMode(rdm);
   if ( !preinitRegister(rdm, pd->fullName() + "/" + rdm->tag()) )
     return DMPtr();
   if ( adm ) {
     preinitRegister(adm, pd->CC()->fullName() + "/" + adm->tag());
     rdm->CC(adm);
     adm->CC(rdm);
   }
 
   return rdm;
 }
 
 tPDPtr EventGenerator::findParticle(string pdgname) const {
   for ( ParticleMap::const_iterator it = particles().begin();
 	it != particles().end(); ++it )
     if ( it->second->PDGName() == pdgname ) return it->second;
   return tPDPtr();
 }
 
 tPMPtr EventGenerator::findMatcher(string name) const {
   for ( MatcherSet::const_iterator it = matchers().begin();
 	it != matchers().end(); ++it )
     if ( (**it).name() == name ) return *it;
   return tPMPtr();
 }
 
 ClassDescription<EventGenerator> EventGenerator::initEventGenerator;
 
 void EventGenerator::Init() {
   
   static ClassDocumentation<EventGenerator> documentation
     ("This is the main class used to administer an event generation run. "
      "The actual generation of each event is handled by the assigned "
      "<interface>EventHandler</interface> object. When the event generator"
      "is properly set up it can be initialized with the command "
      "<interface>MakeRun</interface> and/or saved to a file with the command "
      "<interface>SaveRun</interface>. If saved to a file, the event generator "
      "can be read into another program to produce events. The file can also "
      "be read into the <tt>runThePEG</tt> program where a number of events "
      "determined by the parameter <interface>NumberOfEvents</interface> is "
      "generated with each event analysed by the list of assigned "
      "<interface>AnalysisHandlers</interface>.");
 
   static Reference<EventGenerator,StandardModelBase> interfaceStandardModel
     ("StandardModelParameters",
      "The ThePEG::StandardModelBase object to be used to access standard "
      "model parameters in this run.",
      &EventGenerator::theStandardModel, false, false, true, false);
 
   static Reference<EventGenerator,EventHandler> interfaceEventHandler
     ("EventHandler",
      "The ThePEG::EventHandler object to be used to generate the "
      "individual events in this run.",
      &EventGenerator::theEventHandler, false, false, true, false);
 
   static RefVector<EventGenerator,AnalysisHandler> interfaceAnalysisHandlers
     ("AnalysisHandlers",
      "ThePEG::AnalysisHandler objects to be used to analyze the produced "
      "events in this run.",
      &EventGenerator::theAnalysisHandlers, 0, true, false, true, false);
 
   static Reference<EventGenerator,FactoryBase> interfaceHistogramFactory
     ("HistogramFactory",
      "An associated factory object for handling histograms to be used by "
      "<interface>AnalysisHandlers</interface>.",
      &EventGenerator::theHistogramFactory, true, false, true, true, true);
 
   static Reference<EventGenerator,EventManipulator> interfaceEventManip
     ("EventManipulator",
      "An ThePEG::EventManipulator called each time the generation of an "
      "event is stopped. The ThePEG::EventManipulator object is able to "
      "manipulate the generated event, as opposed to an "
      "ThePEG::AnalysisHandler which may only look at the event.",
      &EventGenerator::theEventManipulator, true, false, true, true);
 
   static RefVector<EventGenerator,ParticleData> interfaceLocalParticles
     ("LocalParticles",
      "Special versions of ThePEG::ParticleData objects to be used "
      "in this run. Note that to delete an object, its number in the list "
      "should be given, rather than its id number.",
      0, 0, false, false, true, false,
      &EventGenerator::setLocalParticles, &EventGenerator::insLocalParticles,
      &EventGenerator::delLocalParticles, &EventGenerator::getLocalParticles);
 
   static RefVector<EventGenerator,Interfaced> interfaceDefaultObjects
     ("DefaultObjects",
      "A vector of pointers to default objects. In a ThePEG::Reference or "
      "ThePEG::RefVector interface with the defaultIfNull() flag set, if a "
      "null pointer is encountered this vector is gone through until an "
      "acceptable object is found in which case the null pointer is replaced "
      "by a pointer to this object.",
      &EventGenerator::theDefaultObjects, 0, true, false, true, false, false);
 
   static Reference<EventGenerator,Strategy> interfaceStrategy
     ("Strategy",
      "An ThePEG::Strategy with additional ThePEG::ParticleData objects to "
      "be used in this run.",
      &EventGenerator::theStrategy, false, false, true, true);
 
   static Reference<EventGenerator,RandomGenerator> interfaceRandomGenerator
     ("RandomNumberGenerator",
      "An ThePEG::RandomGenerator object which should typically interaface to "
      "a CLHEP Random object. This will be the default random number generator "
      "for the run, but individual objects may use their own random generator "
      "if they wish.",
      &EventGenerator::theRandom, true, false, true, false);
 
   static Parameter<EventGenerator,string> interfacePath
     ("Path",
      "The directory where the output files are put.",
      &EventGenerator::thePath, ".", true, false,
       &EventGenerator::setPath, 0, &EventGenerator::defPath);
   interfacePath.directoryType();
 
   static Parameter<EventGenerator,string> interfaceRunName
     ("RunName",
      "The name of this run. This name will be used in the output filenames. "
      "The files wil be placed in the directory specified by the "
      "<interface>Path</interface> parameter"
      "If empty the name of the event generator will be used instead.",
      &EventGenerator::theRunName, "", true, false,
      0, 0, &EventGenerator::name);
 
   static Parameter<EventGenerator,long> interfaceNumberOfEvents
     ("NumberOfEvents",
      "The number of events to be generated in this run. If less than zero, "
      "the number of events is unlimited",
      &EventGenerator::theNumberOfEvents, 1000, -1, Constants::MaxInt,
      true, false, Interface::lowerlim);
 
   static Parameter<EventGenerator,int> interfaceDebugLevel
     ("DebugLevel",
      "The level of debug information sent out to the log file in the run. "
      "Level 0 only gives a limited ammount of warnings and error messages. "
      "Level 1 will print the first few events. "
      "Level 5 will print every event. "
      "Level 9 will print every step in every event.",
      &EventGenerator::theDebugLevel, 0, 0, 9, true, false, true);
 
   static Parameter<EventGenerator,int> interfacePrintEvent
     ("PrintEvent",
      "If the debug level is above zero, print the first 'PrintEvent' events.",
      &EventGenerator::printEvent, 0, 0, 1000, true, false, Interface::lowerlim);
 
   static Parameter<EventGenerator,long> interfaceDumpPeriod
     ("DumpPeriod",
      "If the debug level is above zero, dump the full state of the run every "
      "'DumpPeriod' events. Set it to -1 to disable dumping even in the case of errors.",
      &EventGenerator::dumpPeriod, 0, -1, Constants::MaxInt,
      true, false, Interface::lowerlim);
 
   static Switch<EventGenerator,bool> interfaceKeepAllDumps
     ("KeepAllDumps",
      "Whether all dump files should be kept, labelled by event number.",
      &EventGenerator::keepAllDumps, false, true, false);
   static SwitchOption interfaceKeepAllDumpsYes
     (interfaceKeepAllDumps,
      "Yes",
      "Keep all dump files, labelled by event number.",
      true);
   static SwitchOption interfaceKeepAllDumpsNo
     (interfaceKeepAllDumps,
      "No",
      "Keep only the latest dump file.",
      false);
 
   static Parameter<EventGenerator,long> interfaceDebugEvent
     ("DebugEvent",
      "If the debug level is above zero, step up to the highest debug level "
      "befor event number 'DebugEvent'.",
      &EventGenerator::debugEvent, 0, 0, Constants::MaxInt,
      true, false, Interface::lowerlim);
 
   static Parameter<EventGenerator,int> interfaceMaxWarnings
     ("MaxWarnings",
      "The maximum number of warnings of each type which will be printed.",
      &EventGenerator::maxWarnings,
      10, 1, 100, true, false, Interface::lowerlim);
 
   static Parameter<EventGenerator,int> interfaceMaxErrors
     ("MaxErrors",
      "The maximum number of errors of each type which will be tolerated. "
      "If more errors are reported, the run will be aborted.",
      &EventGenerator::maxErrors,
      10, -1, 100000, true, false, Interface::lowerlim);
 
   static Parameter<EventGenerator,long> interfaceQuickSize
     ("QuickSize",
      "The max absolute id number of particle data objects which are accessed "
      "quickly through a vector indexed by the id number.",
      &EventGenerator::theQuickSize,
      7000, 0, 50000, true, false, Interface::lowerlim);
 
 
   static Command<EventGenerator> interfaceSaveRun
     ("SaveRun",
      "Isolate, initialize and save this event generator to a file, from which "
      "it can be read in and run in another program. If an agument is given "
      "this is used as the run name, otherwise the run name is taken from the "
      "<interface>RunName</interface> parameter.",
      &EventGenerator::doSaveRun, true);
 
 
   static Command<EventGenerator> interfaceMakeRun
     ("MakeRun",
      "Isolate and initialize this event generator and give it a run name. "
      "If no argument is given, the run name is taken from the "
      "<interface>RunName</interface> parameter.",
      &EventGenerator::doMakeRun, true);
 
   interfaceEventHandler.rank(11.0);
   interfaceSaveRun.rank(10.0);
   interfaceMakeRun.rank(9.0);
   interfaceRunName.rank(8.0);
   interfaceNumberOfEvents.rank(7.0);
   interfaceAnalysisHandlers.rank(6.0);
 
 
   static Switch<EventGenerator,bool> interfaceUseStdout
     ("UseStdout",
      "Redirect the logging and output to stdout instead of files.",
      &EventGenerator::useStdout, false, true, false);
   static SwitchOption interfaceUseStdoutYes
     (interfaceUseStdout,
      "Yes",
      "Use stdout instead of log files.",
      true);
   static SwitchOption interfaceUseStdoutNo
     (interfaceUseStdout,
      "No",
      "Use log files.",
      false);
   
 
   static Switch<EventGenerator,int> interfaceLogNonDefault
     ("LogNonDefault",
      "Controls the printout of important interfaces which has been changed from their default values.",
      &EventGenerator::logNonDefault, -1, true, false);
   static SwitchOption interfaceLogNonDefaultYes
     (interfaceLogNonDefault,
      "Yes",
      "Always print changed interfaces.",
      1);
   static SwitchOption interfaceLogNonDefaultOnDebug
     (interfaceLogNonDefault,
      "OnDebug",
      "Only print changed interfaces if debugging is turned on.",
      0);
   static SwitchOption interfaceLogNonDefaultNo
     (interfaceLogNonDefault,
      "No",
      "Don't print changed interfaces.",
      -1);
   interfaceLogNonDefault.setHasDefault(false);
 
 }
 
 EGNoPath::EGNoPath(string path) {
   theMessage << "Cannot set the directory path for output files to '" << path
 	     << "' because the directory did not exist and could not be "
 	     << "created.";
   severity(warning);
 }
 
diff --git a/Repository/EventGenerator.h b/Repository/EventGenerator.h
--- a/Repository/EventGenerator.h
+++ b/Repository/EventGenerator.h
@@ -1,1179 +1,1179 @@
 // -*- C++ -*-
 //
 // EventGenerator.h is a part of ThePEG - Toolkit for HEP Event Generation
 // Copyright (C) 1999-2011 Leif Lonnblad
 //
 // ThePEG is licenced under version 2 of the GPL, see COPYING for details.
 // Please respect the MCnet academic guidelines, see GUIDELINES for details.
 //
 #ifndef ThePEG_EventGenerator_H
 #define ThePEG_EventGenerator_H
 // This is the declaration of the EventGenerator class.
 
 #include "ThePEG/Config/ThePEG.h"
 #include "ThePEG/Utilities/Named.h"
 #include "EventGenerator.fh"
 #include "RandomGenerator.h"
 #include "ThePEG/Repository/UseRandom.h"
 #include "ThePEG/Repository/Strategy.h"
 #include "ThePEG/Repository/CurrentGenerator.fh"
 #include "ThePEG/Utilities/ClassDescription.h"
 #include "ThePEG/Handlers/EventHandler.fh"
 #include "ThePEG/Analysis/FactoryBase.fh"
 #include <fstream>
 #include "EventGenerator.xh"
 
 namespace ThePEG {
 
 /**
  * The EventGenerator class manages a whole event generator run. It
  * keeps a list of all Interfaced objects which are needed for a
  * particular run (these objects each have a pointer back to the
  * EventGenerator). Some objects are special, such as a default
  * RandomGenerator object, a StandardModelBase object and a Strategy
  * object and lists of ParticleData and MatcherBase objects used in
  * the run.
  *
  * The <code>EventGenerator</code> also manages information about the
  * run such as the exceptions being thrown, files to write output and
  * error messages to, etc.
  *
  * There are three main external member functions:<BR>
  * go() generates a specified number of events and exits.<BR>
  *
  * shoot() generates one Event and returns it.<BR>
  *
  * generateEvent() takes an initial Step or a partially generated
  * Event as argument and generates subsequent steps defined in the
  * generator.<BR>
  *
  * doShoot() is a virtual function called by shoot() and may be
  * overridden in sub-classes.<BR>
  *
  * doGenrateEvent() is a virtual function called by generateEvent() and
  * may to be overridden in sub-classes.
  *
  * @see \ref EventGeneratorInterfaces "The interfaces"
  * defined for EventGenerator.
  * @see Interfaced
  * @see RandomGenerator
  * @see StandardModelBase
  * @see Strategy
  * @see ParticleData
  * @see Event
  * @see Step
  * @see FullEventGenerator
  * 
  */
 class EventGenerator: public Interfaced {
 
   /** The Repository is a friend. */
   friend class Repository;
 
 public:
 
   /** A map of integers giving the number of times an exception of the
    *  key type has been thrown. */
   //typedef map<const type_info *, int> ExceptionMap;
   //typedef map<Exception, int, ExceptionComparison > ExceptionMap;
   typedef map<pair<string, Exception::Severity>, int> ExceptionMap;
 
 public:
 
   /** @name Standard constructors and destructors. */
   //@{
   /**
    * Default constructor.
    */
   EventGenerator();
 
   /**
    * Copy-constructor.
    */
   EventGenerator(const EventGenerator &);
 
   /**
    * Destructor.
    */
   virtual ~EventGenerator();
   //@}
 
 public:
 
   /** @name Access special objects in the run. */
   //@{
   /**
    * Return a pointer to the standard model parameters.
    */
   tSMPtr standardModel() const { return theStandardModel; }
 
   /**
    * Return a pointer to the strategy object containing a set of
    * non-default particles to use.
    */
   tStrategyPtr strategy() const { return theStrategy; }
 
   /**
    * Get the currently active EventHandler.
    */
   tEHPtr currentEventHandler() const { return theCurrentEventHandler; }
 
   /**
    * Set the currently active EventHandler.
    */
   void currentEventHandler(tEHPtr eh) { theCurrentEventHandler = eh; }
 
   /**
    * Get the currently active step handler.
    */
   tStepHdlPtr currentStepHandler() const { return theCurrentStepHandler; }
 
   /**
    * Set the currently active step handler.
    */
   void currentStepHandler(tStepHdlPtr sh) { theCurrentStepHandler = sh; }
 
   /**
    * Return a pointer to the EventHandler.
    */
   tEHPtr eventHandler() const { return theEventHandler; }
 
   /**
    * Return the vector of analysis objects to be used in the run.
    */
   AnalysisVector & analysisHandlers() { return theAnalysisHandlers; }
 
   /**
    * Return a pointer to an associated factory objects for handling
    * histograms to be used by <code>AnalysisHandler</code>s.
    */
   tHistFacPtr histogramFactory() const { return theHistogramFactory; }
 
   /**
    * Return the EventManipulator used in the run.
    */
   tEvtManipPtr manipulator() const { return theEventManipulator; }
   //@}
 
 public:
 
   /** @name Main functions to controll the run. */
   //@{
   /**
    * Initialize this generator. This is done automatically if 'go()'
    * is used. Calls the virtual method doInitialize().
    */
-  void initialize();
+  void initialize(bool initOnly = false);
 
   /**
    * Run this EventGenerator session. Calls the virtual method doGo().
    *
    * @param next the number of the firts event to be generated. If
    * negative it is assumed that this generator was previously
    * interrupted (or dumped to a file) and the execution will resume
    * from where it started. Default is 1.
    * @param maxevent the maximum number of events to be generated. If negative
    * the N() is used instead. Default is -1.
    * @param tics if true information the number of events generated
    * and elapsed time will be written to std::cerr after each event.
    */
   void go(long next = 1, long maxevent = -1, bool tics = false);
 
   /**
    * Generate one event. Calls the virtual method doShoot();
    */
   EventPtr shoot();
 
   /**
    * Finish generating an \a event which has already been partially
    * constructed from the outside.  Calls the virtual method do
    * doGenerateEvent().
    */
   EventPtr generateEvent(Event & event);
 
   /**
    * Finish generating an event starting from a \a step which has
    * already been partially constructed from the outside.  Calls the
    * virtual method do doGenerateEvent().
    */
   EventPtr generateEvent(Step & step);
 
   /**
    * Indicate that the run has ended and call finish() for all objects
    * including this one. Note that finish() should not be called
    * directly.
    */
   void finalize();
 
   /**
    * Dynamically load the Main class in the given \a file, making it
    * run its Init() method where it may use this EventGenerator. Also
    * call the initialize function before and the finish() function
    * afterwards.
    */
   bool loadMain(string file);
 
   /**
    * Return the maximum center of mass energy possible for an
    * event. Return zero if the assigned EventHander is not able to
    * generatr full events.
    */
   virtual Energy maximumCMEnergy() const;
 
   /**
    * The number of the event currently being generated.
    */
   long currentEventNumber() const { return ieve; }
 
   /**
    * Return the event being generated.
    */
   tcEventPtr currentEvent() const;
 
   /**
    * Dump the full state of the current run - including the number of
    * generated events, so that it can be fully continued from this point.
    */
   virtual void dump() const;
 
   /**
    * Register a given object as used. Only objects registered in this
    * way will be included in the file with model references.
    */
   void use(const Interfaced & i);
 
   /**
    * Set the random seed for the global random number generator. Also
    * set the interfaced member variable.
    */
   void setSeed(long seed);
 
   /**
    * Log a given exception.
    */
   void logWarning(const Exception &);
 
   /**
    * The number of events to be generated in this run.
    */
   long N() const { return theNumberOfEvents; }
 
   /**
    * Histogram scale. A histogram bin which has been filled with the
    * weights associated with the Event objects should be scaled by
    * this factor to give the correct cross section.
    */
   CrossSection histogramScale() const;
 
   /**
    * The total integrated cross section of the processes generated in
    * this run.
    */
   CrossSection integratedXSec() const;
 
   /**
    * The error estimate for the total integrated cross section of the
    * processes generated in this run.
    */
   CrossSection integratedXSecErr() const;
 
   /**
    * The sum of all weight of the events generated so far.
    */
   double sumWeights() const { return weightSum; }
   //@}
 
   /** @name Functions for accessing output files. */
   //@{
   /**
    * The base filename used in this run. The actual files are called
    * <code>filename.run</code>, <code>filename.dump</code>,
    * <code>filename.out</code>, <code>filename.log</code> and
    * <code>filename.tex</code> for the input configuration file,
    * output dump file, output file, log file, and reference
    * file respectively. The filename is constructed from the path()
    * and runName().
    */
   string filename() const { return path() + "/" + runName(); }
 
   /**
    * Return the name assigned to this run. If no name is given, the
    * name of the EventGenerator object is returned.
    */
   string runName() const { return theRunName.size()? theRunName: name(); }
 
   /**
    * The directory in which the filename() is located
    */
   string path() const { return thePath; }
 
   /**
    * Has the generator been asked to redirect everything to standard
    * output?
    */
   bool useStdOut() const { return useStdout; }
 
   /**
    * Open all ouput files.
    */
   void openOutputFiles();
 
   /**
    * Flush the content of the internal output string stream to the .out file.
    */
   void flushOutputFile();
 
   /**
    * Close all ouput files.
    */
   void closeOutputFiles();
 
   /**
    * Return a reference to the output file stream.
    */
   ofstream & outfile() { return theOutfile; }
 
   /**
    * Return a reference to the log file stream.
    */
   ofstream & logfile() { return theLogfile; }
 
   /**
    * Return a reference to the reference file stream. This file is
    * used to output LaTeX text with information about the models used
    * in the run.
    */
   ofstream & reffile() { return theReffile; }
 
   /**
    * This stream should be used for output of information and
    * statistics of an EventGenerator run in the finish() phase, after
    * the actual generation has finished. When used at other times, the
    * output will be cashed internally before written out in the
    * finish() phase. This is then written to the .out file, or if
    * useStdOut() is true, to BaseRepository::cout().
    */
   ostream & out();
 
   /**
    * Return a reference to the stream connected to the file for logging
    * information. If no file is connected, BaseRepository::cout() will
    * be used instead.
    */
   ostream & log();
 
   /**
    * Return a reference to a stream to be used to redirect cout for
    * external modules which prints out messages there. The output will
    * instead be appended to the log() stream at the end of the run.
    */
   ostream & misc() {
     return theMiscStream;
   }
 
   /**
    * Return a reference to the stream connected to the filea for
    * references from used objects. If no file is connected,
    * BaseRepository::cout() will be used instead.
    */
   ostream & ref();
   //@}
 
   /** @name Access objects included in this run. */
   //@{
   /**
    * Return the set of objects used in this run.
    */
   const ObjectSet & objects() const { return theObjects; }
 
 
   /**
    * Return the map of objects used in this run indexed by their name.
    */
   const ObjectMap & objectMap() const { return theObjectMap; }
 
   /**
    * Return a garbage collected pointer to a given object. If the
    * object is not included in the run, a null pointer will be
    * returned.
    */
   template <typename T>
   typename Ptr<T>::pointer getPtr(const T &) const;
 
   /**
    * Return a pointer to an object present in this run given its full
    * name. Return the null pointer if non-existent.
    */
   IBPtr getPointer(string name) const;
 
   /**
    * Return a pointer to an object of type T present in this run given
    * its full name. Return the null pointer if non-existent. Calls
    * getPointer(string) and dynamically casts the result to the
    * requested pointer type.
    */
   template <typename T>
   typename Ptr<T>::pointer getObject(string name) const {
     return dynamic_ptr_cast<typename Ptr<T>::pointer>(getPointer(name));
   }
 
   /**
    * Return the default object for class T. Returns the null pointer
    * if non-existent.
    */
   template <typename T>
   typename Ptr<T>::pointer getDefault() const;
 
   /**
    * Create a particle instance corresponding to the given \a id
    * number.
    */
   PPtr getParticle(PID id) const;
 
   /**
    * Return a pointer to the ParticleData object corresponding to the
    * given \a id number.
    */
   PDPtr getParticleData(PID id) const;
 
   /**
    * Return a reference to the complete list of matchers in this
    * generator.
    */
   const MatcherSet & matchers() const { return theMatchers; }
 
   /**
    * Return a reference to the complete map of particle data objects
    * in this generator, indexed by their id numbers.
    */
   const ParticleMap & particles() const { return theParticles; }
 
   /**
    * Return a reference to the set of objects which have been
    * registered as used during the current run.
    */
   const ObjectSet & used() const { return usedObjects; }
   //@}
 
 protected:
 
   /**
    * Check if there has been an interrupt signal from the OS.
    * If that's the case, finalize() is called
    */
   void checkSignalState();
 
   /**
    * Return a reference to the default RandomGenerator object in this
    * run.
    */
   RandomGenerator & random() const { return *theRandom; }
 
   /**
    * Finish the setup of an event generator run. Set run name, all
    * particles, matchers and other objects to be used. Is used by the
    * Repository when isolating an EventGenerator.
    */
   void setup(string newRunName, ObjectSet & newObjects,
 	     ParticleMap & newParticles, MatcherSet & newMatchers);
 
   /** @name Main virtual functions to be overridden by sub-classes. */
   //@{
   /**
    * Run this EventGenerator session. Is called from go(long,long,bool).
    */
   virtual void doGo(long next, long maxevent, bool tics);
 
   /**
    * Initialize this generator. Is called from initialize().
    */
-  virtual void doInitialize();
+  virtual void doInitialize(bool initOnly = false);
 
   /**
    * Generate one event. Is called from shoot().
    */
   virtual EventPtr doShoot();
 
   /**
    * Write out the number of events generated and the elapsed time in
    * suitable periods.
    */
   void tic(long currev = 0, long totev = 0) const;
 
   /**
    * Finish generating an event constructed from the outside. Is
    * called by generateEvent(tEventPtr).
    */
   virtual EventPtr doGenerateEvent(tEventPtr);
 
   /**
    * Finish generating an event starting from a Step constructed from
    * the outside. Is called by generateEvent(tStepPtr).
    */
   virtual EventPtr doGenerateEvent(tStepPtr);
   //@}
 
   /**
    * Print the message of an exception to the log file.
    */
   void printException(const Exception &);
 
   /**
    * Log a given exception.
    */
   bool logException(const Exception &, tcEventPtr);
 
   /**
    * Set number of events to be generated.
    */
   void N(long n) { theNumberOfEvents = n; }
 
   /**
    * Set the name of this run
    */
   void runName(string f) { theRunName = f; }
 
 public:
 
   /**
    * Append a tag to the run name. Derived classes may put special
    * meaning to the tags. 
    */
   virtual void addTag(string tag) {
     runName(runName() + tag);
   }
 
 private:
 
   /**
    * Return the vector of default objects.
    */
   const vector<IPtr> & defaultObjects() const { return theDefaultObjects; }
 
   /**
    * Access the special particles used in this generator. Not relevant
    * in the run phase.
    */
   ParticleMap & localParticles() { return theLocalParticles; }
 
   /**
    * Access the special particles used in this generator. Not relevant
    * in the run phase.
    */
   const ParticleMap & localParticles() const { return theLocalParticles; }
 
   /**
    * Set the directory where the output files will be stored.
    */
   void path(string f) { thePath = f; }
 
   /**
    * Set a pointer to the strategy object containing a set of
    * non-default particles to use.
    */
   void strategy(StrategyPtr);
 
   /**
    * Isolate, initialize and save this generator to a file.
    */
   string doSaveRun(string);
 
   /**
    * Isolate and initialize this generator.
    */
   string doMakeRun(string);
 
 public:
 
   /** @name The following functions may be called by objects belonging
       to this event generator during the initialization phase (in the
       doinit() function). It is typically used by objects which need
       to introduce other Interfaced objects depending the parameters
       of the StandardModel object used. Note that objects which use
       these functions <b>MUST</b> override the preInitialize()
       function to return true, otherwize the whole initialization
       procedure may be corrupted. */
   //@{
   /**
    * Register a new object to be included in the run currently being
    * initialized.
    *
    * @param obj (pointer to) the object being registered.
    *
    * @param fullname the full name including the directory path. Note
    * that although the full path is given the object will not be
    * inserted in the Repository, but only in this current
    * EventGenerator.
    *
    * @return false if another object of that name already exists.
    */
   bool preinitRegister(IPtr obj, string fullname);
 
   /**
    * Create a new Interfaced object to be used in the run being
    * initialized.
    *
    * @param classname the class name of the object being created.
    *
    * @param fullname the full name including the directory path. Note
    * that although the full path is given the object will not be
    * inserted in the Repository, but only in this current
    * EventGenerator.
    *
    * @param libraries an optional list of shared libraries to be
    * loaded to be able to create an object of the specified class.
    *
    * @return the created object if the it was successfully
    * created. Return null if the object could not be created or if
    * another object of that name already exists.
    */
   IPtr preinitCreate(string classname, string fullname,	string libraries = "");
 
 
   /**
    * Manipulate an interface of an Interfaced object.
    *
    * @param fullname the name including the full path of an object to
    * be manipulated.
    *
    * @param ifcname the name of the interface to be used.
    *
    * @param cmd the operation to be performed on the interface (set or
    * get).
    *
    * @param value Optional value to be passed to the interface.
    *
    * @return a string containing the result of the operation. If this
    * string starts with "Error: " then something went wrong.
    */
   string preinitInterface(string fullname, string ifcname, string cmd,
 			  string value);
 
   /**
    * Manipulate an interface of vector type (RefVector or ParVector)
    * of an Interfaced object.
    *
    * @param fullname the name including the full path of an object to
    * be manipulated.
    *
    * @param ifcname the name of the interface to be used.
    *
    * @param index the vector index corresponding to the element to be
    * manipulated.
    *
    * @param cmd the operation to be performed on the interface (set,
    * get, insert or erase).
    *
    * @param value Optional value to be passed to the interface.
    *
    * @return a string containing the result of the operation. If this
    * string starts with "Error: " then something went wrong.
    */
   string preinitInterface(string fullname, string ifcname, int index,
 			  string cmd, string value);
 
   /**
    * Manipulate an interface of an Interfaced object.
    *
    * @param obj the object to be manipulated.
    *
    * @param ifcname the name of the interface to be used.
    *
    * @param cmd the operation to be performed on the interface (set or
    * get).
    *
    * @param value Optional value to be passed to the interface.
    *
    * @return a string containing the result of the operation. If this
    * string starts with "Error: " then something went wrong.
    */
   string preinitInterface(IPtr obj, string ifcname, string cmd, string value);
 
   /**
    * Manipulate an interface of vector type (RefVector or ParVector)
    * of an Interfaced object.
    *
    * @param obj the object to be manipulated.
    *
    * @param ifcname the name of the interface to be used.
    *
    * @param index the vector index corresponding to the element to be
    * manipulated.
    *
    * @param cmd the operation to be performed on the interface (set,
    * get, insert or erase).
    *
    * @param value Optional value to be passed to the interface.
    *
    * @return a string containing the result of the operation. If this
    * string starts with "Error: " then something went wrong.
    */
   string preinitInterface(IPtr obj, string ifcname, int index,
 			  string cmd, string value);
 
   /**
    * Find a decaymode given a decay \a tag.
    * @return null if no decay mode was found.
    */
   tDMPtr findDecayMode(string tag) const;
 
   /**
    * Create a decay mode according to the given tag.
    * @return null if no decay mode could be created.
    */
   tDMPtr preinitCreateDecayMode(string tag);
 
   /**
    * Find a particle in this run, using its PDG name.
    * @return null if no particle is found.
    */
   tPDPtr findParticle(string pdgname) const;
 
   /**
    * Find a matcher in this run given its \a name.
    * @return null if no mather is found.
    */
   tPMPtr findMatcher(string name) const;
 
 private:
 
   /**
    * Used internally by preinitCreateDecayMode();
    */
   DMPtr constructDecayMode(string & tag);
 
   //@}
 
 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 global libraries needed for objects used in this EventGenerator.
    */
   const vector<string> & globalLibraries() const {
     return theGlobalLibraries;
   }
 
   //@}
 
   /**
    * Standard Init function used to initialize the interface.
    */
   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;
   //@}
 
 protected:
 
   /** @name Standard Interfaced functions. */
   //@{
   /**
    * Initialize this object after the setup phase before saving an
    * EventGenerator to disk.
    * @throws InitException if object could not be initialized properly.
    */
   virtual void doinit();
 
   /**
    * 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();
 
   /**
    * Additional things to do at the very end after the (do)finish(),
    * such as closing output files etc.
    */
   void finally();
 
   //@}
 
   /**
    * Return the set of all objects to be used in this run.
    */
   ObjectSet & objects() { return theObjects; }
 
   /**
    * Return the map of all objects to be used in this run indexed by
    * their name.
    */
   ObjectMap & objectMap() { return theObjectMap; }
 
   /**
    * Print out the .tex file with descriptions of and references to
    * all models used in the run.
    */
   void generateReferences();
 
   /**
    * Increase and return the count for the given exception.
    */
   int count(const Exception &);
 
 private:
 
 
   /**
    * A vector of default objects.
    */
   vector<IPtr> theDefaultObjects;
 
   /**
    * Map of non-default particles used in this EventGenerator.
    */
   ParticleMap theLocalParticles;
 
   /**
    * Pointer to an object containing standard model parameters.
    */
   SMPtr theStandardModel;
 
   /**
    * Pointer to a strategy object with other non-default particles to
    * be used in this EventGenerator.
    */
   StrategyPtr theStrategy;
 
   /**
    * Pointer to the default RandomGenerator to be used in this run.
    */
   RanGenPtr theRandom;
 
   /**
    * Pointer to the event handler used to generate the indivudual
    * events.
    */
   EHPtr theEventHandler;
 
   /**
    * A vector of all analysis handlers to be called after each event.
    */
   AnalysisVector theAnalysisHandlers;
 
   /**
    * A pointer to an associated factory objects for handling
    * histograms to be used by <code>AnalysisHandler</code>s.
    */
   HistFacPtr theHistogramFactory;
 
   /**
    * A pointer to an optional event manipulator object.
    */
   EvtManipPtr theEventManipulator;
 
   /**
    * The directory where the input and output files resides.
    */
   string thePath;
 
   /**
    * The name of this run.
    */
   string theRunName;
 
   /**
    * A reference to the output file stream.
    */
   ofstream theOutfile;
 
   /**
    * A reference to the log file stream.
    */
   ofstream theLogfile;
 
   /**
    * A reference to the reference file stream.
    */
   ofstream theReffile;
 
   /**
    * A stream to be used to redirect cout for external modules which
    * prints out messages there. The output will instead be appended to
    * the log() stream at the end of the run.
    */
   ostringstream theMiscStream;
 
   /**
    * A string stream used as a buffer for messages written to the .out
    * file. The .out file should in rinciple only be written to in the
    * end of a run, during the finish() phase, but if anything is
    * written before that, it will be cashed in this string stream
    * before written out properly in the end of the run.
    */
   ostringstream theOutStream;
 
   /**
    * Remember the name of the file where the output should be
    * sent. This is set int openOutputFiles().
    */
   string theOutFileName;
 
   /**
    * Number of events to be generated in this run.
    */
   long theNumberOfEvents;
 
   /**
    * The set of all objects to be used in this run.
    */
   ObjectSet theObjects;
 
   /**
    * All objects to be used in this run mapped to their name.
    */
   ObjectMap theObjectMap;
 
   /**
    * The map of all particles to be used in this run, indexed by the
    * id number.
    */
   ParticleMap theParticles;
   /**
    * A vector of particles indexed by the id number for quick access.
    * Only particles with id number less than theQuickSize are
    * available.
    */
   PDVector theQuickParticles;
 
   /**
    * Only particles with id number less than theQuickSize are
    * available in theQuickParticles.
    */
   long theQuickSize;
 
   /**
    * A flag to tell if we are in the pre-initialization phase where
    * objects with preInitialize() functions returning true are
    * initialized before others.
    */
   bool preinitializing;
 
   /**
    * The set of all matchers to be used in this run.
    */
   MatcherSet theMatchers;
 
   /**
    * The set of objects which have actually been used in this run.
    */
   ObjectSet usedObjects;
 
 protected:
 
   /**
    * The current event number;
    */
   long ieve;
 
   /**
    * The sum of the weights of the events produced so far.
    */
   double weightSum;
 
   /**
    * The debug level.
    */
   int theDebugLevel;
 
 private:
 
   /**
    * List all modified interfaces in the log file. If positive always
    * do this, if negative never do it. If zero, only do it if
    * debugging is turned on.
    */
   int logNonDefault;
 
   /**
    * If the debug level is higher than 0, print the first 'printEvent'
    * events to the logfile.
    */
   int printEvent;
 
   /**
    * If the debug level is higher than 0, dump the complete state of
    * this run to the default dump file every 'dumpPeriod' events.
    * If 'dumpPeriod' is -1, dumping is disabled completely,
    * even when runs are aborted.
    */
   long dumpPeriod;
 
   /**
    * If this flag is true, keep all dump files of the run, 
    * labelled by event number.
    */
   bool keepAllDumps;
 
   /**
    * If the debug level is higher than 0, step up to the highest debug
    * level just before the event with number debugEvent is performed.
    */
   long debugEvent;
 
   /**
    * The maximum number of warnings reported of each type. If more
    * than maxWarnings warnings of one type is issued, the generation
    * will continue without reporting this warning.
    */
   int maxWarnings;
 
   /**
    * The maximum number of warnings and errors reported of each
    * type. If more than maxErrors errors is reported for one type the
    * run will be aborted. Disable the check by setting to -1.
    */
   int maxErrors;
 
   /**
    * A map of all Exceptions which have been caught by the event
    * generator and the number of time each exception type has been
    * caught.
    */
   ExceptionMap theExceptions;
 
 private:
 
   /**
    * Utility function for the interface.
    */
   void setLocalParticles(PDPtr pd, int);
 
   /**
    * Utility function for the interface.
    */
   void insLocalParticles(PDPtr pd, int);
 
   /**
    * Utility function for the interface.
    */
   void delLocalParticles(int place);
 
   /**
    * Utility function for the interface.
    */
   vector<PDPtr> getLocalParticles() const;
 
   /**
    * Utility function for the interface.
    */
   void setPath(string newPath);
 
   /**
    * Utility function for the interface.
    */
   string defPath() const;
 
   /**
    * The UseRandom object constructed for the duration of an
    * EventGenerator run so that the default random number generator
    * always can be accessed through the static methods of the
    * UseRandom class.
    */
   UseRandom * theCurrentRandom;
 
   /**
    * The CurrentGenerator object constructed for the duration of an
    * EventGenerator run so that the default event generator always can
    * be accessed through the static methods of the CurrentGenerator
    * class.
    */
   CurrentGenerator * theCurrentGenerator;
 
   /**
    * The currently active EventHandler.
    */
   tEHPtr theCurrentEventHandler;
 
   /**
    * The currently active step handler.
    */
   tStepHdlPtr theCurrentStepHandler;
 
 
   /**
    * Whether to use files or stdout for logging and output.
    */
   bool useStdout;
 
   /**
    * The global libraries needed for objects used in this EventGenerator.
    */
   vector<string> theGlobalLibraries;
 
 private:
 
   /**
    * Describe an abstract class with persistent data.
    */
   static ClassDescription<EventGenerator> initEventGenerator;
 
   /**
    *  Private and non-existent assignment operator.
    */
   EventGenerator & operator=(const EventGenerator &);
 
 };
 
 /** @cond TRAITSPECIALIZATIONS */
 
 /** This template specialization informs ThePEG about the base classes
  *  of EventGenerator. */
 template <>
 struct BaseClassTrait<EventGenerator,1>: public ClassTraitsType {
   /** Typedef of the first base class of EventGenerator. */
   typedef Interfaced NthBase;
 };
 
 /** This template specialization informs ThePEG about the name of the
  *  EventGenerator class. */
 template <>
 struct ClassTraits<EventGenerator>: public ClassTraitsBase<EventGenerator> {
   /** Return a platform-independent class name */
   static string className() { return "ThePEG::EventGenerator"; }
 };
 
 /** @endcond */
 
 }
 
 #ifndef ThePEG_TEMPLATES_IN_CC_FILE
 #include "EventGenerator.tcc"
 #endif
 
 #endif /* ThePEG_EventGenerator_H */
diff --git a/Repository/Repository.cc b/Repository/Repository.cc
--- a/Repository/Repository.cc
+++ b/Repository/Repository.cc
@@ -1,1079 +1,1079 @@
 // -*- C++ -*-
 //
 // Repository.cc is a part of ThePEG - Toolkit for HEP Event Generation
 // Copyright (C) 1999-2011 Leif Lonnblad
 //
 // ThePEG is licenced under version 2 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 Repository class.
 //
 
 // macro is passed in from -D compile flag
 #ifndef THEPEG_PKGLIBDIR
 #error Makefile.am needs to define THEPEG_PKGLIBDIR
 #endif
 
 #include "Repository.h"
 #include "ThePEG/Utilities/Rebinder.h"
 #include "ThePEG/Handlers/EventHandler.h"
 #include "ThePEG/PDT/DecayMode.h"
 #include "ThePEG/Repository/Strategy.h"
 #include "ThePEG/Persistency/PersistentOStream.h"
 #include "ThePEG/Persistency/PersistentIStream.h"
 #include "ThePEG/Utilities/Debug.h"
 #include "ThePEG/Config/algorithm.h"
 #include "ThePEG/Utilities/DynamicLoader.h"
 #include "ThePEG/Utilities/StringUtils.h"
 
 #include <config.h>
 
 // readline options taken from
 // http://autoconf-archive.cryp.to/vl_lib_readline.html 
 // Copyright © 2008 Ville Laurikari <vl@iki.fi> 
 // 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.
 
 #ifdef HAVE_LIBREADLINE
 #  if defined(HAVE_READLINE_READLINE_H)
 #    include <readline/readline.h>
 #  elif defined(HAVE_READLINE_H)
 #    include <readline.h>
 #  else
      extern "C" char *readline (const char *);
 #  endif
 #endif
 
 #ifdef HAVE_READLINE_HISTORY
 #  if defined(HAVE_READLINE_HISTORY_H)
 #    include <readline/history.h>
 #  elif defined(HAVE_HISTORY_H)
 #    include <history.h>
 #  else
      extern "C" void add_history (const char *);
 #  endif
 #endif
 
 using namespace ThePEG;
 
 ParticleMap & Repository::defaultParticles() {
   static ParticleMap theMap;
   return theMap;
 }
 
 
 ParticleDataSet & Repository::particles() {
   static ParticleDataSet theSet;
   return theSet;
 }
 
 MatcherSet & Repository::matchers() {
   static MatcherSet theSet;
   return theSet;
 }
 
 Repository::GeneratorMap & Repository::generators() {
   static GeneratorMap theMap;;
   return theMap;
 }
 
 string & Repository::currentFileName() {
   static string theCurrentFileName;
   return theCurrentFileName;
 }
 
 int & Repository::exitOnError() {
   static int exitonerror = 0;
   return exitonerror;
 }
 
 void Repository::cleanup() {
   generators().clear();
 }
 
 void Repository::Register(IBPtr ip) {
   BaseRepository::Register(ip);
   registerParticle(dynamic_ptr_cast<PDPtr>(ip));
   registerMatcher(dynamic_ptr_cast<PMPtr>(ip));
 }
 
 void Repository::Register(IBPtr ip, string newName) {
   DirectoryAppend(newName);
   BaseRepository::Register(ip, newName);
   registerParticle(dynamic_ptr_cast<PDPtr>(ip));
   registerMatcher(dynamic_ptr_cast<PMPtr>(ip));
 }
 
 void Repository::registerParticle(tPDPtr pd) {
   if ( !pd ) return;
   if ( !member(particles(), pd) ) {
     particles().insert(pd);
     CreateDirectory(pd->fullName());
   }
   if ( pd->id() == 0 ) return;
   if ( !member(defaultParticles(), pd->id()) )
     defaultParticles()[pd->id()] = pd;
   for ( MatcherSet::iterator it = matchers().begin();
 	it != matchers().end(); ++it) (*it)->addPIfMatch(pd);
 }
 
 void Repository::registerMatcher(tPMPtr pm) {
   if ( !pm || member(matchers(), pm) ) return;
   pm->addPIfMatchFrom(particles());
   for ( MatcherSet::iterator it = matchers().begin();
 	it != matchers().end(); ++it) {
     (*it)->addMIfMatch(pm);
     pm->addMIfMatch(*it);
   }
   matchers().insert(pm);
 }
 
 tPDPtr Repository::findParticle(string name) {
   tPDPtr pd;
   string path = name;
   DirectoryAppend(path);
   pd = dynamic_ptr_cast<tPDPtr>(GetPointer(path));
   if ( pd ) return pd;
   for ( ParticleMap::iterator pit = defaultParticles().begin();
 	pit != defaultParticles().end(); ++pit )
     if ( pit->second->PDGName() == name ) return pit->second;
   for ( ParticleDataSet::iterator pit = particles().begin();
 	pit != particles().end(); ++pit )
     if ( (**pit).PDGName() == name ) return *pit;
   return pd;
 }
 
 tPMPtr Repository::findMatcher(string name) {
   for ( MatcherSet::iterator mit = matchers().begin();
 	mit != matchers().end(); ++mit )
     if ( name == (**mit).name() ) return *mit;
   return tPMPtr();
 }
 
 void Repository::saveRun(string EGname, string name, string filename) {
   EGPtr eg = BaseRepository::GetObject<EGPtr>(EGname);
   EGPtr run = makeRun(eg, name);
   PersistentOStream os(filename, globalLibraries());
   if ( ThePEG_DEBUG_ITEM(3) )
     clog() << "Saving event generator '" << name << "'... " << flush;
   os << run;
   if ( ThePEG_DEBUG_ITEM(3) )
     clog() << "done" << endl;
 }
 
 EGPtr Repository::makeRun(tEGPtr eg, string name) {
 
   // Clone all objects relevant for the EventGenerator. This is
   // the EventGenerator itself, all particles and all particle
   // matchers. 'localObject' is the set of all object refered to by
   // the generator particles and matcher and in the end these are
   // cloned as well.
 
   // Clone all Particle matchers
 
   if ( ThePEG_DEBUG_ITEM(3) )
     clog() << "Making event generator '" << name << "':" << endl
 	   << "Updating all objects... " << flush;
 
   if ( ThePEG_DEBUG_ITEM(3) )
     clog() << "done\nCloning matchers and particles... " << flush;
 
   MatcherSet localMatchers;
   ObjectSet localObjects;
   ObjectSet clonedObjects;
   TranslationMap trans;
 
   for ( MatcherSet::iterator mit = matchers().begin();
 	mit != matchers().end(); ++mit ) {
     PMPtr pm = clone(**mit);
     pm->clear();
     trans[*mit] = pm;
     localMatchers.insert(pm);
     clonedObjects.insert(pm);
     localObjects.insert(*mit);
     addReferences(*mit, localObjects);
   }
 
 
   // Clone the particles. But only the ones which should be
   // used. First select the localParticles of the EventGenerator, then
   // add particles from the strategy of the EventGenerator which have
   // not already been selected. Finally add particles from the global
   // default if no default directories has been specified in the
   // strategy which have not already been selected.
   PDVector allParticles;
 
   for ( ParticleMap::const_iterator pit = eg->localParticles().begin();
  	pit != eg->localParticles().end(); ++pit )
     allParticles.push_back(pit->second);
   if ( eg->strategy() ) {
     tcStrategyPtr strat = eg->strategy();
     for ( ParticleMap::const_iterator pit = strat->particles().begin();
  	  pit != strat->particles().end(); ++pit )
       allParticles.push_back(pit->second);
 
     vector<string> pdirs;
     if ( eg->strategy()->localParticlesDir().length() )
       pdirs.push_back(eg->strategy()->localParticlesDir());
     pdirs.insert(pdirs.end(), eg->strategy()->defaultParticlesDirs().begin(),
 		 eg->strategy()->defaultParticlesDirs().end());
 
     for ( int i = 0, N = pdirs.size(); i < N; ++i ) {
       string dir = pdirs[i];
       for ( ParticleDataSet::iterator pit = particles().begin();
 	    pit != particles().end(); ++pit )
 	if ( (**pit).fullName().substr(0, dir.length()) == dir )
 	  allParticles.push_back(*pit);
     }
   }
 
   if ( !eg->strategy() || eg->strategy()->defaultParticlesDirs().empty() )
     for ( ParticleMap::iterator pit = defaultParticles().begin();
 	  pit != defaultParticles().end(); ++pit )
       allParticles.push_back(pit->second);
 
   for ( ParticleDataSet::iterator pit = particles().begin();
 	  pit != particles().end(); ++pit )
       allParticles.push_back(*pit);
 
   ParticleMap localParticles;
 
   for ( PDVector::iterator pit = allParticles.begin();
 	pit != allParticles.end(); ++pit ) {
     ParticleMap::iterator it = localParticles.find((**pit).id());
     if ( it == localParticles.end() ) {
       PDPtr pd = clone(**pit);
       trans[*pit] = pd;
       localParticles[pd->id()] = pd;
       clonedObjects.insert(pd);
       localObjects.insert(*pit);
       addReferences(*pit, localObjects);
     } else {
       trans[*pit] = it->second;
     }
   }
 
   if ( ThePEG_DEBUG_ITEM(3) )
     clog() << "done\nCloning other objects... " << flush;
 
   // Clone the OldEventGenerator object to be used:
   localObjects.insert(eg);
   addReferences(eg, localObjects);
   EGPtr egrun = clone(*eg);
   clonedObjects.insert(egrun);
   trans[eg] = egrun;
 
   for ( ObjectSet::iterator it = localObjects.begin();
 	it != localObjects.end(); ++it ) {
     if ( member(trans.map(), *it) ) continue;
     IBPtr ip = clone(**it);
     trans[*it] = ip;
     clonedObjects.insert(ip);
   }
 
   if ( ThePEG_DEBUG_ITEM(3) )
     clog() << "done\nRebind references... " << flush;
 
   IVector defaults;
 
   trans.translate(inserter(defaults), eg->defaultObjects().begin(),
 		  eg->defaultObjects().end());
   if ( eg->strategy() )
     trans.translate(inserter(defaults),
 		    eg->strategy()->defaultObjects().begin(),
 		    eg->strategy()->defaultObjects().end());
 
   for ( ObjectSet::iterator it = clonedObjects.begin();
 	it != clonedObjects.end(); ++it ) {
     dynamic_cast<Interfaced &>(**it).theGenerator = egrun;
     rebind(**it, trans, defaults);
   }
 
   // Now, dependencies may have changed, so we do a final round of
   // updates.
   if ( ThePEG_DEBUG_ITEM(3) )
     clog() << "done\nUpdating cloned objects... " << flush;
 
 
   if ( ThePEG_DEBUG_ITEM(3) )
     clog() << "done\nInitializing... " << flush;
 
   clonedObjects.erase(egrun);
   egrun->setup(name, clonedObjects, localParticles, localMatchers);
 
   if ( ThePEG_DEBUG_ITEM(3) )
     clog() << "done" << endl;
 
   generators()[name] = egrun;
 
   return egrun;
 
 }
 
 PDPtr Repository::defaultParticle(PID id) {
   ParticleMap::iterator pit = defaultParticles().find(id);
   return pit == defaultParticles().end()? PDPtr(): pit->second;
 }
 
 void Repository::defaultParticle(tPDPtr pdp) {
   if ( pdp ) defaultParticles()[pdp->id()] = pdp;
 }
 
 struct ParticleOrdering {
   bool 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() );
   }
 };
 
 struct MatcherOrdering {
   bool operator()(tcPMPtr m1, tcPMPtr m2) {
     return m1->name() < m2->name() ||
       ( m1->name() == m2->name() && m1->fullName() < m2->fullName() );
   }
 };
 
 struct InterfaceOrdering {
   bool operator()(tcIBPtr i1, tcIBPtr i2) {
     return i1->fullName() < i2->fullName();
   }
 };
 
 void Repository::save(string filename) {
   if ( ThePEG_DEBUG_ITEM(3) )
     clog() << "saving '" << filename << "'... " << flush;
   PersistentOStream os(filename, globalLibraries());
   set<tcPDPtr,ParticleOrdering>
     part(particles().begin(), particles().end());
   set<tcPMPtr,MatcherOrdering>  match(matchers().begin(), matchers().end());
 
   os << objects().size();
   for ( ObjectMap::iterator it = objects().begin();
 	it != objects().end(); ++it ) os << it->second;
   os << defaultParticles() << part << match << generators()
      << directories() << directoryStack() << globalLibraries() << readDirs();
   if ( ThePEG_DEBUG_ITEM(3) )
     clog() << "(" << objects().size() << " objects in " << directories().size()
 	   << " directories) done" << endl;
 }
 
 string Repository::load(string filename) {
   if ( ThePEG_DEBUG_ITEM(3) )
     clog() << "loading '" << filename << "'... " << flush;
   currentFileName() = filename;
   PersistentIStream * is = new PersistentIStream(filename);
   if ( !*is ) {
     delete is;
     // macro is passed in from -D compile flag
     string fullpath = string(THEPEG_PKGLIBDIR) + '/' + filename;
     is = new PersistentIStream(fullpath);
     if ( !*is ) {
       delete is;
       return "Error: Could not find repository '" + filename + "'.";
     }
   }
   *is >> allObjects() >> defaultParticles()
       >> particles() >> matchers() >> generators()
       >> directories() >> directoryStack() >> globalLibraries() >> readDirs();
   delete is;
   objects().clear();
   for ( ObjectSet::iterator it = allObjects().begin();
 	it != allObjects().end(); ++it )
     objects()[(**it).fullName()] = *it;
 
   if ( ThePEG_DEBUG_ITEM(3) )
     clog() << "(" << objects().size() << " objects in " << directories().size()
 	   << " directories) done\nUpdating... " << flush;
   BaseRepository::resetAll(allObjects());
   BaseRepository::update();
 
   if ( ThePEG_DEBUG_ITEM(3) )
     clog() << "done" << endl;
   return "";
 }
 
 void Repository::stats(ostream & os) {
   os << "number of objects:        " << setw(6) << objects().size() << endl;
   os << "number of objects (all):  " << setw(6) << allObjects().size() << endl;
   os << "number of particles:        " << setw(6) << particles().size() << endl;
   os << "number of matchers:         " << setw(6) << matchers().size() << endl;
 }
 
 string Repository::read(string filename, ostream & os) {
   ifstream is;
   string file = filename;
   if ( file[0] == '/' ) {
     if ( ThePEG_DEBUG_LEVEL > 1 ) os << "(= trying " << file << " =)" << endl;
     is.open(file.c_str());
   }
   else {
     vector<string> dirs(readDirs().rbegin(), readDirs().rend());
     dirs.push_back(currentReadDirStack().top());
     while ( dirs.size() ) {
       string dir = dirs.back();
       if ( dir != "" && dir[dir.length() -1] != '/' ) dir += '/';
       file = dir + filename;
       is.clear();
       if ( ThePEG_DEBUG_LEVEL > 1 ) os << "(= trying " << file << " =)" << endl;
       is.open(file.c_str());
       if ( is ) break;
       dirs.pop_back();
     }
   }
   if ( !is ) {
     return "Error: Could not find input file '" + filename + "'";
   }
   currentReadDirStack().push(StringUtils::dirname(file));
   try {
     Repository::read(is, os);
     currentReadDirStack().pop();
   }
   catch ( ... ) {
     currentReadDirStack().pop();
     throw;
   }
   return "";
 }
 
 string Repository::
 modifyEventGenerator(EventGenerator & eg, string filename, ostream & os) {
   ObjectSet objs = eg.objects();
   objs.insert(&eg);
   for ( ObjectSet::iterator it = objs.begin(); it != objs.end(); ++it ) {
     string name = (**it).fullName();
     if ( name.rfind('/') != string::npos )
       CreateDirectory(name.substr(0, name.rfind('/') + 1));
     objects()[name] = *it;
     allObjects().insert(*it);
   }
   
   string msg = read(filename, os);
  
   for_each(objs, mem_fun(&InterfacedBase::reset)); 
   eg.initialize();
 
   if ( !generators().empty() )
     msg += "Warning: new generators were initialized while modifying "
       + eg.fullName() + ".\n";
 
   return msg;
 }
 
 void Repository::resetEventGenerator(EventGenerator & eg) {
 
   ObjectSet objs = eg.objects();
   objs.insert(&eg);
   for ( ObjectSet::iterator it = objs.begin(); it != objs.end(); ++it ) {
     string name = (**it).fullName();
     if ( name.rfind('/') != string::npos )
       CreateDirectory(name.substr(0, name.rfind('/') + 1));
     objects()[name] = *it;
     allObjects().insert(*it);
   }
   
   for_each(objs, mem_fun(&InterfacedBase::reset)); 
-  eg.initialize();
+  eg.initialize(true);
 
 }
 
 void Repository::execAndCheckReply(string line, ostream & os) {
   string reply = exec(line, os);
   if ( reply.size() ) 
     os << reply;
   if ( reply.size() && reply[reply.size()-1] != '\n' ) 
     os << endl;
   if ( exitOnError() && reply.size() >= 7 
        && reply.substr(0, 7) == "Error: " )
     exit(exitOnError());
 }
 
 void Repository::read(istream & is, ostream & os, string prompt) {
 #ifdef HAVE_LIBREADLINE
   if ( &is == &std::cin ) {
     char * line_read = 0;
     do {
       if ( line_read ) {
 	free(line_read);
 	line_read = 0;
       }
       
       line_read = readline(prompt.c_str());
       
       if ( line_read && *line_read ) {
 	string line = line_read;
 	while ( !line.empty() && line[line.size() - 1] == '\\' ) {
 	  line[line.size() - 1] = ' ';
 	  char * cont_read = readline("... ");
 	  if ( cont_read ) {
 	    line += cont_read;
 	    free(cont_read);
 	  }
 	}
 	if ( prompt.empty() && ThePEG_DEBUG_LEVEL > 0 )
 	  os << "(" << line << ")" << endl;
 #ifdef HAVE_READLINE_HISTORY
 	add_history(line.c_str());
 #endif // HAVE_READLINE_HISTORY
 	execAndCheckReply(line, os);
       }
     }
     while ( line_read );
   }
   else {
 #endif // HAVE_LIBREADLINE
     string line;
     if ( prompt.size() ) os << prompt;
     while ( getline(is, line) ) {
       while ( !line.empty() && line[line.size() - 1] == '\\' ) {
 	line[line.size() - 1] = ' ';
 	string cont;
 	if ( prompt.size() ) os << "... ";
 	getline(is, cont);
 	line += cont;
       }
       if ( prompt.empty() && ThePEG_DEBUG_LEVEL > 0 )
 	os << "(" << line << ")" << endl;
       execAndCheckReply(line, os);
       if ( prompt.size() ) os << prompt;
     }
 #ifdef HAVE_LIBREADLINE
   }
 #endif
   if ( prompt.size() ) os << endl;
 }
 
 
 string Repository::copyParticle(tPDPtr p, string newname) {
   DirectoryAppend(newname);
   
   string newdir = newname.substr(0, newname.rfind('/')+1);
   newname =newname.substr(newname.rfind('/')+1);
   if ( newname.empty() ) newname = p->name();
   if ( GetPointer(newdir + newname) )
     return "Error: Cannot create particle " + newdir + newname +
       ". Object already exists.";
   if ( p->CC() && GetPointer(newdir + p->CC()->name()) )
     return "Error: Cannot create anti-particle " + newdir + newname +
       ". Object already exists.";
   PDPtr pd = p->pdclone();
   Register(pd, newdir + newname);
   pd->theDecaySelector.clear();
   pd->theDecayModes.clear();
   pd->isStable = true;
   if ( p->CC() ) {
     PDPtr apd = p->CC()->pdclone();
     Register(apd, newdir + apd->name());
     apd->theDecaySelector.clear();
     apd->theDecayModes.clear();
     apd->isStable = true;
     pd->theAntiPartner = apd;
     apd->theAntiPartner = pd;
     pd->syncAnti = p->syncAnti;
     apd->syncAnti = p->CC()->syncAnti;
   }
   HoldFlag<> dosync(pd->syncAnti, true);
   for ( DecaySet::const_iterator it = p->theDecayModes.begin();
 	it != p->theDecayModes.end(); ++it )
     pd->addDecayMode(*it);
   return "";
 }
 
 void Repository::remove(tIBPtr ip) {
   ObjectMap::iterator it = objects().find(ip->fullName());
   if ( it == objects().end() || ip != it->second ) return;
   objects().erase(it);
   allObjects().erase(ip);
   if ( dynamic_ptr_cast<tPDPtr>(ip) ) {
     particles().erase(dynamic_ptr_cast<tPDPtr>(ip));
     defaultParticles().erase(dynamic_ptr_cast<tPDPtr>(ip)->id());
   }
   if ( dynamic_ptr_cast<tPMPtr>(ip) )
     matchers().erase(dynamic_ptr_cast<tPMPtr>(ip));
 }
 
 string Repository::remove(const ObjectSet & rmset) {
   ObjectSet refset;
   for ( ObjectMap::const_iterator i = objects().begin();
 	i != objects().end(); ++i ) {
     if ( member(rmset, i->second) ) continue;
     IVector ov = DirectReferences(i->second);
     for ( int j = 0, M = ov.size(); j < M; ++j )
       if ( member(rmset, ov[j]) ) {
 	refset.insert(i->second);
 	break;
       }
   }
   if ( refset.empty() ) {
     for ( ObjectSet::iterator oi = rmset.begin(); oi != rmset.end(); ++oi )
       remove(*oi);
     return "";
   }
   string ret = "Error: cannot remove the objects because the following "
     "objects refers to some of them:\n";
   for ( ObjectSet::iterator oi = refset.begin(); oi != refset.end(); ++oi )
     ret += (**oi).fullName() + "\n";
   return ret;
 }
    
 string Repository::exec(string command, ostream & os) {
   string cpcmd = command;
   try {
     string verb = StringUtils::car(command);
     command = StringUtils::cdr(command);
     if ( verb == "help" ) {
       help(command, os);
       return "";
     }
     if ( verb == "rm" ) {
       ObjectSet rmset;
       while ( !command.empty() ) {
 	string name = StringUtils::car(command);
 	DirectoryAppend(name);
 	IBPtr obj = GetPointer(name);
 	if ( !obj ) return "Error: Could not find object named " + name;
 	rmset.insert(obj);
 	command = StringUtils::cdr(command);
       }
       return remove(rmset);
     }
     if ( verb == "rmdir" || verb == "rrmdir" ) {
       string dir = StringUtils::car(command);
       DirectoryAppend(dir);
       if ( dir[dir.size() - 1] != '/' ) dir += '/';
       if ( !member(directories(), dir) )
 	return verb == "rmdir"? "Error: No such directory.": "";
       IVector ov = SearchDirectory(dir);
       if ( ov.size() && verb == "rmdir" )
 	return "Error: Cannot remove a non-empty directory. "
 	  "(Use rrmdir do remove all object and subdirectories.)";
       ObjectSet rmset(ov.begin(), ov.end());
       string ret = remove(rmset);
       if ( !ret.empty() ) return ret;
       StringVector dirs(directories().begin(), directories().end());
       for ( int i = 0, N = dirs.size(); i < N; ++ i )
 	if ( dirs[i].substr(0, dir.size()) == dir )
 	  directories().erase(dirs[i]);
       for ( int i = 0, N = directoryStack().size(); i < N; ++i )
 	if ( directoryStack()[i].substr(0, dir.size()) == dir )
 	  directoryStack()[i] = '/';
       return "";
     }
     if ( verb == "cp" ) {
       string name = StringUtils::car(command);
       DirectoryAppend(name);
       tPDPtr p = dynamic_ptr_cast<tPDPtr>(GetPointer(name));
       if ( p ) return copyParticle(p, StringUtils::cdr(command));
       return BaseRepository::exec(cpcmd, os);
     }
     if ( verb == "setup" ) {
       string name = StringUtils::car(command);
       DirectoryAppend(name);
       IBPtr obj = GetPointer(name);
       if ( !obj ) return "Error: Could not find object named " + name;
       istringstream is(StringUtils::cdr(command));
       readSetup(obj, is);
       // A particle may have been registered before but under the wrong id().
       registerParticle(dynamic_ptr_cast<PDPtr>(obj));
       return "";
     }
     if ( verb == "decaymode" ) {
       string tag = StringUtils::car(command);
       DMPtr dm = DecayMode::constructDecayMode(tag);
       if ( !dm ) return "Error: Could not create decay mode from the tag " +
 		   StringUtils::car(command);
       istringstream is(StringUtils::cdr(command));
       readSetup(dm, is);
       if ( !dm->CC() ) return "";
 
       if ( dm->CC()->parent()->synchronized() ) {
 	dm->CC()->synchronize();
 	return "";
       }
 
       if ( !dm->CC()->decayer() )
 	return FindInterface(dm, "Decayer")->
 	  exec(*dm->CC(), "set", dm->decayer()->fullName());
       return "";
     }
     if ( verb == "makeanti" ) {
       string name = StringUtils::car(command);
       DirectoryAppend(name);
       tPDPtr p = dynamic_ptr_cast<tPDPtr>(GetPointer(name));
       if ( !p ) return "Error: No particle named " + name;
       name = StringUtils::car(StringUtils::cdr(command));
       DirectoryAppend(name);
       tPDPtr ap = dynamic_ptr_cast<tPDPtr>(GetPointer(name));
       if ( !ap ) return "Error: No particle named " + name;
       ParticleData::antiSetup(PDPair(p, ap));
       return "";
     }
     if ( verb == "read" ) {
       string filename = StringUtils::car(command);
       return read(filename, os);
     }
     if ( verb == "load" ) {
       return load(StringUtils::car(command));
     }      
     if ( verb == "save" ) {
       save(StringUtils::car(command));
       return "";
     }
     if ( verb == "lsruns" ) {
       string ret;
       for ( GeneratorMap::iterator ieg = generators().begin();
 	    ieg != generators().end(); ++ieg ) ret += ieg->first + "\n";
       return ret;
     }
     if ( verb == "makerun" ) {
       string runname = StringUtils::car(command);
       string generator = StringUtils::car(StringUtils::cdr(command));
       DirectoryAppend(generator);
       EGPtr eg = BaseRepository::GetObject<EGPtr>(generator);
       makeRun(eg, runname);
       return "";
     }
     if ( verb == "rmrun" ) {
       string runname = StringUtils::car(command);
       generators().erase(runname);
       return "";
     }
     if ( verb == "saverun" || verb == "saverunfile" || verb == "run" ) {
       string runname = StringUtils::car(command);
       string generator = StringUtils::car(StringUtils::cdr(command));
       DirectoryAppend(generator);
       GeneratorMap::iterator ieg = generators().find(runname);
       EGPtr eg;
       if ( ieg == generators().end() ) {
 	eg = BaseRepository::GetObject<EGPtr>(generator);
 	eg = makeRun(eg, runname);
       } else
 	eg = ieg->second;
       if ( !eg )
 	return "Error: Could not create/find run named'" + runname + "'.";
       if ( verb == "run" ) 
 	eg->go();
       else if ( verb == "saverunfile" ) {
 	string file = generator;
 	PersistentOStream os(file, globalLibraries());
 	os << eg;
 	if ( !os ) return "Save failed! (I/O error)";
       } else {
 	string file = eg->filename() + ".run";
 	PersistentOStream os(file, globalLibraries());
 	os << eg;
 	if ( !os ) return "Save failed! (I/O error)";
       }
       return "";
     }
     if ( verb == "removerun" ) {
       string runname = StringUtils::car(command);
       GeneratorMap::iterator ieg = generators().find(runname);
       if ( ieg != generators().end() ) {
 	generators().erase(ieg);
 	return "";
       } else
 	return "Error: No run named '" + runname + "' available.";
     }
     if ( verb == "create" ) {
       string className = StringUtils::car(command);
       command = StringUtils::cdr(command);
       string name = StringUtils::car(command);
       const ClassDescriptionBase * db = DescriptionList::find(className);
       command = StringUtils::cdr(command);
       while ( !db && command.length() ) {
 	string library = StringUtils::car(command);
 	command = StringUtils::cdr(command);
 	DynamicLoader::load(library);
 	db = DescriptionList::find(className);
       }
       if ( !db ) {
 	string msg = "Error: " + className + ": No such class found.";
 	if ( !DynamicLoader::lastErrorMessage.empty() )
 	  msg += "\nerror message from dynamic loader:\n" +
 	    DynamicLoader::lastErrorMessage;
 	return msg;
       }
       IBPtr obj = dynamic_ptr_cast<IBPtr>(db->create());
       if ( !obj ) return "Error: Could not create object of this class class.";
       if ( name.empty() ) return "Error: No name specified.";
       Register(obj, name);
       return "";
     }
     if ( verb == "defaultparticle" ) {
       while ( !command.empty() ) {
 	string name = StringUtils::car(command);
 	DirectoryAppend(name);
 	tPDPtr p = dynamic_ptr_cast<tPDPtr>(GetPointer(name));
 	if ( !p ) return "Error: No particle named " + name;
 	defaultParticle(p);
 	command = StringUtils::cdr(command);
       }
       return "";
     }
     if ( verb == "EXITONERROR" ) {
       exitOnError() = 1;
       return "";
     }
   }
   catch (const Exception & e) {
     e.handle();
     return "Error: " + e.message();
   }
 
   return BaseRepository::exec(cpcmd, os);
 }
 
 void Repository::help(string cmd, ostream & os) {
  
   cmd = StringUtils::car(cmd);
 
   if ( cmd == "cd" )
     os << "Usage: cd <directory>" << endl
        << "Set the current directory to <directory>." << endl;
   else if ( cmd == "mkdir" )
     os << "Usage: mkdir <path-name>" << endl
        << "Create a new directory called with the given path name." << endl;
   else if ( cmd == "rmdir" )
     os << "Usage: rmdir <directory>" << endl
        << "Remove an empty directory." << endl;
   else if ( cmd == "rrmdir" )
     os << "Usage: rrmdir <directory>" << endl
        << "Remove a directory and everything that is in it recursively." << endl
        << "Will only succeed if no other objects refers to the ones to "
        << "be deleted." << endl;
   else if ( cmd == "cp" )
     os << "Usage: cp <object> <path-name>" << endl
        << "Copy the given object to a new object with the given name." << endl;
   else if ( cmd == "setup" )
     os << "Usage: setup <object> <arguments> ..." << endl
        << "Tell a given object to read information given by the arguments."
        << endl;
   else if ( cmd == "decaymode" )
     os << "Usage: decaymode <tag> <branching fraction> <on|off> <decayer-object>"
        << endl
        << "Construct a decay mode from the given decay tag. The resulting "
        << "object will be inserted in the directory with the same path as "
        << "the decaying particle object. The given brancing fraction will "
        << "be set as well as the given decayer object. If the mode should "
        << "be switched on by default 1(on) should be specified (otherwise "
        << "0(off))." << endl;
   else if ( cmd == "makeanti" )
     os << "Usage: makeanti <particle-object> <particle-object>" << endl
        << "Indicate that the two given particle objects are eachothers "
        << "anti-partnets." << endl;
   else if ( cmd == "read" )
     os << "Usage: read <file-name>" << endl
        << "Read more commands from the given file. The file name can be "
        << "given relative to the current directory in the shell, or "
        << "relative to standard directories, or as an absolute path." << endl;
   else if ( cmd == "load" )
     os << "Usage: load <repository-file-name>" << endl
        << "Discard everything in the reopsitory and read in a completely "
        << "new repository from the given file." << endl;
   else if ( cmd == "save" )
     os << "Usage: save <file-name>" << endl
        << "Save the complete repository to the given file." << endl;
   else if ( cmd == "lsruns" )
     os << "Usage: lsruns" << endl
        << "List the run names of all initialized event generators." << endl;
   else if ( cmd == "makerun" )
     os << "Usage: makerun <run-name> <event-generator-object>" << endl
        << "Initialize the given event generator and assign a run name." << endl;
   else if ( cmd == "rmrun" )
     os << "Usage: rmrun <run-name>" << endl
        << "Remove the initialized event generator given by the run name."
        << endl;
   else if ( cmd == "saverun" )
     os << "Usage: saverun <run-name> <event-generator-object>" << endl
        << "Initialize the given event generator and assign a run name "
        << "and save it to a file named <run-name>.run" << endl;
   else if ( cmd == "run" )
     os << "Usage: run <run-name>" << endl
        << "Run the initialized event generator given b the run name." << endl;
   else if ( cmd == "create" )
     os << "Usage: create <class-name> <name> {<dynamic-library>}" << endl
        << "Create an object of the given class and assign the given name. "
        << "Optionally supply a dynamically loaded library where the class "
        << "is included." << endl;
   else if ( cmd == "pushd" )
     os << "Usage: pushd <directory>" << endl
        << "Set the current directory to <directory>, but keep the previous "
        << "working directory on the directory stack." << endl;
   else if ( cmd == "popd" )
     os << "Usage: popd" << endl
        << "Leave the current working directory and set the current "
        << "directory to the previous one on the directory stack." << endl;
   else if ( cmd == "pwd" )
     os << "Usage: pwd" << endl
        << "Print the current working directory." << endl;
   else if ( cmd == "dirs" )
     os << "Usage: dirs" << endl
        << " Print the contents of the directory stack." << endl;
   else if ( cmd == "mv" )
     os << "Usage: mv  <object> <path-name>" << endl
        << "Rename the given object to a new path name." << endl;
   else if ( cmd == "ls" )
     os << "Usage: ls {<directory>}" << endl
        << "List the objects and subdirectories in the current or given "
        << "directory." << endl;
   else if ( cmd == "library" )
     os << "Usage: library <dynamic-library>" << endl
        << "Make new classes available to the repository by dynamically "
        << "linking the given library." << endl;
   else if ( cmd == "globallibrary" )
     os << "Usage: globallibrary <dynamic-library>" << endl
        << "Make new classes available to the repository by dynamically "
        << "linking the given library. If this repository is saved and read "
        << "in again, this library will be linked in from the beginning." << endl;
   else if ( cmd == "rmgloballibrary" )
     os << "Usage: rmgloballibrary <dynamic-library>" << endl
        << "Remove a dynamic library previously added with globallibrary."
        << endl;
   else if ( cmd == "appendpath" )
     os << "Usage: appendpath <unix-directory>" << endl
        << "Add a search path for dynamic libraries to the end of the "
        << "search list." << endl;
   else if ( cmd == "lspaths" )
     os << "Usage: lspaths" << endl
        << "List search paths for dynamic libraries." << endl;
   else if ( cmd == "prependpath" )
     os << "Usage: prependpath <unix-directory>" << endl
        << "Add a search path for dynamic libraries to the beginning of the "
        << "search list." << endl;
   else if ( cmd == "doxygendump" )
     os << "Usage: doxygendump <namespace> <filename>" << endl
        << "Extract doxygen documentation of all loaded classes in the "
        << "given name space and weite it to a file.." << endl;
   else if ( cmd == "mset" || cmd == "minsert" || cmd == "mdo" )
     os << "Usage: " << cmd << " <directory> <class> <interface> <value>" << endl
        << "Recursively find in the given directory all objects of the "
        << "given class and call '" << cmd.substr(1)
        << "' with the given value for the given interface." << endl;
   else if ( cmd == "msetdef" || cmd == "mget" || cmd == "mdef" ||
 	    cmd == "mmin" || cmd == "mmax" || cmd == "merase" )
     os << "Usage: " << cmd << " <directory> <class> <interface>" << endl
        << "Recursively find in the given directory all objects of the given "
        << "class and call '" << cmd.substr(1)
        << "' for the given interface." << endl;
   else if ( cmd == "set" )
     os << "Usage: set <object>:<interface> <value>" << endl
        << "Set the interface for the given object to the given value." << endl;
   else if ( cmd == "setdef" )
     os << "Usage: setdef <object>:<interface>" << endl
        << "Set the interface for the given object to its default value." << endl;
   else if ( cmd == "insert" )
     os << "Usage: insert <object>:<interface> <value>" << endl
        << "Insert a value in the vector interface of the given object." << endl;
   else if ( cmd == "erase" )
     os << "Usage: erase <object>:<interface>" << endl
        << "Erase a value from the vector interface of the given object." << endl;
   else if ( cmd == "do" )
     os << "Usage: do <object>:<command-interface> <arguments>" << endl
        << "Call the command interface of the given object with the "
        << "given arguments." << endl;
   else if ( cmd == "get" )
     os << "Usage: get <object>:<interface>" << endl
        << "Print the value of the interface of the given object." << endl;
   else if ( cmd == "def" )
     os << "Usage: def <object>:<interface>" << endl
        << "Print the default value of the interface of the given object."
        << endl;
   else if ( cmd == "min" )
     os << "Usage: min <object>:<interface>" << endl
        << "Print the minimum value of the interface of the given object."
        << endl;
   else if ( cmd == "max" )
     os << "Usage: max <object>:<interface>" << endl
        << "Print the maximum value of the interface of the given object."
        << endl;
   else if ( cmd == "describe" )
     os << "Usage: describe <object>{:<interface>}" << endl
        << "Describe the given object or an interface of the object." << endl;
   else if ( cmd == "lsclass" )
     os << "Usage: lsclass" << endl
        << "List all classes available in the repository." << endl;
   else if ( cmd == "all" ) {
     os << "Available commands:"
        << endl
        << "* cd, mkdir, rmdir, rrmdir, pwd, cp, mv, rm, pushd, popd, dirs, ls:\n"
        << "  Manipulate the repository structure. Analogous to unix "
        << "shell commands."
        << endl
        << "* create, setup, decaymode makeanti:\n"
        << "  Create or setup an object."
        << endl
        << "* set, get, insert, erase, do, detdef, def, min, max, describe\n"
        << "  mset, minsert, mdo, msetdef, mdef, mmin, mmax, merase:\n"
        << "  Manipulate interfaces to objects."
        << endl
        << "* makerun, saverun, run, lsruns, rmrun:\n"
        << "  Create and handle initialized event genrators which can be run."
        << endl
        << "* read, load, library globallibrary, rmgloballibrary,\n"
        << "  appendpath, prependpath, lspaths, doxygendump:\n"
        << "  Handle files external files and libraries."
        << endl;
     os << "Do 'help syntax' for help on syntax." << endl
        << "Do 'help <command>' for help on a particular command." << endl;
   }
   else if ( cmd == "syntax" )
     os << "* <directory> = '/' | <name> | <directory>/<name>" << endl
        << "  <object> = <name> | <directory>/<name> | <object>:<ref-interface>\n"
        << "  Analogous to a unix file structure, an object can be "
        << "specified with an\n  absolute path or a path relative to "
        << "the current directory." << endl
        << "* <interface> = <interface-name>|<interface-name>[<index>]" << endl
        << "  An interface can be a parameter (floating point, integer or "
        << "string),\n  a switch (integer, possibly named), a reference to "
        << "another object in the\n  repository or a command which takes "
        << "an arbitrary string as argument.\n  There are also vector interfaces "
        << "of parameters and references for which\n  an index must be supplied."
        << endl;
   else {
     if ( !cmd.empty() ) os << "No command '" << cmd << "' found." << endl;
     os << "Common commands:" << endl
        << "* cd, mkdir, rmdir, pwd, cp, mv, rm:\n"
        << "  Manipulate the repository structure. Analogous to unix "
        << "shell commands." << endl
        << "* create, setup:\n"
        << " Create an object." << endl
        << "set, get, insert, erase, do:\n"
        << " Manipulate interfaces to objects." << endl
        << "* makerun, saverun, run, lsruns:\n"
        << " Create and handle initialized event genrators which can be run."
        << endl;
     os << "Do 'help all' for a complete list of commands." << endl
        << "Do 'help syntax' for help on syntax." << endl
        << "Do 'help <command>' for help on a particular command." << endl;
   }
 
 }
 
 Repository::Repository() {
   ++ninstances;
 }
 
 Repository::~Repository() {
   --ninstances;
   if ( ninstances <= 0 ) {
     generators().clear();
   }
 }
 
 int Repository::ninstances = 0;
 
 string Repository::version() {
   return PACKAGE_VERSION;
 }
 
 string Repository::banner() {
   string line = ">>>>>>>>> ThePEG - Toolkit for HEP Event Generation - version "
     + Repository::version() + " ";
   line += string(78 - line.size(), '<');
   return string(78, '>') + "\n" + line + "\n" + string(78, '<') + "\n";
 }