import hep.analysis.*;
import hep.lcd.event.*;
import hep.lcd.util.driver.*;
import hep.physics.jets.*;
import hep.physics.predicate.*;
import hep.physics.*;
import java.util.*;

final public class JetFinder extends Driver
{
   // Create a JadeEJetFinder with a ycut of 0.02
   AbstractJetFinder jetFinder = new JadeEJetFinder(0.02);
   // Create a Predicate that accepts final state charged particles 
   Predicate predicate = new Predicate()
   {
      public boolean accept(Object in)
      {
         Particle p = (Particle) in;
         if (p.getStatusCode() != Particle.FINALSTATE) return false;
         if (p.getType().getCharge() == 0) return false;
         return true;
      }
   };
   public void process(LCDEvent event)
   {
      // We will use the MC truth in this example to find jets
      ParticleVector pv = event.getMCParticles();

      jetFinder.setEvent(pv.particles(),predicate);
      // Fill some diagnostic histograms 
      histogram("Njets").fill(jetFinder.njets());
      histogram("Fewest Tracks").fill(jetFinder.fewestTracks());

      double totalJetEnergy = 0;
      double totalParticleEnergy = 0;
      for (int ijet =0; ijet<jetFinder.njets(); ijet++)
      {
         totalJetEnergy += jetFinder.jet(ijet).t();
         histogram("Jet Energy").fill(jetFinder.jet(ijet).t());
         histogram("Particles in Jet").fill(jetFinder.nParticlesPerJet(ijet));
         // loop over all the tracks in the jet, and add up there energy
         // (should be the same as the jet energy)
         double etot = 0;
         Enumeration e = jetFinder.particlesInJet(ijet);
         while (e.hasMoreElements()) 
            etot += ((Particle) e.nextElement()).getEnergy();
         histogram("Etot").fill(etot);
         totalParticleEnergy += etot;
      }
      histogram("Total Jet Energy").fill(totalJetEnergy);
      histogram("Total Particle Energy").fill(totalParticleEnergy);
   }
}