Print

Print


Commit in java/trunk on MAIN
analysis/src/main/java/org/hps/analysis/examples/DetailedAnalysisDriver.java+21-20372 -> 373
                                                /ECalScoringMatchDriver.java+3-2372 -> 373
                                                /FastTrackAnalysisDriver.java+7-7372 -> 373
                                                /JasAnalysisDriver.java+8-8372 -> 373
                                                /PrintGeometryDriver.java+77added 373
                                                /StarterAnalysisDriver.java+4-2372 -> 373
conditions/src/main/java/org/hps/conditions/deprecated/FieldMap.java+1-1372 -> 373
                                                      /HPSSVTCalibrationConstants.java+1-1372 -> 373
                                                      /SvtUtils.java+2-1372 -> 373
conditions/src/main/java/org/hps/conditions/svt/SvtChannel.java+1-1372 -> 373
                                               /SvtConditionsLoader.java+1-1372 -> 373
                                               /SvtDaqMapping.java+1-1372 -> 373
                                               /SvtTimeShift.java+1-1372 -> 373
distribution/pom.xml+1-1372 -> 373
ecal-readout-sim/src/main/java/org/hps/readout/ecal/FADCEcalReadoutDriver.java+1-1372 -> 373
ecal-recon/src/main/java/org/hps/recon/ecal/EcalCrystalFilter.java+3-3372 -> 373
                                           /EcalEdepToTriggerConverterDriver.java+1-1372 -> 373
evio/src/main/java/org/hps/evio/SVTEvioReader.java+1-1372 -> 373
                               /TestRunEvioToLcio.java+1-1372 -> 373
hps-java/src/main/java/org/lcsim/hps/analysis/ecal/HPSEcalPlotsDriver.java+1-1372 -> 373
hps-java/src/main/java/org/lcsim/hps/evio/SVTEvioReader.java+1-1372 -> 373
                                         /TestRunTriggeredReconToLcio.java+1-1372 -> 373
hps-java/src/main/java/org/lcsim/hps/readout/ecal/DummyTriggerDriver.java+1-1372 -> 373
                                                 /EcalReadoutDriver.java+1-1372 -> 373
                                                 /FADCEcalReadoutDriver.java+1-1372 -> 373
                                                 /FADCTriggerDriver.java+1-1372 -> 373
                                                 /TimeEvolutionEcalReadoutDriver.java+2-2372 -> 373
                                                 /TriggerDriver.java+1-1372 -> 373
                                                 /TriggerableDriver.java+1-1372 -> 373
hps-java/src/main/java/org/lcsim/hps/recon/ecal/EcalEdepToTriggerConverterDriver.java+1-1372 -> 373
hps-java/src/main/java/org/lcsim/hps/recon/tracking/FieldMap.java+1-1372 -> 373
                                                   /HPSSVTCalibrationConstants.java+1-1372 -> 373
                                                   /HPSTrack.java+1-1372 -> 373
                                                   /SimpleSvtReadout.java+2-2372 -> 373
                                                   /SvtUtils.java+1-1372 -> 373
hps-java/src/main/java/org/lcsim/hps/recon/tracking/apv25/Apv25Full.java+2-2372 -> 373
                                                         /HPSAPV25.java+2-2372 -> 373
                                                         /HPSSiSensorReadout.java+1-1372 -> 373
                                                         /RearTransitionModule.java+1-1372 -> 373
                                                         /SvtReadout.java+1-1372 -> 373
hps-java/src/test/java/org/lcsim/hps/recon/tracking/HelicalTrackHitDriverTest.java+1-1372 -> 373
                                                   /TestRunTrackReconTest.java+1-1372 -> 373
parent/pom.xml+32372 -> 373
plugin/pom.xml+1-2372 -> 373
pom.xml+16372 -> 373
tracking/src/main/java/org/hps/recon/tracking/kalman/KalmanFilterDriver.java-1372 -> 373
users/pom.xml+1-1372 -> 373
users/src/main/java/org/lcsim/hps/users/mgraham/KalmanFilterDriver.java+3-2372 -> 373
                                               /KalmanGeom.java+5372 -> 373
util/pom.xml+5372 -> 373
util/src/main/java/org/hps/util/AIDAFrame.java+53added 373
                               /CalculateAcceptanceFromMadGraph.java+773added 373
                               /CollectionSizeDriver.java+76added 373
                               /CompareHistograms.java+87added 373
                               /ConvertToStdhep.java+816added 373
                               /DatFileToStdhep.java+354added 373
                               /DatFileToStdhepTVM.java+357added 373
                               /DumpLHEEventsToASCII.java+586added 373
                               /GenerateBunches.java+160added 373
                               /GenerateSingleParticles.java+142added 373
                               /LCIOFilterDriver.java+92added 373
                               /LHEFileToStdhep.java+260added 373
                               /MergeBunches.java+500added 373
                               /Pair.java+107added 373
                               /RandomGaussian.java+32added 373
                               /Redrawable.java+13added 373
                               /Resettable.java+14added 373
                               /RunControlDialog.java+106added 373
                               /RunControlDriver.java+86added 373
                               /TimerDriver.java+38added 373
                               /TwoTrackFilterDriver.java+43added 373
+4921-87
22 added + 49 modified, total 71 files
Ginormous fixup to make the build work again.

java/trunk/analysis/src/main/java/org/hps/analysis/examples
DetailedAnalysisDriver.java 372 -> 373
--- java/trunk/analysis/src/main/java/org/hps/analysis/examples/DetailedAnalysisDriver.java	2014-03-26 04:31:31 UTC (rev 372)
+++ java/trunk/analysis/src/main/java/org/hps/analysis/examples/DetailedAnalysisDriver.java	2014-03-26 04:40:56 UTC (rev 373)
@@ -2,36 +2,43 @@
  * To change this template, choose Tools | Templates
  * and open the template in the editor.
  */
-package org.hps.examples;
+package org.hps.analysis.examples;
 
-import java.io.IOException;
-import java.util.logging.Level;
-import java.util.logging.Logger;
+import hep.aida.IAnalysisFactory;
+import hep.aida.IHistogram1D;
+import hep.aida.IHistogramFactory;
+import hep.aida.IProfile1D;
+import hep.physics.matrix.BasicMatrix;
 import hep.physics.matrix.SymmetricMatrix;
 import hep.physics.vec.BasicHep3Vector;
 import hep.physics.vec.Hep3Vector;
+import hep.physics.vec.VecOp;
 
+import java.io.FileWriter;
+import java.io.IOException;
+import java.io.PrintWriter;
+import java.util.ArrayList;
 import java.util.HashMap;
 import java.util.List;
 import java.util.Map;
-
-import hep.aida.*;
-
-import hep.physics.matrix.BasicMatrix;
-import hep.physics.vec.VecOp;
-import java.io.FileWriter;
-import java.io.PrintWriter;
-import java.util.ArrayList;
 import java.util.Set;
+import java.util.logging.Level;
+import java.util.logging.Logger;
 
+import org.hps.recon.tracking.FindableTrack;
+import org.hps.recon.tracking.StraightLineTrack;
+import org.hps.recon.tracking.TrackAnalysis;
+import org.hps.recon.vertexing.BilliorTrack;
+import org.hps.recon.vertexing.BilliorVertex;
+import org.hps.recon.vertexing.BilliorVertexer;
 import org.lcsim.detector.IDetectorElement;
 import org.lcsim.event.EventHeader;
 import org.lcsim.event.LCRelation;
 import org.lcsim.event.MCParticle;
+import org.lcsim.event.RawTrackerHit;
 import org.lcsim.event.RelationalTable;
+import org.lcsim.event.SimTrackerHit;
 import org.lcsim.event.Track;
-import org.lcsim.event.RawTrackerHit;
-import org.lcsim.event.SimTrackerHit;
 import org.lcsim.event.TrackerHit;
 import org.lcsim.event.base.BaseRelationalTable;
 import org.lcsim.fit.helicaltrack.HelicalTrackCross;
@@ -41,12 +48,6 @@
 import org.lcsim.fit.helicaltrack.HelixParamCalculator;
 import org.lcsim.fit.helicaltrack.HelixUtils;
 import org.lcsim.fit.helicaltrack.TrackDirection;
-import org.hps.recon.vertexing.BilliorTrack;
-import org.hps.recon.vertexing.BilliorVertex;
-import org.hps.recon.vertexing.StraightLineTrack;
-import org.hps.recon.tracking.FindableTrack;
-import org.hps.recon.tracking.TrackAnalysis;
-import org.hps.recon.vertexing.BilliorVertexer;
 import org.lcsim.recon.tracking.digitization.sisim.SiTrackerHitStrip1D;
 import org.lcsim.recon.tracking.seedtracker.SeedCandidate;
 import org.lcsim.recon.tracking.seedtracker.SeedTrack;

java/trunk/analysis/src/main/java/org/hps/analysis/examples
ECalScoringMatchDriver.java 372 -> 373
--- java/trunk/analysis/src/main/java/org/hps/analysis/examples/ECalScoringMatchDriver.java	2014-03-26 04:31:31 UTC (rev 372)
+++ java/trunk/analysis/src/main/java/org/hps/analysis/examples/ECalScoringMatchDriver.java	2014-03-26 04:40:56 UTC (rev 373)
@@ -1,10 +1,11 @@
-package org.hps.examples;
+package org.hps.analysis.examples;
 
-import hep.aida.IHistogram1D;
 import hep.aida.IHistogram2D;
+
 import java.util.HashMap;
 import java.util.List;
 import java.util.Map;
+
 import org.lcsim.event.EventHeader;
 import org.lcsim.event.MCParticle;
 import org.lcsim.event.SimCalorimeterHit;

java/trunk/analysis/src/main/java/org/hps/analysis/examples
FastTrackAnalysisDriver.java 372 -> 373
--- java/trunk/analysis/src/main/java/org/hps/analysis/examples/FastTrackAnalysisDriver.java	2014-03-26 04:31:31 UTC (rev 372)
+++ java/trunk/analysis/src/main/java/org/hps/analysis/examples/FastTrackAnalysisDriver.java	2014-03-26 04:40:56 UTC (rev 373)
@@ -1,4 +1,4 @@
-package org.hps.examples;
+package org.hps.analysis.examples;
 
 import hep.physics.matrix.BasicMatrix;
 import hep.physics.matrix.SymmetricMatrix;
@@ -17,6 +17,12 @@
 import java.util.logging.Level;
 import java.util.logging.Logger;
 
+import org.hps.recon.tracking.FindableTrack;
+import org.hps.recon.tracking.StraightLineTrack;
+import org.hps.recon.tracking.TrackAnalysis;
+import org.hps.recon.vertexing.BilliorTrack;
+import org.hps.recon.vertexing.BilliorVertex;
+import org.hps.recon.vertexing.BilliorVertexer;
 import org.lcsim.event.EventHeader;
 import org.lcsim.event.LCRelation;
 import org.lcsim.event.MCParticle;
@@ -32,12 +38,6 @@
 import org.lcsim.fit.helicaltrack.HelicalTrackStrip;
 import org.lcsim.fit.helicaltrack.HelixUtils;
 import org.lcsim.fit.helicaltrack.TrackDirection;
-import org.hps.recon.vertexing.BilliorTrack;
-import org.hps.recon.vertexing.BilliorVertex;
-import org.hps.recon.vertexing.StraightLineTrack;
-import org.hps.recon.tracking.FindableTrack;
-import org.hps.recon.tracking.TrackAnalysis;
-import org.hps.recon.vertexing.BilliorVertexer;
 import org.lcsim.recon.tracking.digitization.sisim.SiTrackerHitStrip1D;
 import org.lcsim.recon.tracking.seedtracker.SeedCandidate;
 import org.lcsim.recon.tracking.seedtracker.SeedTrack;

java/trunk/analysis/src/main/java/org/hps/analysis/examples
JasAnalysisDriver.java 372 -> 373
--- java/trunk/analysis/src/main/java/org/hps/analysis/examples/JasAnalysisDriver.java	2014-03-26 04:31:31 UTC (rev 372)
+++ java/trunk/analysis/src/main/java/org/hps/analysis/examples/JasAnalysisDriver.java	2014-03-26 04:40:56 UTC (rev 373)
@@ -1,4 +1,4 @@
-package org.hps.examples;
+package org.hps.analysis.examples;
 
 import hep.aida.IAnalysisFactory;
 import hep.aida.IHistogramFactory;
@@ -20,6 +20,13 @@
 import java.util.logging.Level;
 import java.util.logging.Logger;
 
+import org.hps.recon.tracking.FindableTrack;
+import org.hps.recon.tracking.StraightLineTrack;
+import org.hps.recon.tracking.TrackAnalysis;
+import org.hps.recon.vertexing.BFitter;
+import org.hps.recon.vertexing.BilliorTrack;
+import org.hps.recon.vertexing.BilliorVertex;
+import org.hps.recon.vertexing.BilliorVertexer;
 import org.lcsim.event.EventHeader;
 import org.lcsim.event.LCRelation;
 import org.lcsim.event.MCParticle;
@@ -34,13 +41,6 @@
 import org.lcsim.fit.helicaltrack.HelicalTrackHit;
 import org.lcsim.fit.helicaltrack.HelixParamCalculator;
 import org.lcsim.fit.helicaltrack.HelixUtils;
-import org.hps.recon.vertexing.BFitter;
-import org.hps.recon.vertexing.BilliorTrack;
-import org.hps.recon.vertexing.BilliorVertex;
-import org.hps.recon.vertexing.StraightLineTrack;
-import org.hps.recon.tracking.FindableTrack;
-import org.hps.recon.tracking.TrackAnalysis;
-import org.hps.recon.vertexing.*;
 import org.lcsim.recon.tracking.digitization.sisim.SiTrackerHitStrip1D;
 import org.lcsim.recon.tracking.seedtracker.SeedCandidate;
 import org.lcsim.recon.tracking.seedtracker.SeedTrack;

java/trunk/analysis/src/main/java/org/hps/analysis/examples
PrintGeometryDriver.java added at 373
--- java/trunk/analysis/src/main/java/org/hps/analysis/examples/PrintGeometryDriver.java	                        (rev 0)
+++ java/trunk/analysis/src/main/java/org/hps/analysis/examples/PrintGeometryDriver.java	2014-03-26 04:40:56 UTC (rev 373)
@@ -0,0 +1,77 @@
+package org.hps.analysis.examples;
+
+import hep.physics.vec.BasicHep3Vector;
+import hep.physics.vec.Hep3Vector;
+import java.util.ArrayList;
+import java.util.List;
+import org.lcsim.detector.IDetectorElement;
+import org.lcsim.detector.ITransform3D;
+import org.lcsim.detector.Transform3D;
+import org.lcsim.detector.identifier.IIdentifier;
+import org.lcsim.detector.identifier.Identifier;
+import org.lcsim.detector.tracker.silicon.ChargeCarrier;
+import org.lcsim.detector.tracker.silicon.SiSensor;
+import org.lcsim.detector.tracker.silicon.SiSensorElectrodes;
+import org.lcsim.detector.tracker.silicon.SiTrackerIdentifierHelper;
+import org.lcsim.event.RawTrackerHit;
+import org.lcsim.event.SimTrackerHit;
+import org.lcsim.event.base.BaseRawTrackerHit;
+import org.lcsim.geometry.Detector;
+import org.hps.recon.tracking.MaterialSupervisor;
+import org.hps.recon.tracking.TrackerHitUtils;
+import org.lcsim.recon.tracking.digitization.sisim.TrackerHitType;
+import org.lcsim.util.Driver;
+
+/**
+ *
+ * @author phansson
+ */
+public class PrintGeometryDriver extends Driver {
+    
+    @Override
+    protected void detectorChanged(Detector detector) {
+        System.out.printf("%s: ################# Print geometry ##########################\n",this.getClass().getSimpleName());
+        IDetectorElement detectorElement = detector.getDetectorElement();
+        List<SiSensor> sensors = detectorElement.findDescendants(SiSensor.class);
+        System.out.printf("%s: %5s %40s %40s\n",this.getClass().getSimpleName(),"ID","Pos","u");
+        for (SiSensor sensor: sensors) {
+            Hep3Vector position = sensor.getGeometry().getPosition();
+            Hep3Vector u = this.getUnitVector(sensor, "measured");
+            System.out.printf("%s: %5d %40s %40s\n",this.getClass().getSimpleName(),sensor.getSensorID(),position.toString(),u.toString());
+        }
+        System.out.printf("%s: ###########################################################\n",this.getClass().getSimpleName());
+    }
+    
+    
+    private  Hep3Vector getUnitVector(SiSensor sensor,String type)
+        {
+
+            Hep3Vector unit_vec = new BasicHep3Vector(-99,-99,-99);
+
+            for (ChargeCarrier carrier : ChargeCarrier.values()) {
+                if (sensor.hasElectrodesOnSide(carrier)) {
+                int channel = 1;
+                    long cell_id = sensor.makeStripId(channel, carrier.charge()).getValue();
+                    IIdentifier id = new Identifier(cell_id);
+                    SiTrackerIdentifierHelper _sid_helper = (SiTrackerIdentifierHelper) sensor.getIdentifierHelper();    
+                    SiSensorElectrodes electrodes = sensor.getReadoutElectrodes(carrier);
+                    ITransform3D local_to_global = new Transform3D();// sensor.getGeometry().getLocalToGlobal();
+                    ITransform3D electrodes_to_global = electrodes.getLocalToGlobal();
+                    ITransform3D global_to_hit = local_to_global.inverse();
+                    ITransform3D electrodes_to_hit = Transform3D.multiply(global_to_hit, electrodes_to_global);
+                    if(type=="measured") {
+                        unit_vec = electrodes_to_hit.rotated(electrodes.getMeasuredCoordinate(0));
+                    } else if (type=="unmeasured") {
+                        unit_vec = electrodes_to_hit.rotated(electrodes.getUnmeasuredCoordinate(0));
+                    } else {
+                        throw new UnsupportedOperationException(String.format("type=\"%s\" not supported",type));
+                    }
+                }
+            }
+            return unit_vec;
+        }
+    
+}
+
+
+

java/trunk/analysis/src/main/java/org/hps/analysis/examples
StarterAnalysisDriver.java 372 -> 373
--- java/trunk/analysis/src/main/java/org/hps/analysis/examples/StarterAnalysisDriver.java	2014-03-26 04:31:31 UTC (rev 372)
+++ java/trunk/analysis/src/main/java/org/hps/analysis/examples/StarterAnalysisDriver.java	2014-03-26 04:40:56 UTC (rev 373)
@@ -1,9 +1,12 @@
-package org.hps.examples;
+package org.hps.analysis.examples;
 
 import hep.aida.IHistogram1D;
 import hep.aida.IHistogram2D;
+
 import java.util.ArrayList;
 import java.util.List;
+
+import org.hps.recon.tracking.LCIOTrackAnalysis;
 import org.lcsim.event.EventHeader;
 import org.lcsim.event.LCRelation;
 import org.lcsim.event.MCParticle;
@@ -16,7 +19,6 @@
 import org.lcsim.geometry.compact.Field;
 import org.lcsim.util.Driver;
 import org.lcsim.util.aida.AIDA;
-import org.hps.recon.tracking.LCIOTrackAnalysis;
 
 /*
  * Example analysis driver.

java/trunk/conditions/src/main/java/org/hps/conditions/deprecated
FieldMap.java 372 -> 373
--- java/trunk/conditions/src/main/java/org/hps/conditions/deprecated/FieldMap.java	2014-03-26 04:31:31 UTC (rev 372)
+++ java/trunk/conditions/src/main/java/org/hps/conditions/deprecated/FieldMap.java	2014-03-26 04:40:56 UTC (rev 373)
@@ -10,7 +10,7 @@
 import java.util.StringTokenizer;
 
 import org.lcsim.conditions.ConditionsManager;
-import org.lcsim.hps.util.Pair;
+import org.hps.util.Pair;
 
 /**
 

java/trunk/conditions/src/main/java/org/hps/conditions/deprecated
HPSSVTCalibrationConstants.java 372 -> 373
--- java/trunk/conditions/src/main/java/org/hps/conditions/deprecated/HPSSVTCalibrationConstants.java	2014-03-26 04:31:31 UTC (rev 372)
+++ java/trunk/conditions/src/main/java/org/hps/conditions/deprecated/HPSSVTCalibrationConstants.java	2014-03-26 04:40:56 UTC (rev 373)
@@ -16,7 +16,7 @@
 import org.lcsim.detector.identifier.IIdentifier;
 import org.lcsim.detector.tracker.silicon.SiSensor;
 import org.lcsim.detector.tracker.silicon.SiTrackerIdentifierHelper;
-import org.lcsim.hps.util.Pair;
+import org.hps.util.Pair;
 
 /**
  *

java/trunk/conditions/src/main/java/org/hps/conditions/deprecated
SvtUtils.java 372 -> 373
--- java/trunk/conditions/src/main/java/org/hps/conditions/deprecated/SvtUtils.java	2014-03-26 04:31:31 UTC (rev 372)
+++ java/trunk/conditions/src/main/java/org/hps/conditions/deprecated/SvtUtils.java	2014-03-26 04:40:56 UTC (rev 373)
@@ -18,8 +18,9 @@
 import org.lcsim.detector.tracker.silicon.SiSensor;
 import org.lcsim.detector.tracker.silicon.SiTrackerIdentifierHelper;
 import org.lcsim.geometry.Detector;
-import org.lcsim.hps.util.Pair;
 
+import org.hps.util.Pair;
+
 import static org.hps.conditions.deprecated.StereoPair.detectorVolume;
 
 /**

java/trunk/conditions/src/main/java/org/hps/conditions/svt
SvtChannel.java 372 -> 373
--- java/trunk/conditions/src/main/java/org/hps/conditions/svt/SvtChannel.java	2014-03-26 04:31:31 UTC (rev 372)
+++ java/trunk/conditions/src/main/java/org/hps/conditions/svt/SvtChannel.java	2014-03-26 04:40:56 UTC (rev 373)
@@ -9,7 +9,7 @@
 import org.hps.conditions.AbstractConditionsObject;
 import org.hps.conditions.ConditionsObjectCollection;
 import org.hps.conditions.ConditionsObjectException;
-import org.lcsim.hps.util.Pair;
+import org.hps.util.Pair;
 
 /**
  * This class represents SVT channel setup information, including hybrid, FPGA, and channel numbers.

java/trunk/conditions/src/main/java/org/hps/conditions/svt
SvtConditionsLoader.java 372 -> 373
--- java/trunk/conditions/src/main/java/org/hps/conditions/svt/SvtConditionsLoader.java	2014-03-26 04:31:31 UTC (rev 372)
+++ java/trunk/conditions/src/main/java/org/hps/conditions/svt/SvtConditionsLoader.java	2014-03-26 04:40:56 UTC (rev 373)
@@ -8,7 +8,7 @@
 import org.hps.conditions.svt.SvtTimeShift.SvtTimeShiftCollection;
 import org.lcsim.detector.tracker.silicon.HpsSiSensor;
 import org.lcsim.geometry.Detector;
-import org.lcsim.hps.util.Pair;
+import org.hps.util.Pair;
 
 /**
  * This class loads {@link SvtConditions} data onto <code>HpsSiSensor</code> objects.

java/trunk/conditions/src/main/java/org/hps/conditions/svt
SvtDaqMapping.java 372 -> 373
--- java/trunk/conditions/src/main/java/org/hps/conditions/svt/SvtDaqMapping.java	2014-03-26 04:31:31 UTC (rev 372)
+++ java/trunk/conditions/src/main/java/org/hps/conditions/svt/SvtDaqMapping.java	2014-03-26 04:40:56 UTC (rev 373)
@@ -2,7 +2,7 @@
 
 import org.hps.conditions.AbstractConditionsObject;
 import org.hps.conditions.ConditionsObjectCollection;
-import org.lcsim.hps.util.Pair;
+import org.hps.util.Pair;
 
 public class SvtDaqMapping extends AbstractConditionsObject {
 

java/trunk/conditions/src/main/java/org/hps/conditions/svt
SvtTimeShift.java 372 -> 373
--- java/trunk/conditions/src/main/java/org/hps/conditions/svt/SvtTimeShift.java	2014-03-26 04:31:31 UTC (rev 372)
+++ java/trunk/conditions/src/main/java/org/hps/conditions/svt/SvtTimeShift.java	2014-03-26 04:40:56 UTC (rev 373)
@@ -3,7 +3,7 @@
 import org.hps.conditions.AbstractConditionsObject;
 import org.hps.conditions.ConditionsObjectCollection;
 import org.hps.conditions.ConditionsObjectException;
-import org.lcsim.hps.util.Pair;
+import org.hps.util.Pair;
 
 /**
  * This class is a data holder for associating a time shift with a specific sensor

java/trunk/distribution
pom.xml 372 -> 373
--- java/trunk/distribution/pom.xml	2014-03-26 04:31:31 UTC (rev 372)
+++ java/trunk/distribution/pom.xml	2014-03-26 04:40:56 UTC (rev 373)
@@ -67,7 +67,7 @@
     <dependencies>
         <dependency>
             <groupId>org.hps</groupId>
-            <artifactId>hps-java</artifactId>
+            <artifactId>hps-recon</artifactId>
         </dependency>
         <dependency>
             <groupId>org.hps</groupId>

java/trunk/ecal-readout-sim/src/main/java/org/hps/readout/ecal
FADCEcalReadoutDriver.java 372 -> 373
--- java/trunk/ecal-readout-sim/src/main/java/org/hps/readout/ecal/FADCEcalReadoutDriver.java	2014-03-26 04:31:31 UTC (rev 372)
+++ java/trunk/ecal-readout-sim/src/main/java/org/hps/readout/ecal/FADCEcalReadoutDriver.java	2014-03-26 04:40:56 UTC (rev 373)
@@ -27,7 +27,7 @@
 import org.lcsim.geometry.Detector;
 import org.lcsim.geometry.Subdetector;
 import org.lcsim.geometry.subdetector.HPSEcal3;
-import org.lcsim.hps.util.RandomGaussian;
+import org.hps.util.RandomGaussian;
 import org.lcsim.lcio.LCIOConstants;
 
 /**

java/trunk/ecal-recon/src/main/java/org/hps/recon/ecal
EcalCrystalFilter.java 372 -> 373
--- java/trunk/ecal-recon/src/main/java/org/hps/recon/ecal/EcalCrystalFilter.java	2014-03-26 04:31:31 UTC (rev 372)
+++ java/trunk/ecal-recon/src/main/java/org/hps/recon/ecal/EcalCrystalFilter.java	2014-03-26 04:40:56 UTC (rev 373)
@@ -28,9 +28,9 @@
 import org.lcsim.event.RawTrackerHit;
 import org.lcsim.event.base.BaseRawCalorimeterHit;
 import org.lcsim.geometry.Detector;
-import org.lcsim.hps.util.AIDAFrame;
-import org.lcsim.hps.util.Resettable;
-import org.lcsim.hps.util.Redrawable;
+import org.hps.util.AIDAFrame;
+import org.hps.util.Resettable;
+import org.hps.util.Redrawable;
 import org.lcsim.util.Driver;
 import org.lcsim.util.aida.AIDA;
 

java/trunk/ecal-recon/src/main/java/org/hps/recon/ecal
EcalEdepToTriggerConverterDriver.java 372 -> 373
--- java/trunk/ecal-recon/src/main/java/org/hps/recon/ecal/EcalEdepToTriggerConverterDriver.java	2014-03-26 04:31:31 UTC (rev 372)
+++ java/trunk/ecal-recon/src/main/java/org/hps/recon/ecal/EcalEdepToTriggerConverterDriver.java	2014-03-26 04:40:56 UTC (rev 373)
@@ -5,7 +5,7 @@
 import org.lcsim.event.CalorimeterHit;
 import org.lcsim.event.EventHeader;
 import org.lcsim.geometry.Detector;
-import org.lcsim.hps.util.RandomGaussian;
+import org.hps.util.RandomGaussian;
 import org.lcsim.util.Driver;
 
 /**

java/trunk/evio/src/main/java/org/hps/evio
SVTEvioReader.java 372 -> 373
--- java/trunk/evio/src/main/java/org/hps/evio/SVTEvioReader.java	2014-03-26 04:31:31 UTC (rev 372)
+++ java/trunk/evio/src/main/java/org/hps/evio/SVTEvioReader.java	2014-03-26 04:40:56 UTC (rev 373)
@@ -18,7 +18,7 @@
 //--- hps-java ---//
 import org.lcsim.event.RawTrackerHit;
 import org.lcsim.event.base.BaseRawTrackerHit;
-import org.lcsim.hps.util.Pair;
+import org.hps.util.Pair;
 import org.lcsim.lcio.LCIOUtil;
 //--- Constants ---//
 import static org.hps.evio.EventConstants.SVT_BANK_TAG;

java/trunk/evio/src/main/java/org/hps/evio
TestRunEvioToLcio.java 372 -> 373
--- java/trunk/evio/src/main/java/org/hps/evio/TestRunEvioToLcio.java	2014-03-26 04:31:31 UTC (rev 372)
+++ java/trunk/evio/src/main/java/org/hps/evio/TestRunEvioToLcio.java	2014-03-26 04:40:56 UTC (rev 373)
@@ -19,7 +19,7 @@
 import org.jlab.coda.jevio.EvioEvent;
 import org.jlab.coda.jevio.EvioReader;
 import org.lcsim.event.EventHeader;
-import org.lcsim.hps.util.RunControlDialog;
+import org.hps.util.RunControlDialog;
 import org.lcsim.job.JobControlManager;
 import org.lcsim.lcio.LCIOWriter;
 

java/trunk/hps-java/src/main/java/org/lcsim/hps/analysis/ecal
HPSEcalPlotsDriver.java 372 -> 373
--- java/trunk/hps-java/src/main/java/org/lcsim/hps/analysis/ecal/HPSEcalPlotsDriver.java	2014-03-26 04:31:31 UTC (rev 372)
+++ java/trunk/hps-java/src/main/java/org/lcsim/hps/analysis/ecal/HPSEcalPlotsDriver.java	2014-03-26 04:40:56 UTC (rev 373)
@@ -24,7 +24,7 @@
 import org.lcsim.hps.recon.ecal.HPSEcalCluster;
 import org.lcsim.hps.recon.ecal.HPSCalorimeterHit;
 import org.lcsim.hps.readout.ecal.TriggerDriver;
-import org.lcsim.hps.util.ClockSingleton;
+import org.hps.util.ClockSingleton;
 import org.lcsim.units.SystemOfUnits;
 import org.lcsim.util.Driver;
 import org.lcsim.util.aida.AIDA;

java/trunk/hps-java/src/main/java/org/lcsim/hps/evio
SVTEvioReader.java 372 -> 373
--- java/trunk/hps-java/src/main/java/org/lcsim/hps/evio/SVTEvioReader.java	2014-03-26 04:31:31 UTC (rev 372)
+++ java/trunk/hps-java/src/main/java/org/lcsim/hps/evio/SVTEvioReader.java	2014-03-26 04:40:56 UTC (rev 373)
@@ -23,7 +23,7 @@
 import static org.lcsim.hps.evio.EventConstants.SVT_BANK_TAG;
 import org.lcsim.hps.recon.tracking.HPSSVTConstants;
 import org.lcsim.hps.recon.tracking.SvtUtils;
-import org.lcsim.hps.util.Pair;
+import org.hps.util.Pair;
 import org.lcsim.lcio.LCIOUtil;
 
 /**

java/trunk/hps-java/src/main/java/org/lcsim/hps/evio
TestRunTriggeredReconToLcio.java 372 -> 373
--- java/trunk/hps-java/src/main/java/org/lcsim/hps/evio/TestRunTriggeredReconToLcio.java	2014-03-26 04:31:31 UTC (rev 372)
+++ java/trunk/hps-java/src/main/java/org/lcsim/hps/evio/TestRunTriggeredReconToLcio.java	2014-03-26 04:40:56 UTC (rev 373)
@@ -18,7 +18,7 @@
 import org.lcsim.hps.conditions.QuietBaseLCSimEvent;
 import org.lcsim.hps.readout.ecal.ReadoutTimestamp;
 import org.lcsim.hps.readout.ecal.TriggerDriver;
-import org.lcsim.hps.util.ClockSingleton;
+import org.hps.util.ClockSingleton;
 import org.lcsim.util.Driver;
 import org.lcsim.lcio.LCIOWriter;
 

java/trunk/hps-java/src/main/java/org/lcsim/hps/readout/ecal
DummyTriggerDriver.java 372 -> 373
--- java/trunk/hps-java/src/main/java/org/lcsim/hps/readout/ecal/DummyTriggerDriver.java	2014-03-26 04:31:31 UTC (rev 372)
+++ java/trunk/hps-java/src/main/java/org/lcsim/hps/readout/ecal/DummyTriggerDriver.java	2014-03-26 04:40:56 UTC (rev 373)
@@ -1,7 +1,7 @@
 package org.lcsim.hps.readout.ecal;
 
 import org.lcsim.event.EventHeader;
-import org.lcsim.hps.util.ClockSingleton;
+import org.hps.util.ClockSingleton;
 
 /**
  * Free-running trigger - triggers on every Nth event

java/trunk/hps-java/src/main/java/org/lcsim/hps/readout/ecal
EcalReadoutDriver.java 372 -> 373
--- java/trunk/hps-java/src/main/java/org/lcsim/hps/readout/ecal/EcalReadoutDriver.java	2014-03-26 04:31:31 UTC (rev 372)
+++ java/trunk/hps-java/src/main/java/org/lcsim/hps/readout/ecal/EcalReadoutDriver.java	2014-03-26 04:40:56 UTC (rev 373)
@@ -5,7 +5,7 @@
 
 import org.lcsim.event.CalorimeterHit;
 import org.lcsim.event.EventHeader;
-import org.lcsim.hps.util.ClockSingleton;
+import org.hps.util.ClockSingleton;
 import org.lcsim.lcio.LCIOConstants;
 
 /**

java/trunk/hps-java/src/main/java/org/lcsim/hps/readout/ecal
FADCEcalReadoutDriver.java 372 -> 373
--- java/trunk/hps-java/src/main/java/org/lcsim/hps/readout/ecal/FADCEcalReadoutDriver.java	2014-03-26 04:31:31 UTC (rev 372)
+++ java/trunk/hps-java/src/main/java/org/lcsim/hps/readout/ecal/FADCEcalReadoutDriver.java	2014-03-26 04:40:56 UTC (rev 373)
@@ -21,7 +21,7 @@
 import org.lcsim.hps.recon.ecal.ECalUtils;
 import org.lcsim.hps.recon.ecal.EcalConditions;
 import org.lcsim.hps.recon.ecal.HPSRawCalorimeterHit;
-import org.lcsim.hps.util.*;
+import org.hps.util.*;
 import org.lcsim.lcio.LCIOConstants;
 import static org.lcsim.hps.recon.ecal.ECalUtils.*;
 

java/trunk/hps-java/src/main/java/org/lcsim/hps/readout/ecal
FADCTriggerDriver.java 372 -> 373
--- java/trunk/hps-java/src/main/java/org/lcsim/hps/readout/ecal/FADCTriggerDriver.java	2014-03-26 04:31:31 UTC (rev 372)
+++ java/trunk/hps-java/src/main/java/org/lcsim/hps/readout/ecal/FADCTriggerDriver.java	2014-03-26 04:40:56 UTC (rev 373)
@@ -14,7 +14,7 @@
 import org.lcsim.geometry.Detector;
 import org.lcsim.hps.recon.ecal.ECalUtils;
 import org.lcsim.hps.recon.ecal.HPSEcalCluster;
-import org.lcsim.hps.util.ClockSingleton;
+import org.hps.util.ClockSingleton;
 import org.lcsim.util.aida.AIDA;
 
 /**

java/trunk/hps-java/src/main/java/org/lcsim/hps/readout/ecal
TimeEvolutionEcalReadoutDriver.java 372 -> 373
--- java/trunk/hps-java/src/main/java/org/lcsim/hps/readout/ecal/TimeEvolutionEcalReadoutDriver.java	2014-03-26 04:31:31 UTC (rev 372)
+++ java/trunk/hps-java/src/main/java/org/lcsim/hps/readout/ecal/TimeEvolutionEcalReadoutDriver.java	2014-03-26 04:40:56 UTC (rev 373)
@@ -6,8 +6,8 @@
 
 import org.lcsim.event.CalorimeterHit;
 import org.lcsim.hps.recon.ecal.HPSCalorimeterHit;
-import org.lcsim.hps.util.ClockSingleton;
-import org.lcsim.hps.util.RingBuffer;
+import org.hps.util.ClockSingleton;
+import org.hps.util.RingBuffer;
 
 /**
  * Performs readout of ECal hits.

java/trunk/hps-java/src/main/java/org/lcsim/hps/readout/ecal
TriggerDriver.java 372 -> 373
--- java/trunk/hps-java/src/main/java/org/lcsim/hps/readout/ecal/TriggerDriver.java	2014-03-26 04:31:31 UTC (rev 372)
+++ java/trunk/hps-java/src/main/java/org/lcsim/hps/readout/ecal/TriggerDriver.java	2014-03-26 04:40:56 UTC (rev 373)
@@ -12,7 +12,7 @@
 import java.util.logging.Logger;
 import org.lcsim.event.EventHeader;
 import org.lcsim.hps.evio.TriggerData;
-import org.lcsim.hps.util.ClockSingleton;
+import org.hps.util.ClockSingleton;
 import org.lcsim.lcio.LCIOWriter;
 
 /**

java/trunk/hps-java/src/main/java/org/lcsim/hps/readout/ecal
TriggerableDriver.java 372 -> 373
--- java/trunk/hps-java/src/main/java/org/lcsim/hps/readout/ecal/TriggerableDriver.java	2014-03-26 04:31:31 UTC (rev 372)
+++ java/trunk/hps-java/src/main/java/org/lcsim/hps/readout/ecal/TriggerableDriver.java	2014-03-26 04:40:56 UTC (rev 373)
@@ -3,7 +3,7 @@
 import java.util.LinkedList;
 import java.util.Queue;
 import org.lcsim.event.EventHeader;
-import org.lcsim.hps.util.ClockSingleton;
+import org.hps.util.ClockSingleton;
 import org.lcsim.util.Driver;
 
 /**

java/trunk/hps-java/src/main/java/org/lcsim/hps/recon/ecal
EcalEdepToTriggerConverterDriver.java 372 -> 373
--- java/trunk/hps-java/src/main/java/org/lcsim/hps/recon/ecal/EcalEdepToTriggerConverterDriver.java	2014-03-26 04:31:31 UTC (rev 372)
+++ java/trunk/hps-java/src/main/java/org/lcsim/hps/recon/ecal/EcalEdepToTriggerConverterDriver.java	2014-03-26 04:40:56 UTC (rev 373)
@@ -5,7 +5,7 @@
 import org.lcsim.event.CalorimeterHit;
 import org.lcsim.event.EventHeader;
 import org.lcsim.geometry.Detector;
-import org.lcsim.hps.util.RandomGaussian;
+import org.hps.util.RandomGaussian;
 import org.lcsim.util.Driver;
 
 /**

java/trunk/hps-java/src/main/java/org/lcsim/hps/recon/tracking
FieldMap.java 372 -> 373
--- java/trunk/hps-java/src/main/java/org/lcsim/hps/recon/tracking/FieldMap.java	2014-03-26 04:31:31 UTC (rev 372)
+++ java/trunk/hps-java/src/main/java/org/lcsim/hps/recon/tracking/FieldMap.java	2014-03-26 04:40:56 UTC (rev 373)
@@ -7,7 +7,7 @@
 
 import org.lcsim.conditions.ConditionsManager;
 import org.lcsim.hps.event.BeamlineConstants;
-import org.lcsim.hps.util.Pair;
+import org.hps.util.Pair;
 
 /**
 

java/trunk/hps-java/src/main/java/org/lcsim/hps/recon/tracking
HPSSVTCalibrationConstants.java 372 -> 373
--- java/trunk/hps-java/src/main/java/org/lcsim/hps/recon/tracking/HPSSVTCalibrationConstants.java	2014-03-26 04:31:31 UTC (rev 372)
+++ java/trunk/hps-java/src/main/java/org/lcsim/hps/recon/tracking/HPSSVTCalibrationConstants.java	2014-03-26 04:40:56 UTC (rev 373)
@@ -16,7 +16,7 @@
 import org.lcsim.detector.tracker.silicon.SiSensor;
 import org.lcsim.detector.tracker.silicon.SiTrackerIdentifierHelper;
 import org.lcsim.hps.conditions.CalibrationDriver;
-import org.lcsim.hps.util.Pair;
+import org.hps.util.Pair;
 
 /**
  *

java/trunk/hps-java/src/main/java/org/lcsim/hps/recon/tracking
HPSTrack.java 372 -> 373
--- java/trunk/hps-java/src/main/java/org/lcsim/hps/recon/tracking/HPSTrack.java	2014-03-26 04:31:31 UTC (rev 372)
+++ java/trunk/hps-java/src/main/java/org/lcsim/hps/recon/tracking/HPSTrack.java	2014-03-26 04:40:56 UTC (rev 373)
@@ -21,7 +21,7 @@
 import org.lcsim.spacegeom.SpaceVector;
 import static org.lcsim.constants.Constants.fieldConversion;
 import org.lcsim.event.MCParticle;
-import org.lcsim.hps.util.Pair;
+import org.hps.util.Pair;
 
 /**
  * Class HPSTrack: extension of HelicalTrackFit to include HPS-specific

java/trunk/hps-java/src/main/java/org/lcsim/hps/recon/tracking
SimpleSvtReadout.java 372 -> 373
--- java/trunk/hps-java/src/main/java/org/lcsim/hps/recon/tracking/SimpleSvtReadout.java	2014-03-26 04:31:31 UTC (rev 372)
+++ java/trunk/hps-java/src/main/java/org/lcsim/hps/recon/tracking/SimpleSvtReadout.java	2014-03-26 04:40:56 UTC (rev 373)
@@ -19,8 +19,8 @@
 import org.lcsim.event.base.BaseRawTrackerHit;
 import org.lcsim.geometry.Detector;
 import org.lcsim.hps.readout.ecal.TriggerableDriver;
-import org.lcsim.hps.util.ClockSingleton;
-import org.lcsim.hps.util.RandomGaussian;
+import org.hps.util.ClockSingleton;
+import org.hps.util.RandomGaussian;
 import org.lcsim.recon.tracking.digitization.sisim.CDFSiSensorSim;
 import org.lcsim.recon.tracking.digitization.sisim.SiElectrodeData;
 import org.lcsim.recon.tracking.digitization.sisim.SiElectrodeDataCollection;

java/trunk/hps-java/src/main/java/org/lcsim/hps/recon/tracking
SvtUtils.java 372 -> 373
--- java/trunk/hps-java/src/main/java/org/lcsim/hps/recon/tracking/SvtUtils.java	2014-03-26 04:31:31 UTC (rev 372)
+++ java/trunk/hps-java/src/main/java/org/lcsim/hps/recon/tracking/SvtUtils.java	2014-03-26 04:40:56 UTC (rev 373)
@@ -19,7 +19,7 @@
 import org.lcsim.detector.tracker.silicon.SiTrackerIdentifierHelper;
 import org.lcsim.geometry.Detector;
 
-import org.lcsim.hps.util.Pair;
+import org.hps.util.Pair;
 import org.lcsim.hps.recon.tracking.StereoPair.detectorVolume;
 
 /**

java/trunk/hps-java/src/main/java/org/lcsim/hps/recon/tracking/apv25
Apv25Full.java 372 -> 373
--- java/trunk/hps-java/src/main/java/org/lcsim/hps/recon/tracking/apv25/Apv25Full.java	2014-03-26 04:31:31 UTC (rev 372)
+++ java/trunk/hps-java/src/main/java/org/lcsim/hps/recon/tracking/apv25/Apv25Full.java	2014-03-26 04:40:56 UTC (rev 373)
@@ -4,8 +4,8 @@
 import org.lcsim.hps.recon.tracking.HPSSVTConstants;
 
 //--- hps-java ---//
-import org.lcsim.hps.util.ClockSingleton;
-import org.lcsim.hps.util.RingBuffer;
+import org.hps.util.ClockSingleton;
+import org.hps.util.RingBuffer;
 
 /**
  * 

java/trunk/hps-java/src/main/java/org/lcsim/hps/recon/tracking/apv25
HPSAPV25.java 372 -> 373
--- java/trunk/hps-java/src/main/java/org/lcsim/hps/recon/tracking/apv25/HPSAPV25.java	2014-03-26 04:31:31 UTC (rev 372)
+++ java/trunk/hps-java/src/main/java/org/lcsim/hps/recon/tracking/apv25/HPSAPV25.java	2014-03-26 04:40:56 UTC (rev 373)
@@ -9,8 +9,8 @@
 import org.lcsim.util.aida.AIDA;
 
 //--- hps-java ---//
-import org.lcsim.hps.util.ClockSingleton;
-import org.lcsim.hps.util.RingBuffer;
+import org.hps.util.ClockSingleton;
+import org.hps.util.RingBuffer;
 
 /**
  *

java/trunk/hps-java/src/main/java/org/lcsim/hps/recon/tracking/apv25
HPSSiSensorReadout.java 372 -> 373
--- java/trunk/hps-java/src/main/java/org/lcsim/hps/recon/tracking/apv25/HPSSiSensorReadout.java	2014-03-26 04:31:31 UTC (rev 372)
+++ java/trunk/hps-java/src/main/java/org/lcsim/hps/recon/tracking/apv25/HPSSiSensorReadout.java	2014-03-26 04:40:56 UTC (rev 373)
@@ -40,7 +40,7 @@
 //--- hps-java ---//
 import org.lcsim.hps.recon.tracking.apv25.HPSAPV25.APV25Channel.APV25AnalogPipeline;
 import org.lcsim.hps.recon.tracking.SvtUtils;
-import org.lcsim.hps.util.ClockSingleton;
+import org.hps.util.ClockSingleton;
 
 /**
  * Class used to Readout HPS APV25's

java/trunk/hps-java/src/main/java/org/lcsim/hps/recon/tracking/apv25
RearTransitionModule.java 372 -> 373
--- java/trunk/hps-java/src/main/java/org/lcsim/hps/recon/tracking/apv25/RearTransitionModule.java	2014-03-26 04:31:31 UTC (rev 372)
+++ java/trunk/hps-java/src/main/java/org/lcsim/hps/recon/tracking/apv25/RearTransitionModule.java	2014-03-26 04:40:56 UTC (rev 373)
@@ -11,7 +11,7 @@
 import org.lcsim.util.Driver;
 
 //--- hps-java ---//
-import org.lcsim.hps.util.RandomGaussian;
+import org.hps.util.RandomGaussian;
 
 //--- Constants ---//
 import static org.lcsim.hps.recon.tracking.HPSSVTConstants.TOTAL_STRIPS_PER_SENSOR;

java/trunk/hps-java/src/main/java/org/lcsim/hps/recon/tracking/apv25
SvtReadout.java 372 -> 373
--- java/trunk/hps-java/src/main/java/org/lcsim/hps/recon/tracking/apv25/SvtReadout.java	2014-03-26 04:31:31 UTC (rev 372)
+++ java/trunk/hps-java/src/main/java/org/lcsim/hps/recon/tracking/apv25/SvtReadout.java	2014-03-26 04:40:56 UTC (rev 373)
@@ -27,7 +27,7 @@
 
 //--- hps-java ---//
 import org.lcsim.hps.recon.tracking.SvtUtils;
-import org.lcsim.hps.util.ClockSingleton;
+import org.hps.util.ClockSingleton;
 
 //--- Constants ---//
 import static org.lcsim.hps.recon.tracking.HPSSVTConstants.TOTAL_APV25_CHANNELS;

java/trunk/hps-java/src/test/java/org/lcsim/hps/recon/tracking
HelicalTrackHitDriverTest.java 372 -> 373
--- java/trunk/hps-java/src/test/java/org/lcsim/hps/recon/tracking/HelicalTrackHitDriverTest.java	2014-03-26 04:31:31 UTC (rev 372)
+++ java/trunk/hps-java/src/test/java/org/lcsim/hps/recon/tracking/HelicalTrackHitDriverTest.java	2014-03-26 04:40:56 UTC (rev 373)
@@ -25,7 +25,7 @@
 import org.lcsim.util.test.TestUtil.TestOutputFile;
 
 import org.lcsim.hps.conditions.CalibrationDriver;
-import org.lcsim.hps.util.CompareHistograms;
+import org.hps.util.CompareHistograms;
 
 import org.freehep.record.loop.RecordLoop.Command;
 

java/trunk/hps-java/src/test/java/org/lcsim/hps/recon/tracking
TestRunTrackReconTest.java 372 -> 373
--- java/trunk/hps-java/src/test/java/org/lcsim/hps/recon/tracking/TestRunTrackReconTest.java	2014-03-26 04:31:31 UTC (rev 372)
+++ java/trunk/hps-java/src/test/java/org/lcsim/hps/recon/tracking/TestRunTrackReconTest.java	2014-03-26 04:40:56 UTC (rev 373)
@@ -19,7 +19,7 @@
 import org.lcsim.event.Track;
 import org.lcsim.event.TrackerHit;
 import org.lcsim.hps.conditions.CalibrationDriver;
-import org.lcsim.hps.util.CompareHistograms;
+import org.hps.util.CompareHistograms;
 import org.lcsim.recon.tracking.digitization.sisim.config.RawTrackerHitSensorSetup;
 import org.lcsim.util.Driver;
 import org.lcsim.util.aida.AIDA;

java/trunk/parent
pom.xml 372 -> 373
--- java/trunk/parent/pom.xml	2014-03-26 04:31:31 UTC (rev 372)
+++ java/trunk/parent/pom.xml	2014-03-26 04:40:56 UTC (rev 373)
@@ -107,13 +107,45 @@
                 <artifactId>hps-conditions</artifactId>
                 <version>3.0.2-SNAPSHOT</version>
             </dependency>
+<!--            
             <dependency>
                 <groupId>org.hps</groupId>
                 <artifactId>hps-java</artifactId>
                 <version>3.0.2-SNAPSHOT</version>
             </dependency>
+-->            
             <dependency>
                 <groupId>org.hps</groupId>
+                <artifactId>hps-ecal-recon</artifactId>
+                <version>3.0.2-SNAPSHOT</version>
+            </dependency>
+            <dependency>
+                <groupId>org.hps</groupId>
+                <artifactId>hps-ecal-readout-sim</artifactId>
+                <version>3.0.2-SNAPSHOT</version>
+            </dependency>
+            <dependency>
+                <groupId>org.hps</groupId>
+                <artifactId>hps-tracking</artifactId>
+                <version>3.0.2-SNAPSHOT</version>
+            </dependency>
+            <dependency>
+                <groupId>org.hps</groupId>
+                <artifactId>hps-evio</artifactId>
+                <version>3.0.2-SNAPSHOT</version>
+            </dependency>
+            <dependency>
+                <groupId>org.hps</groupId>
+                <artifactId>hps-recon</artifactId>
+                <version>3.0.2-SNAPSHOT</version>
+            </dependency>
+            <dependency>
+                <groupId>org.hps</groupId>
+                <artifactId>hps-analysis</artifactId>
+                <version>3.0.2-SNAPSHOT</version>
+            </dependency>
+            <dependency>
+                <groupId>org.hps</groupId>
                 <artifactId>hps-monitoring-drivers</artifactId>
                 <version>3.0.2-SNAPSHOT</version>
             </dependency>

java/trunk/plugin
pom.xml 372 -> 373
--- java/trunk/plugin/pom.xml	2014-03-26 04:31:31 UTC (rev 372)
+++ java/trunk/plugin/pom.xml	2014-03-26 04:40:56 UTC (rev 373)
@@ -52,7 +52,6 @@
                     </redirectUrls>
                     <includes>
                         <include>org.hps:hps-users</include>
-                        <include>org.hps:hps-java</include>
                         <include>org.hps:hps-conditions</include>
                         <include>org.hps:hps-util</include>
                         <include>org.hps:hps-detector-data</include>
@@ -83,7 +82,7 @@
     <dependencies>
         <dependency>
             <groupId>org.hps</groupId>
-            <artifactId>hps-java</artifactId>
+            <artifactId>hps-recon</artifactId>
         </dependency>
         <dependency>
             <groupId>org.hps</groupId>

java/trunk
pom.xml 372 -> 373
--- java/trunk/pom.xml	2014-03-26 04:31:31 UTC (rev 372)
+++ java/trunk/pom.xml	2014-03-26 04:40:56 UTC (rev 373)
@@ -136,9 +136,17 @@
                 <module>et</module>
                 <module>detector-data</module>
                 <module>conditions</module>
+                <module>ecal-readout-sim</module>
+                <module>ecal-recon</module>
+                <module>evio</module>
+                <module>recon</module>
+                <module>tracking</module>
+<!--                
                 <module>hps-java</module>
+-->             
                 <module>monitoring-drivers</module>
                 <module>monitoring-app</module>
+                <module>analysis</module>
                 <module>users</module>
                 <module>distribution</module>
                 <module>plugin</module>
@@ -147,13 +155,21 @@
         <profile>
             <id>site</id>
             <modules>
+                <module>analysis</module>
                 <module>conditions</module>
+                <module>ecal-readout-sim</module>
+                <module>ecal-recon</module>
+                <module>evio</module>
                 <module>et</module>
+<!--                
                 <module>hps-java</module>                
+-->                
                 <module>jevio</module>
                 <module>monitoring-app</module>
                 <module>monitoring-drivers</module>
                 <module>plugin</module>                                                                              
+                <module>recon</module>
+                <module>tracking</module>
                 <module>users</module>                
                 <module>util</module>
             </modules>

java/trunk/tracking/src/main/java/org/hps/recon/tracking/kalman
KalmanFilterDriver.java 372 -> 373
--- java/trunk/tracking/src/main/java/org/hps/recon/tracking/kalman/KalmanFilterDriver.java	2014-03-26 04:31:31 UTC (rev 372)
+++ java/trunk/tracking/src/main/java/org/hps/recon/tracking/kalman/KalmanFilterDriver.java	2014-03-26 04:40:56 UTC (rev 373)
@@ -2,7 +2,6 @@
  * To change this template, choose Tools | Templates
  * and open the template in the editor.
  */
-
 package org.hps.recon.tracking.kalman;
 
 import java.util.List;

java/trunk/users
pom.xml 372 -> 373
--- java/trunk/users/pom.xml	2014-03-26 04:31:31 UTC (rev 372)
+++ java/trunk/users/pom.xml	2014-03-26 04:40:56 UTC (rev 373)
@@ -22,7 +22,7 @@
         <dependency>
             <groupId>org.hps</groupId>
             <artifactId>hps-analysis</artifactId>
-        </dependency>        
+        </dependency> 
     </dependencies>
     
     <build>

java/trunk/users/src/main/java/org/lcsim/hps/users/mgraham
KalmanFilterDriver.java 372 -> 373
--- java/trunk/users/src/main/java/org/lcsim/hps/users/mgraham/KalmanFilterDriver.java	2014-03-26 04:31:31 UTC (rev 372)
+++ java/trunk/users/src/main/java/org/lcsim/hps/users/mgraham/KalmanFilterDriver.java	2014-03-26 04:40:56 UTC (rev 373)
@@ -9,7 +9,9 @@
 import java.util.List;
 
 import org.hps.recon.tracking.TrackAnalysis;
-import org.hps.recon.tracking.TrackUtils;
+import org.hps.recon.tracking.kalman.FullFitKalman;
+import org.hps.recon.tracking.kalman.ShapeDispatcher;
+import org.hps.recon.tracking.kalman.TrackUtils;
 import org.lcsim.event.EventHeader;
 import org.lcsim.event.LCRelation;
 import org.lcsim.event.MCParticle;
@@ -27,7 +29,6 @@
 import org.lcsim.recon.tracking.trfbase.TrackVector;
 import org.lcsim.recon.tracking.trfbase.VTrack;
 import org.lcsim.recon.tracking.trfdca.SurfDCA;
-import org.lcsim.recon.tracking.trffit.FullFitKalman;
 import org.lcsim.recon.tracking.trffit.HTrack;
 import org.lcsim.util.Driver;
 import org.lcsim.util.aida.AIDA;

java/trunk/users/src/main/java/org/lcsim/hps/users/mgraham
KalmanGeom.java 372 -> 373
--- java/trunk/users/src/main/java/org/lcsim/hps/users/mgraham/KalmanGeom.java	2014-03-26 04:31:31 UTC (rev 372)
+++ java/trunk/users/src/main/java/org/lcsim/hps/users/mgraham/KalmanGeom.java	2014-03-26 04:40:56 UTC (rev 373)
@@ -9,6 +9,11 @@
 import java.util.List;
 import java.util.Set;
 
+import org.hps.recon.tracking.kalman.KalmanSurface;
+import org.hps.recon.tracking.kalman.PropDCAXY;
+import org.hps.recon.tracking.kalman.PropXYDCA;
+import org.hps.recon.tracking.kalman.ShapeDispatcher;
+import org.hps.recon.tracking.kalman.util.PropDCAZ;
 import org.lcsim.detector.IDetectorElement;
 import org.lcsim.detector.ILogicalVolume;
 import org.lcsim.detector.IPhysicalVolume;

java/trunk/util
pom.xml 372 -> 373
--- java/trunk/util/pom.xml	2014-03-26 04:31:31 UTC (rev 372)
+++ java/trunk/util/pom.xml	2014-03-26 04:40:56 UTC (rev 373)
@@ -24,6 +24,11 @@
             <artifactId>lcsim-distribution</artifactId>
             <version>${lcsimVersion}</version>
         </dependency>
+        <dependency>
+            <groupId>org.apache.commons</groupId>
+            <artifactId>commons-math3</artifactId>
+            <version>3.2</version>
+        </dependency>
     </dependencies>
     
 </project>

java/trunk/util/src/main/java/org/hps/util
AIDAFrame.java added at 373
--- java/trunk/util/src/main/java/org/hps/util/AIDAFrame.java	                        (rev 0)
+++ java/trunk/util/src/main/java/org/hps/util/AIDAFrame.java	2014-03-26 04:40:56 UTC (rev 373)
@@ -0,0 +1,53 @@
+package org.hps.util;
+
+import hep.aida.*;
+import hep.aida.ref.plotter.PlotterUtilities;
+import java.awt.BorderLayout;
+import javax.swing.*;
+
+/**
+ *
+ * @author Sho Uemura <[log in to unmask]>
+ * @version $Id: AIDAFrame.java,v 1.1 2013/10/25 19:41:01 jeremy Exp $
+ * @deprecated
+ */
+@Deprecated
+public class AIDAFrame extends JFrame {
+
+    JPanel controlsPanel;
+    JMenuBar menubar;
+    JTabbedPane tabbedPane;
+
+    public AIDAFrame() {
+        tabbedPane = new JTabbedPane();
+        this.getContentPane().setLayout(new BorderLayout());
+
+        menubar = new JMenuBar();
+        this.setJMenuBar(menubar);
+
+        this.add(tabbedPane, BorderLayout.CENTER);
+
+        controlsPanel = new JPanel();
+        controlsPanel.setLayout(new BoxLayout(controlsPanel, BoxLayout.X_AXIS));
+        this.add(controlsPanel, BorderLayout.SOUTH);
+    }
+
+    public void addPlotter(IPlotter plotter) {
+        JPanel plotterPanel = new JPanel(new BorderLayout());
+        // Now embed the plotter
+        plotterPanel.add(PlotterUtilities.componentForPlotter(plotter), BorderLayout.CENTER);
+        tabbedPane.add(plotter.title(), plotterPanel);
+    }
+
+    public JTabbedPane getTabbedPane() {
+        return tabbedPane;
+    }
+
+    public JPanel getControlsPanel() {
+        return controlsPanel;
+    }
+
+    public JMenuBar getMenubar() {
+        return menubar;
+    }
+}

java/trunk/util/src/main/java/org/hps/util
CalculateAcceptanceFromMadGraph.java added at 373
--- java/trunk/util/src/main/java/org/hps/util/CalculateAcceptanceFromMadGraph.java	                        (rev 0)
+++ java/trunk/util/src/main/java/org/hps/util/CalculateAcceptanceFromMadGraph.java	2014-03-26 04:40:56 UTC (rev 373)
@@ -0,0 +1,773 @@
+/*
+ * To change this template, choose Tools | Templates
+ * and open the template in the editor.
+ */
+package org.hps.util;
+
+/**
+ *
+ * @author mgraham
+ */
+import hep.physics.vec.BasicHep3Vector;
+import hep.physics.vec.BasicHepLorentzVector;
+import hep.physics.vec.Hep3Vector;
+import hep.physics.vec.HepLorentzVector;
+import java.io.*;
+import java.util.*;
+import java.util.logging.Level;
+import java.util.logging.Logger;
+import org.apache.commons.cli.CommandLine;
+import org.apache.commons.cli.CommandLineParser;
+import org.apache.commons.cli.Option;
+import org.apache.commons.cli.Options;
+import org.apache.commons.cli.ParseException;
+import org.apache.commons.cli.PosixParser;
+import org.lcsim.fit.helicaltrack.HelixParamCalculator;
+
+public class CalculateAcceptanceFromMadGraph {
+
+    static boolean expDecay = false;  //set a ctau decay length
+    static boolean flatDecay = false; //decay uniformily in some range
+    static boolean trident = false;  //are these trident events or A' signal events
+    static double _declength = 0.0;   //A' decay length  (mm)
+    static double _xoff = 0.0;   //set the x,y,z origin offsets...
+    static double _yoff = 0.0;
+    static double _zoff = 0.03;
+    static double aMass = 99;  //Aprime mass (MeV)
+    static double sigx = 0.00001;        // Luminous region size in x (mm)
+    static double sigy = 0.02;        // Luminous region size in y (mm)
+    static double sigz = 0.02;         // Luminous region size in z (mm)
+    static double maxLen = 200; // maximum decay length (mm)
+    static int nInFiles = 1000;  //number of input files
+    static int nmax = 500000;  //maximum number of events to write to 1 stdhep file (new one opens if n>nmax)
+    static String fileType = "lhe";
+    static int nread = -1;  // a running total of number of events read/written to stdhep files
+    static boolean _eventFilter = false;
+    static boolean _isMuon = false;
+    static int _nEleRequired = 2;
+    static double sensorWidth = 40;
+    static double sensorLength = 100;
+    static double gap = Math.sin(0.015);
+    static double gapBig = Math.sin(0.030);
+    static int nLayers = 6;
+    static double[] x = {100, 200, 300, 500, 700, 900};
+    static double[] ySize = { sensorLength / 2, sensorLength / 2, sensorLength / 2, sensorLength / 2, sensorLength, sensorLength};
+    static double[] zSize = { sensorWidth, sensorWidth, sensorWidth, sensorWidth, sensorWidth, sensorWidth};
+    static double[] zGap = {x[0] * gap, x[1] * gap, x[2] * gap, x[3] * gap, x[4] * gap, x[5] * gap};
+    
+//    static double[] ySizeFull = {sensorWidth, sensorWidth, sensorWidth, 3 * sensorWidth / 2, 2 * sensorWidth, 7 * sensorWidth / 2, 4 * sensorLength,};
+//    static double[] zSizeFull = {sensorWidth, sensorWidth, 2 * sensorWidth, 2 * sensorWidth, sensorLength, sensorLength, sensorLength};
+//    static double[] zGapFull = {x[0] * gap, x[1] * gap, x[2] * gap, x[3] * gap, x[4] * gap, x[5] * gap, x[6] * gap};
+    static int nGenerated = 0;
+    static int nPassNoMax = 0;
+    
+    static int nPassFull = 0;
+    static int nPassLyr50 = 0;
+    /*
+     * static double maxMass = 1000.0;
+     * static double bField = 1.0;
+     * static double _pCut = 0.25;
+     * static double _ecm = 6.6; //GeV
+     */
+    static String _custom = "";
+    static double maxMass = 1000.0;
+    static double bField = 1.0;
+    static double _pCut = 0.05;
+    static double _ecm = 4.4; //GeV
+    static double binSize = 1.0;
+    static int nbins = (int) (maxMass / binSize);
+    static int[] genMass = new int[nbins];
+    //static int[] recoMassLyr1 = new int[nbins];
+    static int[] recoMassLyr1Full = new int[nbins];
+    static int[] recoMassLyr1NoMax = new int[nbins];
+
+    static int[] recoMassLyr50Full = new int[nbins];
+
+    public static void doAccounting(List<Boolean> passEle50, List<Boolean> passPos50, List<Boolean> passEleNoMax, List<Boolean> passPosNoMax, List<Boolean> passEleFull, List<Boolean> passPosFull, boolean passEvt, double invMass) {
+
+        boolean passLyr700Full = false;
+        boolean passLyr700Full50 = false;
+        boolean passLyr100Full = false;
+        boolean passLyr50Full = false;
+        boolean passLyr700NoMax = false;
+        boolean passLyr100NoMax = false;
+       
+        //find the bin...
+        int bin = (int) (invMass / maxMass * nbins);
+//        System.out.println("invMass = "+invMass + "...goes in bin #"+bin);
+        if (bin < nbins) {
+            genMass[bin]++;
+            nGenerated++;
+
+            if (passEleFull.get(4) && passPosFull.get(4))
+                passLyr700Full = true;
+            if (passEleNoMax.get(4) && passPosNoMax.get(4))
+                passLyr700NoMax = true;
+            if (passEle50.get(4) && passPos50.get(4))
+                passLyr700Full50 = true;
+           
+
+            //see if they were in layer 1
+            if (passEleFull.get(0) && passPosFull.get(0))
+                passLyr100Full = true;
+
+            if (passEleNoMax.get(0) && passPosNoMax.get(0))
+                passLyr100NoMax = true;
+
+            if (passEle50.get(0) && passPos50.get(0))
+                passLyr50Full = true;
+
+            //ok...fill the histograms
+            if (passLyr700Full && passLyr100Full && passEvt) {
+                recoMassLyr1Full[bin]++;
+                nPassFull++;
+            }
+
+            if (passLyr700Full50 && passLyr50Full && passEvt) {
+                recoMassLyr50Full[bin]++;
+                nPassLyr50++;
+            }
+
+            if (passLyr700NoMax && passLyr100NoMax && passEvt) {
+                recoMassLyr1NoMax[bin]++;
+                nPassNoMax++;
+            }
+
+        
+
+
+
+        } else {
+//            System.out.println("Mass out of range!  "+invMass);
+        }
+
+    }
+
+    private static Options createCommandLineOptions() {
+        Options options = new Options();
+
+        options.addOption(new Option("e", true, "Beam Energy (GeV)"));
+        options.addOption(new Option("n", true, "Number of files to run."));
+        options.addOption(new Option("b", true, "B-Field"));
+        options.addOption(new Option("t", true, "Rad, BH, or FullRadBH"));
+        options.addOption(new Option("u", false, "Is muon decay?"));
+        options.addOption(new Option("c", true, "Custom String"));
+        return options;
+    }
+
+    /**
+     * @param args the command line arguments
+     * @throws IOException
+     */
+    public static void main(String[] args) throws IOException {
+
+
+        // Set up command line parsing.
+        Options options = createCommandLineOptions();
+
+        CommandLineParser parser = new PosixParser();
+
+        // Parse command line arguments.
+        CommandLine cl = null;
+        try {
+            cl = parser.parse(options, args);
+            System.out.println("Trying parser");
+        } catch (ParseException e) {
+            throw new RuntimeException("Problem parsing command line options.", e);
+        }
+
+        String ninString = String.valueOf(nInFiles);
+        String ecmString = String.valueOf(_ecm);
+        String bString = "0.5";
+        String eptString = String.valueOf(_ecm);
+        String typeString = "Rad";
+        eptString = convertDecimal(eptString);
+
+
+        if (cl.hasOption("n")) {
+            ninString = cl.getOptionValue("n");
+            nInFiles = Integer.valueOf(ninString);
+            System.out.println(ninString);
+        }
+
+
+
+        if (cl.hasOption("e")) {
+            ecmString = cl.getOptionValue("e");
+            _ecm = Double.valueOf(ecmString);
+            System.out.println(ecmString);
+            eptString = convertDecimal(ecmString);
+        }
+        if (cl.hasOption("b")) {
+            bString = cl.getOptionValue("b");
+            bField = Double.valueOf(bString);
+            System.out.println(bString);
+        }
+
+        if (cl.hasOption("t")) {
+            typeString = cl.getOptionValue("t");
+            System.out.println(typeString);
+        }
+
+        if (cl.hasOption("u"))
+            _isMuon = true;
+        boolean _hasCustomString = false;
+        if (cl.hasOption("c")) {
+            _custom = cl.getOptionValue("c");
+            _hasCustomString = true;
+            System.out.println("Using custom string = " + _custom);
+        }
+        
+        
+        String fDir = "/nfs/slac/g/hps/mgraham/DarkPhoton/MadGraph/Events" + eptString + typeString + "/";
+//        String fDir = "./";
+//        String inLabel = "W" + eptString + "GeV_Ap" + massString + "MeV_";
+        String inLabel = "W" + eptString + "GeV_" + typeString + "_";
+
+        String inPost = "_unweighted_events.lhe";
+
+
+//        String outDir = "/nfs/slac/g/hps/mgraham/DarkPhoton/SignalEvents/";
+        String outDir = "./Acceptance/";
+        for (int i = 0; i < nInFiles; i++) {
+            int fnum = i + 1;
+            String snum = "_" + fnum;
+            if (fnum < 10000)
+                snum = "_0" + fnum;
+            if (fnum < 1000)
+                snum = "_00" + fnum;
+            if (fnum < 100)
+                snum = "_000" + fnum;
+            if (fnum < 10)
+                snum = "_0000" + fnum;
+
+            String infile = "";
+            if (fileType.contains("dat")) {
+//                infile = fDir + fileLabel + snum + ".dat";
+//                System.out.println(infile);
+            } else if (fileType.contains("lhe")) {
+                infile = fDir + inLabel + i + inPost;
+                System.out.println("Unzipping " + infile);
+                String cmd = "gunzip " + infile + ".gz";
+                Process p = Runtime.getRuntime().exec(cmd);
+                try {
+                    p.waitFor();
+                } catch (InterruptedException ex) {
+                    Logger.getLogger(CalculateAcceptanceFromMadGraph.class.getName()).log(Level.SEVERE, null, ex);
+                }
+            }
+            File f = new File(infile);
+            if (nread == -1 && f.exists())
+                System.out.println("==== processing " + infile + " ====");
+            if (f.exists())
+                nread += process(infile);
+            if (fileType.contains("lhe")) {
+                String cmd = "gzip " + infile;
+                Process p = Runtime.getRuntime().exec(cmd);
+                try {
+                    p.waitFor();
+                } catch (InterruptedException ex) {
+                    Logger.getLogger(CalculateAcceptanceFromMadGraph.class.getName()).log(Level.SEVERE, null, ex);
+                }
+            }
+
+        }
+        //ok ... now spit out histograms
+        System.out.println("nGenerated = " + nGenerated);
+//        System.out.println("nPass(Test) = " + nPassTest);
+
+        System.out.println("nPass(Full) = " + nPassFull);
+        System.out.println("nPass(Lyr50)= " + nPassLyr50);
+        System.out.println("nPass(NoMax) = " + nPassNoMax);
+        System.out.println("*********    Histograms      ***********   ");
+        System.out.println("bin     mass   Gen    Lyr1     Target50   NoMax ");
+        for (int kk = 0; kk < nbins; kk++) {
+            double mass = ((double) kk / nbins) * maxMass;
+//            System.out.println(kk+"\t"+mass+"\t"+genMass[kk]+"\t"+recoMassLyr1[kk]+"\t"+recoMassLyr50[kk]);
+//            System.out.printf("%d\t%4.1f\t%d\t%d\t%d\t%d\n", kk, mass, genMass[kk], recoMassLyr1[kk], recoMassLyr50[kk], recoMassLyr1Full[kk]);
+            System.out.printf("%d\t%4.1f\t%d\t%d\t%d\t%d\n", kk, mass, genMass[kk], recoMassLyr1Full[kk], recoMassLyr50Full[kk], recoMassLyr1NoMax[kk]);
+        }
+        /*
+         * outputFile(outDir + typeString + eptString + "_Test_1T.dat",
+         * recoMassLyr1);
+         * outputFile(outDir + typeString + eptString + "_Full_1T.dat",
+         * recoMassLyr1Full);
+         * outputFile(outDir + typeString + eptString + "_lyr50_1T.dat",
+         * recoMassLyr50);
+         * outputFile(outDir + typeString + eptString + "_generated_1T.dat",
+         * genMass);
+         */
+
+//        outputFile(outDir + typeString + eptString + "_Test.dat", recoMassLyr1);
+        outputFile(outDir + typeString + eptString + "_Full.dat", recoMassLyr1Full);
+        outputFile(outDir + typeString + eptString + "_NoMax.dat", recoMassLyr1NoMax);     
+        outputFile(outDir + typeString + eptString + "_lyr50.dat", recoMassLyr50Full);
+        outputFile(outDir + typeString + eptString + "_generated.dat", genMass);
+
+
+    }
+
+    @SuppressWarnings("static-access")
+    private static int lineCounter(StreamTokenizer tok) throws IOException {
+        int lines = 0;
+        while (tok.nextToken() != tok.TT_EOF) {
+            if (tok.ttype == tok.TT_EOL)
+                lines++;
+            if (tok.ttype == tok.TT_WORD && tok.sval.startsWith("nev"))
+                return lines;
+        }
+        //shouldn't get here...but maybe
+        return lines;
+    }
+
+    private static void outputFile(String fName, int[] hist) throws IOException {
+        FileOutputStream fos = new FileOutputStream(fName);
+        PrintWriter osw = new PrintWriter(fos);
+        for (int kk = 0; kk < nbins; kk++) //            double mass = ((double)kk/nbins)*maxMass;
+        //            System.out.println(kk+"\t"+mass+"\t"+genMass[kk]+"\t"+recoMassLyr1[kk]+"\t"+recoMassLyr50[kk]);
+        //            System.out.printf("%d\t%4.1f\t%d\t%d\t%d\n",kk,mass,genMass[kk],recoMassLyr1[kk],recoMassLyr50[kk]);
+        
+            osw.println(hist[kk]);
+        osw.close();
+        fos.close();
+
+    }
+
+    private static int getnevts(StreamTokenizer lctok) throws IOException {
+        int nevts = -1;
+        if (fileType.contains("dat"))
+            return lineCounter(lctok);
+        else if (fileType.contains("lhe")) {
+            while (nevts == -1)
+                nevts = getNumberOfEvents(lctok);
+            return nevts;
+        }
+        return nevts;
+    }
+
+    private static int process(String infile) throws IOException {
+        Random generator = new Random();
+
+        FileReader lc = new FileReader(infile);
+        StreamTokenizer lctok = new StreamTokenizer(lc);
+        lctok.resetSyntax();
+        lctok.wordChars(33, 255);
+        lctok.parseNumbers();
+
+        lctok.whitespaceChars(0, ' ');
+        lctok.eolIsSignificant(true);
+        int nevts = getnevts(lctok);
+        lc.close();
+        System.out.println("Found " + nevts + " events");
+
+        FileReader fr = new FileReader(infile);
+
+        StreamTokenizer tok = new StreamTokenizer(fr);
+
+        tok.resetSyntax();
+        tok.wordChars(33, 255);
+        tok.parseNumbers();
+
+        tok.whitespaceChars(0, ' ');
+        tok.eolIsSignificant(true);
+
+//        System.out.println("Found " + nevts + "  events");
+        int nreq = (int) nevts;
+        int ngen = (int) nevts;
+        int nwrit = (int) nevts;
+        float ecm = (float) _ecm;
+        float xsec = (float) 99999997952.;
+        double rn1 = 12345321;
+        double rn2 = 66666666;
+//        StdhepBeginRun sb = new StdhepBeginRun(nreq, ngen, nwrit, ecm, xsec, rn1, rn2);
+//        sw.writeRecord(sb);
+
+
+        tok.resetSyntax();
+        tok.wordChars(33, 255);
+        tok.wordChars('0', '9');        // java.io.StreamTokenizer fails to parse
+        tok.wordChars('e', 'e');        // scientific notation like "1.09E-008".
+        tok.wordChars('E', 'E');        // The solution is to read and parse
+        tok.wordChars('.', '.');        // coordinates as "words".
+        tok.wordChars('+', '+');        // You run into trouble if the input file
+        tok.wordChars('-', '-');        // contains text with "e" or "E" which is
+        tok.whitespaceChars(0, ' ');
+        tok.eolIsSignificant(true);
+
+
+
+        double[] beam = {0, 0, 0, 0};
+        int nevhep = 0;
+        for (int icross = 0; icross < nwrit; icross++) {
+            Hep3Vector beamVec =
+                    new BasicHep3Vector(sigx * generator.nextGaussian() + _xoff,
+                    sigy * generator.nextGaussian() + _yoff,
+                    sigz * generator.nextGaussian() + _zoff);
+
+            beam[0] = beamVec.x();
+            beam[1] = beamVec.y();
+            beam[2] = beamVec.z();
+
+            double tmpDecLen = 0;
+
+
+            readLHEEvent(tok, beam, icross);
+
+
+        }
+        fr.close();
+
+
+        return nwrit;
+
+
+    }
+
+    @SuppressWarnings("static-access")
+    private static List<Double> getNumbersInLine(StreamTokenizer tok) throws IOException {
+        List<Double> nums = new ArrayList<Double>();
+        while (tok.nextToken() != tok.TT_EOF) {
+            if (tok.ttype == tok.TT_EOL)
+                break;
+            String tokVal = tok.sval;
+//            System.out.println(tokVal);
+            nums.add(Double.valueOf(tokVal).doubleValue());
+        }
+
+        return nums;
+    }
+
+    @SuppressWarnings("static-access")
+    private static int getNumberOfEvents(StreamTokenizer tok) throws IOException {
+        boolean fndNumber = false;
+        boolean fndOf = false;
+        boolean fndEvents = false;
+        int evts = -1;
+        while (tok.nextToken() != tok.TT_EOF) {
+//            System.out.println(tok.toString());
+            if (tok.ttype == tok.TT_EOL)
+                break;
+            if (tok.ttype == tok.TT_WORD && tok.sval.contentEquals("Number")) //              System.out.println(tok.toString());
+            
+                fndNumber = true;
+            if (tok.ttype == tok.TT_WORD && tok.sval.contentEquals("of"))
+                fndOf = true;
+            if (tok.ttype == tok.TT_WORD && tok.sval.contentEquals("Events"))
+                fndEvents = true;
+            if (tok.ttype == tok.TT_NUMBER && fndEvents && fndOf && fndNumber)
+                evts = (int) tok.nval;
+        }
+        return evts;
+    }
+
+    @SuppressWarnings("static-access")
+    private static void getToNextEvent(StreamTokenizer tok) throws IOException {
+        while (tok.nextToken() != tok.TT_EOF) //            System.out.println(tok.toString());
+        
+            if (tok.ttype == tok.TT_WORD && tok.sval.contentEquals("<event>")) {
+                tok.nextToken();//get to the EOL
+                return;
+            }
+    }
+
+    static private double expWeight(double x) {
+        return Math.exp(-x / _declength);
+    }
+
+    static private double expWeight(double x, double gamma) {
+        return Math.exp(-x / (gamma * _declength));
+    }
+
+    static private double findMaxWeight() {
+        Random generator = new Random();
+        int ntrials = 100000;
+        double maxlength = maxLen;
+        double maxWeight = 0;
+        for (int i = 0; i < ntrials; i++) {
+            double x = generator.nextDouble() * maxlength;
+            double wght = expWeight(x);
+            if (wght > maxWeight)
+                maxWeight = wght;
+        }
+
+        return maxWeight;
+    }
+
+    static private double getDecayLength(double MaxWeight, double gamma) {
+        Random generator = new Random();
+        double maxlength = maxLen;
+        double dl = 0;
+        double draw = generator.nextDouble();
+        double tmpwght = 0;
+        while (tmpwght < draw) {
+            dl = generator.nextDouble() * maxlength;
+            tmpwght = expWeight(dl, gamma) / MaxWeight;
+        }
+        return dl;
+    }
+
+    static private double getDecayLength(double MaxWeight) {
+        Random generator = new Random();
+        double maxlength = maxLen;
+        double dl = 0;
+        double draw = generator.nextDouble();
+        double tmpwght = 0;
+        while (tmpwght < draw) {
+            dl = generator.nextDouble() * maxlength;
+            tmpwght = expWeight(dl) / MaxWeight;
+        }
+        return dl;
+    }
+
+    static private void readLHEEvent(StreamTokenizer tok, double[] beam, int nevhep) throws IOException {
+        Random generator = new Random();
+        getToNextEvent(tok);
+        List<Double> nums = getNumbersInLine(tok);
+
+        if (nums.size() != 6)
+            throw new RuntimeException("Unexpected entry for number of particles");
+        int nhep = nums.get(0).intValue();
+//        System.out.println("Number of particles for event " + nevhep + ": " + nhep);
+
+        List<Boolean> passEleTarget50 = new ArrayList<Boolean>();
+        List<Boolean> passPosTarget50 = new ArrayList<Boolean>();
+        List<Boolean> passEleNoMax = new ArrayList<Boolean>();
+        List<Boolean> passPosNoMax = new ArrayList<Boolean>();
+        List<Boolean> passEleFull = new ArrayList<Boolean>();
+        List<Boolean> passPosFull = new ArrayList<Boolean>();
+        List<Boolean> passRecoilTarget50 = new ArrayList<Boolean>();
+        List<Boolean> passRecoilNoMax = new ArrayList<Boolean>();
+        List<Boolean> passRecoilFull = new ArrayList<Boolean>();
+        //Hep3Vector pEle = new BasicHep3Vector();
+        //Hep3Vector pPos = new BasicHep3Vector();
+        //Hep3Vector pRecoil = new BasicHep3Vector();
+        HepLorentzVector pEle = new BasicHepLorentzVector();
+        HepLorentzVector pPos = new BasicHepLorentzVector();
+        HepLorentzVector pRecoil = new BasicHepLorentzVector();
+        int i = 0;
+        int pdgid = 0;
+        double[] ApMom = {0, 0, 0};
+        double mom[] = {0, 0, 0};
+        double ene = 0;
+        int charge;
+        boolean foundRecoil = false;
+        for (int npart = 0; npart < nhep; npart++) {
+            List<Double> vals = getNumbersInLine(tok);
+            if (vals.size() != 13)
+                throw new RuntimeException("Unexpected entry for a particle");
+            if (vals.get(1).intValue() != 9) {//ignore the vertex for now
+//                int ip = vals.get(0).intValue();
+//                if (ip != i + 1) {
+//                    throw new RuntimeException("Particle numbering mismatch");
+//                }
+
+                pdgid = vals.get(0).intValue();
+//                System.out.println(idhepTmp);
+//                System.out.println(pdgid+"   "+vals.get(1).intValue());
+                if (Math.abs(pdgid) == 611 || (Math.abs(pdgid) == 11 && vals.get(1).intValue() == 1)) {
+//                if (Math.abs(pdgid) == 611) {
+                    //                  System.out.println("Ok...getting info for this particle");
+                    for (int j = 0; j < 3; j++)
+                        mom[j] = vals.get(j + 6);
+                    ene = vals.get(10);
+                    Hep3Vector p = rotate(mom[0], mom[1], mom[2]);
+                    //                   Hep3Vector p = rotate(mom[1], mom[0], mom[2]); //flip x,y because my trident files have cut on thetaX that may bias things
+                    Hep3Vector o = rotate(beam[0], beam[1], beam[2]);
+                    charge = 1;
+                    if (pdgid == 611)
+                        charge = -1;
+                    HepLorentzVector pl = new BasicHepLorentzVector(ene, p);
+                    HelixParamCalculator hpc = new HelixParamCalculator(p, o, charge, bField);
+                    double d0 = hpc.getDCA();
+                    double phi0 = hpc.getPhi0();
+                    double z0 = hpc.getZ0();
+                    double slope = hpc.getSlopeSZPlane();
+                    double R = hpc.getRadius();
+                    double x0 = hpc.getX0();
+                    double y0 = hpc.getY0();
+                    double xc = getxc(R, d0, phi0);
+                    double yc = getyc(R, d0, phi0);;
+
+//                     System.out.println(p.toString());
+//                     System.out.println("d0 = "+d0+"; phi0 = "+phi0+"; z0 = "+z0+"; slope = "+slope+"; R = "+R);
+//                       System.out.println("x0 = "+x0+"; y0 = "+y0+"; xc = "+xc+"; yc = "+yc);
+                    List<Boolean> passLayerTarget50 = new ArrayList<Boolean>();
+                    List<Boolean> passLayerNoMax = new ArrayList<Boolean>();
+                    List<Boolean> passLayerFull = new ArrayList<Boolean>();
+                    for (int ii = 0; ii < nLayers; ii++) {
+                        double pathL = PathToXPlane(x0, y0, xc, yc, R, x[ii]);
+//                        System.out.println("path length "+pathL);
+                        Hep3Vector posL = PointOnHelix(xc, yc, R, phi0, z0, slope, pathL);
+//                        System.out.println("Position "+posL.toString());
+                        //                       passLayer.add(inAcceptance(posL, ySize[ii], zSize[ii], zGap[ii]));
+                        passLayerFull.add(inAcceptance(posL, ySize[ii], zSize[ii], zGap[ii]));
+                        passLayerNoMax.add(inAcceptance(posL, 9999999, 9999999, zGap[ii]));                      
+                        
+                          double pathLTg50 = PathToXPlane(x0, y0, xc, yc, R, x[ii]-50.0);
+//                        System.out.println("path length "+pathL);
+                        Hep3Vector posLTg50 = PointOnHelix(xc, yc, R, phi0, z0, slope, pathLTg50);
+//                        System.out.println("Position "+posL.toString());
+                         passLayerTarget50.add(inAcceptance(posLTg50, ySize[ii], zSize[ii], zGap[ii]));
+                    }
+
+                    if (pdgid == 611) {  //electron from A'
+                        passEleTarget50 = passLayerTarget50;
+                        passEleNoMax = passLayerNoMax;
+                        passEleFull = passLayerFull;
+                        pEle = pl;
+                    } else if (pdgid == -611 || pdgid == -11) {//positron
+                        pPos = pl;
+                        passPosTarget50 = passLayerTarget50;
+                        passPosNoMax = passLayerNoMax;
+                        passPosFull = passLayerFull;
+                    } else if (pdgid == 11)
+                        if (!foundRecoil) {
+                            foundRecoil = true;
+                            passRecoilTarget50 = passLayerTarget50;
+                            passRecoilNoMax = passLayerNoMax;
+                            passRecoilFull = passLayerFull;
+                            pRecoil = pl;
+                        } //                        else{                    //                             passEle = passLayer;
+                    //                            passEleFull = passLayerFull;
+                    //                            pEle = p;
+                    //                        }                    
+
+                }
+
+                i++;
+            }
+        }
+        double invMass = getInvMass(pEle.v3(), pPos.v3());
+        doAccounting(passEleTarget50, passPosTarget50, passEleNoMax, passPosNoMax, passEleFull, passPosFull, eventPass(pEle.v3(), pPos.v3()), 1000.0 * invMass);
+        //       doAccounting(passRecoil, passPos, passRecoilFull, passPosFull, eventPass(pRecoil, pPos), 1000.0 * getInvMass(pRecoil, pPos));
+    }
+
+    public static Hep3Vector rotate(double x, double y, double z) {
+        return new BasicHep3Vector(z, x, y);
+    }
+
+    public static String convertDecimal(String num) {
+        if (num.contains("."))
+            num = num.replace(".", "pt");
+        return num;
+    }
+
+    public static boolean inAcceptance(Hep3Vector position, double yExt, double zExt, double zGap) {
+        double ypos = position.y();
+        if (Math.abs(ypos) > yExt)
+            return false;
+        double zpos = position.z();
+        if (Math.abs(zpos) < zGap)
+            return false;
+        if (Math.abs(zpos) > zGap + zExt)
+            return false;
+
+        return true;
+    }
+
+    public static boolean eventPass(Hep3Vector p1, Hep3Vector p2) {
+        //       System.out.println("p1.magnitude = "+p1.magnitude()+"; p2.magnitude = "+p2.magnitude()+"; 0.8*_ecm = "+0.8*_ecm);
+
+        if (p1.magnitude() + p2.magnitude() < 0.8 * _ecm)//trigger requires 80% of beam energy
+        
+            return false;
+//        System.out.println("Passed totenergy");
+        if (p1.magnitude() < _pCut)
+            return false;
+        if (p2.magnitude() < _pCut)
+            return false;
+        if (p2.z() * p1.z() > 0) // this is basically the opposite quadrant cut in the trigger (B-field makes them opposite in y)
+        
+            return false;
+        //      System.out.println("Event is good!!!!!");
+        return true;
+
+    }
+
+    public static Double PathToXPlane(double x0, double y0, double xc, double yc, double RC, double x) {
+        //  Create a list to hold the path lengths
+        Double path;
+
+        double y = yc + Math.signum(RC) * Math.sqrt(RC * RC - Math.pow(x - xc, 2));
+//        System.out.println("x = "+x+"; y = "+y);
+        double s = PathCalc(xc, yc, RC, x0, y0, x, y);
+
+//        System.out.println("PathToXPlane :  s = "+s+"; sFromClass = "+sFromClass);
+
+        path = s;
+
+        return path;
+    }
+
+    private static double PathCalc(double xc, double yc, double RC, double x1, double y1, double x2, double y2) {
+        //  Find the angle between these points measured wrt the circle center
+        double phi1 = Math.atan2(y1 - yc, x1 - xc);
+        double phi2 = Math.atan2(y2 - yc, x2 - xc);
+        double dphi = phi2 - phi1;
+        //  Make sure dphi is in the valid range (-pi, pi)
+        if (dphi > Math.PI)
+            dphi -= 2. * Math.PI;
+        if (dphi < -Math.PI)
+            dphi += 2. * Math.PI;
+        //  Return the arc length
+        return -RC * dphi;
+    }
+
+    public static Hep3Vector PointOnHelix(double xc, double yc, double RC, double phi0, double z0, double slope, double s) {
+        //  Find the azimuthal direction at this path length      
+        double phi = phi0 - s / RC;
+        //  Calculate the position on the helix at this path length
+        double x = xc - RC * Math.sin(phi);
+        double y = yc + RC * Math.cos(phi);
+        double z = z0 + s * slope;
+        //  Return the position as a Hep3Vector
+        return new BasicHep3Vector(x, y, z);
+    }
+
+    private static double getxc(double R, double d0, double phi0) {
+        return (R - d0) * Math.sin(phi0);
+    }
+
+    private static double getyc(double R, double d0, double phi0) {
+        return -(R - d0) * Math.cos(phi0);
+    }
+
+    public static double getInvMass(Hep3Vector p1, Hep3Vector p2) {
+        double esum = 0.;
+        double pxsum = 0.;
+        double pysum = 0.;
+        double pzsum = 0.;
+        double me = 0.000511;
+        if (_isMuon)
+            me = 0.1057;
+        // Loop over tracks
+
+
+        double p1x = p1.x();
+        double p1y = p1.y();
+        double p1z = p1.z();
+        double p1mag2 = p1x * p1x + p1y * p1y + p1z * p1z;
+        double e1 = Math.sqrt(p1mag2 + me * me);
+        pxsum += p1x;
+        pysum += p1y;
+        pzsum += p1z;
+        esum += e1;
+
+        double p2x = p2.x();
+        double p2y = p2.y();
+        double p2z = p2.z();
+        double p2mag2 = p2x * p2x + p2y * p2y + p2z * p2z;
+        double e2 = Math.sqrt(p2mag2 + me * me);
+        pxsum += p2x;
+        pysum += p2y;
+        pzsum += p2z;
+        esum += e2;
+        double psum = Math.sqrt(pxsum * pxsum + pysum * pysum + pzsum * pzsum);
+        double evtmass = esum * esum - psum * psum;
+
+        if (evtmass > 0)
+            return Math.sqrt(evtmass);
+        else
+            return -99;
+    }
+}

java/trunk/util/src/main/java/org/hps/util
CollectionSizeDriver.java added at 373
--- java/trunk/util/src/main/java/org/hps/util/CollectionSizeDriver.java	                        (rev 0)
+++ java/trunk/util/src/main/java/org/hps/util/CollectionSizeDriver.java	2014-03-26 04:40:56 UTC (rev 373)
@@ -0,0 +1,76 @@
+package org.hps.util;
+
+import java.util.ArrayList;
+import java.util.HashMap;
+import java.util.List;
+import java.util.Map;
+import org.lcsim.event.EventHeader;
+import org.lcsim.util.Driver;
+
+/**
+ * Prints a summary of collections seen in the file, and their average sizes.
+ * @author Sho Uemura <[log in to unmask]>
+ * @version $Id: CollectionSizeDriver.java,v 1.3 2013/04/02 01:11:11 meeg Exp $
+ */
+public class CollectionSizeDriver extends Driver {
+
+    int eventCount = 0;
+    private Map<String, CollectionStats> collections = new HashMap<String, CollectionStats>();
+
+    @Override
+    public void process(EventHeader event) {
+        List<List<Object>> listOfLists = event.get(Object.class);
+        for (List<Object> list : listOfLists) {
+            String name = event.getMetaData(list).getName();
+            Class type = event.getMetaData(list).getType();
+
+            CollectionStats stats = collections.get(name);
+            if (stats == null) {
+                stats = new CollectionStats(name, type);
+                collections.put(name, stats);
+            }
+
+            stats.addCount(list.size());
+        }
+
+        eventCount++;
+    }
+
+    @Override
+    public void endOfData() {
+        System.out.format("Read %d events\n", eventCount);
+        List<String> names = new ArrayList<String>(collections.keySet());
+        java.util.Collections.sort(names);
+        for (String name:names){
+            collections.get(name).printStats(eventCount);
+        }
+    }
+
+    private class CollectionStats {
+
+        String name;
+        Class type;
+        boolean hasHits;
+        int nHits;
+        double eventsWithCollection = 0;
+        double totalCount = 0;
+
+        public CollectionStats(String name, Class type) {
+            this.name = name;
+            this.type = type;
+        }
+
+        public void addCount(int count) {
+            eventsWithCollection++;
+            totalCount += count;
+        }
+
+        public void printStats(int eventCount) {
+            double fractionWithCollection = eventsWithCollection / eventCount;
+            double averageCollectionSize = totalCount / eventsWithCollection;
+
+            System.out.format("%s (%s): %f of events had this collection, with an average of %f elements\n", name, type.getSimpleName(), fractionWithCollection, averageCollectionSize);
+
+        }
+    }
+}

java/trunk/util/src/main/java/org/hps/util
CompareHistograms.java added at 373
--- java/trunk/util/src/main/java/org/hps/util/CompareHistograms.java	                        (rev 0)
+++ java/trunk/util/src/main/java/org/hps/util/CompareHistograms.java	2014-03-26 04:40:56 UTC (rev 373)
@@ -0,0 +1,87 @@
+package org.hps.util;
+
+import hep.aida.IAxis;
+import hep.aida.IHistogram1D;
+import java.util.logging.Level;
+import java.util.logging.Logger;
+import org.apache.commons.math.MathException;
+import org.apache.commons.math.stat.descriptive.StatisticalSummaryValues;
+import org.apache.commons.math.stat.inference.TTestImpl;
+import org.apache.commons.math3.distribution.KolmogorovSmirnovDistribution;
+
+/**
+ *
+ * Class to do various comparisons of histograms Singleton instance with lazy
+ * instantiation
+ *
+ * @author phansson
+ */
+public class CompareHistograms {
+
+    public static CompareHistograms _instance = null;
+    TTestImpl tTest;
+
+    private CompareHistograms() {
+        tTest = new TTestImpl();
+    }
+
+    public static CompareHistograms instance() {
+        if (_instance == null) {
+            _instance = new CompareHistograms();
+        }
+        return _instance;
+    }
+
+    public double getTTestPValue(double m1, double m2, double v1, double v2, int n1, int n2) {
+        StatisticalSummaryValues stat1 = new StatisticalSummaryValues(m1, v1, n1, 1., 0., 0.);
+        StatisticalSummaryValues stat2 = new StatisticalSummaryValues(m2, v2, n2, 1., 0., 0.);
+
+        double p_value = -1;
+        try {
+            p_value = tTest.tTest(stat1, stat2);
+        } catch (IllegalArgumentException ex) {
+            Logger.getLogger(CompareHistograms.class.getName()).log(Level.SEVERE, null, ex);
+        } catch (MathException ex) {
+            Logger.getLogger(CompareHistograms.class.getName()).log(Level.SEVERE, null, ex);
+        }
+        return p_value;
+
+    }
+
+    public boolean getTTest(double alpha, double m1, double m2, double v1, double v2, int n1, int n2) {
+        StatisticalSummaryValues stat1 = new StatisticalSummaryValues(m1, v1, n1, 1., 0., 0.);
+        StatisticalSummaryValues stat2 = new StatisticalSummaryValues(m2, v2, n2, 1., 0., 0.);
+
+        boolean nullHypoIsRejected = false;
+        try {
+            nullHypoIsRejected = tTest.tTest(stat1, stat2, alpha);
+        } catch (IllegalArgumentException ex) {
+            Logger.getLogger(CompareHistograms.class.getName()).log(Level.SEVERE, null, ex);
+        } catch (MathException ex) {
+            Logger.getLogger(CompareHistograms.class.getName()).log(Level.SEVERE, null, ex);
+        }
+        return nullHypoIsRejected;
+    }
+
+    public static double getKolmogorovPValue(IHistogram1D reference, IHistogram1D test) {
+        double integralMax = 0.0;
+        double refIntegral = reference.binHeight(IAxis.UNDERFLOW_BIN);
+        double testIntegral = test.binHeight(IAxis.UNDERFLOW_BIN);
+        double integralDiff = Math.abs(refIntegral / reference.allEntries() - testIntegral / test.allEntries());
+        if (integralDiff > integralMax) {
+            integralMax = integralDiff;
+        }
+        for (int i = 0; i < reference.axis().bins(); i++) {
+            refIntegral += reference.binHeight(i);
+            testIntegral += test.binHeight(i);
+
+            integralDiff = Math.abs(refIntegral / reference.allEntries() - testIntegral / test.allEntries());
+            if (integralDiff > integralMax) {
+                integralMax = integralDiff;
+            }
+        }
+        int n = (int) Math.ceil(Math.sqrt((reference.allEntries() * test.allEntries()) / (reference.allEntries() + test.allEntries())));
+        KolmogorovSmirnovDistribution dist = new KolmogorovSmirnovDistribution(n);
+        return 1.0 - dist.cdf(integralMax);
+    }
+}

java/trunk/util/src/main/java/org/hps/util
ConvertToStdhep.java added at 373
--- java/trunk/util/src/main/java/org/hps/util/ConvertToStdhep.java	                        (rev 0)
+++ java/trunk/util/src/main/java/org/hps/util/ConvertToStdhep.java	2014-03-26 04:40:56 UTC (rev 373)
@@ -0,0 +1,816 @@
+/*
+ * To change this template, choose Tools | Templates
+ * and open the template in the editor.
+ */
+package org.hps.util;
+
+/**
+ *
+ * @author Mathew Thomas Graham <[log in to unmask]>
+ * $Id: ConvertToStdhep.java,v 1.12 2013/10/29 17:24:34 mgraham Exp $ 
+ */
+import java.io.FileReader;
+import java.io.IOException;
+import java.io.StreamTokenizer;
+import java.util.ArrayList;
+import java.util.List;
+
+import hep.io.stdhep.StdhepBeginRun;
+import hep.io.stdhep.StdhepEndRun;
+import hep.io.stdhep.StdhepEvent;
+import hep.io.stdhep.StdhepWriter;
+import hep.physics.vec.BasicHep3Vector;
+import hep.physics.vec.Hep3Vector;
+import java.io.File;
+import java.util.Random;
+import java.util.logging.Level;
+import java.util.logging.Logger;
+import org.apache.commons.cli.CommandLine;
+import org.apache.commons.cli.CommandLineParser;
+import org.apache.commons.cli.HelpFormatter;
+import org.apache.commons.cli.Option;
+import org.apache.commons.cli.Options;
+import org.apache.commons.cli.ParseException;
+import org.apache.commons.cli.PosixParser;
+import org.lcsim.detector.IRotation3D;
+import org.lcsim.detector.RotationGeant;
+
+public class ConvertToStdhep {
+
+    static boolean expDecay = false;  //set a ctau decay length
+    static boolean flatDecay = false; //decay uniformily in some range
+    static boolean trident = false;  //are these trident events or A' signal events
+    static double _declength = 0.0;   //A' decay length  (mm)
+    static double _xoff = 0.0;   //set the x,y,z origin offsets...
+    static double _yoff = 0.0;
+    static double _zoff = 0.03;
+    static double aMass = 99;  //Aprime mass (MeV)
+    static double sigx = 0.2;        // Luminous region size in x (mm)
+    static double sigy = 0.02;        // Luminous region size in y (mm)
+    static double sigz = 0.0;         // Luminous region size in z (mm)
+//beam is positioned so that at first beam direction is in z, then rotated to correct orientation    
+    static double rotx = 0.00;        // Rotation of beam about X
+    static double roty = 0.03;        // Rotation of beam about Y
+    static double rotz = 0.00;         // Rotation of beam about Z
+    static double maxLen = 200; // maximum decay length (mm)
+    static double _ecm = 6.6; //GeV
+    static int nInFiles = 10000;  //number of input files
+    static int nBegin=0;
+    static StdhepWriter sw;
+    static int nmax = 500000;  //maximum number of events to write to 1 stdhep file (new one opens if n>nmax)
+    static String fileType = "lhe";
+    static IRotation3D rot = new RotationGeant(rotx, roty, rotz);
+//        static String fileType="dat";
+    static int nread = -1;  // a running total of number of events read/written to stdhep files
+    static boolean _eventFilter = false;
+    static boolean _isMuon=false;
+    static String  _custom="";
+//    static int _nEleRequired = 2;
+     static int _nEleRequired = 0;
+    private static Options createCommandLineOptions() {
+        Options options = new Options();
+
+        options.addOption(new Option("m", true, "A' Mass (MeV)"));
+        options.addOption(new Option("e", true, "Beam Energy (GeV)"));
+        options.addOption(new Option("n", true, "Number of files to run."));
+        options.addOption(new Option("b", true, "First file number."));
+        options.addOption(new Option("x", true, "Beam sigma in x"));
+        options.addOption(new Option("y", true, "Beam sigma in y"));
+        options.addOption(new Option("s", false, "Filter Events"));
+        options.addOption(new Option("u", false, "Is muonic decay?"));
+        options.addOption(new Option("t", false, "Is trident decay?"));
+        options.addOption(new Option("c", true, "Custom String"));
+        options.addOption(new Option("h", "print this message"));
+
+        return options;
+    }
+
+    /**
+     * @param args the command line arguments
+     * @throws IOException
+     */
+    public static void main(String[] args) throws IOException {
+
+
+        // Set up command line parsing.
+        Options options = createCommandLineOptions();
+
+        CommandLineParser parser = new PosixParser();
+
+        // Parse command line arguments.
+        CommandLine cl = null;
+        try {
+            cl = parser.parse(options, args);
+            System.out.println("Trying parser");
+        } catch (ParseException e) {
+            throw new RuntimeException("Problem parsing command line options.", e);
+        }
+        String massString = String.valueOf(aMass);
+        String ninString = String.valueOf(nInFiles);
+        String nbegString = String.valueOf(nBegin);
+        String ecmString = String.valueOf(_ecm);
+        String eptString = String.valueOf(_ecm);
+         String sigxString = String.valueOf(sigx);
+          String sigyString = String.valueOf(sigy);
+        eptString = convertDecimal(eptString);
+        boolean _hasCustomString=false;
+        if(cl.hasOption("h")) {
+            HelpFormatter formatter = new HelpFormatter();
+            formatter.printHelp("ConvertToStdhep", options);
+            return;
+        }
+            
+         if (cl.hasOption("t")) {
+            trident = true;
+            System.out.println("Is a trident decay");
+         }
+        // LCIO output file.
+        if (cl.hasOption("m")) {
+            massString = cl.getOptionValue("m");
+            if(!trident) aMass = Integer.valueOf(massString);
+            System.out.println(massString);
+        }
+
+        if (cl.hasOption("n")) {
+            ninString = cl.getOptionValue("n");
+            nInFiles = Integer.valueOf(ninString);
+            System.out.println(ninString);
+        }
+          if (cl.hasOption("b")) {
+            nbegString = cl.getOptionValue("b");
+            nBegin = Integer.valueOf(nbegString);
+            System.out.println(nbegString);
+        }
+        
+         if (cl.hasOption("x")) {
+            sigxString = cl.getOptionValue("x");
+            sigx = Double.valueOf(sigxString);
+            System.out.println(sigxString);
+        }
+           if (cl.hasOption("y")) {
+            sigyString = cl.getOptionValue("y");
+            sigy = Double.valueOf(sigyString);
+            System.out.println(sigyString);
+        }
+
+        if (cl.hasOption("e")) {
+            ecmString = cl.getOptionValue("e");
+            _ecm = Double.valueOf(ninString);
+            System.out.println(ecmString);
+            eptString = convertDecimal(ecmString);
+        }
+
+        String filter = "all";
+        if (cl.hasOption("s")) {
+            _eventFilter = true;
+            filter = "selected";
+        }
+         if (cl.hasOption("u")) {
+            _isMuon = true;
+            System.out.println("Is a muonic decay");
+         }
+         if (cl.hasOption("c")) {
+            _custom = cl.getOptionValue("c");
+            _hasCustomString=true;
+            System.out.println("Using custom string = "+_custom);
+         }
+        
+          sigxString=convertMicron(sigx);
+          sigyString=convertMicron(sigy);
+
+//        String postfix = "_20ux200u_beamspot_gammactau_0cm.stdhep";
+//        String postfix = "_"+sigxString+"x"+sigyString+"_beamspot_gammactau_0cm.stdhep";
+            String postfix = "_"+sigxString+"x"+sigyString+"_beamspot_gammactau_0cm_30mrad.stdhep";
+//        String fDir="/nfs/slac/g/hps/mgraham/DarkPhoton/tvm/testrun/";
+//        String fileLabel = "ap2.2gev40mevsel";
+
+        //            String fDir="/nfs/slac/g/hps/mgraham/DarkPhoton/tvm/trident/full/";
+        //      String fileLabel = "full6.6gev";
+
+        //String fDir = "/nfs/slac/g/hps/mgraham/DarkPhoton/MadGraph/aMassEvents2pt2Ap100MeV/";
+        //String fileLabel = "ap2.2gev100mevall";
+        //String inLabel = "W2pt2GeV_Ap100MeV_";
+            
+        String fDir = "/nfs/slac/g/hps/mgraham/DarkPhoton/MadGraph/Events" + eptString + "Ap" + massString + "MeV/";       
+        String fileLabel = "ap" + ecmString + "gev" + massString + "mev" + filter;
+        String inLabel = "W" + eptString + "GeV_Ap" + massString + "MeV_";
+        if(trident){
+         fDir = "/nfs/slac/g/hps/mgraham/DarkPhoton/MadGraph/Events" + eptString +  massString + "/";       
+         fileLabel = "ap" + ecmString + "gev"+ massString  + filter;
+         inLabel = "W" + eptString + "GeV_" + massString + "_";
+        }
+        if(_isMuon){
+          fDir = "/nfs/slac/g/hps/mgraham/DarkPhoton/MadGraph/Events" + eptString + "Ap" + massString + "MeVMuon/";       
+         fileLabel = "ap" + ecmString + "gev" + massString + "mevMuon" + filter;
+          inLabel = "W" + eptString + "GeV_Ap" + massString + "MeVMuon_";
+        }
+        if(_hasCustomString){
+          fDir = "/nfs/slac/g/hps/mgraham/DarkPhoton/MadGraph/Events" + eptString + "Ap" + massString + "MeV"+_custom+"/";       
+         fileLabel = "ap" + ecmString + "gev" + massString + "mev"+_custom + filter;
+          inLabel = "W" + eptString + "GeV_Ap" + massString + "MeV"+_custom+"_";
+                  
+        }
+        String inPost = "_unweighted_events.lhe";
+
+
+        String outDir = "/nfs/slac/g/hps/mgraham/DarkPhoton/SignalEvents/";
+        
+        int nOutFile = nBegin;
+        System.out.println(fDir + fileLabel);
+        for (int i = nBegin; i < nBegin+nInFiles; i++) {
+            int fnum = i + 1;
+            String snum = "_" + fnum;
+            if (fnum < 10000) {
+                snum = "_0" + fnum;
+            }
+            if (fnum < 1000) {
+                snum = "_00" + fnum;
+            }
+            if (fnum < 100) {
+                snum = "_000" + fnum;
+            }
+            if (fnum < 10) {
+                snum = "_0000" + fnum;
+            }
+
+            String infile = "";
+            if (fileType.contains("dat")) {
+                infile = fDir + fileLabel + snum + ".dat";
+//                System.out.println(infile);
+            } else if (fileType.contains("lhe")) {
+                infile = fDir + inLabel + i + inPost;
+                System.out.println("Unzipping " + infile);
+                String cmd = "gunzip " + infile + ".gz";
+                Process p = Runtime.getRuntime().exec(cmd);
+                try {
+                    p.waitFor();
+                } catch (InterruptedException ex) {
+                    Logger.getLogger(ConvertToStdhep.class.getName()).log(Level.SEVERE, null, ex);
+                }
+            }
+            File f = new File(infile);
+            if (nread == -1 && f.exists()) {
+                nOutFile++;
+                String outfile = outDir + fileLabel + "_" + nOutFile + postfix;//replace .txt by .stdhep
+                System.out.println("==== processing " + infile + " into " + outfile + "  aP mass = " + aMass + "====");
+                openStdHepFile(outfile);
+            }
+            if (f.exists()) {
+                nread += process(infile);
+            }
+            if (fileType.contains("lhe")) {
+                String cmd = "gzip " + infile;
+                Process p = Runtime.getRuntime().exec(cmd);
+                try {
+                    p.waitFor();
+                } catch (InterruptedException ex) {
+                    Logger.getLogger(ConvertToStdhep.class.getName()).log(Level.SEVERE, null, ex);
+                }
+            }
+            if (nread > nmax) {
+                nread = -1;
+                closeStdHepFile();
+            }
+        }
+        closeStdHepFile();
+    }
+
+    @SuppressWarnings("static-access")
+    private static int lineCounter(StreamTokenizer tok) throws IOException {
+        int lines = 0;
+        while (tok.nextToken() != tok.TT_EOF) {
+            if (tok.ttype == tok.TT_EOL) {
+                lines++;
+            }
+            if (tok.ttype == tok.TT_WORD && tok.sval.startsWith("nev")) {
+                return lines;
+            }
+        }
+        //shouldn't get here...but maybe
+        return lines;
+    }
+
+    private static void openStdHepFile(String outfile) throws IOException {
+
+        int nwrit = (int) nmax;
+
+        sw = new StdhepWriter(outfile, "Imported Stdhep Events",
+                "From file", nwrit);
+        sw.setCompatibilityMode(false);
+    }
+
+    private static int getnevts(StreamTokenizer lctok) throws IOException {
+        int nevts = -1;
+        if (fileType.contains("dat")) {
+            return lineCounter(lctok);
+        } else if (fileType.contains("lhe")) {
+            while (nevts == -1) {
+                nevts = getNumberOfEvents(lctok);
+            }
+            return nevts;
+        }
+        return nevts;
+    }
+
+    private static int process(String infile) throws IOException {
+        Random generator = new Random();
+
+        FileReader lc = new FileReader(infile);
+        StreamTokenizer lctok = new StreamTokenizer(lc);
+        lctok.resetSyntax();
+        lctok.wordChars(33, 255);
+        lctok.parseNumbers();
+
+        lctok.whitespaceChars(0, ' ');
+        lctok.eolIsSignificant(true);
+        int nevts = getnevts(lctok);
+        lc.close();
+        System.out.println("Found " + nevts + " events");
+
+        FileReader fr = new FileReader(infile);
+
+        StreamTokenizer tok = new StreamTokenizer(fr);
+
+        tok.resetSyntax();
+        tok.wordChars(33, 255);
+        tok.parseNumbers();
+
+        tok.whitespaceChars(0, ' ');
+        tok.eolIsSignificant(true);
+
+//        System.out.println("Found " + nevts + "  events");
+        int nreq = (int) nevts;
+        int ngen = (int) nevts;
+        int nwrit = (int) nevts;
+        float ecm = (float) _ecm;
+        float xsec = (float) 99999997952.;
+        double rn1 = 12345321;
+        double rn2 = 66666666;
+//        StdhepBeginRun sb = new StdhepBeginRun(nreq, ngen, nwrit, ecm, xsec, rn1, rn2);
+//        sw.writeRecord(sb);
+
+
+        tok.resetSyntax();
+        tok.wordChars(33, 255);
+        tok.wordChars('0', '9');        // java.io.StreamTokenizer fails to parse
+        tok.wordChars('e', 'e');        // scientific notation like "1.09E-008".
+        tok.wordChars('E', 'E');        // The solution is to read and parse
+        tok.wordChars('.', '.');        // coordinates as "words".
+        tok.wordChars('+', '+');        // You run into trouble if the input file
+        tok.wordChars('-', '-');        // contains text with "e" or "E" which is
+        tok.whitespaceChars(0, ' ');
+        tok.eolIsSignificant(true);
+
+
+
+        double[] beam = {0, 0, 0, 0};
+        int nevhep = 0;
+        for (int icross = 0; icross < nwrit; icross++) {
+            Hep3Vector beamVecOrig =
+                    new BasicHep3Vector(sigx * generator.nextGaussian() + _xoff,
+                    sigy * generator.nextGaussian() + _yoff,
+                    sigz * generator.nextGaussian() + _zoff);
+            Hep3Vector beamVec = rot.rotated(beamVecOrig);
+            beam[0] = beamVec.x();
+            beam[1] = beamVec.y();
+            beam[2] = beamVec.z();
+
+            double tmpDecLen = 0;
+
+            if (fileType.contains("lhe")) {
+                writeLHEEvent(tok, beam, icross);
+            } else if (fileType.contains("dat")) {
+                writeDATEvent(tok, beam, tmpDecLen, icross);
+            }
+
+        }
+        fr.close();
+
+
+        return nwrit;
+
+
+    }
+
+    private static void closeStdHepFile() throws IOException {
+        if (sw != null) {
+            int nreqe = (int) nread;
+            int ngene = (int) nread;
+            int nwrite = (int) nread;
+            float ecme = (float) _ecm;
+            float xsece = (float) 99999997952.;
+            double rn1e = 12345321;
+            double rn2e = 66666666;
+            StdhepEndRun se = new StdhepEndRun(nreqe, ngene, nwrite, ecme, xsece, rn1e, rn2e);
+            sw.writeRecord(se);
+            sw.close();
+        }
+        System.out.println("Ok...done with closing!");
+    }
+
+    @SuppressWarnings("static-access")
+    private static List<Double> getNumbersInLine(StreamTokenizer tok) throws IOException {
+        List<Double> nums = new ArrayList<Double>();
+        while (tok.nextToken() != tok.TT_EOF) {
+            if (tok.ttype == tok.TT_EOL) {
+                break;
+            }
+            String tokVal = tok.sval;
+//            System.out.println(tokVal);
+            nums.add(Double.valueOf(tokVal).doubleValue());
+        }
+
+        return nums;
+    }
+
+    @SuppressWarnings("static-access")
+    private static int getNumberOfEvents(StreamTokenizer tok) throws IOException {
+        boolean fndNumber = false;
+        boolean fndOf = false;
+        boolean fndEvents = false;
+        int evts = -1;
+        while (tok.nextToken() != tok.TT_EOF) {
+//            System.out.println(tok.toString());
+            if (tok.ttype == tok.TT_EOL) {
+                break;
+            }
+            if (tok.ttype == tok.TT_WORD && tok.sval.contentEquals("Number")) {
+                //              System.out.println(tok.toString());
+                fndNumber = true;
+            }
+            if (tok.ttype == tok.TT_WORD && tok.sval.contentEquals("of")) {
+                fndOf = true;
+            }
+            if (tok.ttype == tok.TT_WORD && tok.sval.contentEquals("Events")) {
+                fndEvents = true;
+            }
+            if (tok.ttype == tok.TT_NUMBER && fndEvents && fndOf && fndNumber) {
+                evts = (int) tok.nval;
+            }
+        }
+        return evts;
+    }
+
+    @SuppressWarnings("static-access")
+    private static void getToNextEvent(StreamTokenizer tok) throws IOException {
+        while (tok.nextToken() != tok.TT_EOF) //            System.out.println(tok.toString());
+        {
+            if (tok.ttype == tok.TT_WORD && tok.sval.contentEquals("<event>")) {
+                tok.nextToken();//get to the EOL
+                return;
+            }
+        }
+    }
+
+    static private double expWeight(double x) {
+        return Math.exp(-x / _declength);
+    }
+
+    static private double expWeight(double x, double gamma) {
+        return Math.exp(-x / (gamma * _declength));
+    }
+
+    /*
+     * Old code written by Matt 
+    static private double findMaxWeight() {
+        Random generator = new Random();
+        int ntrials = 100000;
+        double maxlength = maxLen;
+        double maxWeight = 0;
+        for (int i = 0; i < ntrials; i++) {
+            double x = generator.nextDouble() * maxlength;
+            double wght = expWeight(x);
+            if (wght > maxWeight) {
+                maxWeight = wght;
+            }
+        }
+
+        return maxWeight;
+    }
+
+    static private double getDecayLength(double MaxWeight, double gamma) {
+        Random generator = new Random();
+        double maxlength = maxLen;
+        double dl = 0;
+        double draw = generator.nextDouble();
+        double tmpwght = 0;
+        while (tmpwght < draw) {
+            dl = generator.nextDouble() * maxlength;
+            tmpwght = expWeight(dl, gamma) / MaxWeight;
+        }
+        return dl;
+    }*/
+
+    static private double getDecayLength(double gamma){
+    	Random generator = new Random();
+    	double a = generator.nextDouble();
+    	double l = -gamma*_declength*Math.log(1-a);
+    	return l; 
+    }
+    
+    /*
+     * Old code written by Matt
+    static private double getDecayLength(double MaxWeight) {
+        Random generator = new Random();
+        double maxlength = maxLen;
+        double dl = 0;
+        double draw = generator.nextDouble();
+        double tmpwght = 0;
+        while (tmpwght < draw) {
+            dl = generator.nextDouble() * maxlength;
+            tmpwght = expWeight(dl) / MaxWeight;
+        }
+        return dl;
+    }*/
+
+    static private void writeDATEvent(StreamTokenizer tok, double[] beam, double decLen, int nevhep) throws IOException {
+        List<Double> vals = getNumbersInLine(tok);
+//            System.out.println(nums.toString());
+
+        if (vals.size() != 16) {
+            throw new RuntimeException("Unexpected entry for event:  size = " + vals.size());
+        }
+
+//            int nhep = nums.get(0).intValue();
+        int nhep = 4;  // two daughters of the A' and the recoil e-
+
+//            System.out.println("Number of particles for event " + nevhep + ": " + nhep);
+
+
+        int isthep[] = new int[nhep];
+        int idhep[] = new int[nhep];
+        int jmohep[] = new int[2 * nhep];
+        int jdahep[] = new int[2 * nhep];
+        double phep[] = new double[5 * nhep];
+        double vhep[] = new double[4 * nhep];
+        int i = 0;
+
+        double[] ApMom = {0, 0, 0};
+
+        for (int npart = 0; npart < nhep; npart++) {
+
+            isthep[i] = 1;
+            if (npart == 0) {
+                isthep[i] = 2;
+            }
+//                 if (npart == 0) isthep[i] = 0;
+//                 if (npart == 0) isthep[i] = 1;
+            idhep[i] = 622;
+            if (npart == 1) {
+                idhep[i] = -11;
+            }
+            if (npart == 2) {
+                idhep[i] = 11;
+            }
+            if (npart == 3) {
+                idhep[i] = 11;
+            }
+            jmohep[2 * i] = 0;
+            jmohep[2 * i + 1] = 0;
+            jdahep[2 * i] = 2;
+            jdahep[2 * i + 1] = 3;
+            if (npart == 1 || npart == 2) {
+                jmohep[2 * i] = 1;
+                jmohep[2 * i + 1] = 1;
+                jdahep[2 * i] = 0;
+                jdahep[2 * i + 1] = 0;
+            }
+            if (npart == 3) {
+                jmohep[2 * i] = 0;
+                jmohep[2 * i + 1] = 0;
+                jdahep[2 * i] = 0;
+                jdahep[2 * i + 1] = 0;
+            }
+            for (int j = 0; j < 4; j++) {
+                phep[5 * i + j] = vals.get(4 * i + j);
+            }
+            phep[5 * i + 4] = 0.51109989000E-03;
+            if (npart == 0 && !trident) {
+                phep[5 * i + 4] = aMass / 1000.0;
+                /*
+                 ApMom[0] = phep[5 * i + 2];
+                 ApMom[1] = phep[5 * i + 1];
+                 ApMom[2] = phep[5 * i + 0];
+                 * 
+                 */
+                ApMom[0] = phep[5 * i + 0];
+                ApMom[1] = phep[5 * i + 1];
+                ApMom[2] = phep[5 * i + 2];
+            }
+            for (int j = 0; j < 4; j++) {
+                vhep[4 * i + j] = beam[j];
+            }
+            //decay the A' and daughters daughters at _declength
+            if (!trident && (npart == 1 || npart == 2 || npart == 0)) {
+                if (!expDecay && !flatDecay) {
+                    vhep[4 * i + 0] = beam[0] + _declength;
+                } else {
+                    double totApMom = Math.sqrt(ApMom[0] * ApMom[0] + ApMom[1] * ApMom[1] + ApMom[2] * ApMom[2]);
+//                        System.out.println("Decay at : " + tmpDecLen);
+                    vhep[4 * i + 0] = beam[0] + decLen * ApMom[0] / totApMom;
+                    vhep[4 * i + 1] = beam[1] + decLen * ApMom[1] / totApMom;
+                    vhep[4 * i + 2] = beam[2] + decLen * ApMom[2] / totApMom;
+                }
+            }
+            double px = phep[5 * i + 0];
+            double pz = phep[5 * i + 2];
+//            phep[5 * i + 0] = pz;// these two are from back in the lcsim/jlab coordinate system days
+//            phep[5 * i + 2] = px;//
+            phep[5 * i + 0] = px;
+            phep[5 * i + 2] = pz;
+            //                                if (i == 0 || i == nhep - 1) {
+/*
+             System.out.println(i + " st: " + isthep[i] + " id: " + idhep[i] +
+             " jmo: " + jmohep[2 * i] + " " + jmohep[2 * i + 1] +
+             " jda: " + jdahep[2 * i] + " " + jdahep[2 * i + 1]);
+             System.out.println("p: " + phep[5 * i] + " " + phep[5 * i + 1] + " " +
+             phep[5 * i + 2] + " " + phep[5 * i + 3] + " " + phep[5 * i + 4]);
+             System.out.println("v: " + vhep[4 * i] + " " + vhep[4 * i + 1] + " " +
+             vhep[4 * i + 2] + " " + vhep[4 * i + 3]);
+             */
+            //                                }
+            i++;
+//                }
+        }
+        StdhepEvent ev = new StdhepEvent(nevhep, nhep, isthep, idhep, jmohep, jdahep, phep, vhep);
+        sw.writeRecord(ev);
+    }
+
+    static private void writeLHEEvent(StreamTokenizer tok, double[] beam, int nevhep) throws IOException {
+        Random generator = new Random();
+        getToNextEvent(tok);
+        List<Double> nums = getNumbersInLine(tok);
+
+        if (nums.size() != 6) {
+            throw new RuntimeException("Unexpected entry for number of particles");
+        }
+        int nhep = nums.get(0).intValue();
+//        System.out.println("Number of particles for event " + nevhep + ": " + nhep);
+
+        double decLen = 0;
+        double maxWght = 0;
+
+        /*
+         * No longer needed
+         * 
+        if (expDecay) {
+            maxWght = findMaxWeight();
+        }*/
+        int isthep[] = new int[nhep];
+        int idhep[] = new int[nhep];
+        int jmohep[] = new int[2 * nhep];
+        int jdahep[] = new int[2 * nhep];
+        double phep[] = new double[5 * nhep];
+        double vhep[] = new double[4 * nhep];
+        int i = 0;
+        int idhepTmp = 0;
+        double[] ApMom = {0, 0, 0};
+        double ApMass = 0;
+        double ApEnergy = 0;
+        boolean acceptEvent = false;
+        int nElePass = 0;
+        for (int npart = 0; npart < nhep; npart++) {
+            List<Double> vals = getNumbersInLine(tok);
+            if (vals.size() != 13) {
+                throw new RuntimeException("Unexpected entry for a particle");
+            }
+            if (vals.get(1).intValue() != 9) {//ignore the vertex for now
+//                int ip = vals.get(0).intValue();
+//                if (ip != i + 1) {
+//                    throw new RuntimeException("Particle numbering mismatch");
+//                }
+                isthep[i] = vals.get(1).intValue();
+
+                if (vals.get(1).intValue() == -1) {
+                    isthep[i] = 3;
+                }
+                idhepTmp = vals.get(0).intValue();
+//                System.out.println(idhepTmp);
+                idhep[i] = idhepTmp;
+                if (idhep[i] == 611) {
+                    idhep[i] = 11;
+                }
+                if (idhep[i] == -611) {
+                    idhep[i] = -11;
+                }
+                jmohep[2 * i] = vals.get(2).intValue();
+                jmohep[2 * i + 1] = vals.get(3).intValue();
+                jdahep[2 * i] = vals.get(4).intValue();
+                jdahep[2 * i + 1] = vals.get(5).intValue();
+                for (int j = 0; j < 5; j++) {
+                    phep[5 * i + j] = vals.get(j + 6);
+                }
+                Hep3Vector pRot = rotateToDetector(phep[5 * i + 0], phep[5 * i + 1], phep[5 * i + 2]);
+                phep[5 * i + 0] = pRot.x();
+                phep[5 * i + 1] = pRot.y();
+                phep[5 * i + 2] = pRot.z();
+                if (Math.abs(idhepTmp) == 622) {
+                    /*                  
+                     ApMom[0] = phep[5 * i + 2];
+                     ApMom[1] = phep[5 * i + 1];
+                     ApMom[2] = phep[5 * i + 0];
+                     */
+                    ApMom[0] = pRot.x();
+                    ApMom[1] = pRot.y();
+                    ApMom[2] = pRot.z();
+                    ApMass = vals.get(10);
+                    ApEnergy = vals.get(9);
+                }
+                for (int j = 0; j < 4; j++) {
+                    vhep[4 * i + j] = beam[j];
+                }
+
+                if (!trident && (Math.abs(idhepTmp) == 611 || Math.abs(idhepTmp) == 622)) {
+                    double gamma = ApEnergy / ApMass;
+                    if (expDecay) {
+                        decLen = getDecayLength(gamma);
+                    	// decLen = getDecayLength(maxWght, gamma);
+                    }
+                    if (flatDecay) {
+                        decLen = generator.nextDouble() * maxLen;
+                    }
+                    if (!expDecay && !flatDecay) {
+                        vhep[4 * i + 0] = beam[0] + decLen;
+                    } else {
+                        double totApMom = Math.sqrt(ApMom[0] * ApMom[0] + ApMom[1] * ApMom[1] + ApMom[2] * ApMom[2]);
+                        System.out.println("Decay at : " + decLen);
+                        vhep[4 * i + 0] = beam[0] + decLen * ApMom[0] / totApMom;
+                        vhep[4 * i + 1] = beam[1] + decLen * ApMom[1] / totApMom;
+                        vhep[4 * i + 2] = beam[2] + decLen * ApMom[2] / totApMom;
+                    }
+                }
+
+                if (Math.abs(idhepTmp) == 611 || Math.abs(idhepTmp) == 11) {
+                    if (inAcceptance(pRot)) {
+//                        acceptEvent = true;
+                        nElePass++;
+                    }
+                }
+
+                // swap x and z axes...
+                /*Don't do this anymore!  We do stuff in JLAB frame now...
+                 double px = phep[5 * i + 0];
+                 double pz = phep[5 * i + 2];
+                 phep[5 * i + 0] = pz;
+                 phep[5 * i + 2] = px;
+
+                 */
+                //                                if (i == 0 || i == nhep - 1) {
+//                    System.out.println(i + " st: " + isthep[i] + " id: " + idhep[i] +
+//                            " jmo: " + jmohep[2 * i] + " " + jmohep[2 * i + 1] +
+//                            " jda: " + jdahep[2 * i] + " " + jdahep[2 * i + 1]);
+//                    System.out.println("p: " + phep[5 * i] + " " + phep[5 * i + 1] + " " +
+//                            phep[5 * i + 2] + " " + phep[5 * i + 3] + " " + phep[5 * i + 4]);
+//                    System.out.println("v: " + vhep[4 * i] + " " + vhep[4 * i + 1] + " " +
+//                            vhep[4 * i + 2] + " " + vhep[4 * i + 3]);
+//                                }
+                i++;
+            }
+        }
+        StdhepEvent ev = new StdhepEvent(nevhep, nhep, isthep, idhep, jmohep, jdahep, phep, vhep);
+        if (nElePass >= _nEleRequired) {
+            acceptEvent = true;
+        }
+        if (acceptEvent) {
+            sw.writeRecord(ev);
+        } else {
+//            System.out.println("LHE Event failed acceptance cuts");
+        }
+    }
+
+    public static Hep3Vector rotateToDetector(double x, double y, double z) {
+        Hep3Vector vecOrig =
+                new BasicHep3Vector(x, y, z);
+        return rot.rotated(vecOrig);
+    }
+
+    public static String convertDecimal(String num) {
+        if (num.contains(".")) {
+            num = num.replace(".", "pt");
+        }
+        return num;
+    }
+    
+    public static String convertMicron(double num) {
+        double mic=num*1000.0;
+        String out=Integer.toString((int)mic);
+        return out+"u";
+    }
+
+    public static boolean inAcceptance(Hep3Vector ph) {
+        boolean ok = false;
+        double[] p = {ph.x(), ph.y(), ph.z()};
+        double ptot = Math.sqrt(p[0] * p[0] + p[1] * p[1] + p[2] * p[2]);
+
+        double sinThx = p[0] / Math.sqrt(p[0] * p[0] + p[2] * p[2]);
+        double sinThy = p[1] / Math.sqrt(p[1] * p[1] + p[2] * p[2]);
+        // for now, just use thetay (non-bend direction)
+//         System.out.println("px = "+p[0]+"; py = "+p[1]+"; pz = "+p[2]);
+//        System.out.println(sinThy+" "+sinThx+" "+ptot);
+
+        if (Math.abs(sinThy) > 0.012 && ptot > 0.1) {
+            ok = true;
+        }
+        return ok;
+    }
+}

java/trunk/util/src/main/java/org/hps/util
DatFileToStdhep.java added at 373
--- java/trunk/util/src/main/java/org/hps/util/DatFileToStdhep.java	                        (rev 0)
+++ java/trunk/util/src/main/java/org/hps/util/DatFileToStdhep.java	2014-03-26 04:40:56 UTC (rev 373)
@@ -0,0 +1,354 @@
+/*
+ * To change this template, choose Tools | Templates
+ * and open the template in the editor.
+ */
+package org.hps.util;
+
+/**
+ *
+ * @author richp
+ * modified by mbussonn to take arguments from command line
+ */
+import java.io.FileReader;
+import java.io.IOException;
+import java.io.StreamTokenizer;
+import java.util.ArrayList;
+import java.util.List;
+
+import hep.io.stdhep.StdhepBeginRun;
+import hep.io.stdhep.StdhepEndRun;
+import hep.io.stdhep.StdhepEvent;
+import hep.io.stdhep.StdhepWriter;
+import java.util.Random;
+
+public class DatFileToStdhep {
+
+    static boolean expDecay = false;
+    static boolean flatDecay = false;
+    static boolean trident = false;
+//    static double _declength = 0.0;//A' decay length (mm)
+     static double _declength = 0.0;//A' decay length (mm)
+    static double _xoff = 0.03;
+    static double _yoff = 0;
+    static double _zoff = 0;
+    static double sigx = 0.0;        // Luminous region size in x (mm)
+    static double sigy = 0.01;        // Luminous region size in y (mm)
+    static double sigz = 0.01;         // Luminous region size in z (mm)
+    static double aMass = 0.05;  //Aprime mass (GeV)
+    static double maxLen=200; // maximum decay length (mm)
+    static double _ecm=5.5; //GeV
+
+    /**
+     * @param args the command line arguments
+     * @throws IOException
+     */
+    public static void main(String[] args) throws IOException {
+//        int nfiles = 6;
+//        String[] files = {"ap5.5gev050mevsel.dat", "ap5.5gev100mevsel.dat", "ap5.5gev150mevsel.dat", "ap5.5gev200mevsel.dat", "ap5.5gev250mevsel.dat", "ap5.5gev300mevsel.dat"};
+//        double[] mass = {0.05, 0.1, 0.15, 0.2, 0.25, 0.3};
+
+        // int nfiles = 10;
+        //String[] files = {"ap5.5gev050mevall.dat", "ap5.5gev100mevall.dat", "ap5.5gev150mevall.dat", "ap5.5gev200mevall.dat", "ap5.5gev250mevall.dat", "ap5.5gev300mevall.dat", "ap5.5gev400mevall.dat", "ap5.5gev500mevall.dat", "ap5.5gev600mevall.dat", "ap5.5gev700mevall.dat"};
+        //double[] mass = {0.05, 0.1, 0.15, 0.2, 0.25, 0.3, 0.4, 0.5, 0.6, 0.7};
+
+//          int nfiles=10;
+//          String fileLabel="ap5.5gev100mevsel";
+//          double apMass=0.1;
+//          _ecm=5.5;
+          
+            int nfiles=40;
+          String fileLabel="ap2.2gev80mevsel";
+          double apMass=0.08;
+          _ecm=2.2;
+
+//           int nfiles=7;
+//        String fileLabel="ap3.3gev075mevsel";
+//        double apMass=0.075;
+
+
+//           int nfiles=1;
+//          String fileLabel="ap5.5gev200mevall";
+//          double apMass=0.2;
+//          _ecm=5.5;
+
+        for (int i = 0; i < nfiles; i++) {
+
+//            String file = "/a/surrey10/vol/vol0/g.hps/mgraham/DarkPhoton/SignalEvents/" + files[i];
+//            aMass = mass[i];
+            int fnum=i+1;
+            String file = "/a/surrey10/vol/vol0/g.hps/mgraham/DarkPhoton/SignalEvents/" +fileLabel+"_"+fnum+".dat";
+//            String file = "/a/surrey10/vol/vol0/g.hps/mgraham/DarkPhoton/SignalEvents/" +fileLabel+".dat";
+            aMass = apMass;
+
+             String infile = file;
+//        String outfile = file.substring(0, file.length() - 4) + "_100u_beamspot.stdhep";//replace .txt by .stdhep
+//          String outfile = file.substring(0, file.length() - 4) + "_100u_beamspot_5cm.stdhep";//replace .txt by .stdhep
+//            String outfile = file.substring(0, file.length() - 4) + "_10u_beamspot_0cm.stdhep";//replace .txt by .stdhep
+//            String outfile = file.substring(0, file.length() - 4) + "_10u_beamspot_FlatDecay.stdhep";//replace .txt by .stdhep
+            String outfile = file.substring(0, file.length() - 4) + "_10u_beamspot_gammactau_0cm.stdhep";//replace .txt by .stdhep
+            System.out.println("==== processing " + infile + " into " + outfile + "  aP mass = " + aMass + "====");
+            process(infile, outfile);
+        }
+    }
+
+    @SuppressWarnings("static-access")
+    private static int lineCounter(StreamTokenizer tok) throws IOException {
+        int lines = 0;
+        while (tok.nextToken() != tok.TT_EOF) {
+            if (tok.ttype == tok.TT_EOL)
+                lines++;
+            if (tok.ttype == tok.TT_WORD && tok.sval.startsWith("nev"))
+                return lines;
+        }
+        //shouldn't get here...but maybe
+        return lines;
+    }
+
+    private static void process(String infile, String outfile) throws IOException {
+        Random generator = new Random();
+
+        FileReader lc = new FileReader(infile);
+        StreamTokenizer lctok = new StreamTokenizer(lc);
+        lctok.resetSyntax();
+        lctok.wordChars(33, 255);
+        lctok.parseNumbers();
+
+        lctok.whitespaceChars(0, ' ');
+        lctok.eolIsSignificant(true);
+        int nevts = lineCounter(lctok);
+        lc.close();
+        FileReader fr = new FileReader(infile);
+
+        StreamTokenizer tok = new StreamTokenizer(fr);
+
+        tok.resetSyntax();
+        tok.wordChars(33, 255);
+        tok.parseNumbers();
+
+        tok.whitespaceChars(0, ' ');
+        tok.eolIsSignificant(true);
+
+        System.out.println("Found " + nevts + "  events");
+        int nreq = (int) nevts;
+        int ngen = (int) nevts;
+        int nwrit = (int) nevts;
+        float ecm = (float) _ecm;
+//        float ecm = (float) 3.3;
+        float xsec = (float) 99999997952.;
+        double rn1 = 12345321;
+        double rn2 = 66666666;
+        StdhepWriter sw = new StdhepWriter(outfile, "Imported Stdhep Events",
+                "From file " + infile, nwrit);
+        sw.setCompatibilityMode(false);
+        StdhepBeginRun sb = new StdhepBeginRun(nreq, ngen, nwrit, ecm, xsec, rn1, rn2);
+        sw.writeRecord(sb);
+
+
+        tok.resetSyntax();
+        tok.wordChars(33, 255);
+        tok.wordChars('0', '9');        // java.io.StreamTokenizer fails to parse
+        tok.wordChars('e', 'e');        // scientific notation like "1.09E-008".
+        tok.wordChars('E', 'E');        // The solution is to read and parse
+        tok.wordChars('.', '.');        // coordinates as "words".
+        tok.wordChars('+', '+');        // You run into trouble if the input file
+        tok.wordChars('-', '-');        // contains text with "e" or "E" which is
+        tok.whitespaceChars(0, ' ');
+        tok.eolIsSignificant(true);
+
+        double maxWght = 0;
+        if (expDecay) maxWght = findMaxWeight();
+
+        double[] beam = {0, 0, 0, 0};
+        int nevhep = 0;
+        for (int icross = 0; icross < nwrit; icross++) {
+            beam[0] = sigx * generator.nextGaussian() + _xoff;
+            beam[1] = sigy * generator.nextGaussian() + _yoff;
+            beam[2] = sigz * generator.nextGaussian() + _zoff;
+
+//            getToNextEvent(tok);
+            List<Double> vals = getNumbersInLine(tok);
+//            System.out.println(nums.toString());
+
+            if (vals.size() != 16)
+                throw new RuntimeException("Unexpected entry for event:  size = " + vals.size());
+
+            nevhep++;
+//            int nhep = nums.get(0).intValue();
+            int nhep = 4;  // two daughters of the A' and the recoil e-
+
+//            System.out.println("Number of particles for event " + nevhep + ": " + nhep);
+
+
+            int isthep[] = new int[nhep];
+            int idhep[] = new int[nhep];
+            int jmohep[] = new int[2 * nhep];
+            int jdahep[] = new int[2 * nhep];
+            double phep[] = new double[5 * nhep];
+            double vhep[] = new double[4 * nhep];
+            int i = 0;
+            double tmpDecLen = 0;
+            double[] ApMom = {0, 0, 0};
+            if (expDecay) tmpDecLen = getDecayLength(maxWght);
+            if (flatDecay) tmpDecLen =generator.nextDouble()*maxLen;
+            for (int npart = 0; npart < nhep; npart++) {
+                
+                isthep[i] = 1;
+                if (npart == 0) isthep[i] = 2;
+//                 if (npart == 0) isthep[i] = 0;
+//                 if (npart == 0) isthep[i] = 1;
+                idhep[i] = 622;
+                if (npart == 1) idhep[i] = -11;
+                if (npart == 2) idhep[i] = 11;
+                if (npart == 3) idhep[i] = 11;
+                jmohep[2 * i] = 0;
+                jmohep[2 * i + 1] = 0;
+                jdahep[2 * i] = 2;
+                jdahep[2 * i + 1] = 3;
+                if (npart == 1 || npart == 2) {
+                    jmohep[2 * i] = 1;
+                    jmohep[2 * i + 1] = 1;
+                    jdahep[2 * i] = 0;
+                    jdahep[2 * i + 1] = 0;
+                }
+                if (npart == 3) {
+                    jmohep[2 * i] = 0;
+                    jmohep[2 * i + 1] = 0;
+                    jdahep[2 * i] = 0;
+                    jdahep[2 * i + 1] = 0;
+                }
+                for (int j = 0; j < 4; j++)
+                    phep[5 * i + j] = vals.get(4 * i + j);
+                phep[5 * i + 4] = 0.51109989000E-03;
+                if (npart == 0 && !trident) {
+                    phep[5 * i + 4] = aMass;
+                    ApMom[0] = phep[5 * i + 2];
+                    ApMom[1] = phep[5 * i + 1];
+                    ApMom[2] = phep[5 * i + 0];
+                }
+                for (int j = 0; j < 4; j++)
+                    vhep[4 * i + j] = beam[j];
+                //decay the A' and daughters daughters at _declength
+                if (!trident && (npart == 1 || npart == 2 || npart == 0))
+                    if (!expDecay&&!flatDecay)
+                        vhep[4 * i + 0] = beam[0] + _declength;
+                    else {
+                        double totApMom = Math.sqrt(ApMom[0] * ApMom[0] + ApMom[1] * ApMom[1] + ApMom[2] * ApMom[2]);
+//                        System.out.println("Decay at : " + tmpDecLen);
+                        vhep[4 * i + 0] = beam[0] + tmpDecLen * ApMom[0] / totApMom;
+                        vhep[4 * i + 1] = beam[1] + tmpDecLen * ApMom[1] / totApMom;
+                        vhep[4 * i + 2] = beam[2] + tmpDecLen * ApMom[2] / totApMom;
+                    }
+                double px = phep[5 * i + 0];
+                double pz = phep[5 * i + 2];
+                phep[5 * i + 0] = pz;
+                phep[5 * i + 2] = px;
+                //                                if (i == 0 || i == nhep - 1) {
+/*
+                System.out.println(i + " st: " + isthep[i] + " id: " + idhep[i] +
+                " jmo: " + jmohep[2 * i] + " " + jmohep[2 * i + 1] +
+                " jda: " + jdahep[2 * i] + " " + jdahep[2 * i + 1]);
+                System.out.println("p: " + phep[5 * i] + " " + phep[5 * i + 1] + " " +
+                phep[5 * i + 2] + " " + phep[5 * i + 3] + " " + phep[5 * i + 4]);
+                System.out.println("v: " + vhep[4 * i] + " " + vhep[4 * i + 1] + " " +
+                vhep[4 * i + 2] + " " + vhep[4 * i + 3]);
+                 */
+                //                                }
+                i++;
+//                }
+            }
+            StdhepEvent ev = new StdhepEvent(nevhep, nhep, isthep, idhep, jmohep, jdahep, phep, vhep);
+            sw.writeRecord(ev);
+        }
+
+        int nreqe = (int) nevts;
+        int ngene = (int) nevts;
+        int nwrite = (int) nevts;
+        float ecme = (float) 6.0;
+        float xsece = (float) 99999997952.;
+        double rn1e = 12345321;
+        double rn2e = 66666666;
+        StdhepEndRun se = new StdhepEndRun(nreqe, ngene, nwrite, ecme, xsece, rn1e, rn2e);
+        sw.writeRecord(se);
+
+        sw.close();
+        fr.close();
+        System.out.println("Ok...done!");
+    }
+
+    @SuppressWarnings("static-access")
+    private static List<Double> getNumbersInLine(StreamTokenizer tok) throws IOException {
+        List<Double> nums = new ArrayList<Double>();
+        while (tok.nextToken() != tok.TT_EOF) {
+            if (tok.ttype == tok.TT_EOL)
+                break;
+            String tokVal = tok.sval;
+//            System.out.println(tokVal);
+            nums.add(Double.valueOf(tokVal).doubleValue());
+        }
+
+        return nums;
+    }
+
+    @SuppressWarnings("static-access")
+    private static double getNumberOfEvents(StreamTokenizer tok) throws IOException {
+        boolean fndNumber = false;
+        boolean fndOf = false;
+        boolean fndEvents = false;
+        double evts = -999;
+        while (tok.nextToken() != tok.TT_EOF) {
+//            System.out.println(tok.toString());
+            if (tok.ttype == tok.TT_EOL)
+                break;
+            if (tok.ttype == tok.TT_WORD && tok.sval.contentEquals("Number"))
+                fndNumber = true;
+            if (tok.ttype == tok.TT_WORD && tok.sval.contentEquals("of"))
+                fndOf = true;
+            if (tok.ttype == tok.TT_WORD && tok.sval.contentEquals("Events"))
+                fndEvents = true;
+            if (tok.ttype == tok.TT_NUMBER && fndEvents && fndOf && fndNumber)
+                evts = tok.nval;
+        }
+        return evts;
+    }
+
+    @SuppressWarnings("static-access")
+    private static void getToNextEvent(StreamTokenizer tok) throws IOException {
+        while (tok.nextToken() != tok.TT_EOF)
+            //            System.out.println(tok.toString());
+            if (tok.ttype == tok.TT_WORD && tok.sval.contentEquals("<event>")) {
+                tok.nextToken();//get to the EOL
+                return;
+            }
+    }
+
+    static private double expWeight(double x) {
+        return Math.exp(-x / _declength);
+    }
+
+    static private double findMaxWeight() {
+        Random generator = new Random();
+        int ntrials = 100000;
+        double maxlength = maxLen;
+        double maxWeight = 0;
+        for (int i = 0; i < ntrials; i++) {
+            double x = generator.nextDouble() * maxlength;
+            double wght = expWeight(x);
+            if (wght > maxWeight) maxWeight = wght;
+        }
+
+        return maxWeight;
+    }
+
+    static private double getDecayLength(double MaxWeight) {
+        Random generator = new Random();
+        double maxlength = maxLen;
+        double dl = 0;
+        double draw = generator.nextDouble();
+        double tmpwght = 0;
+        while (tmpwght < draw) {
+            dl = generator.nextDouble() * maxlength;
+            tmpwght = expWeight(dl) / MaxWeight;
+        }
+        return dl;
+    }
+}

java/trunk/util/src/main/java/org/hps/util
DatFileToStdhepTVM.java added at 373
--- java/trunk/util/src/main/java/org/hps/util/DatFileToStdhepTVM.java	                        (rev 0)
+++ java/trunk/util/src/main/java/org/hps/util/DatFileToStdhepTVM.java	2014-03-26 04:40:56 UTC (rev 373)
@@ -0,0 +1,357 @@
+/*
+ * To change this template, choose Tools | Templates
+ * and open the template in the editor.
+ */
+package org.hps.util;
+
+/**
+ *
+ * @author richp
+ * modified by mbussonn to take arguments from command line
+ */
+import java.io.FileReader;
+import java.io.IOException;
+import java.io.StreamTokenizer;
+import java.util.ArrayList;
+import java.util.List;
+
+import hep.io.stdhep.StdhepBeginRun;
+import hep.io.stdhep.StdhepEndRun;
+import hep.io.stdhep.StdhepEvent;
+import hep.io.stdhep.StdhepWriter;
+import java.io.File;
+import java.util.Random;
+
+public class DatFileToStdhepTVM {
+
+    static boolean expDecay = true;
+    static boolean flatDecay = false;
+    static boolean trident = false;
+    static double _declength = 0.0;//A' decay length (mm)
+    static double _xoff = 0.03;
+    static double _yoff = 0;
+    static double _zoff = 0;
+    static double sigx = 0.0;        // Luminous region size in x (mm)
+    static double sigy = 0.01;        // Luminous region size in y (mm)
+    static double sigz = 0.01;         // Luminous region size in z (mm)
+    static double aMass = 0.05;  //Aprime mass (GeV)
+    static double maxLen = 200; // maximum decay length (mm)
+    static double _ecm = 5.5; //GeV
+    static StdhepWriter sw;
+    static int nmax = 500000;
+
+    /**
+     * @param args the command line arguments
+     * @throws IOException
+     */
+    public static void main(String[] args) throws IOException {
+        int nInFiles = 10000;
+        double apMass = 0.08;
+        _ecm = 2.2;
+        _declength=0;//mm
+        sigx = 0.02;
+        sigy = 0.2;
+
+        String fileLabel = "ap6.6gev200mevsel";
+        String postfix = "_20u_beamspot_gammactau_5cm.stdhep";
+
+        int nread = -1;
+        int nOutFile = 0;
+        for (int i = 0; i < nInFiles; i++) {
+            int fnum = i + 1;
+            String snum = "_" + fnum;
+            if (fnum < 1000) snum = "_0" + fnum;
+            if (fnum < 100) snum = "_00" + fnum;
+            if (fnum < 10) snum = "_000" + fnum;
+
+            aMass = apMass;
+            String file = "/a/surrey10/vol/vol0/g.hps/mgraham/DarkPhoton/tvm/ap6.6gev/" + fileLabel + snum + ".dat";
+            String infile = file;
+            if (nread == -1) {
+                nOutFile++;
+                String outfile = "/a/surrey10/vol/vol0/g.hps/mgraham/DarkPhoton/SignalEvents/" + fileLabel + "_" + nOutFile + postfix;//replace .txt by .stdhep
+                System.out.println("==== processing " + infile + " into " + outfile + "  aP mass = " + aMass + "====");
+                openStdHepFile(outfile);
+            }
+            File f = new File(infile);
+            if (f.exists()) nread += process(infile);
+            if (nread > nmax) {
+                nread = -1;
+                closeStdHepFile();
+            }
+        }
+        closeStdHepFile();
+    }
+
+    @SuppressWarnings("static-access")
+    private static int lineCounter(StreamTokenizer tok) throws IOException {
+        int lines = 0;
+        while (tok.nextToken() != tok.TT_EOF) {
+            if (tok.ttype == tok.TT_EOL)
+                lines++;
+            if (tok.ttype == tok.TT_WORD && tok.sval.startsWith("nev"))
+                return lines;
+        }
+        //shouldn't get here...but maybe
+        return lines;
+    }
+
+    private static void openStdHepFile(String outfile) throws IOException {
+
+        int nwrit = (int) nmax;
+
+
+        sw = new StdhepWriter(outfile, "Imported Stdhep Events",
+                "From file", nwrit);
+        sw.setCompatibilityMode(false);
+    }
+
+    private static int process(String infile) throws IOException {
+        Random generator = new Random();
+
+        FileReader lc = new FileReader(infile);
+        StreamTokenizer lctok = new StreamTokenizer(lc);
+        lctok.resetSyntax();
+        lctok.wordChars(33, 255);
+        lctok.parseNumbers();
+
+        lctok.whitespaceChars(0, ' ');
+        lctok.eolIsSignificant(true);
+        int nevts = lineCounter(lctok);
+        lc.close();
+        FileReader fr = new FileReader(infile);
+
+        StreamTokenizer tok = new StreamTokenizer(fr);
+
+        tok.resetSyntax();
+        tok.wordChars(33, 255);
+        tok.parseNumbers();
+
+        tok.whitespaceChars(0, ' ');
+        tok.eolIsSignificant(true);
+
+        System.out.println("Found " + nevts + "  events");
+        int nreq = (int) nevts;
+        int ngen = (int) nevts;
+        int nwrit = (int) nevts;
+        float ecm = (float) _ecm;
+        float xsec = (float) 99999997952.;
+        double rn1 = 12345321;
+        double rn2 = 66666666;
+        StdhepBeginRun sb = new StdhepBeginRun(nreq, ngen, nwrit, ecm, xsec, rn1, rn2);
+        sw.writeRecord(sb);
+
+
+        tok.resetSyntax();
+        tok.wordChars(33, 255);
+        tok.wordChars('0', '9');        // java.io.StreamTokenizer fails to parse
+        tok.wordChars('e', 'e');        // scientific notation like "1.09E-008".
+        tok.wordChars('E', 'E');        // The solution is to read and parse
+        tok.wordChars('.', '.');        // coordinates as "words".
+        tok.wordChars('+', '+');        // You run into trouble if the input file
+        tok.wordChars('-', '-');        // contains text with "e" or "E" which is
+        tok.whitespaceChars(0, ' ');
+        tok.eolIsSignificant(true);
+
+        double maxWght = 0;
+        if (expDecay) maxWght = findMaxWeight();
+
+        double[] beam = {0, 0, 0, 0};
+        int nevhep = 0;
+        for (int icross = 0; icross < nwrit; icross++) {
+            beam[0] = sigx * generator.nextGaussian() + _xoff;
+            beam[1] = sigy * generator.nextGaussian() + _yoff;
+            beam[2] = sigz * generator.nextGaussian() + _zoff;
+
+//            getToNextEvent(tok);
+            List<Double> vals = getNumbersInLine(tok);
+//            System.out.println(nums.toString());
+
+            if (vals.size() != 16)
+                throw new RuntimeException("Unexpected entry for event:  size = " + vals.size());
+
+            nevhep++;
+//            int nhep = nums.get(0).intValue();
+            int nhep = 4;  // two daughters of the A' and the recoil e-
+
+//            System.out.println("Number of particles for event " + nevhep + ": " + nhep);
+
+
+            int isthep[] = new int[nhep];
+            int idhep[] = new int[nhep];
+            int jmohep[] = new int[2 * nhep];
+            int jdahep[] = new int[2 * nhep];
+            double phep[] = new double[5 * nhep];
+            double vhep[] = new double[4 * nhep];
+            int i = 0;
+            double tmpDecLen = 0;
+            double[] ApMom = {0, 0, 0};
+            if (expDecay) tmpDecLen = getDecayLength(maxWght);
+            if (flatDecay) tmpDecLen = generator.nextDouble() * maxLen;
+            for (int npart = 0; npart < nhep; npart++) {
+
+                isthep[i] = 1;
+                if (npart == 0) isthep[i] = 2;
+//                 if (npart == 0) isthep[i] = 0;
+//                 if (npart == 0) isthep[i] = 1;
+                idhep[i] = 622;
+                if (npart == 1) idhep[i] = -11;
+                if (npart == 2) idhep[i] = 11;
+                if (npart == 3) idhep[i] = 11;
+                jmohep[2 * i] = 0;
+                jmohep[2 * i + 1] = 0;
+                jdahep[2 * i] = 2;
+                jdahep[2 * i + 1] = 3;
+                if (npart == 1 || npart == 2) {
+                    jmohep[2 * i] = 1;
+                    jmohep[2 * i + 1] = 1;
+                    jdahep[2 * i] = 0;
+                    jdahep[2 * i + 1] = 0;
+                }
+                if (npart == 3) {
+                    jmohep[2 * i] = 0;
+                    jmohep[2 * i + 1] = 0;
+                    jdahep[2 * i] = 0;
+                    jdahep[2 * i + 1] = 0;
+                }
+                for (int j = 0; j < 4; j++)
+                    phep[5 * i + j] = vals.get(4 * i + j);
+                phep[5 * i + 4] = 0.51109989000E-03;
+                if (npart == 0 && !trident) {
+                    phep[5 * i + 4] = aMass;
+                    ApMom[0] = phep[5 * i + 2];
+                    ApMom[1] = phep[5 * i + 1];
+                    ApMom[2] = phep[5 * i + 0];
+                }
+                for (int j = 0; j < 4; j++)
+                    vhep[4 * i + j] = beam[j];
+                //decay the A' and daughters daughters at _declength
+                if (!trident && (npart == 1 || npart == 2 || npart == 0))
+                    if (!expDecay && !flatDecay)
+                        vhep[4 * i + 0] = beam[0] + _declength;
+                    else {
+                        double totApMom = Math.sqrt(ApMom[0] * ApMom[0] + ApMom[1] * ApMom[1] + ApMom[2] * ApMom[2]);
+//                        System.out.println("Decay at : " + tmpDecLen);
+                        vhep[4 * i + 0] = beam[0] + tmpDecLen * ApMom[0] / totApMom;
+                        vhep[4 * i + 1] = beam[1] + tmpDecLen * ApMom[1] / totApMom;
+                        vhep[4 * i + 2] = beam[2] + tmpDecLen * ApMom[2] / totApMom;
+                    }
+                double px = phep[5 * i + 0];
+                double pz = phep[5 * i + 2];
+                phep[5 * i + 0] = pz;
+                phep[5 * i + 2] = px;
+                //                                if (i == 0 || i == nhep - 1) {
+/*
+                System.out.println(i + " st: " + isthep[i] + " id: " + idhep[i] +
+                " jmo: " + jmohep[2 * i] + " " + jmohep[2 * i + 1] +
+                " jda: " + jdahep[2 * i] + " " + jdahep[2 * i + 1]);
+                System.out.println("p: " + phep[5 * i] + " " + phep[5 * i + 1] + " " +
+                phep[5 * i + 2] + " " + phep[5 * i + 3] + " " + phep[5 * i + 4]);
+                System.out.println("v: " + vhep[4 * i] + " " + vhep[4 * i + 1] + " " +
+                vhep[4 * i + 2] + " " + vhep[4 * i + 3]);
+                 */
+                //                                }
+                i++;
+//                }
+            }
+            StdhepEvent ev = new StdhepEvent(nevhep, nhep, isthep, idhep, jmohep, jdahep, phep, vhep);
+            sw.writeRecord(ev);
+        }
+        fr.close();
+        int nreqe = (int) nevts;
+        int ngene = (int) nevts;
+        int nwrite = (int) nevts;
+        float ecme = (float) 6.0;
+        float xsece = (float) 99999997952.;
+        double rn1e = 12345321;
+        double rn2e = 66666666;
+        StdhepEndRun se = new StdhepEndRun(nreqe, ngene, nwrite, ecme, xsece, rn1e, rn2e);
+        sw.writeRecord(se);
+        return nwrit;
+
+
+    }
+
+    private static void closeStdHepFile() throws IOException {
+
+        sw.close();
+        System.out.println("Ok...done!");
+    }
+
+    @SuppressWarnings("static-access")
+    private static List<Double> getNumbersInLine(StreamTokenizer tok) throws IOException {
+        List<Double> nums = new ArrayList<Double>();
+        while (tok.nextToken() != tok.TT_EOF) {
+            if (tok.ttype == tok.TT_EOL)
+                break;
+            String tokVal = tok.sval;
+//            System.out.println(tokVal);
+            nums.add(Double.valueOf(tokVal).doubleValue());
+        }
+
+        return nums;
+    }
+
+    @SuppressWarnings("static-access")
+    private static double getNumberOfEvents(StreamTokenizer tok) throws IOException {
+        boolean fndNumber = false;
+        boolean fndOf = false;
+        boolean fndEvents = false;
+        double evts = -999;
+        while (tok.nextToken() != tok.TT_EOF) {
+//            System.out.println(tok.toString());
+            if (tok.ttype == tok.TT_EOL)
+                break;
+            if (tok.ttype == tok.TT_WORD && tok.sval.contentEquals("Number"))
+                fndNumber = true;
+            if (tok.ttype == tok.TT_WORD && tok.sval.contentEquals("of"))
+                fndOf = true;
+            if (tok.ttype == tok.TT_WORD && tok.sval.contentEquals("Events"))
+                fndEvents = true;
+            if (tok.ttype == tok.TT_NUMBER && fndEvents && fndOf && fndNumber)
+                evts = tok.nval;
+        }
+        return evts;
+    }
+
+    @SuppressWarnings("static-access")
+    private static void getToNextEvent(StreamTokenizer tok) throws IOException {
+        while (tok.nextToken() != tok.TT_EOF)
+            //            System.out.println(tok.toString());
+            if (tok.ttype == tok.TT_WORD && tok.sval.contentEquals("<event>")) {
+                tok.nextToken();//get to the EOL
+                return;
+            }
+    }
+
+    static private double expWeight(double x) {
+        return Math.exp(-x / _declength);
+    }
+
+    static private double findMaxWeight() {
+        Random generator = new Random();
+        int ntrials = 100000;
+        double maxlength = maxLen;
+        double maxWeight = 0;
+        for (int i = 0; i < ntrials; i++) {
+            double x = generator.nextDouble() * maxlength;
+            double wght = expWeight(x);
+            if (wght > maxWeight) maxWeight = wght;
+        }
+
+        return maxWeight;
+    }
+
+    static private double getDecayLength(double MaxWeight) {
+        Random generator = new Random();
+        double maxlength = maxLen;
+        double dl = 0;
+        double draw = generator.nextDouble();
+        double tmpwght = 0;
+        while (tmpwght < draw) {
+            dl = generator.nextDouble() * maxlength;
+            tmpwght = expWeight(dl) / MaxWeight;
+        }
+        return dl;
+    }
+}

java/trunk/util/src/main/java/org/hps/util
DumpLHEEventsToASCII.java added at 373
--- java/trunk/util/src/main/java/org/hps/util/DumpLHEEventsToASCII.java	                        (rev 0)
+++ java/trunk/util/src/main/java/org/hps/util/DumpLHEEventsToASCII.java	2014-03-26 04:40:56 UTC (rev 373)
@@ -0,0 +1,586 @@
+/*
+ * To change this template, choose Tools | Templates
+ * and open the template in the editor.
+ */
+package org.hps.util;
+
+/**
+
+ @author Mathew Thomas Graham <[log in to unmask]> $Id:
+ ConvertToStdhep.java,v 1.9 2013/02/27 18:50:10 mgraham Exp $
+ */
+import java.io.FileReader;
+import java.io.IOException;
+import java.io.StreamTokenizer;
+import java.util.ArrayList;
+import java.util.List;
+
+import hep.physics.vec.BasicHep3Vector;
+import hep.physics.vec.Hep3Vector;
+import java.io.*;
+import java.util.Random;
+import java.util.logging.Level;
+import java.util.logging.Logger;
+import org.apache.commons.cli.CommandLine;
+import org.apache.commons.cli.CommandLineParser;
+import org.apache.commons.cli.Option;
+import org.apache.commons.cli.Options;
+import org.apache.commons.cli.ParseException;
+import org.apache.commons.cli.PosixParser;
+import org.lcsim.detector.IRotation3D;
+import org.lcsim.detector.RotationGeant;
+
+public class DumpLHEEventsToASCII {
+
+    static FileWriter fw;
+    static PrintWriter pw;
+    static boolean expDecay = false;  //set a ctau decay length
+    static boolean flatDecay = false; //decay uniformily in some range
+    static boolean trident = false;  //are these trident events or A' signal events
+    static double _declength = 0.0;   //A' decay length  (mm)
+    static double _xoff = 0.0;   //set the x,y,z origin offsets...
+    static double _yoff = 0.0;
+    static double _zoff = 0.03;
+    static double aMass = 99;  //Aprime mass (MeV)
+    static double sigx = 0.2;        // Luminous region size in x (mm)
+    static double sigy = 0.02;        // Luminous region size in y (mm)
+    static double sigz = 0.0;         // Luminous region size in z (mm)
+//beam is positioned so that at first beam direction is in z, then rotated to correct orientation    
+    static double rotx = 0.00;        // Rotation of beam about X
+    static double roty = 0.03;        // Rotation of beam about Y
+    static double rotz = 0.00;         // Rotation of beam about Z
+    static double maxLen = 200; // maximum decay length (mm)
+    static double _ecm = 6.6; //GeV
+    static int nInFiles = 10000;  //number of input files
+    static int nBegin = 0;
+    static int nmax = 500000;  //maximum number of events to write to 1 stdhep file (new one opens if n>nmax)
+    static String fileType = "lhe";
+    static IRotation3D rot = new RotationGeant(rotx, roty, rotz);
+//        static String fileType="dat";
+    static int nread = -1;  // a running total of number of events read/written to stdhep files
+    static boolean _eventFilter = false;
+    static boolean _isMuon = false;
+//    static int _nEleRequired = 2;
+    static int _nEleRequired = 0;
+
+    private static Options createCommandLineOptions() {
+        Options options = new Options();
+
+        options.addOption(new Option("m", true, "A' Mass (MeV)"));
+        options.addOption(new Option("e", true, "Beam Energy (GeV)"));
+        options.addOption(new Option("n", true, "Number of files to run."));
+        options.addOption(new Option("b", true, "First file number."));
+        options.addOption(new Option("x", true, "Beam sigma in x"));
+        options.addOption(new Option("y", true, "Beam sigma in y"));
+        options.addOption(new Option("s", false, "Filter Events"));
+        options.addOption(new Option("u", false, "Is muonic decay?"));
+        options.addOption(new Option("t", false, "Is Trident?"));
+
+        return options;
+    }
+
+    /**
+     @param args the command line arguments
+     @throws IOException
+     */
+    public static void main(String[] args) throws IOException {
+
+
+        // Set up command line parsing.
+        Options options = createCommandLineOptions();
+
+        CommandLineParser parser = new PosixParser();
+
+        // Parse command line arguments.
+        CommandLine cl = null;
+        try {
+            cl = parser.parse(options, args);
+            System.out.println("Trying parser");
+        } catch (ParseException e) {
+            throw new RuntimeException("Problem parsing command line options.", e);
+        }
+        String massString = String.valueOf(aMass);
+        String ninString = String.valueOf(nInFiles);
+        String nbegString = String.valueOf(nBegin);
+        String ecmString = String.valueOf(_ecm);
+        String eptString = String.valueOf(_ecm);
+        String sigxString = String.valueOf(sigx);
+        String sigyString = String.valueOf(sigy);
+        eptString = convertDecimal(eptString);
+        if (cl.hasOption("t")) {
+	    trident=true;
+        }
+        if (cl.hasOption("m")) {
+            massString = cl.getOptionValue("m");
+            if (!trident)
+                aMass = Integer.valueOf(massString);
+            System.out.println(massString);
+        }
+
+        if (cl.hasOption("n")) {
+            ninString = cl.getOptionValue("n");
+            nInFiles = Integer.valueOf(ninString);
+            System.out.println(ninString);
+        }
+        if (cl.hasOption("b")) {
+            nbegString = cl.getOptionValue("b");
+            nBegin = Integer.valueOf(nbegString);
+            System.out.println(nbegString);
+        }
+
+        if (cl.hasOption("x")) {
+            sigxString = cl.getOptionValue("x");
+            sigx = Double.valueOf(sigxString);
+            System.out.println(sigxString);
+        }
+        if (cl.hasOption("y")) {
+            sigyString = cl.getOptionValue("y");
+            sigy = Double.valueOf(sigyString);
+            System.out.println(sigyString);
+        }
+
+        if (cl.hasOption("e")) {
+            ecmString = cl.getOptionValue("e");
+            _ecm = Double.valueOf(ninString);
+            System.out.println(ecmString);
+            eptString = convertDecimal(ecmString);
+        }
+
+        String filter = "all";
+        if (cl.hasOption("s")) {
+            _eventFilter = true;
+            filter = "selected";
+        }
+        if (cl.hasOption("u")) {
+            _isMuon = true;
+        }
+        sigxString = convertMicron(sigx);
+        sigyString = convertMicron(sigy);
+
+//        String postfix = "_20ux200u_beamspot_gammactau_0cm.stdhep";
+//        String postfix = "_"+sigxString+"x"+sigyString+"_beamspot_gammactau_0cm.stdhep";
+        String postfix = ".dat";
+//        String fDir="/nfs/slac/g/hps/mgraham/DarkPhoton/tvm/testrun/";
+//        String fileLabel = "ap2.2gev40mevsel";
+
+        //            String fDir="/nfs/slac/g/hps/mgraham/DarkPhoton/tvm/trident/full/";
+        //      String fileLabel = "full6.6gev";
+
+        //String fDir = "/nfs/slac/g/hps/mgraham/DarkPhoton/MadGraph/aMassEvents2pt2Ap100MeV/";
+        //String fileLabel = "ap2.2gev100mevall";
+        //String inLabel = "W2pt2GeV_Ap100MeV_";
+
+        String fDir = "/nfs/slac/g/hps/mgraham/DarkPhoton/MadGraph/Events" + eptString + "Ap" + massString + "MeV/";
+        String fileLabel = "ap" + ecmString + "gev" + massString + "mev" + filter;
+        String inLabel = "W" + eptString + "GeV_Ap" + massString + "MeV_";
+        if (trident) {
+            fDir = "/nfs/slac/g/hps/mgraham/DarkPhoton/MadGraph/Events" + eptString + massString + "/";
+            fileLabel = "ap" + ecmString + massString + filter;
+            inLabel = "W" + eptString + "GeV_" + massString + "_";
+        }
+        if (_isMuon) {
+            fDir = "/nfs/slac/g/hps/mgraham/DarkPhoton/MadGraph/Events" + eptString + "Ap" + massString + "MeVMuon/";
+            fileLabel = "ap" + ecmString + "gev" + massString + "mevMuon" + filter;
+            inLabel = "W" + eptString + "GeV_Ap" + massString + "MeVMuon_";
+        }
+        String inPost = "_unweighted_events.lhe";
+
+
+        String outDir = "/nfs/slac/g/hps/mgraham/DarkPhoton/GeneratedEvents/";
+
+        int nOutFile = nBegin;
+        System.out.println(fDir + fileLabel);
+        for (int i = nBegin; i < nBegin + nInFiles; i++) {
+            int fnum = i + 1;
+            String snum = "_" + fnum;
+            if (fnum < 10000) {
+                snum = "_0" + fnum;
+            }
+            if (fnum < 1000) {
+                snum = "_00" + fnum;
+            }
+            if (fnum < 100) {
+                snum = "_000" + fnum;
+            }
+            if (fnum < 10) {
+                snum = "_0000" + fnum;
+            }
+
+            String infile = "";
+            if (fileType.contains("dat")) {
+                infile = fDir + fileLabel + snum + ".dat";
+//                System.out.println(infile);
+            } else if (fileType.contains("lhe")) {
+                infile = fDir + inLabel + i + inPost;
+                System.out.println("Unzipping " + infile);
+                String cmd = "gunzip " + infile + ".gz";
+                Process p = Runtime.getRuntime().exec(cmd);
+                try {
+                    p.waitFor();
+                } catch (InterruptedException ex) {
+                    Logger.getLogger(DumpLHEEventsToASCII.class.getName()).log(Level.SEVERE, null, ex);
+                }
+            }
+            File f = new File(infile);
+            if (nread == -1 && f.exists()) {
+                nOutFile++;
+                String outfile = outDir + fileLabel + "_" + nOutFile + postfix;//replace .txt by .stdhep
+                System.out.println("==== processing " + infile + " into " + outfile + "  aP mass = " + aMass + "====");
+                openASCIIFile(outfile);
+            }
+            if (f.exists()) {
+                nread += process(infile);
+            }
+            if (fileType.contains("lhe")) {
+                String cmd = "gzip " + infile;
+                Process p = Runtime.getRuntime().exec(cmd);
+                try {
+                    p.waitFor();
+                } catch (InterruptedException ex) {
+                    Logger.getLogger(DumpLHEEventsToASCII.class.getName()).log(Level.SEVERE, null, ex);
+                }
+            }
+            if (nread > nmax) {
+                nread = -1;
+                closeASCIIFile();
+            }
+        }
+        closeASCIIFile();
+    }
+
+    @SuppressWarnings("static-access")
+    private static int lineCounter(StreamTokenizer tok) throws IOException {
+        int lines = 0;
+        while (tok.nextToken() != tok.TT_EOF) {
+            if (tok.ttype == tok.TT_EOL) {
+                lines++;
+            }
+            if (tok.ttype == tok.TT_WORD && tok.sval.startsWith("nev")) {
+                return lines;
+            }
+        }
+        //shouldn't get here...but maybe
+        return lines;
+    }
+
+    private static int getnevts(StreamTokenizer lctok) throws IOException {
+        int nevts = -1;
+        if (fileType.contains("dat")) {
+            return lineCounter(lctok);
+        } else if (fileType.contains("lhe")) {
+            while (nevts == -1) {
+                nevts = getNumberOfEvents(lctok);
+            }
+            return nevts;
+        }
+        return nevts;
+    }
+
+    private static int process(String infile) throws IOException {
+        Random generator = new Random();
+
+        FileReader lc = new FileReader(infile);
+        StreamTokenizer lctok = new StreamTokenizer(lc);
+        lctok.resetSyntax();
+        lctok.wordChars(33, 255);
+        lctok.parseNumbers();
+
+        lctok.whitespaceChars(0, ' ');
+        lctok.eolIsSignificant(true);
+        int nevts = getnevts(lctok);
+        lc.close();
+        System.out.println("Found " + nevts + " events");
+
+        FileReader fr = new FileReader(infile);
+
+        StreamTokenizer tok = new StreamTokenizer(fr);
+
+        tok.resetSyntax();
+        tok.wordChars(33, 255);
+        tok.parseNumbers();
+
+        tok.whitespaceChars(0, ' ');
+        tok.eolIsSignificant(true);
+
+//        System.out.println("Found " + nevts + "  events");
+        int nreq = (int) nevts;
+        int ngen = (int) nevts;
+        int nwrit = (int) nevts;
+        float ecm = (float) _ecm;
+        float xsec = (float) 99999997952.;
+        double rn1 = 12345321;
+        double rn2 = 66666666;
+//        StdhepBeginRun sb = new StdhepBeginRun(nreq, ngen, nwrit, ecm, xsec, rn1, rn2);
+//        sw.writeRecord(sb);
+
+
+        tok.resetSyntax();
+        tok.wordChars(33, 255);
+        tok.wordChars('0', '9');        // java.io.StreamTokenizer fails to parse
+        tok.wordChars('e', 'e');        // scientific notation like "1.09E-008".
+        tok.wordChars('E', 'E');        // The solution is to read and parse
+        tok.wordChars('.', '.');        // coordinates as "words".
+        tok.wordChars('+', '+');        // You run into trouble if the input file
+        tok.wordChars('-', '-');        // contains text with "e" or "E" which is
+        tok.whitespaceChars(0, ' ');
+        tok.eolIsSignificant(true);
+
+
+
+        double[] beam = {0, 0, 0, 0};
+        int nevhep = 0;
+        for (int icross = 0; icross < nwrit; icross++) {
+            Hep3Vector beamVecOrig =
+                    new BasicHep3Vector(sigx * generator.nextGaussian() + _xoff,
+                    sigy * generator.nextGaussian() + _yoff,
+                    sigz * generator.nextGaussian() + _zoff);
+            Hep3Vector beamVec = rot.rotated(beamVecOrig);
+            beam[0] = beamVec.x();
+            beam[1] = beamVec.y();
+            beam[2] = beamVec.z();
+
+            double tmpDecLen = 0;
+
+            if (fileType.contains("lhe")) {
+                writeLHEEvent(tok, beam, icross);
+            }
+
+        }
+        fr.close();
+
+
+        return nwrit;
+
+
+    }
+
+    private static void openASCIIFile(String outfile) throws IOException {
+        try {
+            fw = new FileWriter(outfile);
+            pw = new PrintWriter(fw);
+        } catch (IOException ex) {
+            Logger.getLogger(DumpLHEEventsToASCII.class.getName()).log(Level.SEVERE, null, ex);
+        }
+
+        System.out.println("Ok...opened " + outfile);
+    }
+
+    private static void closeASCIIFile() throws IOException {
+        pw.close();
+        try {
+            fw.close();
+        } catch (IOException ex) {
+            Logger.getLogger(DumpLHEEventsToASCII.class.getName()).log(Level.SEVERE, null, ex);
+        }
+        System.out.println("Ok...done with closing!");
+    }
+
+    @SuppressWarnings("static-access")
+    private static List<Double> getNumbersInLine(StreamTokenizer tok) throws IOException {
+        List<Double> nums = new ArrayList<Double>();
+        while (tok.nextToken() != tok.TT_EOF) {
+            if (tok.ttype == tok.TT_EOL) {
+                break;
+            }
+            String tokVal = tok.sval;
+//            System.out.println(tokVal);
+            nums.add(Double.valueOf(tokVal).doubleValue());
+        }
+
+        return nums;
+    }
+
+    @SuppressWarnings("static-access")
+    private static int getNumberOfEvents(StreamTokenizer tok) throws IOException {
+        boolean fndNumber = false;
+        boolean fndOf = false;
+        boolean fndEvents = false;
+        int evts = -1;
+        while (tok.nextToken() != tok.TT_EOF) {
+//            System.out.println(tok.toString());
+            if (tok.ttype == tok.TT_EOL) {
+                break;
+            }
+            if (tok.ttype == tok.TT_WORD && tok.sval.contentEquals("Number")) {
+                //              System.out.println(tok.toString());
+                fndNumber = true;
+            }
+            if (tok.ttype == tok.TT_WORD && tok.sval.contentEquals("of")) {
+                fndOf = true;
+            }
+            if (tok.ttype == tok.TT_WORD && tok.sval.contentEquals("Events")) {
+                fndEvents = true;
+            }
+            if (tok.ttype == tok.TT_NUMBER && fndEvents && fndOf && fndNumber) {
+                evts = (int) tok.nval;
+            }
+        }
+        return evts;
+    }
+
+    @SuppressWarnings("static-access")
+    private static void getToNextEvent(StreamTokenizer tok) throws IOException {
+        while (tok.nextToken() != tok.TT_EOF) //            System.out.println(tok.toString());
+        {
+            if (tok.ttype == tok.TT_WORD && tok.sval.contentEquals("<event>")) {
+                tok.nextToken();//get to the EOL
+                return;
+            }
+        }
+    }
+
+    static private double expWeight(double x) {
+        return Math.exp(-x / _declength);
+    }
+
+    static private double expWeight(double x, double gamma) {
+        return Math.exp(-x / (gamma * _declength));
+    }
+
+    /*
+     Old code written by Matt static private double findMaxWeight() { Random
+     generator = new Random(); int ntrials = 100000; double maxlength = maxLen;
+     double maxWeight = 0; for (int i = 0; i < ntrials; i++) { double x =
+     generator.nextDouble() * maxlength; double wght = expWeight(x); if (wght >
+     maxWeight) { maxWeight = wght; } }
+
+     return maxWeight; }
+
+     static private double getDecayLength(double MaxWeight, double gamma) {
+     Random generator = new Random(); double maxlength = maxLen; double dl = 0;
+     double draw = generator.nextDouble(); double tmpwght = 0; while (tmpwght <
+     draw) { dl = generator.nextDouble() * maxlength; tmpwght = expWeight(dl,
+     gamma) / MaxWeight; } return dl; }
+     */
+    static private double getDecayLength(double gamma) {
+        Random generator = new Random();
+        double a = generator.nextDouble();
+        double l = -gamma * _declength * Math.log(1 - a);
+        return l;
+    }
+
+    /*
+     Old code written by Matt static private double getDecayLength(double
+     MaxWeight) { Random generator = new Random(); double maxlength = maxLen;
+     double dl = 0; double draw = generator.nextDouble(); double tmpwght = 0;
+     while (tmpwght < draw) { dl = generator.nextDouble() * maxlength; tmpwght =
+     expWeight(dl) / MaxWeight; } return dl; }
+     */
+    static private void writeLHEEvent(StreamTokenizer tok, double[] beam, int nevhep) throws IOException {
+        Random generator = new Random();
+        getToNextEvent(tok);
+        List<Double> nums = getNumbersInLine(tok);
+
+        if (nums.size() != 6) {
+            throw new RuntimeException("Unexpected entry for number of particles");
+        }
+        int nhep = nums.get(0).intValue();
+	//        System.out.println("Number of particles for event " + nevhep + ": " + nhep);
+
+        double decLen = 0;
+        double maxWght = 0;
+
+        /*
+         No longer needed
+
+         if (expDecay) { maxWght = findMaxWeight(); }
+         */
+
+        double phepEle[] = new double[5];
+        double phepPos[] = new double[5];
+        double phepRec[] = new double[5];
+        double phepNuc[] = new double[5];
+
+
+        int idhepTmp = 0;
+        double[] ApMom = {0, 0, 0};
+        double ApMass = 0;
+        double ApEnergy = 0;
+        boolean acceptEvent = false;
+        int nElePass = 0;
+        for (int npart = 0; npart < nhep; npart++) {
+            List<Double> vals = getNumbersInLine(tok);
+            if (vals.size() != 13) {
+                throw new RuntimeException("Unexpected entry for a particle");
+            }
+	    idhepTmp = vals.get(0).intValue();
+//	    System.out.println(idhepTmp);
+            if (vals.get(1).intValue() == 9) {//apparently, vertices aren't counted in nhep
+		nhep++;
+	    }
+
+            if (vals.get(1).intValue() == 1) {//ignore initial  & intermediate state particles
+		//		System.out.println("Ok...good"+idhepTmp);
+
+
+
+                for (int j = 0; j < 5; j++) {
+                    if (idhepTmp == 611)
+                        phepEle[j] = vals.get(j + 6);                    
+                    if (idhepTmp == -611)
+                        phepPos[j] = vals.get(j + 6);
+                    if (idhepTmp == 11)
+                        phepRec[j] = vals.get(j + 6);
+                    if (idhepTmp == -623){
+                        phepNuc[j] = vals.get(j + 6);
+			//			System.out.println("Found the recoil nucleus");
+		    }
+                }
+
+
+
+
+
+            }
+
+
+
+        }
+        //StdhepEvent ev = new StdhepEvent(nevhep, nhep, isthep, idhep, jmohep, jdahep, phep, vhep);
+
+        pw.format("%d ", nevhep);
+        pw.format("%5.5f %5.5f %5.5f %5.5f %5.5f ", phepEle[0], phepEle[1], phepEle[2], phepEle[3], phepEle[4]);
+        pw.format("%5.5f %5.5f %5.5f %5.5f %5.5f ", phepPos[0], phepPos[1], phepPos[2], phepPos[3], phepPos[4]);
+        pw.format("%5.5f %5.5f %5.5f %5.5f %5.5f ", phepRec[0], phepRec[1], phepRec[2], phepRec[3], phepRec[4]);
+        pw.format("%5.5f %5.5f %5.5f %5.5f %5.5f ", phepNuc[0], phepNuc[1], phepNuc[2], phepNuc[3], phepNuc[4]);
+
+        pw.println();
+
+    }
+
+    public static Hep3Vector rotateToDetector(double x, double y, double z) {
+        Hep3Vector vecOrig =
+                new BasicHep3Vector(x, y, z);
+        return rot.rotated(vecOrig);
+    }
+
+    public static String convertDecimal(String num) {
+        if (num.contains(".")) {
+            num = num.replace(".", "pt");
+        }
+        return num;
+    }
+
+    public static String convertMicron(double num) {
+        double mic = num * 1000.0;
+        String out = Integer.toString((int) mic);
+        return out + "u";
+    }
+
+    public static boolean inAcceptance(Hep3Vector ph) {
+        boolean ok = false;
+        double[] p = {ph.x(), ph.y(), ph.z()};
+        double ptot = Math.sqrt(p[0] * p[0] + p[1] * p[1] + p[2] * p[2]);
+
+        double sinThx = p[0] / Math.sqrt(p[0] * p[0] + p[2] * p[2]);
+        double sinThy = p[1] / Math.sqrt(p[1] * p[1] + p[2] * p[2]);
+        // for now, just use thetay (non-bend direction)
+//         System.out.println("px = "+p[0]+"; py = "+p[1]+"; pz = "+p[2]);
+//        System.out.println(sinThy+" "+sinThx+" "+ptot);
+
+        if (Math.abs(sinThy) > 0.012 && ptot > 0.1) {
+            ok = true;
+        }
+        return ok;
+    }
+}

java/trunk/util/src/main/java/org/hps/util
GenerateBunches.java added at 373
--- java/trunk/util/src/main/java/org/hps/util/GenerateBunches.java	                        (rev 0)
+++ java/trunk/util/src/main/java/org/hps/util/GenerateBunches.java	2014-03-26 04:40:56 UTC (rev 373)
@@ -0,0 +1,160 @@
+/*
+ * Simple java program to generate single particles of fixed momentum uniformly
+ * distributed in pseudorapidity.
+ */
+package org.hps.util;
+
+import hep.io.stdhep.StdhepEvent;
+import hep.io.stdhep.StdhepWriter;
+import hep.physics.particle.properties.ParticleType;
+import hep.physics.particle.properties.ParticlePropertyManager;
+import java.io.IOException;
+import java.util.Random;
+
+/**
+ *
+ * @author mgraham
+ */
+public class GenerateBunches {
+
+    //  Edit the following declarations to set desired paramters
+    static String dir = "/a/surrey10/vol/vol0/g.hps/mgraham/DarkPhoton/SingleParticleSamples/5.5GeV-100u/";        // Output directory
+// static String dir = "/a/surrey10/vol/vol0/g.hps/mgraham/DarkPhoton/SingleParticleSamples/";
+    static String file = "electron_5.5GeV_7.5ns_100na_400bunches_";  // File name
+//    static String file = "electron_6GeV_25ns_10bunches_";  // File name
+
+    static int nevt = 400;            // Number of events/file to generate
+    static int nfiles = 400;             //number of files to generate
+    static int start=400;
+
+    static double current = 100;  //nanoamps
+    static double bunchtime=7.5;  //nanoseconds
+
+    static double convert=6.25;   //electrons/ns in a nanoamp
+    static String ext = "stdhep";      // File extension
+
+//    static int nele = 15000;            // Number of elecrons in a bunch (25ns)
+    static int nele = (int) Math.round(current*bunchtime*convert);            // Number of elecrons in a bunch (7.5ns)
+    
+    
+    static int pdgid = 11;             // PDG code for particle to generate (11=electrons, 13 = muons, 211 = pions)
+    static boolean flipsign = false;    // Set to false if you only want a specific charge
+    static double pmin = 5.5;         // Minimum particle momentum at 90 degrees (GeV)
+    static double pmax = 5.5;         // Maximum particle momentum at 90 degrees (GeV)
+    static boolean pfixed = true;      // Set to false for fixed pt
+    static double sigx = 0.1;        // Luminous region size in x (mm)
+    static double sigy = 0.1;        // Luminous region size in y (mm)
+    static double sigz = 0.001;         // Luminous region size in z (mm)
+    static double sigpx = 0.001;        // momentum spread
+    static double sigpy = 0.001;        // 
+    static double sigpz = 0.001;         //
+    static double xoff = -1.0;         // offset of the beam in the xdir (so that it goes through the target)
+
+    public static void main(String[] args) throws IOException {
+
+        //  Instantiate the random number generators
+        Random generator = new Random();
+        generator.setSeed(start);
+        //  Decode the pdgid
+        ParticleType pid = ParticlePropertyManager.getParticlePropertyProvider().get(pdgid);
+        String pname = pid.getName();
+
+
+        for (int n = start; n < start+nfiles; n++) {
+            //  Open the output file
+            String fname = dir + file + n + "." + ext;
+            StdhepWriter sw = new StdhepWriter(fname, "Bunch",
+                    "Bunch", nevt);
+            sw.setCompatibilityMode(false);
+
+            //  Loop over the events
+            for (int icross = 0; icross < nevt; icross++) {
+
+                //  Generate the momentum at 90 degrees
+
+
+                //  Fill the event record variables
+                //  Set the event number
+                int nevhep = icross;
+
+                //  Set the number of particles in the event
+                int nhep = nele;
+                int isthep[] = new int[nhep];
+                int idhep[] = new int[nhep];
+                int jmohep[] = new int[2 * nhep];
+                int jdahep[] = new int[2 * nhep];
+                double phep[] = new double[5 * nhep];
+                double vhep[] = new double[4 * nhep];
+                for (int jj = 0; jj < nhep; jj++) {
+
+                    double ptot = pmin + (pmax - pmin) * generator.nextDouble();
+                    double px = sigpx * generator.nextGaussian();
+                    double py = sigpy * generator.nextGaussian();
+                    //  Generate the pseudorapidity and calculate the polar angle
+
+                    //  Figure out the transverse momentum and mass
+
+                    double pt = Math.sqrt(px * px + py * py);
+                    double theta = Math.asin(pt / ptot);
+                    double m = pid.getMass();
+
+                    //  Generate the aximutha angle
+                    double phi = 2. * Math.PI * generator.nextDouble();
+
+                    //  Generate the IP
+                    double x0 = sigx * generator.nextGaussian();
+                    double y0 = sigy * generator.nextGaussian();
+                    double z0 = sigz * generator.nextGaussian();
+                    double t0 = 0.;
+                    //  Set the status code of the particle
+
+                    isthep[jj] = 1;
+
+                    //  Set the particle ID of the particle
+
+                    idhep[jj] = pdgid;
+                    if (flipsign && generator.nextDouble() > 0.5)
+                        idhep[jj] = -pdgid;
+
+                    //  Set the mother and daughter pointers
+
+                    for (int i = 0; i < 2; i++) {
+                        jmohep[2 * jj + i] = 0;
+                        jdahep[2 * jj + i] = 0;
+                    }
+
+                    //  Set the momentum/energy/mass
+
+//            phep[0] = pt * Math.cos(phi);
+//            phep[1] = pt * Math.sin(phi);
+//            phep[2] = pt / Math.tan(theta);
+// swap x and z
+                    phep[5 * jj + 2] = pt * Math.cos(phi);
+                    phep[5 * jj + 1] = pt * Math.sin(phi);
+                    phep[5 * jj + 0] = pt / Math.tan(theta);
+                    double p2 = pt * pt + phep[2] * phep[2];
+                    phep[5 * jj + 3] = Math.sqrt(p2 + m * m);
+                    phep[5 * jj + 4] = m;
+
+                    //  Set the particle origin
+
+//            vhep[0] = x0;
+//            vhep[1] = y0;
+//           vhep[2] = z0;
+                    vhep[4 * jj + 2] = x0;
+                    vhep[4 * jj + 1] = y0;
+                    vhep[4 * jj + 0] = z0 + xoff;
+                    vhep[4 * jj + 3] = t0;
+                }
+                //  Create an event record
+                StdhepEvent ev = new StdhepEvent(nevhep, nhep, isthep, idhep, jmohep, jdahep, phep, vhep);
+
+                //  Write out the event record
+                sw.writeRecord(ev);
+            }
+
+            //  Done with generating particles - close the file
+            sw.close();
+        }
+    }
+}
\ No newline at end of file

java/trunk/util/src/main/java/org/hps/util
GenerateSingleParticles.java added at 373
--- java/trunk/util/src/main/java/org/hps/util/GenerateSingleParticles.java	                        (rev 0)
+++ java/trunk/util/src/main/java/org/hps/util/GenerateSingleParticles.java	2014-03-26 04:40:56 UTC (rev 373)
@@ -0,0 +1,142 @@
+/*
+ * Simple java program to generate single particles of fixed momentum uniformly
+ * distributed in pseudorapidity.
+ */
+package org.hps.util;
+
+import hep.io.stdhep.StdhepEvent;
+import hep.io.stdhep.StdhepWriter;
+import hep.physics.particle.properties.ParticleType;
+import hep.physics.particle.properties.ParticlePropertyManager;
+import java.io.IOException;
+import java.util.Random;
+
+/**
+ *
+ * @author partridge
+ */
+public class GenerateSingleParticles {
+
+    //  Edit the following declarations to set desired paramters
+    static String dir = "/nfs/sulky21/g.ec.u12/users/mgraham/DarkPhoton/SingleParticleSamples/";        // Output directory
+//    static String file = "electron_6GeV_10spills";  // File name
+    static String file = "electron_6GeV_10000_XDir";  // File name
+    static String ext = "stdhep";      // File extension
+//    static int nevt = 15000*10;            // Number of events to generate
+    static int nevt = 10000;            // Number of events to generate
+    static int pdgid = 11;             // PDG code for particle to generate (11=electrons, 13 = muons, 211 = pions)
+    static boolean flipsign = false;    // Set to false if you only want a specific charge
+    static double pmin = 6.;         // Minimum particle momentum at 90 degrees (GeV)
+    static double pmax = 1.;         // Maximum particle momentum at 90 degrees (GeV)
+    static boolean pfixed = true;      // Set to false for fixed pt
+    static double sigx = 0.001;        // Luminous region size in x (mm)
+    static double sigy = 0.001;        // Luminous region size in y (mm)
+    static double sigz = 0.001;         // Luminous region size in z (mm)
+
+    /*
+    static double sigpx = 0.001;        // momentum spread
+    static double sigpy = 0.001;        // 
+    static double sigpz = 0.001;         //
+*/
+    static double sigpx = 0.6;        // momentum spread
+    static double sigpy = 0.6;        //
+    static double sigpz = 0.001;         //
+    public static void main(String[] args) throws IOException {
+
+        //  Instantiate the random number generators
+        Random generator = new Random();
+
+        //  Decode the pdgid
+        ParticleType pid = ParticlePropertyManager.getParticlePropertyProvider().get(pdgid);
+        String pname = pid.getName();
+
+        //  Open the output file
+        String fname = dir + file + "." + ext;
+        StdhepWriter sw = new StdhepWriter(fname, "Single particles",
+                "Single particles", nevt);
+        sw.setCompatibilityMode(false);
+
+        //  Loop over the events
+        for (int icross = 0; icross < nevt; icross++) {
+
+            //  Generate the momentum at 90 degrees
+            double ptot = pmin + (pmax - pmin) * generator.nextDouble();
+            double px = sigpx * generator.nextGaussian();
+            double py = sigpy * generator.nextGaussian();
+            //  Generate the pseudorapidity and calculate the polar angle
+
+            //  Figure out the transverse momentum and mass
+
+            double pt = Math.sqrt(px * px + py * py);
+            double theta = Math.asin(pt / ptot);
+            double m = pid.getMass();
+
+            //  Generate the aximutha angle
+            double phi = 2. * Math.PI * generator.nextDouble();
+
+            //  Generate the IP
+            double x0 = sigx * generator.nextGaussian();
+            double y0 = sigy * generator.nextGaussian();
+            double z0 = sigz * generator.nextGaussian();
+            double t0 = 0.;
+
+            //  Fill the event record variables
+            //  Set the event number
+            int nevhep = icross;
+
+            //  Set the number of particles in the event
+            int nhep = 1;
+
+            //  Set the status code of the particle
+            int isthep[] = new int[2];
+            isthep[0] = 1;
+
+            //  Set the particle ID of the particle
+            int idhep[] = new int[2];
+            idhep[0] = pdgid;
+            if (flipsign && generator.nextDouble() > 0.5) {
+                idhep[0] = -pdgid;
+            }
+
+            //  Set the mother and daughter pointers
+            int jmohep[] = new int[2];
+            int jdahep[] = new int[2];
+            for (int i = 0; i < 2; i++) {
+                jmohep[i] = 0;
+                jdahep[i] = 0;
+            }
+
+            //  Set the momentum/energy/mass
+            double phep[] = new double[5];
+//            phep[0] = pt * Math.cos(phi);
+//            phep[1] = pt * Math.sin(phi);
+//            phep[2] = pt / Math.tan(theta);
+// swap x and z
+            phep[2] = pt * Math.cos(phi);
+            phep[1] = pt * Math.sin(phi);
+            phep[0] = pt / Math.tan(theta);
+            double p2 = pt * pt + phep[2] * phep[2];
+            phep[3] = Math.sqrt(p2 + m * m);
+            phep[4] = m;
+
+            //  Set the particle origin
+            double vhep[] = new double[4];
+//            vhep[0] = x0;
+//            vhep[1] = y0;
+//           vhep[2] = z0;
+            vhep[2] = x0;
+            vhep[1] = y0;
+            vhep[0] = z0;
+            vhep[3] = t0;
+
+            //  Create an event record
+            StdhepEvent ev = new StdhepEvent(nevhep, nhep, isthep, idhep, jmohep, jdahep, phep, vhep);
+
+            //  Write out the event record
+            sw.writeRecord(ev);
+        }
+
+        //  Done with generating particles - close the file
+        sw.close();
+    }
+}
\ No newline at end of file

java/trunk/util/src/main/java/org/hps/util
LCIOFilterDriver.java added at 373
--- java/trunk/util/src/main/java/org/hps/util/LCIOFilterDriver.java	                        (rev 0)
+++ java/trunk/util/src/main/java/org/hps/util/LCIOFilterDriver.java	2014-03-26 04:40:56 UTC (rev 373)
@@ -0,0 +1,92 @@
+/*
+ * To change this template, choose Tools | Templates
+ * and open the template in the editor.
+ */
+package org.hps.util;
+import java.io.IOException;
+import org.lcsim.event.EventHeader;
+import org.lcsim.event.Track;
+import org.lcsim.util.Driver;
+import org.lcsim.lcio.LCIOWriter;
+
+/**
+ *
+ * @author phansson
+ */
+public abstract class LCIOFilterDriver extends Driver {
+    protected String outputFile;
+    protected LCIOWriter writer;
+    protected boolean debug = false;
+    
+    public LCIOFilterDriver() {        
+    }
+    
+    public void setOutputFilePath(String output) {
+        this.outputFile = output;
+    }
+    
+    public void setDebug(boolean debug) {
+        this.debug = debug;
+    }
+    
+    abstract boolean eventFilter(EventHeader event);
+
+    private void setupWriter() {
+        // Cleanup existing writer.
+        if (writer != null) {
+            try {
+                writer.flush();
+                writer.close();
+                writer = null;
+            } catch (IOException x) {
+                System.err.println(x.getMessage());
+            }
+        }
+
+        // Setup new writer.
+        try {
+            writer = new LCIOWriter(outputFile);
+        } catch (IOException x) {
+            throw new RuntimeException("Error creating writer", x);
+        }
+
+
+        try {
+            writer.reOpen();
+        } catch (IOException x) {
+            throw new RuntimeException("Error rewinding LCIO file", x);
+        }
+    }
+
+    protected void startOfData() {
+        setupWriter();
+    }
+
+    protected void endOfData() {
+        try {
+            writer.close();
+        } catch (IOException x) {
+            throw new RuntimeException("Error rewinding LCIO file", x);
+        }
+    }
+
+    protected void process(EventHeader event) {
+
+        if(eventFilter(event)) {
+            try {
+                writer.write(event);
+            } catch (IOException x) {
+                throw new RuntimeException("Error writing LCIO file", x);
+            }
+        }
+    }
+
+    protected void suspend() {
+        try {
+            writer.flush();
+        } catch (IOException x) {
+            throw new RuntimeException("Error flushing LCIO file", x);
+        }
+    }
+    
+}

java/trunk/util/src/main/java/org/hps/util
LHEFileToStdhep.java added at 373
--- java/trunk/util/src/main/java/org/hps/util/LHEFileToStdhep.java	                        (rev 0)
+++ java/trunk/util/src/main/java/org/hps/util/LHEFileToStdhep.java	2014-03-26 04:40:56 UTC (rev 373)
@@ -0,0 +1,260 @@
+/*
+ * To change this template, choose Tools | Templates
+ * and open the template in the editor.
+ */
+package org.hps.util;
+
+/**
+ *
+ * @author richp
+ * modified by mbussonn to take arguments from command line
+ */
+import java.io.FileReader;
+import java.io.IOException;
+import java.io.StreamTokenizer;
+import java.util.ArrayList;
+import java.util.List;
+
+import hep.io.stdhep.StdhepBeginRun;
+import hep.io.stdhep.StdhepEndRun;
+import hep.io.stdhep.StdhepEvent;
+import hep.io.stdhep.StdhepWriter;
+import java.util.Random;
+
+public class LHEFileToStdhep {
+
+    /**
+     * @param args the command line arguments
+     * @throws IOException
+     */
+    public static void main(String[] args) throws IOException {
+//        String file = args[0];
+        String file = "/nfs/sulky21/g.ec.u12/users/mgraham/DarkPhoton/SignalEvents/6W_0.200_A_unweighted_events.lhe";
+//        String file = "/nfs/sulky21/g.ec.u12/users/mgraham/DarkPhoton/SignalEvents/6GeV_W_0.500_unweighted_events.lhe";
+        String infile = file;
+        String outfile = file.substring(0, file.length() - 4) + "_100u_beamspot.stdhep";//replace .txt by .stdhep
+        System.out.println("==== processing " + infile + " into " + outfile + " ====");
+        process(infile, outfile);
+    }
+
+    private static void process(String infile, String outfile) throws IOException {
+//        try {
+        Random generator = new Random();
+        double _xoff = 0.03;
+        double _yoff = 0;
+        double _zoff = 0;
+        double sigx = 0.0;        // Luminous region size in x (mm)
+        double sigy = 0.1;        // Luminous region size in y (mm)
+        double sigz = 0.1;         // Luminous region size in z (mm)
+
+        FileReader fr = new FileReader(infile);
+        StreamTokenizer tok = new StreamTokenizer(fr);
+        tok.resetSyntax();
+        tok.wordChars(33, 255);
+        tok.parseNumbers();
+
+        tok.whitespaceChars(0, ' ');
+        tok.eolIsSignificant(true);
+        double nevts = -999;
+        while (nevts == -999) {
+            nevts = getNumberOfEvents(tok);
+        }
+        System.out.println("Found " + nevts + "events");
+//        return;
+
+        //List<Double> beg = getNumbersInLine(tok);
+        //if (beg.size() != 7) {
+        //throw new RuntimeException("Unexpected entry in begin run record");
+        //}
+        int nreq = (int) nevts;
+        int ngen = (int) nevts;
+        int nwrit = (int) nevts;
+        float ecm = (float) 6.0;
+        float xsec = (float) 99999997952.;
+        double rn1 = 12345321;
+        double rn2 = 66666666;
+        StdhepWriter sw = new StdhepWriter(outfile, "Imported Stdhep Events",
+                "From file " + infile, nwrit);
+        sw.setCompatibilityMode(false);
+        StdhepBeginRun sb = new StdhepBeginRun(nreq, ngen, nwrit, ecm, xsec, rn1, rn2);
+        sw.writeRecord(sb);
+
+
+        tok.resetSyntax();
+        tok.wordChars(33, 255);
+        tok.wordChars('0', '9');        // java.io.StreamTokenizer fails to parse
+        tok.wordChars('e', 'e');        // scientific notation like "1.09E-008".
+        tok.wordChars('E', 'E');        // The solution is to read and parse
+        tok.wordChars('.', '.');        // coordinates as "words".
+        tok.wordChars('+', '+');        // You run into trouble if the input file
+        tok.wordChars('-', '-');        // contains text with "e" or "E" which is
+        tok.whitespaceChars(0, ' ');
+        tok.eolIsSignificant(true);
+
+
+        double[] beam = {0, 0, 0, 0};
+        int nevhep = 0;
+        for (int icross = 0; icross < nwrit; icross++) {
+            beam[0] = sigx * generator.nextGaussian() + _xoff;
+            beam[1] = sigy * generator.nextGaussian() + _yoff;
+            beam[2] = sigz * generator.nextGaussian() + _zoff;
+            getToNextEvent(tok);
+            List<Double> nums = getNumbersInLine(tok);
+//            System.out.println(nums.toString());
+
+            if (nums.size() != 6) {
+                throw new RuntimeException("Unexpected entry for number of particles");
+            }
+            nevhep++;
+            int nhep = nums.get(0).intValue();
+            System.out.println("Number of particles for event " + nevhep + ": " + nhep);
+
+
+            int isthep[] = new int[nhep];
+            int idhep[] = new int[nhep];
+            int jmohep[] = new int[2 * nhep];
+            int jdahep[] = new int[2 * nhep];
+            double phep[] = new double[5 * nhep];
+            double vhep[] = new double[4 * nhep];
+            int i = 0;
+            for (int npart = 0; npart < nhep; npart++) {
+                List<Double> vals = getNumbersInLine(tok);
+                if (vals.size() != 13) {
+                    throw new RuntimeException("Unexpected entry for a particle");
+                }
+                if (vals.get(1).intValue() != 9) {//ignore the vertex for now
+
+//                int ip = vals.get(0).intValue();
+//                if (ip != i + 1) {
+//                    throw new RuntimeException("Particle numbering mismatch");
+//                }
+                    isthep[i] = vals.get(1).intValue();
+
+                    if (vals.get(1).intValue() == -1) {
+                        isthep[i] = 3;
+                    }
+
+
+                    idhep[i] = vals.get(0).intValue();
+                    if (idhep[i] == 611) {
+                        idhep[i] = 11;
+                    }
+                    if (idhep[i] == -611) {
+                        idhep[i] = -11;
+                    }
+                    jmohep[2 * i] = vals.get(2).intValue();
+                    jmohep[2 * i + 1] = vals.get(3).intValue();
+                    jdahep[2 * i] = vals.get(4).intValue();
+                    jdahep[2 * i + 1] = vals.get(5).intValue();
+                    for (int j = 0; j < 5; j++) {
+                        phep[5 * i + j] = vals.get(j + 6);
+                    }
+
+                    for (int j = 0; j < 4; j++) {
+//                    vhep[4 * i + j] = vals.get(j + 12);
+
+                        vhep[4 * i + j] = beam[j];
+
+                    }
+                    // swap x and z axes...
+                    double px = phep[5 * i + 0];
+                    double pz = phep[5 * i + 2];
+                    phep[5 * i + 0] = pz;
+                    phep[5 * i + 2] = px;
+                    //                                if (i == 0 || i == nhep - 1) {
+                    System.out.println(i + " st: " + isthep[i] + " id: " + idhep[i] +
+                            " jmo: " + jmohep[2 * i] + " " + jmohep[2 * i + 1] +
+                            " jda: " + jdahep[2 * i] + " " + jdahep[2 * i + 1]);
+                    System.out.println("p: " + phep[5 * i] + " " + phep[5 * i + 1] + " " +
+                            phep[5 * i + 2] + " " + phep[5 * i + 3] + " " + phep[5 * i + 4]);
+                    System.out.println("v: " + vhep[4 * i] + " " + vhep[4 * i + 1] + " " +
+                            vhep[4 * i + 2] + " " + vhep[4 * i + 3]);
+//                                }
+                    i++;
+                }
+            }
+            StdhepEvent ev = new StdhepEvent(nevhep, nhep, isthep, idhep, jmohep, jdahep, phep, vhep);
+            sw.writeRecord(ev);
+        }
+//        List<Double> end = getNumbersInLine(tok);
+//        if (end.size() != 7) {
+//            throw new RuntimeException("Unexpected entry in begin run record");
+//        }
+
+        int nreqe = (int) nevts;
+        int ngene = (int) nevts;
+        int nwrite = (int) nevts;
+        float ecme = (float) 6.0;
+        float xsece = (float) 99999997952.;
+        double rn1e = 12345321;
+        double rn2e = 66666666;
+        StdhepEndRun se = new StdhepEndRun(nreqe, ngene, nwrite, ecme, xsece, rn1e, rn2e);
+        sw.writeRecord(se);
+
+        sw.close();
+        fr.close();
+        //        } catch (IOException e) {
+        //             System.out.println("Error opening " + infile);
+        //        }
+        System.out.println("Ok...done!");
+    }
+
+    @SuppressWarnings("static-access")
+    private static List<Double> getNumbersInLine(StreamTokenizer tok) throws IOException {
+        List<Double> nums = new ArrayList<Double>();
+        while (tok.nextToken() != tok.TT_EOF) {
+//            System.out.println(tok.toString());
+            if (tok.ttype == tok.TT_EOL) {
+                break;
+            }
+
+//            if (tok.ttype != tok.TT_NUMBER) {
+//                throw new RuntimeException("Non numeric data encountered");
+//            }
+
+            String tokVal = tok.sval;
+            nums.add(Double.valueOf(tokVal).doubleValue());
+        }
+
+        return nums;
+    }
+
+    @SuppressWarnings("static-access")
+    private static double getNumberOfEvents(StreamTokenizer tok) throws IOException {
+        boolean fndNumber = false;
+        boolean fndOf = false;
+        boolean fndEvents = false;
+        double evts = -999;
+        while (tok.nextToken() != tok.TT_EOF) {
+//            System.out.println(tok.toString());
+            if (tok.ttype == tok.TT_EOL) {
+                break;
+            }
+            if (tok.ttype == tok.TT_WORD && tok.sval.contentEquals("Number")) {
+                fndNumber = true;
+            }
+            if (tok.ttype == tok.TT_WORD && tok.sval.contentEquals("of")) {
+                fndOf = true;
+            }
+            if (tok.ttype == tok.TT_WORD && tok.sval.contentEquals("Events")) {
+                fndEvents = true;
+            }
+            if (tok.ttype == tok.TT_NUMBER && fndEvents && fndOf && fndNumber) {
+                evts = tok.nval;
+            }
+        }
+        return evts;
+    }
+
+    @SuppressWarnings("static-access")
+    private static void getToNextEvent(StreamTokenizer tok) throws IOException {
+        while (tok.nextToken() != tok.TT_EOF) {
+//            System.out.println(tok.toString());           
+            if (tok.ttype == tok.TT_WORD && tok.sval.contentEquals("<event>")) {
+                tok.nextToken();//get to the EOL
+                return;
+            }
+        }
+
+    }
+}

java/trunk/util/src/main/java/org/hps/util
MergeBunches.java added at 373
--- java/trunk/util/src/main/java/org/hps/util/MergeBunches.java	                        (rev 0)
+++ java/trunk/util/src/main/java/org/hps/util/MergeBunches.java	2014-03-26 04:40:56 UTC (rev 373)
@@ -0,0 +1,500 @@
+package org.hps.util;
+
+/**
+ * MergeBunches.java
+ * Driver to merge bunch trains for HPS and displace them in time
+ * much of this code was taken from org.lcsim.util.OverlayDriver.java
+ * Created 6/8/2011 @author mgraham
+ */
+import hep.physics.particle.properties.ParticleType;
+import hep.physics.vec.BasicHep3Vector;
+import hep.physics.vec.BasicHepLorentzVector;
+import hep.physics.vec.Hep3Vector;
+import hep.physics.vec.HepLorentzVector;
+import java.io.IOException;
+import java.util.ArrayList;
+import java.util.HashMap;
+import java.util.List;
+import java.util.Map;
+import java.util.logging.Level;
+import java.util.logging.Logger;
+import org.lcsim.detector.IDetectorElement;
+import org.lcsim.event.EventHeader;
+import org.lcsim.event.EventHeader.LCMetaData;
+import org.lcsim.event.GenericObject;
+import org.lcsim.event.MCParticle;
+import org.lcsim.event.SimCalorimeterHit;
+import org.lcsim.event.SimTrackerHit;
+import org.lcsim.event.base.BaseLCSimEvent;
+import org.lcsim.event.base.BaseMCParticle;
+import org.lcsim.event.base.BaseSimCalorimeterHit;
+import org.lcsim.event.base.BaseSimTrackerHit;
+import org.lcsim.util.Driver;
+import org.lcsim.lcio.LCIOConstants;
+import org.lcsim.lcio.LCIOUtil;
+import org.lcsim.lcio.LCIOWriter;
+import org.lcsim.lcio.SIOMCParticle;
+import org.lcsim.util.loop.LCIODriver;
+
+public class MergeBunches extends Driver {
+
+    String outFile = "default.slcio";
+    private LCIOWriter writer;
+    BaseLCSimEvent newEvent;
+    static double startT = -40.0;
+    static double deltaT = 2.0;
+    static int nBunches = 40;    
+    double offsetT = startT;
+    int bunchCounter = 0;
+    int eventCounter = 0;
+    protected Map<String, Map<Long, SimCalorimeterHit>> caloHitMap;
+    protected List<MCParticle> overlayMcParticles;
+    protected List<MCParticle> allMcParticles;
+    protected Map<MCParticle, MCParticle> mcParticleReferences;
+
+    /**
+     * @param args the command line arguments
+     * @throws IOException
+     */
+    public static void main(String[] args) throws IOException {
+        MergeBunches mb = new MergeBunches();
+        mb.parseArgs(args);
+
+
+//         LCReader* lcReader = LCFactory::getInstance()->createLCReader() ;
+
+
+    }
+
+    public MergeBunches() throws IOException {
+
+//        LCIODriver lcioDriver = new LCIODriver(outFile);
+         writer=new LCIOWriter(outFile);
+        caloHitMap = new HashMap<String, Map<Long, SimCalorimeterHit>>();
+        overlayMcParticles = new ArrayList<MCParticle>();
+        allMcParticles = new ArrayList<MCParticle>();
+        mcParticleReferences = new HashMap<MCParticle, MCParticle>();
+
+    }
+
+    public void process(EventHeader event) {
+
+
+        if (bunchCounter == 0)
+            newEvent = new BaseLCSimEvent(event.getRunNumber(), eventCounter, event.getDetectorName());
+        mergeEvents(newEvent, event, offsetT);
+        bunchCounter++;
+        offsetT += deltaT;
+        if (bunchCounter == nBunches) {
+            System.out.println("Writing events #"+eventCounter);
+            eventCounter++;
+            offsetT = startT;
+            bunchCounter = 0;
+            try {
+                writer.write(newEvent);
+            } catch (IOException ex) {
+                Logger.getLogger(MergeBunches.class.getName()).log(Level.SEVERE, null, ex);
+            }
+        }
+    }
+
+    /**
+     * Merges all collections from the given events and applies a time offset
+     * to all entries in all collections of the overlay event.
+     * @param event the event where everything is merged into
+     * @param overlayEvent the event overlaid
+     * @param overlayTime the time offset for the overlay event
+     */
+    protected void mergeEvents(EventHeader event, EventHeader overlayEvent, double overlayTime) {
+
+        // need to copy list of collections to avoid concurrent modification
+        List<LCMetaData> overlayCollections = new ArrayList<LCMetaData>(overlayEvent.getMetaData());
+        for (LCMetaData overlayCollection : overlayCollections) {
+            String overlayCollectionName = overlayCollection.getName();
+            if (event.hasItem(overlayCollectionName)) {
+                this.mergeCollections(event.getMetaData((List) event.get(overlayCollectionName)), overlayCollection, overlayTime);
+            } else {
+                // event does not contain corresponding collection from overlayEvent, just put it there
+                // First move hits and apply timing cuts
+                List collection = this.moveCollectionToTime(overlayCollection, overlayTime);
+                this.putCollection(overlayCollection, (List) overlayEvent.get(overlayCollectionName), event);
+            }
+        }
+    }
+
+    /**
+     * Shifts an event in time. Moves all entries in all collections
+     * in the event by the given offset in time.
+     * @param event the event to move in time
+     * @param time the time shift applied to all entries in all collections
+     */
+    protected void moveEventToTime(EventHeader event, double time) {
+        // need to copy list of collections to avoid concurrent modification
+        List<LCMetaData> collections = new ArrayList<LCMetaData>(event.getMetaData());
+        for (LCMetaData collection : collections) {
+            List movedCollection = this.moveCollectionToTime(collection, time);
+            if (movedCollection != null) {
+                // replace the original collection
+                event.remove(collection.getName());
+                this.putCollection(collection, movedCollection, event);
+            }
+        }
+    }
+
+    /**
+     * Shifts a collection in time. Moves all entries in the collection
+     * by the given offset in time. If a readout time is set for the
+     * given collection, all entries outside of that window will be removed.
+     * @param collection the collection to move in time
+     * @param time the time shift applied to all entries in the collection
+     * @return returns the list of moved entries
+     */
+    protected List moveCollectionToTime(LCMetaData collection, double time) {
+        EventHeader event = collection.getEvent();
+        String collectionName = collection.getName();
+        Class collectionType = collection.getType();
+        int flags = collection.getFlags();
+        if (this.getHistogramLevel() > HLEVEL_NORMAL)
+            System.out.println("Moving collection: " + collectionName + " of type " + collectionType + " to " + time + "ns");
+
+        double timeWindow = 0;
+
+        List movedCollection;
+        if (collectionType.isAssignableFrom(MCParticle.class)) {
+            // MCParticles
+            // don't create new list, just move existing particles
+            movedCollection = event.get(MCParticle.class, collectionName);
+            for (MCParticle mcP : (List<MCParticle>) movedCollection) {
+                ((SIOMCParticle) mcP).setTime(mcP.getProductionTime() + time);
+            }
+        } else if (collectionType.isAssignableFrom(SimTrackerHit.class)) {
+            // SimTrackerHits
+            movedCollection = new ArrayList<SimTrackerHit>();
+            for (SimTrackerHit hit : (List<SimTrackerHit>) event.get(SimTrackerHit.class, collectionName)) {
+                ((BaseSimTrackerHit) hit).setTime(hit.getTime() + time);
+                movedCollection.add(hit);
+            }
+        } else if (collectionType.isAssignableFrom(SimCalorimeterHit.class)) {
+            // SimCalorimeterHits
+            movedCollection = new ArrayList<SimCalorimeterHit>();
+            // check if hit contains PDGIDs
+            boolean hasPDG = LCIOUtil.bitTest(flags, LCIOConstants.CHBIT_PDG);
+            List<SimCalorimeterHit> hits = event.get(SimCalorimeterHit.class, collectionName);
+            int nSimCaloHits = hits.size();
+            int nHitsMoved = 0;
+            for (SimCalorimeterHit hit : event.get(SimCalorimeterHit.class, collectionName)) {
+                // check if earliest energy deposit is later than relevant time window
+
+                BaseSimCalorimeterHit movedHit = null;
+                nHitsMoved++;
+                if (this.getHistogramLevel() > HLEVEL_HIGH && nHitsMoved % 100 == 0)
+                    System.out.print("Moved " + nHitsMoved + " / " + nSimCaloHits + " hits\n");
+                movedHit = (BaseSimCalorimeterHit) hit;
+                movedHit.shiftTime(time);//adds this amount of time to all the times of SimCalorimeterHits
+                movedCollection.add(movedHit);
+            }
+        } else if (collectionType.isAssignableFrom(GenericObject.class)) {
+            // nothing to do for GenericObjects
+            return event.get(GenericObject.class, collectionName);
+        } else {
+            System.err.println("Unable to move collection: " + collectionName + " of type " + collectionType);
+            return null;
+        }
+        return movedCollection;
+    }
+
+    /**
+     * Adds a collection to an event using the meta data information from the
+     * given collection and the entries from the given list.
+     * @param collection the collection to take the meta data from
+     * @param entries the list of entries to put into the event
+     * @param event the event to put the collection
+     */
+    protected void putCollection(LCMetaData collection, List entries, EventHeader event) {
+        String[] readout = collection.getStringParameters().get("READOUT_NAME");
+        if (readout != null) {
+            event.put(collection.getName(), entries, collection.getType(), collection.getFlags(), readout[0]);
+        } else {
+            event.put(collection.getName(), entries, collection.getType(), collection.getFlags());
+        }
+        if (this.getHistogramLevel() > HLEVEL_NORMAL)
+            System.out.println("Putting collection " + collection.getName() + " into event.");
+    }
+
+    /**
+     * Merges two collections and applies a time offset to all entries in
+     * the overlay collection.
+     * @param collection the collection where the overlay collection is merged into
+     * @param overlayCollection the collection overlaid
+     * @param overlayTime the time offset for the overlay collection
+     * @return returns <c>false</c> if unable to merge collections, otherwise <c>true</c>
+     */
+    protected boolean mergeCollections(LCMetaData collection, LCMetaData overlayCollection, double overlayTime) {
+        String collectionName = collection.getName();
+        Class collectionType = collection.getType();
+        Class overlayCollectionType = overlayCollection.getType();
+        if (this.getHistogramLevel() > HLEVEL_NORMAL)
+        System.out.println("Merging collection: " + collectionName + " of type " + collectionType + ".");
+        if (!collectionType.equals(overlayCollectionType)) {
+            System.err.println("Can not merge collections: " + collectionName
+                    + " of type " + collectionType + " and " + overlayCollectionType);
+            return false;
+        }
+
+        // move the overlay hits in time, signal should have been moved already
+        List overlayEntries = this.moveCollectionToTime(overlayCollection, overlayTime);
+        //List overlayEntries = overlayCollection.getEvent().get(overlayCollectionType, overlayCollection.getName());
+        // Check if there are actually entries to overlay
+        if (overlayEntries.isEmpty())
+            return true;
+        EventHeader event = collection.getEvent();
+
+        if (collectionType.isAssignableFrom(MCParticle.class)) {
+            // Nothing to do. Only add mc particles that are connected to something kept in the event.
+            // This is done in the other steps below.
+            if (!collectionName.equals(event.MC_PARTICLES)) {
+                event.get(MCParticle.class, collectionName).addAll(overlayEntries);
+            }
+
+        } else if (collectionType.isAssignableFrom(SimTrackerHit.class)) {
+            // SimTrackerHits: just append all hits from overlayEvents
+            List<SimTrackerHit> signalTrackerHits = event.get(SimTrackerHit.class, collectionName);
+
+            // add contributing mc particles to lists
+            for (SimTrackerHit hit : (List<SimTrackerHit>) overlayEntries) {
+                SimTrackerHit overlayHit = copySimTrackerHit(hit, collection);
+                signalTrackerHits.add(overlayHit);
+            }
+//            System.out.println("Overlaid TrackerHits!");
+        } else if (collectionType.isAssignableFrom(SimCalorimeterHit.class)) {
+            // SimCalorimeterHits: need to merge hits in cells which are hit in both events
+            // check if map has already been filled
+            Map<Long, SimCalorimeterHit> hitMap;
+            List<SimCalorimeterHit> signalCaloHits = event.get(SimCalorimeterHit.class, collectionName);
+            if (!caloHitMap.containsKey(collectionName)) {
+                // build map of cells which are hit in signalEvent
+                hitMap = new HashMap<Long, SimCalorimeterHit>();
+                for (SimCalorimeterHit hit : signalCaloHits) {
+                    hitMap.put(hit.getCellID(), hit);
+                }
+                caloHitMap.put(collectionName, hitMap);
+            } else {
+                hitMap = caloHitMap.get(collectionName);
+            }
+
+            boolean hasPDG = LCIOUtil.bitTest(collection.getFlags(), LCIOConstants.CHBIT_PDG);
+            // loop over the hits from the overlay event
+            int nHitsMerged = 0;
+            int nSimCaloHits = overlayEntries.size();
+            for (SimCalorimeterHit hit : (List<SimCalorimeterHit>) overlayEntries) {
+                long cellID = hit.getCellID();
+
+                nHitsMerged++;
+                if (this.getHistogramLevel() > HLEVEL_HIGH && nHitsMerged % 100 == 0)
+                    System.out.print("Merged " + nHitsMerged + " / " + nSimCaloHits + " hits\n");
+                if (hitMap.containsKey(cellID)) {
+                    SimCalorimeterHit oldHit = hitMap.get(hit.getCellID());
+                    int nHitMcP = oldHit.getMCParticleCount();
+                    int nOverlayMcP = hit.getMCParticleCount();
+                    int nMcP = nHitMcP + nOverlayMcP;
+                    // arrays of mc particle contributions to the hit
+                    Object[] mcpList = new Object[nMcP];
+                    float[] eneList = new float[nMcP];
+                    float[] timeList = new float[nMcP];
+                    int[] pdgList = null;
+                    if (hasPDG)
+                        pdgList = new int[nMcP];
+                    double rawEnergy = 0.;
+                    // fill arrays with values from hit
+                    for (int i = 0; i != nHitMcP; i++) {
+                        mcpList[i] = oldHit.getMCParticle(i);
+                        eneList[i] = (float) oldHit.getContributedEnergy(i);
+                        timeList[i] = (float) oldHit.getContributedTime(i);
+                        if (hasPDG)
+                            pdgList[i] = oldHit.getPDG(i);
+                        rawEnergy += eneList[i];
+                    }
+                    // add values of overlay hit
+                    for (int i = 0; i != nOverlayMcP; i++) {
+                        int j = nHitMcP + i;
+                        MCParticle hitMC = hit.getMCParticle(i);
+                        if (hitMC != null) {
+                            if (!mcParticleReferences.containsKey(hitMC)) {
+                                this.addOverlayMcParticle(hitMC);
+                            }
+                            mcpList[j] = mcParticleReferences.get(hitMC);
+                        }
+                        eneList[j] = (float) hit.getContributedEnergy(i);
+                        timeList[j] = (float) hit.getContributedTime(i);
+                        if (hasPDG)
+                            pdgList[j] = hit.getPDG(i);
+                        rawEnergy += eneList[j];
+                    }
+                    // need to set time to 0 so it is recalculated from the timeList
+                    SimCalorimeterHit mergedHit = new BaseSimCalorimeterHit(oldHit.getCellID(),
+                            rawEnergy, 0., mcpList, eneList, timeList, pdgList);
+                    mergedHit.setMetaData(collection);
+                    // replace old hit with merged hit
+                    signalCaloHits.remove(oldHit);
+                    signalCaloHits.add(mergedHit);
+                    hitMap.put(cellID, mergedHit);
+                } else {
+                    SimCalorimeterHit overlayHit = copySimCalorimeterHit(hit, collection, hasPDG);
+                    signalCaloHits.add(overlayHit);
+                    hitMap.put(cellID, overlayHit);
+                }
+
+            }
+        } else if (collectionType.isAssignableFrom(GenericObject.class)) {
+            // need to implement all kinds of possible GenericObjects separately
+            if (collectionName.equals("MCParticleEndPointEnergy")) {
+                // TODO decide what to do with this collection in the overlay events
+                // TODO would need to resolve the position of kept mc particles and keep the same position here
+                //event.get(GenericObject.class, collectionName).addAll(overlayEntries);
+                //event.remove("MCParticleEndPointEnergy");
+            } else {
+                System.err.println("Can not merge collection " + collectionName
+                        + " of type " + collectionType + ". Unhandled type.");
+                return false;
+            }
+        }
+        return true;
+    }
+
+    /**
+     * Deep copy of an SimCalorimeterHit. Necessary in order to be able to close an
+     * overlay event.
+     * @param hit The hit to be copied
+     * @param meta The meta data that will be attached to the hit
+     * @param hasPDG Flag if the pdg code of the mc contriutions should be saved
+     * @return The copied SimCalorimeterHit
+     */
+    protected SimCalorimeterHit copySimCalorimeterHit(SimCalorimeterHit hit, LCMetaData meta, boolean hasPDG) {
+        long id = hit.getCellID();
+        double rawEnergy = hit.getRawEnergy();
+        double time = hit.getTime();
+        int nMCP = hit.getMCParticleCount();
+        Object[] mcparts = new Object[nMCP];
+        float[] energies = new float[nMCP];
+        float[] times = new float[nMCP];
+        int[] pdgs = null;
+        if (hasPDG)
+            pdgs = new int[nMCP];
+        // fill arrays with values from hit
+        for (int i = 0; i != nMCP; i++) {
+            MCParticle hitMC = hit.getMCParticle(i);
+            if (hitMC != null) {
+                this.addOverlayMcParticle(hitMC);
+                mcparts[i] = mcParticleReferences.get(hitMC);
+            }
+            energies[i] = (float) hit.getContributedEnergy(i);
+            times[i] = (float) hit.getContributedTime(i);
+            if (hasPDG)
+                pdgs[i] = hit.getPDG(i);
+        }
+
+        BaseSimCalorimeterHit copyHit = new BaseSimCalorimeterHit(id, rawEnergy, time, mcparts, energies, times, pdgs);
+
+        copyHit.setMetaData(meta);
+
+        return copyHit;
+    }
+
+    /**
+     * Deep copy of an SimTrackerHit. Necessary in order to be able to close an
+     * overlay event.
+     * @param hit The hit to be copied
+     * @param meta The meta data that will be attached to the hit
+     * @return The copied SimTrackerHit
+     */
+    protected SimTrackerHit copySimTrackerHit(SimTrackerHit hit, LCMetaData meta) {
+
+        double[] position = new double[3];
+        double[] momentum = new double[3];
+        double[] hitp = hit.getPosition();
+        double[] hitm = hit.getMomentum();
+        for (int i = 0; i != 3; i++) {
+            position[i] = hitp[i];
+            momentum[i] = hitm[i];
+        }
+        double dEdx = hit.getdEdx();
+        double pathLength = hit.getPathLength();
+        double time = hit.getTime();
+        int cellID = hit.getCellID();
+        MCParticle hitMC = hit.getMCParticle();
+        MCParticle mcParticle = null;
+        if (hitMC != null) {
+            this.addOverlayMcParticle(hitMC);
+            mcParticle = mcParticleReferences.get(hitMC);
+        }
+        IDetectorElement de = null;
+
+        return new BaseSimTrackerHit(position, dEdx, momentum, pathLength, time, cellID, mcParticle, meta, de);
+    }
+
+    /**
+     * Deep copy of an mc particle. Necessary in order to be able to close an
+     * overlay event. The parent and daught relations are <b>not</b> set for the
+     * copied mc particle. Because those should most likely also point to copies
+     * this should be handled somewhere else.
+     * @param mcParticle The mc particle to be copied
+     * @return the copied mc particle
+     */
+    static public MCParticle copyMcParticle(MCParticle mcParticle) {
+        Hep3Vector origin = new BasicHep3Vector(mcParticle.getOriginX(), mcParticle.getOriginY(), mcParticle.getOriginZ());
+        HepLorentzVector p = new BasicHepLorentzVector(mcParticle.getEnergy(), new double[]{mcParticle.getPX(), mcParticle.getPY(), mcParticle.getPZ()});
+        ParticleType ptype = mcParticle.getType().getParticlePropertyProvider().get(mcParticle.getPDGID());
+        int status = mcParticle.getGeneratorStatus();
+        double time = mcParticle.getProductionTime();
+        BaseMCParticle copyMcP = new BaseMCParticle(origin, p, ptype, status, time);
+        // override the mass and charge from the particle type to prevent unknown particle exceptions
+        copyMcP.setMass(mcParticle.getMass());
+        copyMcP.setCharge(mcParticle.getCharge());
+        copyMcP.setSimulatorStatus(mcParticle.getSimulatorStatus().getValue());
+        return copyMcP;
+    }
+
+    /**
+     * Copies an mc particle and stores it together with  the copy in a map.
+     * Adds it to the list of mc particles as well as the overlay mc particles.
+     * Also copies and keeps all ancestors.
+     * @param event
+     * @param particle
+     */
+    protected void addOverlayMcParticle(MCParticle particle) {
+        if (!mcParticleReferences.containsKey(particle)) {
+            // keep a copy of the mc particle instead of the original in order to close the background event
+            MCParticle mcp = copyMcParticle(particle);
+            mcParticleReferences.put(particle, mcp);
+            overlayMcParticles.add(mcp);
+            allMcParticles.add(mcp);
+            List<MCParticle> parents = particle.getParents();
+            // keep the parents as well and set the parent daughter relations
+            for (MCParticle parent : parents) {
+                this.addOverlayMcParticle(parent);
+                ((BaseMCParticle) mcParticleReferences.get(parent)).addDaughter(mcp);
+            }
+        }
+    }
+
+    private static void usage() {
+        System.out.println("java MergeBunches [-o <format>] [<input> [<output>]]");
+        System.exit(0);
+    }
+    private String format;
+
+    void parseArgs(String[] args) {
+        for (int i = 0; i < args.length; i++) {
+            String arg = args[i];
+            if ("-o".equals(arg)) {
+                i++;
+                if (i >= args.length)
+                    usage();
+                format = args[i];
+            }
+
+        }
+
+
+    }
+}

java/trunk/util/src/main/java/org/hps/util
Pair.java added at 373
--- java/trunk/util/src/main/java/org/hps/util/Pair.java	                        (rev 0)
+++ java/trunk/util/src/main/java/org/hps/util/Pair.java	2014-03-26 04:40:56 UTC (rev 373)
@@ -0,0 +1,107 @@
+
+package org.hps.util;
+
+
+/**
+ * A Class to hold a pair of immutable objects
+ * 
+ * 
+ * @author Omar Moreno <[log in to unmask]>
+ * @version $Id: Pair.java,v 1.1 2012/03/26 07:05:28 omoreno Exp $
+ */
+public class Pair<T, S> implements Comparable<Pair<T, S>> {
+    
+    private final T firstElement;
+    private final S secondElement;
+    
+    /**
+     * Default constructor 
+     * 
+     * @param firstElement
+     *      The first element in the pair
+     * @param secondElement
+     *      The second element in the pair
+     */
+    public Pair(T firstElement, S secondElement)
+    {
+        this.firstElement = firstElement;
+        this.secondElement = secondElement;
+    }
+    
+    /**
+     * Get the first element in the pair
+     * 
+     * @return firstElement
+     *      The first element in the pair
+     */
+    public T getFirstElement()
+    {
+        return firstElement;
+    }
+    
+    /**
+     * Get the second element in the pair
+     * 
+     * @return secondElement
+     *      The second element in the pair
+     */
+    public S getSecondElement()
+    {
+        return secondElement;
+    }
+    
+    /**
+     * Compares this pair to the specified pair
+     * 
+     * @param pair
+     *      The pair to compare to
+     * 
+     * @return returns 0, 1 or -1 if the hash code of the pair is equal, greater
+     *         than or less than the specified pair
+     */
+    @Override
+    public int compareTo(Pair<T,S> pair){
+        if(pair != null){
+            if(pair.equals(this)) return 0;
+            else if(pair.hashCode() > this.hashCode()) return 1;
+            else if(pair.hashCode() < this.hashCode()) return -1;
+        }
+        
+        return -1;
+    }
+
+    /**
+     * The hash code for the pair
+     */
+    @Override
+    public int hashCode()
+    {
+        int hashCode = firstElement.hashCode() + (31*secondElement.hashCode());
+        return hashCode;
+    }
+
+    /**
+     * Checks if the elements in this pair are equal to the elements of the 
+     * specified pair
+     * 
+     * @param obj
+     *      The pair to compare to
+     * @return true if both elements are equal, false otherwise
+     */
+    @Override
+    public boolean equals(Object obj) {
+        
+        if (obj == null) return false;
+      
+        if(obj.getClass() == Pair.class){
+        
+            final Pair<T, S> pair = (Pair<T, S>) obj;
+            if(!this.firstElement.equals(pair.firstElement) 
+               && (this.firstElement == null || !this.firstElement.equals(pair.firstElement))) return false;
+            if (this.secondElement != pair.secondElement 
+               && (this.secondElement == null || !this.secondElement.equals(pair.secondElement))) return false;
+        }
+        
+        return true;
+    }
+}

java/trunk/util/src/main/java/org/hps/util
RandomGaussian.java added at 373
--- java/trunk/util/src/main/java/org/hps/util/RandomGaussian.java	                        (rev 0)
+++ java/trunk/util/src/main/java/org/hps/util/RandomGaussian.java	2014-03-26 04:40:56 UTC (rev 373)
@@ -0,0 +1,32 @@
+package org.hps.util;
+
+//--- java ---//
+import java.util.Random;
+
+/**
+ * 
+ * @author Omar Moreno
+ * @version $Id: RandomGaussian.java,v 1.1 2012/08/27 19:01:36 omoreno Exp $
+ */
+public class RandomGaussian {
+
+    private static Random randNumberGenerator;
+        
+    /**
+     * Class shouldn't be instantiated by anyone 
+     */
+    private RandomGaussian(){
+    }
+
+    /**
+     * Generates a Gaussian distributed number with given mean and standard deviation
+     *
+     * @param mean : Mean of the distribution
+     * @param sigma : Standard deviation of the distribution
+     * @return Gaussian distributed number
+     */
+    public static double getGaussian(double mean, double sigma){
+            if(randNumberGenerator == null) randNumberGenerator = new Random();
+            return mean + randNumberGenerator.nextGaussian()*sigma;
+    }
+}

java/trunk/util/src/main/java/org/hps/util
Redrawable.java added at 373
--- java/trunk/util/src/main/java/org/hps/util/Redrawable.java	                        (rev 0)
+++ java/trunk/util/src/main/java/org/hps/util/Redrawable.java	2014-03-26 04:40:56 UTC (rev 373)
@@ -0,0 +1,13 @@
+package org.hps.util;
+
+/**
+ * Drivers that will be attached to monitoring system should implement 
+ * this if they will only redraw plots every N events, or when redraw() is called.
+ * Setting eventRefreshRate = 0 should disable automatic redrawing.
+ * @deprecated Individual Drivers should implement this behavior.  No interface should be necessary.
+ */
+@Deprecated
+public interface Redrawable {
+    public void redraw();
+    public void setEventRefreshRate(int eventRefreshRate);
+}

java/trunk/util/src/main/java/org/hps/util
Resettable.java added at 373
--- java/trunk/util/src/main/java/org/hps/util/Resettable.java	                        (rev 0)
+++ java/trunk/util/src/main/java/org/hps/util/Resettable.java	2014-03-26 04:40:56 UTC (rev 373)
@@ -0,0 +1,14 @@
+package org.hps.util;
+
+/**
+ * Drivers that will be attached to monitoring system should implement 
+ * this if they will be reset when the "reset" button is pressed on the
+ * monitoring app.
+ * @author Jeremy McCormick <[log in to unmask]>
+ * @deprecated Use standard methods like {@link org.lcsim.util.Driver#startOfData()} 
+ * or {@link org.lcsim.util.Driver#detectorChanged(Detector)}.
+ */
+@Deprecated
+public interface Resettable {
+    void reset();
+}

java/trunk/util/src/main/java/org/hps/util
RunControlDialog.java added at 373
--- java/trunk/util/src/main/java/org/hps/util/RunControlDialog.java	                        (rev 0)
+++ java/trunk/util/src/main/java/org/hps/util/RunControlDialog.java	2014-03-26 04:40:56 UTC (rev 373)
@@ -0,0 +1,106 @@
+package org.hps.util;
+
+import java.awt.event.ActionEvent;
+import java.awt.event.ActionListener;
+import java.io.File;
+import java.io.IOException;
+import javax.swing.BoxLayout;
+import javax.swing.JButton;
+import javax.swing.JFileChooser;
+import javax.swing.JFrame;
+import org.lcsim.event.EventHeader;
+import org.lcsim.util.aida.AIDA;
+
+/**
+ * Lightweight driver for stepping through events in offline analysis, without
+ * running the MonitoringApp.
+ *
+ * @author Sho Uemura <[log in to unmask]>
+ * @version $Id: RunControlDialog.java,v 1.1 2013/10/25 19:41:01 jeremy Exp $
+ * @deprecated
+ */
+@Deprecated
+public class RunControlDialog implements ActionListener {
+
+    JButton nextButton;
+    JButton runButton;
+    JButton saveButton;
+    JFrame nextFrame;
+    boolean run = false;
+    final Object syncObject = new Object();
+
+    public RunControlDialog() {
+        nextFrame = new JFrame();
+        nextFrame.setAlwaysOnTop(true);
+        nextFrame.getContentPane().setLayout(new BoxLayout(nextFrame.getContentPane(), BoxLayout.X_AXIS));
+
+        nextButton = new JButton("Next event");
+        nextButton.addActionListener(this);
+        nextFrame.add(nextButton);
+
+        runButton = new JButton("Run");
+        runButton.addActionListener(this);
+        nextFrame.add(runButton);
+
+        saveButton = new JButton("Save");
+        saveButton.addActionListener(this);
+        nextFrame.add(saveButton);
+
+        nextFrame.pack();
+        nextFrame.setVisible(true);
+        nextFrame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
+    }
+
+    //return true to process the event; return false to discard; waits if in pause mode
+    public boolean process(EventHeader event) {
+        if (!run) {
+            synchronized (syncObject) {
+                try {
+                    syncObject.wait();
+                } catch (InterruptedException e) {
+                }
+            }
+        }
+        return true;
+    }
+
+    @Override
+    public void actionPerformed(ActionEvent ae) {
+        if (ae.getSource() == nextButton) {
+            synchronized (syncObject) {
+                syncObject.notify();
+            }
+        }
+        if (ae.getSource() == runButton) {
+            if (!run) {
+                runButton.setText("Pause");
+                run = true;
+                synchronized (syncObject) {
+                    syncObject.notify();
+                }
+            } else {
+                run = false;
+                runButton.setText("Run");
+            }
+        }
+        if (ae.getSource() == saveButton) {
+            savePlots();
+        }
+    }
+
+    /**
+     * Save plots to a selected output file.
+     */
+    private void savePlots() {
+        JFileChooser fc = new JFileChooser();
+        int r = fc.showSaveDialog(nextFrame);
+        if (r == JFileChooser.APPROVE_OPTION) {
+            File fileName = fc.getSelectedFile();
+            try {
+                AIDA.defaultInstance().saveAs(fileName);
+            } catch (IOException e) {
+                e.printStackTrace();
+            }
+        }
+    }
+}

java/trunk/util/src/main/java/org/hps/util
RunControlDriver.java added at 373
--- java/trunk/util/src/main/java/org/hps/util/RunControlDriver.java	                        (rev 0)
+++ java/trunk/util/src/main/java/org/hps/util/RunControlDriver.java	2014-03-26 04:40:56 UTC (rev 373)
@@ -0,0 +1,86 @@
+package org.hps.monitoring.deprecated;
+
+import java.awt.event.ActionEvent;
+import java.awt.event.ActionListener;
+import javax.swing.BoxLayout;
+import javax.swing.JButton;
+import javax.swing.JFrame;
+import org.lcsim.event.EventHeader;
+import org.lcsim.util.Driver;
+
+/**
+ * Lightweight driver for stepping through events in offline analysis, without
+ * running the MonitoringApp.
+ *
+ * @author Sho Uemura <[log in to unmask]>
+ * @version $Id: RunControlDriver.java,v 1.1 2013/10/25 19:41:01 jeremy Exp $
+ * @deprecated
+ */
+@Deprecated
+public class RunControlDriver extends Driver implements ActionListener {
+
+    JButton nextButton;
+    JButton runButton;
+    JFrame nextFrame;
+    boolean run = false;
+    final Object syncObject;
+
+    public RunControlDriver() {
+        syncObject = new Object();
+    }
+
+    @Override
+    protected void startOfData() {
+        nextFrame = new JFrame();
+        nextFrame.setAlwaysOnTop(true);
+        nextFrame.getContentPane().setLayout(new BoxLayout(nextFrame.getContentPane(), BoxLayout.X_AXIS));
+
+        nextButton = new JButton("Next event");
+        nextButton.addActionListener(this);
+        nextFrame.add(nextButton);
+        runButton = new JButton("Run");
+        runButton.addActionListener(this);
+        nextFrame.add(runButton);
+
+        nextFrame.pack();
+        nextFrame.setVisible(true);
+    }
+
+    @Override
+    protected void process(EventHeader event) {
+        if (!run) {
+            synchronized (syncObject) {
+                try {
+                    syncObject.wait();
+                } catch (InterruptedException e) {
+                }
+            }
+        }
+    }
+
+    @Override
+    protected void endOfData() {
+        nextFrame.setVisible(false);
+    }
+
+    @Override
+    public void actionPerformed(ActionEvent ae) {
+        if (ae.getSource() == nextButton) {
+            synchronized (syncObject) {
+                syncObject.notify();
+            }
+        }
+        if (ae.getSource() == runButton) {
+            if (!run) {
+                runButton.setText("Pause");
+                run = true;
+                synchronized (syncObject) {
+                    syncObject.notify();
+                }
+            } else {
+                run = false;
+                runButton.setText("Run");
+            }
+        }
+    }
+}

java/trunk/util/src/main/java/org/hps/util
TimerDriver.java added at 373
--- java/trunk/util/src/main/java/org/hps/util/TimerDriver.java	                        (rev 0)
+++ java/trunk/util/src/main/java/org/hps/util/TimerDriver.java	2014-03-26 04:40:56 UTC (rev 373)
@@ -0,0 +1,38 @@
+package org.hps.util;
+
+import org.lcsim.event.EventHeader;
+import org.lcsim.util.Driver;
+
+/**
+ * Lightweight timer driver. Add one copy of this driver to measure time per event; add multiple copies to measure time between two points in the execute list.
+ * @author Sho Uemura <[log in to unmask]>
+ * @version $Id: TimerDriver.java,v 1.1 2012/08/08 01:02:21 meeg Exp $
+ */
+public class TimerDriver extends Driver {
+
+    private static long time = Long.MIN_VALUE;
+    private long timeElapsed;
+    private int count = 0;
+    private String name = "unnamed";
+    private boolean verbose = false;
+
+    public void setName(String name) {
+        this.name = name;
+    }
+
+    @Override
+    public void process(EventHeader event) {
+        long oldTime = time;
+        time = System.nanoTime();
+        if (oldTime != Long.MIN_VALUE) {
+            long dt = time - oldTime;
+            timeElapsed += dt;
+            count++;
+            if (verbose) {
+                System.out.format("Timer %s: dt %f, timeElapsed %d, count %d, mean time %f ms\n", name, dt / 1.0e6, timeElapsed, count, (timeElapsed / 1.0e6) / count);
+            } else {
+                System.out.format("Timer %s: dt %f, mean time %f ms\n", name, dt / 1.0e6, (timeElapsed / 1.0e6) / count);
+            }
+        }
+    }
+}

java/trunk/util/src/main/java/org/hps/util
TwoTrackFilterDriver.java added at 373
--- java/trunk/util/src/main/java/org/hps/util/TwoTrackFilterDriver.java	                        (rev 0)
+++ java/trunk/util/src/main/java/org/hps/util/TwoTrackFilterDriver.java	2014-03-26 04:40:56 UTC (rev 373)
@@ -0,0 +1,43 @@
+package org.hps.util;
+
+import org.lcsim.event.EventHeader;
+import org.lcsim.event.Track;
+
+/**
+ *
+ * @author phansson
+ */
+public class TwoTrackFilterDriver extends LCIOFilterDriver {
+
+    private String trackCollectionName = "MatchedTracks";
+
+    public TwoTrackFilterDriver() {
+    }
+
+    public void setTrackCollectionNamePath(String trackCollection) {
+        this.trackCollectionName = trackCollection;
+    }
+
+    @Override
+    boolean eventFilter(EventHeader event) {
+        boolean pass = false;
+
+        if (!event.hasCollection(Track.class, trackCollectionName)) {
+            throw new RuntimeException("Error, event doesn't have the track collection");
+        }
+
+        if (this.debug) {
+            System.out.printf("%s: %d tracks in event %d\n", this.getClass().getSimpleName(), event.get(Track.class, trackCollectionName).size(), event.getEventNumber());
+        }
+
+        if (event.get(Track.class, trackCollectionName).size() > 1) {
+            if (this.debug) {
+                System.out.printf("%s: write event %d \n", this.getClass().getSimpleName(), event.getEventNumber());
+            }
+            pass = true;
+        }
+
+
+        return pass;
+    }
+}
SVNspam 0.1