[Avida-SVN] r2648 - in development/source: actions cpu main

beckma24 at myxo.css.msu.edu beckma24 at myxo.css.msu.edu
Mon Jun 16 08:40:37 PDT 2008


Author: beckma24
Date: 2008-06-16 11:40:36 -0400 (Mon, 16 Jun 2008)
New Revision: 2648

Modified:
   development/source/actions/EnvironmentActions.cc
   development/source/actions/PopulationActions.cc
   development/source/actions/PrintActions.cc
   development/source/cpu/cHardwareBase.cc
   development/source/cpu/cHardwareBase.h
   development/source/cpu/cHardwareCPU.cc
   development/source/cpu/cHardwareCPU.h
   development/source/cpu/cHardwareGX.h
   development/source/cpu/cTestCPUInterface.cc
   development/source/cpu/cTestCPUInterface.h
   development/source/main/cAvidaConfig.h
   development/source/main/cDeme.cc
   development/source/main/cDeme.h
   development/source/main/cDemeCellEvent.cc
   development/source/main/cDemeCellEvent.h
   development/source/main/cOrgInterface.h
   development/source/main/cOrgMovementPredicate.h
   development/source/main/cOrganism.cc
   development/source/main/cOrganism.h
   development/source/main/cPhenotype.cc
   development/source/main/cPhenotype.h
   development/source/main/cPopulation.cc
   development/source/main/cPopulation.h
   development/source/main/cPopulationInterface.cc
   development/source/main/cPopulationInterface.h
   development/source/main/cResourceCount.cc
   development/source/main/cResourceCount.h
   development/source/main/cStats.cc
   development/source/main/cStats.h
   development/source/main/cTaskLib.cc
   development/source/main/cTaskLib.h
Log:
Added alarm messages, deme testament, cell attacks, attack removal, etc.  This commit breaks one of my consistency test which I will be replacing shortly

Modified: development/source/actions/EnvironmentActions.cc
===================================================================
--- development/source/actions/EnvironmentActions.cc	2008-06-15 23:58:31 UTC (rev 2647)
+++ development/source/actions/EnvironmentActions.cc	2008-06-16 15:40:36 UTC (rev 2648)
@@ -734,11 +734,20 @@
   int m_delay; // deme age when event occurs
   int m_duration; // length of event; subverted when deme is reset
   bool m_static_pos;
-  int m_time_to_live; // update when event no longer exists
-  int m_id;
+  int m_total_events; // total number of unique event to create; they may overlab
+  bool m_static_position;
   
 public:
-  cActionDelayedDemeEvent(cWorld* world, const cString& args) : cAction(world, args), m_x1(-1), m_y1(-1), m_x2(-1), m_y2(-1), m_delay(-1), m_duration(-1), m_static_pos(1), m_time_to_live(-1), m_id(-1)
+  cActionDelayedDemeEvent(cWorld* world, const cString& args) : 
+    cAction(world, args)
+  , m_x1(-1)
+  , m_y1(-1)
+  , m_x2(-1)
+  , m_y2(-1)
+  , m_delay(-1)
+  , m_duration(-1)
+  , m_total_events(1)
+  , m_static_position(true)
   {
     cString largs(args);
     if (largs.GetSize()) m_x1 = largs.PopWord().AsInt();
@@ -747,26 +756,79 @@
     if (largs.GetSize()) m_y2 = largs.PopWord().AsInt();
     if (largs.GetSize()) m_delay = largs.PopWord().AsInt();
     if (largs.GetSize()) m_duration = largs.PopWord().AsInt();
-    if (largs.GetSize()) m_static_pos = largs.PopWord().AsInt();
-    if (largs.GetSize()) m_time_to_live = largs.PopWord().AsInt();
-    if (largs.GetSize()) m_id = largs.PopWord().AsInt();
+    if (largs.GetSize()) m_static_position = static_cast<bool>(largs.PopWord().AsInt());
+    if (largs.GetSize()) m_total_events = largs.PopWord().AsInt();
   }
   
-  static const cString GetDescription() { return "Arguments: <int x1> <int y1> <int x2> <int y2> <int delay> <int duraion> <int static_position> <int time_to_live> <event ID>"; }
+  static const cString GetDescription() { return "Arguments: <int x1> <int y1> <int x2> <int y2> <int delay> <int duraion> <bool static_position> <int total_events>"; }
   
   void Process(cAvidaContext& ctx)
   {
     cPopulation& pop = m_world->GetPopulation();
     int numDemes = pop.GetNumDemes();
     for(int i = 0; i < numDemes; i++) {
-      pop.GetDeme(i).SetCellEvent(m_x1, m_y1, m_x2, m_y2, m_delay, m_duration, m_static_pos, m_time_to_live, m_id);
+      pop.GetDeme(i).SetCellEvent(m_x1, m_y1, m_x2, m_y2, m_delay, m_duration, m_static_position, m_total_events);
     }
   }
 };
 
+class cActionDelayedDemeEventsPerSlots : public cAction
+{
+private:
+  int m_x1, m_y1, m_x2, m_y2; // bounding box of event in deme
+  int m_delay; // deme age when event occurs
+  int m_duration; // length of event; subverted when deme is reset
+  int m_total_slots; // total number of slots
+  int m_total_events_per_slot_max; // maximum number of unique event to create per slot; they may overlab
+  int m_total_events_per_slot_min; // minimum number of unique event to create per slot; they may overlab
+  int m_tolal_event_flow_levels; // total number of evenly spaced event flow levels; not all flow levels will be represented in a single deme
+  bool m_static_position;
+  
+public:
+  cActionDelayedDemeEventsPerSlots(cWorld* world, const cString& args) : 
+    cAction(world, args)
+  , m_x1(-1)
+  , m_y1(-1)
+  , m_x2(-1)
+  , m_y2(-1)
+  , m_delay(-1)
+  , m_duration(-1)
+  , m_total_slots(1)
+  , m_total_events_per_slot_max(1)
+  , m_total_events_per_slot_min(1)
+  , m_tolal_event_flow_levels(1)
+  , m_static_position(true)
+  {
+    cString largs(args);
+    if (largs.GetSize()) m_x1 = largs.PopWord().AsInt();
+    if (largs.GetSize()) m_y1 = largs.PopWord().AsInt();
+    if (largs.GetSize()) m_x2 = largs.PopWord().AsInt();
+    if (largs.GetSize()) m_y2 = largs.PopWord().AsInt();
+    if (largs.GetSize()) m_delay = largs.PopWord().AsInt();
+    if (largs.GetSize()) m_duration = largs.PopWord().AsInt();
+    if (largs.GetSize()) m_static_position = static_cast<bool>(largs.PopWord().AsInt());
+    if (largs.GetSize()) m_total_slots = largs.PopWord().AsInt();
+    if (largs.GetSize()) m_total_events_per_slot_max = largs.PopWord().AsInt();
+    if (largs.GetSize()) m_total_events_per_slot_min = largs.PopWord().AsInt();
+    if (largs.GetSize()) m_tolal_event_flow_levels = largs.PopWord().AsInt();
+  }
+  
+  static const cString GetDescription() { return "Arguments: <int x1> <int y1> <int x2> <int y2> <int delay> <int duraion> <bool static_position> <int total_slots_per_deme> <int total_events_per_slot_max> <int total_events_per_slot_min> <int tolal_event_flow_levels>"; }
+  
+  void Process(cAvidaContext& ctx)
+  {
+    cPopulation& pop = m_world->GetPopulation();
+    int numDemes = pop.GetNumDemes();
+    for(int i = 0; i < numDemes; i++) {
+      pop.GetDeme(i).SetCellEventSlots(m_x1, m_y1, m_x2, m_y2, m_delay, m_duration, m_static_position, m_total_slots, m_total_events_per_slot_max, m_total_events_per_slot_min, m_tolal_event_flow_levels);
+    }
+  }
+};
+
 void RegisterEnvironmentActions(cActionLibrary* action_lib)
 {
   action_lib->Register<cActionDelayedDemeEvent>("DelayedDemeEvent");
+  action_lib->Register<cActionDelayedDemeEventsPerSlots>("DelayedDemeEventsPerSlots");
   action_lib->Register<cActionInjectResource>("InjectResource");
   action_lib->Register<cActionInjectScaledResource>("InjectScaledResource");
   action_lib->Register<cActionOutflowScaledResource>("OutflowScaledResource");

Modified: development/source/actions/PopulationActions.cc
===================================================================
--- development/source/actions/PopulationActions.cc	2008-06-15 23:58:31 UTC (rev 2647)
+++ development/source/actions/PopulationActions.cc	2008-06-16 15:40:36 UTC (rev 2648)
@@ -1267,7 +1267,11 @@
     'corners'   - ...demes with upper left and lower right corners filled.
     'deme-age'  - ...demes that are a certain age
     'birth-count' ...demes that have had a certain number of births.
+<<<<<<< .working
     'sat-mov-pred'  - ...demes whose movement predicate was previously satisfied
+=======
+    'events-killed' ...demes that have killed a certian number of events
+>>>>>>> .merge-right.r2644
 */
 
 class cActionReplicateDemes : public cAction
@@ -1287,6 +1291,7 @@
     else if (in_trigger == "deme-age") m_rep_trigger = 3;
     else if (in_trigger == "birth-count") m_rep_trigger = 4;
     else if (in_trigger == "sat-mov-pred") m_rep_trigger = 5;
+    else if (in_trigger == "events-killed") m_rep_trigger = 6;
     else {
       cString err("Unknown replication trigger '");
       err += in_trigger;

Modified: development/source/actions/PrintActions.cc
===================================================================
--- development/source/actions/PrintActions.cc	2008-06-15 23:58:31 UTC (rev 2647)
+++ development/source/actions/PrintActions.cc	2008-06-16 15:40:36 UTC (rev 2648)
@@ -110,6 +110,7 @@
 STATS_OUT_FILE(PrintPerDemeGenPerFounderData,   deme_gen_between_founders.dat );
 // @WRE: Added output event for collected visit counts
 STATS_OUT_FILE(PrintCellVisitsData,         visits.dat			);
+STATS_OUT_FILE(PrintFlowRateTuples,         flow_rate_tuples.dat);
 
 
 #define POP_OUT_FILE(METHOD, DEFAULT)                                                     /*  1 */ \
@@ -128,6 +129,7 @@
 
 POP_OUT_FILE(PrintPhenotypeData,       phenotype_count.dat );
 POP_OUT_FILE(PrintPhenotypeStatus,     phenotype_status.dat);
+POP_OUT_FILE(PrintDemeTestamentStats,  deme_testament.dat  );
 
 
 class cActionPrintData : public cAction
@@ -2649,6 +2651,7 @@
   // Stats Out Files
   action_lib->Register<cActionPrintAverageData>("PrintAverageData");
   action_lib->Register<cActionPrintDemeAverageData>("PrintDemeAverageData");
+  action_lib->Register<cActionPrintFlowRateTuples>("PrintFlowRateTuples");
   action_lib->Register<cActionPrintErrorData>("PrintErrorData");
   action_lib->Register<cActionPrintVarianceData>("PrintVarianceData");
   action_lib->Register<cActionPrintDominantData>("PrintDominantData");
@@ -2681,6 +2684,8 @@
   action_lib->Register<cActionPrintPhenotypeData>("PrintPhenotypeData");
   action_lib->Register<cActionPrintPhenotypeStatus>("PrintPhenotypeStatus");
   
+  action_lib->Register<cActionPrintDemeTestamentStats>("PrintDemeTestamentStats");
+  
   // deme output files
   action_lib->Register<cActionPrintDemeAllStats>("PrintDemeAllStats");
   action_lib->Register<cActionPrintDemeAllStats>("PrintDemeStats"); //duplicate of previous
@@ -2707,9 +2712,8 @@
   //Coalescence Clade Actions
   action_lib->Register<cActionPrintCCladeCounts>("PrintCCladeCounts");
   action_lib->Register<cActionPrintCCladeFitnessHistogram>("PrintCCladeFitnessHistogram");
-  action_lib->Register<cActionPrintCCladeRelativeFitnessHistogram>("PrintCCladeRelativeFitnessHistogram");
+  action_lib->Register<cActionPrintCCladeRelativeFitnessHistogram>("PrintCCladeRelativeFitnessHistogram");  
   
-  
   // Processed Data
   action_lib->Register<cActionPrintData>("PrintData");
   action_lib->Register<cActionPrintInstructionAbundanceHistogram>("PrintInstructionAbundanceHistogram");

Modified: development/source/cpu/cHardwareBase.cc
===================================================================
--- development/source/cpu/cHardwareBase.cc	2008-06-15 23:58:31 UTC (rev 2647)
+++ development/source/cpu/cHardwareBase.cc	2008-06-16 15:40:36 UTC (rev 2648)
@@ -806,18 +806,30 @@
 }
 
 bool cHardwareBase::Inst_DoubleEnergyUsage(cAvidaContext& ctx) {
-  double energy_req = inst_energy_cost[IP().GetNextInst().GetOp()]
+/*  double energy_req = inst_energy_cost[IP().GetNextInst().GetOp()]
                         * cMerit::EnergyToMerit(organism->GetPhenotype().GetStoredEnergy() * organism->GetPhenotype().GetEnergyUsageRatio() * 2.0, m_world)
                         / 100.0; //compensate by factor of 100
-
-  return organism->GetPhenotype().DoubleEnergyUsage(energy_req);
+*/
+  organism->GetPhenotype().DoubleEnergyUsage();
+  double newOrgMerit = cMerit::EnergyToMerit(organism->GetPhenotype().GetStoredEnergy()  * organism->GetPhenotype().GetEnergyUsageRatio(), m_world);
+  organism->UpdateMerit(newOrgMerit);
+  return true;
 }
 
 bool cHardwareBase::Inst_HalfEnergyUsage(cAvidaContext& ctx) {
   organism->GetPhenotype().HalfEnergyUsage();
+  double newOrgMerit = cMerit::EnergyToMerit(organism->GetPhenotype().GetStoredEnergy()  * organism->GetPhenotype().GetEnergyUsageRatio(), m_world);
+  organism->UpdateMerit(newOrgMerit);
   return true;
 }
 
+bool cHardwareBase::Inst_DefaultEnergyUsage(cAvidaContext& ctx) {
+  organism->GetPhenotype().DefaultEnergyUsage();
+  double newOrgMerit = cMerit::EnergyToMerit(organism->GetPhenotype().GetStoredEnergy()  * organism->GetPhenotype().GetEnergyUsageRatio(), m_world);
+  organism->UpdateMerit(newOrgMerit);
+  return true;
+}
+
 // This method will test to see if all costs have been paid associated
 // with executing an instruction and only return true when that instruction
 // should proceed.
@@ -845,8 +857,8 @@
           if(m_world->GetConfig().LOG_SLEEP_TIMES.Get() == 1) {
             pop.AddBeginSleep(cellID,m_world->GetStats().GetUpdate());
           }
-          pop.GetCell(cellID).GetOrganism()->SetSleeping(true);
-          m_world->GetStats().incNumAsleep(pop.GetCell(cellID).GetDemeID());
+          organism->SetSleeping(true);
+          organism->GetOrgInterface().GetDeme()->IncSleepingCount();
         }
       } else {
         organism->GetPhenotype().SetToDie();

Modified: development/source/cpu/cHardwareBase.h
===================================================================
--- development/source/cpu/cHardwareBase.h	2008-06-15 23:58:31 UTC (rev 2647)
+++ development/source/cpu/cHardwareBase.h	2008-06-16 15:40:36 UTC (rev 2648)
@@ -189,6 +189,9 @@
   // --------  State Transfer  --------
   virtual void InheritState(cHardwareBase& in_hardware){ ; }
   
+  //alarm
+  virtual bool Jump_To_Alarm_Label(int jump_label) { return false; }
+  
 protected:
   // --------  No-Operation Instruction --------
   bool Inst_Nop(cAvidaContext& ctx);  // A no-operation instruction that does nothing! 
@@ -200,6 +203,7 @@
   // --------  Execution Speed Instruction --------
   bool Inst_DoubleEnergyUsage(cAvidaContext& ctx);
   bool Inst_HalfEnergyUsage(cAvidaContext& ctx);
+  bool Inst_DefaultEnergyUsage(cAvidaContext& ctx);
 };
 
 

Modified: development/source/cpu/cHardwareCPU.cc
===================================================================
--- development/source/cpu/cHardwareCPU.cc	2008-06-15 23:58:31 UTC (rev 2647)
+++ development/source/cpu/cHardwareCPU.cc	2008-06-16 15:40:36 UTC (rev 2648)
@@ -211,6 +211,9 @@
     tInstLibEntry<tMethod>("if-resources", &cHardwareCPU::Inst_IfResources, nInstFlag::STALL),
     // Data collection
     tInstLibEntry<tMethod>("collect-cell-data", &cHardwareCPU::Inst_CollectCellData, nInstFlag::STALL),
+    tInstLibEntry<tMethod>("kill-cell-event", &cHardwareCPU::Inst_KillCellEvent, nInstFlag::STALL),
+    tInstLibEntry<tMethod>("kill-faced-cell-event", &cHardwareCPU::Inst_KillFacedCellEvent, nInstFlag::STALL),
+    tInstLibEntry<tMethod>("collect-cell-data-and-kill-event", &cHardwareCPU::Inst_CollectCellDataAndKillEvent, nInstFlag::STALL),
 
     tInstLibEntry<tMethod>("donate-rnd", &cHardwareCPU::Inst_DonateRandom, nInstFlag::STALL),
     tInstLibEntry<tMethod>("donate-kin", &cHardwareCPU::Inst_DonateKin, nInstFlag::STALL),
@@ -230,16 +233,25 @@
     tInstLibEntry<tMethod>("rotate-left-one", &cHardwareCPU::Inst_RotateLeftOne, nInstFlag::STALL),
     tInstLibEntry<tMethod>("rotate-right-one", &cHardwareCPU::Inst_RotateRightOne, nInstFlag::STALL),
     tInstLibEntry<tMethod>("rotate-label", &cHardwareCPU::Inst_RotateLabel, nInstFlag::STALL),
+    tInstLibEntry<tMethod>("rotate-to-unoccupied-cell", &cHardwareCPU::Inst_RotateUnoccupiedCell, nInstFlag::STALL),
+    tInstLibEntry<tMethod>("rotate-to-occupied-cell", &cHardwareCPU::Inst_RotateOccupiedCell, nInstFlag::STALL),
+    tInstLibEntry<tMethod>("rotate-to-event-cell", &cHardwareCPU::Inst_RotateEventCell, nInstFlag::STALL),
     
+    
     tInstLibEntry<tMethod>("set-cmut", &cHardwareCPU::Inst_SetCopyMut),
     tInstLibEntry<tMethod>("mod-cmut", &cHardwareCPU::Inst_ModCopyMut),
     tInstLibEntry<tMethod>("get-cell-xy", &cHardwareCPU::Inst_GetCellPosition),
     tInstLibEntry<tMethod>("get-cell-x", &cHardwareCPU::Inst_GetCellPositionX),
     tInstLibEntry<tMethod>("get-cell-y", &cHardwareCPU::Inst_GetCellPositionY),
     tInstLibEntry<tMethod>("dist-from-diag", &cHardwareCPU::Inst_GetDistanceFromDiagonal),
+
     // @WRE additions for movement
     tInstLibEntry<tMethod>("tumble", &cHardwareCPU::Inst_Tumble, nInstFlag::STALL),
     tInstLibEntry<tMethod>("move", &cHardwareCPU::Inst_Move, nInstFlag::STALL),
+    tInstLibEntry<tMethod>("move-to-event", &cHardwareCPU::Inst_MoveToEvent, nInstFlag::STALL),
+    tInstLibEntry<tMethod>("if-event-in-unoccupied-neighbor-cell", &cHardwareCPU::Inst_IfNeighborEventInUnoccupiedCell),
+    tInstLibEntry<tMethod>("if-event-in-faced-cell", &cHardwareCPU::Inst_IfFacingEventCell),
+    tInstLibEntry<tMethod>("if-event-in-current-cell", &cHardwareCPU::Inst_IfEventInCell),
     
     // Threading instructions
     tInstLibEntry<tMethod>("fork-th", &cHardwareCPU::Inst_ForkThread),
@@ -355,7 +367,11 @@
     tInstLibEntry<tMethod>("kazi",	&cHardwareCPU::Inst_Kazi, nInstFlag::STALL),
     tInstLibEntry<tMethod>("kazi5", &cHardwareCPU::Inst_Kazi5, nInstFlag::STALL),
     tInstLibEntry<tMethod>("die", &cHardwareCPU::Inst_Die, nInstFlag::STALL),
+    tInstLibEntry<tMethod>("relinquishEnergyToFutureDeme", &cHardwareCPU::Inst_RelinquishEnergyToFutureDeme, nInstFlag::STALL),
+    tInstLibEntry<tMethod>("relinquishEnergyToNeighborOrganisms", &cHardwareCPU::Inst_RelinquishEnergyToNeighborOrganisms, nInstFlag::STALL),
+    tInstLibEntry<tMethod>("relinquishEnergyToOrganismsInDeme", &cHardwareCPU::Inst_RelinquishEnergyToOrganismsInDeme, nInstFlag::STALL),
 
+
     // Sleep and time
     tInstLibEntry<tMethod>("sleep", &cHardwareCPU::Inst_Sleep, nInstFlag::STALL),
     tInstLibEntry<tMethod>("sleep1", &cHardwareCPU::Inst_Sleep, nInstFlag::STALL),
@@ -386,11 +402,21 @@
     // Energy usage
     tInstLibEntry<tMethod>("double-energy-usage", &cHardwareCPU::Inst_DoubleEnergyUsage, nInstFlag::STALL),
     tInstLibEntry<tMethod>("half-energy-usage", &cHardwareCPU::Inst_HalfEnergyUsage, nInstFlag::STALL),
+    tInstLibEntry<tMethod>("default-energy-usage", &cHardwareCPU::Inst_DefaultEnergyUsage, nInstFlag::STALL),
 
     // Messaging
     tInstLibEntry<tMethod>("send-msg", &cHardwareCPU::Inst_SendMessage, nInstFlag::STALL),
     tInstLibEntry<tMethod>("retrieve-msg", &cHardwareCPU::Inst_RetrieveMessage, nInstFlag::STALL),
-        
+
+    // Alarms
+    tInstLibEntry<tMethod>("send-alarm-msg-local", &cHardwareCPU::Inst_Alarm_MSG_local, nInstFlag::STALL),
+    tInstLibEntry<tMethod>("send-alarm-msg-multihop", &cHardwareCPU::Inst_Alarm_MSG_multihop, nInstFlag::STALL),
+    tInstLibEntry<tMethod>("send-alarm-msg-bit-cons24-local", &cHardwareCPU::Inst_Alarm_MSG_Bit_Cons24_local, nInstFlag::STALL),
+    tInstLibEntry<tMethod>("send-alarm-msg-bit-cons24-multihop", &cHardwareCPU::Inst_Alarm_MSG_Bit_Cons24_multihop, nInstFlag::STALL),
+    tInstLibEntry<tMethod>("alarm-label-high", &cHardwareCPU::Inst_Alarm_Label),
+    tInstLibEntry<tMethod>("alarm-label-low", &cHardwareCPU::Inst_Alarm_Label),
+
+
     // Placebo instructions
     tInstLibEntry<tMethod>("skip", &cHardwareCPU::Inst_Skip),
 
@@ -1676,7 +1702,6 @@
 void cHardwareCPU::InheritState(cHardwareBase& in_hardware)
 { 
   m_epigenetic_state = true;
-
   cHardwareCPU& in_h = (cHardwareCPU&)in_hardware; 
   const cLocalThread& thread = in_h.GetThread(in_h.GetCurThread());
   for (int i=0; i<NUM_REGISTERS; i++) {
@@ -1687,8 +1712,6 @@
   m_threads[m_cur_thread].stack = m_epigenetic_saved_stack;
 }
 
-
-
 //////////////////////////
 // And the instructions...
 //////////////////////////
@@ -2632,6 +2655,10 @@
   // const bool viable = Divide_CheckViable(ctx, div_point, child_size);
   // these checks should be done, but currently they make some assumptions
   // that crash when evaluating this kind of organism -- JEB
+  
+  // check if repro can replace an existing organism
+  if(m_world->GetConfig().REPRO_METHOD.Get() == 0 && organism->IsNeighborCellOccupied())
+    return false;
 
   if (organism->GetPhenotype().GetCurBonus() < m_world->GetConfig().REQUIRED_BONUS.Get()) return false;
   
@@ -2749,9 +2776,60 @@
 bool cHardwareCPU::Inst_Die(cAvidaContext& ctx)
 {
   organism->Die();
-  return true; 
+  return true;
 }
 
+bool cHardwareCPU::Inst_RelinquishEnergyToFutureDeme(cAvidaContext& ctx)
+{
+  double stored_energy = organism->GetPhenotype().GetStoredEnergy() * m_world->GetConfig().FRAC_ENERGY_RELINQUISH.Get();
+  // put stored energy into testament pool for offspring deme
+  cDeme* deme = organism->GetOrgInterface().GetDeme();
+  if(deme == NULL)
+    return false;  // in test CPU
+  deme->IncreaseTotalEnergyTestament(stored_energy);
+  m_world->GetStats().SumEnergyTestamentToFutureDeme().Add(stored_energy);
+  organism->Die();
+  return true;
+}
+
+bool cHardwareCPU::Inst_RelinquishEnergyToNeighborOrganisms(cAvidaContext& ctx)
+{
+  double stored_energy = organism->GetPhenotype().GetStoredEnergy() * m_world->GetConfig().FRAC_ENERGY_RELINQUISH.Get();
+  // put stored energy into toBeApplied energy pool of neighbor organisms
+  int numOcuppiedNeighbors(0);
+  int orginalFacing = organism->GetFacing();
+  for(int i = 0; i < organism->GetNeighborhoodSize(); i++) {
+    if(organism->IsNeighborCellOccupied()) {
+      // count neighboring organisms
+      numOcuppiedNeighbors++;
+    }
+    organism->Rotate(1);
+  }  
+  assert(organism->GetFacing() == orginalFacing);
+
+  for(int i = 0; i < organism->GetNeighborhoodSize(); i++) {
+    if(organism->IsNeighborCellOccupied()) {
+      // give energy testament to neighboring organisms
+      organism->GetNeighbor()->GetPhenotype().EnergyTestament(stored_energy/numOcuppiedNeighbors);
+    }
+    organism->Rotate(1);
+  }
+  assert(organism->GetFacing() == orginalFacing);
+  m_world->GetStats().SumEnergyTestamentToNeighborOrganisms().Add(stored_energy);
+  organism->Die();
+  return true;
+}
+
+bool cHardwareCPU::Inst_RelinquishEnergyToOrganismsInDeme(cAvidaContext& ctx) {
+  double stored_energy = organism->GetPhenotype().GetStoredEnergy() * m_world->GetConfig().FRAC_ENERGY_RELINQUISH.Get();
+  // put stored energy into toBeApplied energy pool of neighbor organisms
+
+  organism->DivideOrgTestamentAmongDeme(stored_energy);
+  m_world->GetStats().SumEnergyTestamentToDemeOrganisms().Add(stored_energy);
+  organism->Die();
+  return true;
+}
+
 // The inject instruction can be used instead of a divide command, paired
 // with an allocate.  Note that for an inject to work, one needs to have a
 // broad range for sizes allowed to be allocated.
@@ -3215,12 +3293,50 @@
 
 
 bool cHardwareCPU::Inst_CollectCellData(cAvidaContext& ctx) {
-  int cellID = organism->GetCellID();
   const int out_reg = FindModifiedRegister(REG_BX);
-  GetRegister(out_reg) = m_world->GetPopulation().GetCell(cellID).GetCellData();
+  GetRegister(out_reg) = organism->GetCellData();
   return true;
 }
 
+bool cHardwareCPU::Inst_KillCellEvent(cAvidaContext& ctx) {
+  // Fail if we're running in the test CPU.
+  if((organism->GetOrgInterface().GetDemeID() < 0) || (organism->GetCellID() < 0))
+    return false;
+
+  const int reg = FindModifiedRegister(REG_BX);
+  int eventID = organism->GetCellData();
+  GetRegister(reg) = organism->GetOrgInterface().GetDeme()->KillCellEvent(eventID);
+  return true;
+}
+
+bool cHardwareCPU::Inst_KillFacedCellEvent(cAvidaContext& ctx) {
+  // Fail if we're running in the test CPU.
+  if((organism->GetOrgInterface().GetDemeID() < 0) || (organism->GetCellID() < 0))
+    return false;
+
+  const int reg = FindModifiedRegister(REG_BX);
+  int eventID = organism->GetNeighborCellContents();
+  GetRegister(reg) = organism->GetOrgInterface().GetDeme()->KillCellEvent(eventID);
+  
+  if(GetRegister(reg))
+    organism->SetEventKilled();
+  
+  return true;
+}
+
+bool cHardwareCPU::Inst_CollectCellDataAndKillEvent(cAvidaContext& ctx) {
+  // Fail if we're running in the test CPU.
+  if((organism->GetOrgInterface().GetDemeID() < 0) || (organism->GetCellID() < 0))
+    return false;
+  
+  const int out_reg = FindModifiedRegister(REG_BX);
+  int eventID = organism->GetCellData();
+  GetRegister(out_reg) = eventID;
+  
+  organism->GetOrgInterface().GetDeme()->KillCellEvent(eventID);
+  return true;
+}
+
 void cHardwareCPU::DoDonate(cOrganism* to_org)
 {
   assert(to_org != NULL);
@@ -3891,6 +4007,50 @@
   return true;
 }
 
+bool cHardwareCPU::Inst_RotateUnoccupiedCell(cAvidaContext& ctx) {
+  const int reg_used = FindModifiedRegister(REG_BX);
+  
+  for(int i = 0; i < organism->GetNeighborhoodSize(); i++) {
+    if(!organism->IsNeighborCellOccupied()) // faced cell is unoccupied
+    {
+      GetRegister(reg_used) = 1;      
+      return true;
+    }
+    organism->Rotate(1); // continue to rotate
+  }  
+  GetRegister(reg_used) = 0;
+  return true;
+}
+
+bool cHardwareCPU::Inst_RotateOccupiedCell(cAvidaContext& ctx) {
+  const int reg_used = FindModifiedRegister(REG_BX);
+  
+  for(int i = 0; i < organism->GetNeighborhoodSize(); i++) {
+    if(organism->IsNeighborCellOccupied()) { // faced cell is occupied
+      GetRegister(reg_used) = 1;      
+      return true;
+    }
+    organism->Rotate(1); // continue to rotate
+  }  
+  GetRegister(reg_used) = 0;
+  return true;
+}
+
+
+bool cHardwareCPU::Inst_RotateEventCell(cAvidaContext& ctx) {
+  const int reg_used = FindModifiedRegister(REG_BX);
+  
+  for(int i = 0; i < organism->GetNeighborhoodSize(); i++) {
+    if(organism->GetCellData() > 0) { // event in faced cell
+      GetRegister(reg_used) = 1;      
+      return true;
+    }
+    organism->Rotate(1); // continue to rotate
+  }  
+  GetRegister(reg_used) = 0;
+  return true;
+}
+
 bool cHardwareCPU::Inst_SetCopyMut(cAvidaContext& ctx)
 {
   const int reg_used = FindModifiedRegister(REG_BX);
@@ -4031,8 +4191,55 @@
   }
 }
 
+bool cHardwareCPU::Inst_MoveToEvent(cAvidaContext& ctx) {
+  const int reg_used = FindModifiedRegister(REG_BX);
+  int orginalFacing = organism->GetFacing();
+  
+  for(int i = 0; i < organism->GetNeighborhoodSize(); i++) {
+    if(organism->GetNeighborCellContents() > 0) { 
+      Inst_Move(ctx);
+      GetRegister(reg_used) = 1;
+      return true;
+    }
+    organism->Rotate(1);
+  }
+  assert(organism->GetFacing() == orginalFacing);
+  Inst_Move(ctx);
+  GetRegister(reg_used) = 0;
+  return true;
+}
+
+bool cHardwareCPU::Inst_IfNeighborEventInUnoccupiedCell(cAvidaContext& ctx) {
+  int orginalFacing = organism->GetFacing();
+  
+  for(int i = 0; i < organism->GetNeighborhoodSize(); i++) {
+    if(organism->GetNeighborCellContents() > 0 && !organism->IsNeighborCellOccupied()) { 
+      return true;
+    }
+    organism->Rotate(1);
+  }
+  assert(organism->GetFacing() == orginalFacing);
+  IP().Advance();
+  return true;
+}
+
+bool cHardwareCPU::Inst_IfFacingEventCell(cAvidaContext& ctx) {
+  if(organism->GetNeighborCellContents() > 0) { 
+      return true;
+  }
+  IP().Advance();
+  return true;
+}
+
+bool cHardwareCPU::Inst_IfEventInCell(cAvidaContext& ctx) {
+  if(organism->GetCellData() > 0) { 
+      return true;
+  }
+  IP().Advance();
+  return true;
+}
+
 // Multi-threading.
-
 bool cHardwareCPU::Inst_ForkThread(cAvidaContext& ctx)
 {
   IP().Advance();
@@ -4440,7 +4647,7 @@
     pop.AddEndSleep(cellID, m_world->GetStats().GetUpdate());
   }
   organism->SetSleeping(false);  //this instruction get executed at the end of a sleep cycle
-  m_world->GetStats().decNumAsleep(pop.GetCell(cellID).GetDemeID());
+  GetOrganism()->GetOrgInterface().GetDeme()->DecSleepingCount();
   if(m_world->GetConfig().APPLY_ENERGY_METHOD.Get() == 2) {
     organism->GetPhenotype().RefreshEnergy();
     organism->GetPhenotype().ApplyToEnergyStore();
@@ -4878,7 +5085,65 @@
   return true;
 }
 
+bool cHardwareCPU::Inst_Alarm_MSG_multihop(cAvidaContext& ctx) {
+  const int reg_used = FindModifiedRegister(REG_BX);  
+  return organism->BcastAlarmMSG(ctx, abs(GetRegister(reg_used)%2), m_world->GetConfig().BCAST_HOPS.Get()); // jump to Alarm-label-  odd=high  even=low
+}
 
+bool cHardwareCPU::Inst_Alarm_MSG_Bit_Cons24_multihop(cAvidaContext& ctx) {
+  const int reg_used = FindModifiedRegister(REG_BX);
+  return organism->BcastAlarmMSG(ctx, (BitCount(GetRegister(reg_used) & MASK24) >= CONSENSUS24) ? 1 : 0, m_world->GetConfig().BCAST_HOPS.Get());// jump to Alarm-label-high OR Alarm-label-low
+}
+
+bool cHardwareCPU::Inst_Alarm_MSG_local(cAvidaContext& ctx) {
+  const int reg_used = FindModifiedRegister(REG_BX);  
+  return organism->BcastAlarmMSG(ctx, abs(GetRegister(reg_used)%2), 1); // jump to Alarm-label-  odd=high  even=low
+}
+
+bool cHardwareCPU::Inst_Alarm_MSG_Bit_Cons24_local(cAvidaContext& ctx) {
+  const int reg_used = FindModifiedRegister(REG_BX);
+  return organism->BcastAlarmMSG(ctx, (BitCount(GetRegister(reg_used) & MASK24) >= CONSENSUS24) ? 1 : 0, 1);// jump to Alarm-label-high OR Alarm-label-low
+}
+
+
+bool cHardwareCPU::Inst_Alarm_Label(cAvidaContext& ctx) {
+  return true;
+}
+
+bool cHardwareCPU::Jump_To_Alarm_Label(int jump_label) {
+  if(organism->IsSleeping()) {
+    return false;
+  }
+
+  cString channel;
+  
+  if(jump_label == 1) {
+    channel = "high";
+  } else if(jump_label == 0) {
+    channel = "low";
+  } else {
+    assert(false);
+  }
+  
+  cInstruction label_inst = GetInstSet().GetInst(cStringUtil::Stringf("alarm-label-")+channel);
+  
+  cHeadCPU search_head(IP());
+  int start_pos = search_head.GetPosition();
+  search_head++;
+  
+  while (start_pos != search_head.GetPosition()) {
+    if (search_head.GetInst() == label_inst) {
+      // move IP to here
+      IP().Set(search_head.GetPosition());
+      m_advance_ip = false; // Don't automatically move the IP
+      return true;
+    }
+    search_head++;
+  }
+  return false;
+}
+
+
 //// Placebo insts ////
 bool cHardwareCPU::Inst_Skip(cAvidaContext& ctx)
 {
@@ -5142,7 +5407,7 @@
   cPopulationCell& mycell = pop.GetCell(cellid);
   cDeme &deme = pop.GetDeme(pop.GetCell(cellid).GetDemeID());
   cResourceCount deme_resource_count = deme.GetDemeResourceCount();
-  int relative_cell_id = deme.GetRelativeCellID(cellid);
+//  int relative_cell_id = deme.GetRelativeCellID(cellid);
   //tArray<double> cell_resources = deme_resource_count.GetCellResources(relative_cell_id);
   tArray<double> cell_resources;
 
@@ -5280,7 +5545,7 @@
   cPopulationCell& mycell = pop.GetCell(cellid);
   cDeme &deme = pop.GetDeme(pop.GetCell(cellid).GetDemeID());
   cResourceCount deme_resource_count = deme.GetDemeResourceCount();
-  int relative_cell_id = deme.GetRelativeCellID(cellid);
+//  int relative_cell_id = deme.GetRelativeCellID(cellid);
   //tArray<double> cell_resources = deme_resource_count.GetCellResources(relative_cell_id);
   tArray<double> cell_resources;
 
@@ -5424,7 +5689,7 @@
   cPopulationCell& mycell = pop.GetCell(cellid);
   cDeme &deme = pop.GetDeme(pop.GetCell(cellid).GetDemeID());
   cResourceCount deme_resource_count = deme.GetDemeResourceCount();
-  int relative_cell_id = deme.GetRelativeCellID(cellid);
+//  int relative_cell_id = deme.GetRelativeCellID(cellid);
   //tArray<double> cell_resources = deme_resource_count.GetCellResources(relative_cell_id);
   tArray<double> cell_resources;
 
@@ -5548,7 +5813,7 @@
 
 bool cHardwareCPU::Inst_Explore(cAvidaContext& ctx)
 {
-  int num_rotations = 0;
+//  int num_rotations = 0;
 
   cPopulation& pop = m_world->GetPopulation();
   int cellid = organism->GetCellID();
@@ -5557,12 +5822,12 @@
     return true;
   }
 
-  cPopulationCell& mycell = pop.GetCell(cellid);
+//  cPopulationCell& mycell = pop.GetCell(cellid);
   cDeme &deme = pop.GetDeme(pop.GetCell(cellid).GetDemeID());
   cResourceCount deme_resource_count = deme.GetDemeResourceCount();
 
   int fromcellID, destcellID;
-  int cell_data;
+//  int cell_data;
 
   // Pheromone drop stuff
   double pher_amount = 0;
@@ -5680,7 +5945,7 @@
   double pher_amount = 0; // this is used in logging
   int drop_mode = -1;
 
-int smc = mycell.ConnectionList().GetSize();
+//int smc = mycell.ConnectionList().GetSize();
  //SingleProcess shows decent-looking cellids until the end.  maybe this is a deme replication problem (probably)
   cPopulationCell faced = mycell.GetCellFaced();
 
@@ -5695,7 +5960,7 @@
     mycell.ConnectionList().CircNext();
   }
 
-  assert(faced == pop.GetCell(fromcellID).GetCellFaced());
+//  assert(faced == pop.GetCell(fromcellID).GetCellFaced());
 
   // Rotate until we face the neighbor with a target.
   // If there was no winner, just move forward.
@@ -5828,7 +6093,7 @@
     mycell.ConnectionList().CircNext();
   }
 
-  assert(faced == pop.GetCell(fromcellID).GetCellFaced());
+//  assert(faced == pop.GetCell(fromcellID).GetCellFaced());
 
   // Rotate until we face the neighbor with a target.
   // If there was no winner, just move forward.
@@ -5960,7 +6225,7 @@
     mycell.ConnectionList().CircNext();
   }
 
-  assert(faced == pop.GetCell(fromcellID).GetCellFaced());
+//  assert(faced == pop.GetCell(fromcellID).GetCellFaced());
 
   // Rotate until we face the neighbor with a target.
   // If there was no winner, just move forward.

Modified: development/source/cpu/cHardwareCPU.h
===================================================================
--- development/source/cpu/cHardwareCPU.h	2008-06-15 23:58:31 UTC (rev 2647)
+++ development/source/cpu/cHardwareCPU.h	2008-06-16 15:40:36 UTC (rev 2648)
@@ -440,6 +440,9 @@
   bool Inst_Kazi(cAvidaContext& ctx);
   bool Inst_Kazi5(cAvidaContext& ctx);
   bool Inst_Die(cAvidaContext& ctx);
+  bool Inst_RelinquishEnergyToFutureDeme(cAvidaContext& ctx);
+  bool Inst_RelinquishEnergyToNeighborOrganisms(cAvidaContext& ctx);
+  bool Inst_RelinquishEnergyToOrganismsInDeme(cAvidaContext& ctx);
 
   // I/O and Sensory
   bool Inst_TaskGet(cAvidaContext& ctx);
@@ -464,6 +467,9 @@
   //! Execute the following instruction if all resources are above their min level.
   bool Inst_IfResources(cAvidaContext& ctx);
   bool Inst_CollectCellData(cAvidaContext& ctx);
+  bool Inst_KillCellEvent(cAvidaContext& ctx);
+  bool Inst_KillFacedCellEvent(cAvidaContext& ctx);
+  bool Inst_CollectCellDataAndKillEvent(cAvidaContext& ctx);
 
   void DoDonate(cOrganism * to_org);
   void DoEnergyDonate(cOrganism* to_org);
@@ -491,6 +497,9 @@
   bool Inst_RotateLeftOne(cAvidaContext& ctx);
   bool Inst_RotateRightOne(cAvidaContext& ctx);
   bool Inst_RotateLabel(cAvidaContext& ctx);
+  bool Inst_RotateOccupiedCell(cAvidaContext& ctx);
+  bool Inst_RotateUnoccupiedCell(cAvidaContext& ctx);
+  bool Inst_RotateEventCell(cAvidaContext& ctx);
   bool Inst_SetCopyMut(cAvidaContext& ctx);
   bool Inst_ModCopyMut(cAvidaContext& ctx);
   bool Inst_GetCellPosition(cAvidaContext& ctx);
@@ -501,6 +510,10 @@
   // @WRE additions for movement
   bool Inst_Tumble(cAvidaContext& ctx);
   bool Inst_Move(cAvidaContext& ctx);
+  bool Inst_MoveToEvent(cAvidaContext& ctx);
+  bool Inst_IfNeighborEventInUnoccupiedCell(cAvidaContext& ctx);
+  bool Inst_IfFacingEventCell(cAvidaContext& ctx);
+  bool Inst_IfEventInCell(cAvidaContext& ctx);
 
   // Multi-threading...
 
@@ -601,6 +614,15 @@
   bool Inst_SendMessage(cAvidaContext& ctx);
   bool Inst_RetrieveMessage(cAvidaContext& ctx);
   
+  //// Alarm ////
+  bool Inst_Alarm_MSG_local(cAvidaContext& ctx);
+  bool Inst_Alarm_MSG_multihop(cAvidaContext& ctx);
+  bool Inst_Alarm_MSG_Bit_Cons24_local(cAvidaContext& ctx);
+  bool Inst_Alarm_MSG_Bit_Cons24_multihop(cAvidaContext& ctx);
+  bool Inst_Alarm_Label(cAvidaContext& ctx);
+  bool Jump_To_Alarm_Label(int jump_label);
+
+  
   //// Placebo ////
   bool Inst_Skip(cAvidaContext& ctx);
 

Modified: development/source/cpu/cHardwareGX.h
===================================================================
--- development/source/cpu/cHardwareGX.h	2008-06-15 23:58:31 UTC (rev 2647)
+++ development/source/cpu/cHardwareGX.h	2008-06-16 15:40:36 UTC (rev 2648)
@@ -370,6 +370,7 @@
    // --------  Parasite Stuff  --------
   bool InjectHost(const cCodeLabel& in_label, const cGenome& injection);
 
+
   // --------  Input/Output Buffers  --------
   virtual tBuffer<int>& GetInputBuf() { return m_current->GetInputBuf(); }
   virtual tBuffer<int>& GetOutputBuf() { return m_current->GetOutputBuf(); }

Modified: development/source/cpu/cTestCPUInterface.cc
===================================================================
--- development/source/cpu/cTestCPUInterface.cc	2008-06-15 23:58:31 UTC (rev 2647)
+++ development/source/cpu/cTestCPUInterface.cc	2008-06-16 15:40:36 UTC (rev 2648)
@@ -41,6 +41,10 @@
   return NULL;
 }
 
+bool cTestCPUInterface::IsNeighborCellOccupied() {
+  return false;
+}
+
 int cTestCPUInterface::GetNumNeighbors()
 {
   return 0;

Modified: development/source/cpu/cTestCPUInterface.h
===================================================================
--- development/source/cpu/cTestCPUInterface.h	2008-06-15 23:58:31 UTC (rev 2647)
+++ development/source/cpu/cTestCPUInterface.h	2008-06-16 15:40:36 UTC (rev 2648)
@@ -49,6 +49,9 @@
   cDeme* GetDeme() { return 0; }
   void SetCellID(int in_id) { ; }
   void SetDemeID(int in_id) { ; }
+  
+  int GetCellData() { return -1; }
+  void SetCellData(const int newData) { ; }
 
   int GetPrevSeenCellID() { return 0; }
   int GetPrevTaskCellID() { return 0; }
@@ -59,7 +62,9 @@
 
   bool Divide(cAvidaContext& ctx, cOrganism* parent, cGenome& child_genome);
   cOrganism* GetNeighbor();
+  bool IsNeighborCellOccupied();
   int GetNumNeighbors();
+  int GetNeighborCellContents() { return 0; }
   void Rotate(int direction = 1);
   void Breakpoint() { ; }
   int GetInputAt(int& input_pointer);
@@ -84,6 +89,9 @@
   int GetFacing() { return 0; }
   bool SendMessage(cOrgMessage& msg) { return false; }
   
+  bool BcastAlarm(int jump_label, int bcast_range) { return false; }
+  
+  void DivideOrgTestamentAmongDeme(double value) {;}
 };
 
 

Modified: development/source/main/cAvidaConfig.h
===================================================================
--- development/source/main/cAvidaConfig.h	2008-06-15 23:58:31 UTC (rev 2647)
+++ development/source/main/cAvidaConfig.h	2008-06-16 15:40:36 UTC (rev 2648)
@@ -283,6 +283,8 @@
   CONFIG_ADD_VAR(RANDOM_SEED, int, 0, "Random number seed (0 for based on time)");
   CONFIG_ADD_VAR(HARDWARE_TYPE, int, 0, "0 = Original CPUs\n1 = New SMT CPUs\n2 = Transitional SMT\n3 = Experimental CPU\n4 = Gene Expression CPU");
   CONFIG_ADD_VAR(SPECULATIVE, bool, 1, "Enable speculative execution");
+  CONFIG_ADD_VAR(BCAST_HOPS, int, 1, "Number of hops to broadcast an alarm");
+  CONFIG_ADD_VAR(ALARM_SELF, bool, 0, "Does sending an alarm move sender IP to alarm label?\n0=no\n1=yes");
   
   CONFIG_ADD_GROUP(CONFIG_FILE_GROUP, "Configuration Files");
   CONFIG_ADD_VAR(DATA_DIR, cString, "data", "Directory in which config files are found");
@@ -296,7 +298,7 @@
   CONFIG_ADD_GROUP(DEME_GROUP, "Demes and Germlines");
   CONFIG_ADD_VAR(NUM_DEMES, int, 1, "Number of independent groups in the\npopulation (default=1).");
   CONFIG_ADD_VAR(DEMES_USE_GERMLINE, int, 0, "Whether demes use a distinct germline (default=0).");
-  CONFIG_ADD_VAR(DEMES_PREVENT_STERILE, int, 0, "Whether to prevent sterile demes from\nreplicating (default=0).");
+  CONFIG_ADD_VAR(DEMES_PREVENT_STERILE, int, 0, "Whether to prevent sterile demes from\nreplicating (default=0 or no).");
   CONFIG_ADD_VAR(DEMES_RESET_RESOURCES, int, 0, "Reset resources in demes on replication. \n0 = reset both demes \n1 = reset target deme \n2 = deme resources remain unchanged\n");
   CONFIG_ADD_VAR(DEMES_REPLICATE_SIZE, int, 1, "Number of identical organisms to create or copy from the\nsource deme to the target deme (default=1).");
   CONFIG_ADD_VAR(DEMES_PROB_ORG_TRANSFER, double, 0.0, "Probablity of an organism being transferred from the\nsource deme to the target deme (default=0.0).");
@@ -305,6 +307,8 @@
   CONFIG_ADD_VAR(DEMES_ORGANISM_FACING, int, 0, "How organisms are facing during deme replication.\n0=unchanged (default).\n1=northwest.\n2=random.");
   CONFIG_ADD_VAR(DEMES_MAX_AGE, int, 500, "The maximum age of a deme (in updates) to be\nused for age-based replication (default=500).");
   CONFIG_ADD_VAR(DEMES_MAX_BIRTHS, int, 100, "The maximum number of births that can occur\nwithin a deme; used with birth-count\nreplication (default=100).");
+  CONFIG_ADD_VAR(DEMES_MIM_EVENTS_KILLED_RATIO, double, 0.7, "Minimum ratio of events killed required for event period to be a success.");
+  CONFIG_ADD_VAR(DEMES_MIM_SUCCESSFUL_EVENT_PERIODS, int, 1, "Minimum number of consecutive event periods that must be a success.");
   CONFIG_ADD_VAR(GERMLINE_COPY_MUT, double, 0.0075, "Prob. of copy mutations occuring during\ngermline replication (default=0.0075).");
   CONFIG_ADD_VAR(GERMLINE_INS_MUT, double, 0.05, "Prob. of an insertion mutation occuring\nduring germline replication (default=0.05).");
   CONFIG_ADD_VAR(GERMLINE_DEL_MUT, double, 0.05, "Prob. of a deletion mutation occuring\nduring germline replication (default=0.05).");
@@ -336,6 +340,7 @@
   CONFIG_ADD_VAR(INJECT_METHOD, int, 0, "0 = Leaves the parasite thread state untouched.\n1 = Resets the calling thread state on inject");
   CONFIG_ADD_VAR(GENERATION_INC_METHOD, int, 1, "0 = Only the generation of the child is\n    increased on divide.\n1 = Both the generation of the mother and child are\n    increased on divide (good with DIVIDE_METHOD 1).");
   CONFIG_ADD_VAR(RESET_INPUTS_ON_DIVIDE, int, 0, "Reset environment inputs of parent upon successful divide.");
+  CONFIG_ADD_VAR(REPRO_METHOD, int, 1, "Replace existing organism: 1=yes");
 	
   CONFIG_ADD_GROUP(RECOMBINATION_GROUP, "Sexual Recombination and Modularity");
   CONFIG_ADD_VAR(RECOMBINATION_PROB, double, 1.0, "probability of recombination in div-sex");
@@ -478,6 +483,10 @@
   CONFIG_ADD_VAR(APPLY_ENERGY_METHOD, int, 0, "When should rewarded energy be applied to current energy?\n0 = on divide\n1 = on completion of task\n2 = on sleep");  
   CONFIG_ADD_VAR(FRAC_ENERGY_TRANSFER, double, 0.0, "Fraction of replaced organism's energy take by new resident");
   CONFIG_ADD_VAR(LOG_SLEEP_TIMES, bool, 0, "Log sleep start and end times. 0/1 (off/on)\nWARNING: may use lots of memory.");
+  CONFIG_ADD_VAR(FRAC_ENERGY_RELINQUISH, double, 1.0, "Fraction of organisms energy to relinquish");
+  CONFIG_ADD_VAR(ENERGY_PASSED_ON_DEME_REPLICATION_METHOD, int, 0, "Who get energy passed from a parent deme\n0 = Energy divided among organisms injected to offspring deme\n1 = Energy divided among cells in offspring deme");
+  CONFIG_ADD_VAR(INHERIT_EXE_RATE, int, 0, "Inherit energy rate from parent? 0=no  1=yes");
+  CONFIG_ADD_VAR(ATTACK_DECAY_RATE, double, 0.0, "Percent of cell's energy decayed by attack");
 
   CONFIG_ADD_GROUP(SECOND_PASS_GROUP, "Tracking metrics known after the running experiment previously");
   CONFIG_ADD_VAR(TRACK_CCLADES, int, 0, "Enable tracking of coalescence clades");

Modified: development/source/main/cDeme.cc
===================================================================
--- development/source/main/cDeme.cc	2008-06-15 23:58:31 UTC (rev 2647)
+++ development/source/main/cDeme.cc	2008-06-16 15:40:36 UTC (rev 2648)
@@ -30,6 +30,7 @@
 #include "cPopulation.h"
 #include "cPopulationCell.h"
 #include "cResource.h"
+#include "cStats.h"
 #include "cWorld.h"
 #include "cOrgMessagePredicate.h"
 #include "cOrgMovementPredicate.h"
@@ -42,6 +43,7 @@
   last_birth_count = 0;
   cur_org_count = 0;
   last_org_count = 0;
+  birth_count_perslot = 0;
   m_world = world;
 
   _current_merit = 1.0;
@@ -107,12 +109,51 @@
 }
 
 void cDeme::ProcessUpdate() {
+  energyUsage.Clear();
+
+  if(IsEmpty()) {  // deme is not processed if no organisms are present
+    total_energy_testament = 0.0;
+    return;
+  }
+
+  for(int i = 0; i < GetSize(); i++) {
+    cPopulationCell& cell = GetCell(i);
+    if(cell.IsOccupied()) {
+      energyUsage.Add(cell.GetOrganism()->GetPhenotype().GetEnergyUsageRatio());
+    }
+  }  
+
   for(int i = 0; i < cell_events.Size(); i++) {
     cDemeCellEvent& event = cell_events[i];
-    if(event.GetDelay() == _age) {
-      event.ActivateEvent(m_world); //start event
+    
+    if(event.IsActive() && event.GetDelay() < _age && _age <= event.GetDelay()+event.GetDuration()) {
+      //remove energy from cells  (should be done with outflow, but this will work for now)
       int eventCell = event.GetNextEventCellID();
+      cResource* res = m_world->GetEnvironment().GetResourceLib().GetResource("CELL_ENERGY");
+      
       while(eventCell != -1) {
+        cPopulationCell& cell = m_world->GetPopulation().GetCell(GetCellID(eventCell));
+        if(event.GetEventID() == cell.GetCellData()){
+          if(cell.IsOccupied()) {
+            // remove energy from organism
+            cPhenotype& orgPhenotype = cell.GetOrganism()->GetPhenotype();
+            orgPhenotype.ReduceEnergy(orgPhenotype.GetStoredEnergy()*m_world->GetConfig().ATTACK_DECAY_RATE.Get());
+          }
+          //remove energy from cell... organism might not takeup all of a cell's energy
+          tArray<double> cell_resources = deme_resource_count.GetCellResources(eventCell);  // uses global cell_id; is this a problem
+          cell_resources[res->GetID()] *= m_world->GetConfig().ATTACK_DECAY_RATE.Get();
+          deme_resource_count.ModifyCell(cell_resources, eventCell);
+        }
+        eventCell = event.GetNextEventCellID();
+      }
+    }
+    
+    
+    
+    if(!event.IsActive() && event.GetDelay() == _age) {
+      event.ActivateEvent(); //start event
+      int eventCell = event.GetNextEventCellID();
+      while(eventCell != -1) {
         // place event ID in cells' data
         if(event.IsDecayed()) {
           m_world->GetPopulation().GetCell(GetCellID(eventCell)).SetCellData(event.GetEventIDDecay(GetCellPosition(eventCell)));
@@ -124,44 +165,83 @@
         std::pair<int, int> pos = GetCellPosition(eventCell);
         m_world->GetStats().IncEventCount(pos.first, pos.second);
 
+
+        //TODO // increase outflow of energy from these cells if not event currently present
+        
+        
         eventCell = event.GetNextEventCellID();
       }
-    } else if(event.GetDelay()+event.GetDuration() == _age) {
+    } else if(event.IsActive() && event.GetDelay()+event.GetDuration() == _age) {
       int eventCell = event.GetNextEventCellID();
       while(eventCell != -1) {
         if(event.GetEventID() == m_world->GetPopulation().GetCell(GetCellID(eventCell)).GetCellData()) { // eventID == CellData
           //set cell data to 0
           m_world->GetPopulation().GetCell(GetCellID(eventCell)).SetCellData(0);
-          eventCell = event.GetNextEventCellID();
+
+        //  TODO // remove energy outflow from these cells
+
         }
+        eventCell = event.GetNextEventCellID();
       }
       event.DeactivateEvent();  //event over
     }
   }
+  
+  for(vector<pair<int, int> >::iterator iter = event_slot_end_points.begin(); iter < event_slot_end_points.end(); iter++) {
+    if(_age == (*iter).first) {
+      // at end point              
+      if(GetEventsKilledThisSlot() >= m_world->GetConfig().DEMES_MIM_EVENTS_KILLED_RATIO.Get() * (*iter).second)
+        consecutiveSuccessfulEventPeriods++;
+      else
+        consecutiveSuccessfulEventPeriods = 0;
+      
+      // update stats.flow_rate_tuples
+      std::map<int, flow_rate_tuple>& flowRateTuples = m_world->GetStats().FlowRateTuples();
+
+      flowRateTuples[(*iter).second].orgCount.Add(GetOrgCount());
+      flowRateTuples[(*iter).second].eventsKilled.Add(GetEventsKilledThisSlot());
+      flowRateTuples[(*iter).second].attemptsToKillEvents.Add(GetEventKillAttemptsThisSlot());
+      flowRateTuples[(*iter).second].AvgEnergyUsageRatio.Add(energyUsage.Average());
+      flowRateTuples[(*iter).second].totalBirths.Add(birth_count_perslot);
+      flowRateTuples[(*iter).second].currentSleeping.Add(sleeping_count);
+      birth_count_perslot = 0;
+      eventsKilledThisSlot = 0;
+      eventKillAttemptsThisSlot = 0;
+      break;
+    }
+  }
   ++_age;
 }
 
 void cDeme::Reset(bool resetResources, double deme_energy)
 {
+  double additional_resource = 0.0;
   // Handle energy model
   if (m_world->GetConfig().ENERGY_ENABLED.Get())
   {
     assert(cur_org_count>0);
     
-    total_org_energy = deme_energy;
-    if(total_org_energy < 0.0)
-      total_org_energy = 0.0;
+    total_energy_testament = 0.0;
     
-    // split deme energy evenly between organisms in deme
-    for (int i=0; i<GetSize(); i++) {
-      int cellid = GetCellID(i);
-      cPopulationCell& cell = m_world->GetPopulation().GetCell(cellid);
-      if(cell.IsOccupied()) {
-        cOrganism* organism = cell.GetOrganism();
-        cPhenotype& phenotype = organism->GetPhenotype();
-        phenotype.SetEnergy(phenotype.GetStoredEnergy() + total_org_energy/static_cast<double>(cur_org_count));
-        phenotype.SetMerit(cMerit(cMerit::EnergyToMerit(phenotype.GetStoredEnergy() * phenotype.GetEnergyUsageRatio(), m_world)));
+    if(m_world->GetConfig().ENERGY_PASSED_ON_DEME_REPLICATION_METHOD.Get() == 0) {
+      total_org_energy = deme_energy;
+      if(total_org_energy < 0.0)
+        total_org_energy = 0.0;
+    
+      // split deme energy evenly between organisms in deme
+      for (int i=0; i<GetSize(); i++) {
+        int cellid = GetCellID(i);
+        cPopulationCell& cell = m_world->GetPopulation().GetCell(cellid);
+        if(cell.IsOccupied()) {
+          cOrganism* organism = cell.GetOrganism();
+          cPhenotype& phenotype = organism->GetPhenotype();
+          phenotype.SetEnergy(phenotype.GetStoredEnergy() + total_org_energy/static_cast<double>(cur_org_count));
+          phenotype.SetMerit(cMerit(cMerit::EnergyToMerit(phenotype.GetStoredEnergy() * phenotype.GetEnergyUsageRatio(), m_world)));
+        }
       }
+    } else if(m_world->GetConfig().ENERGY_PASSED_ON_DEME_REPLICATION_METHOD.Get() == 1) {
+      // split deme energy evenly between cell in deme
+      additional_resource = deme_energy;  // spacial resource handles resource division
     }
   }
   
@@ -171,12 +251,18 @@
   cur_birth_count = 0;
   cur_normalized_time_used = 0;
   injected_count = 0;
+  birth_count_perslot = 0;
+  eventsKilled = 0;
+  eventsKilledThisSlot = 0;
+  eventKillAttempts = 0;
+  eventKillAttemptsThisSlot = 0;
+  sleeping_count = 0;
   
+  consecutiveSuccessfulEventPeriods = 0;
+  
   cur_task_exe_count.SetAll(0);
   cur_reaction_count.SetAll(0);
 
-  if(resetResources) deme_resource_count.ReinitializeResources();
-
   //reset remaining message predicates
   for(int i = 0; i < message_pred_list.Size(); i++) {
     (*message_pred_list[i]).Reset();
@@ -186,6 +272,8 @@
     (*movement_pred_list[i]).Reset();
   }
 
+  if(resetResources)
+    deme_resource_count.ReinitializeResources(additional_resource);
 }
 
 
@@ -377,23 +465,89 @@
   deme_resource_count.ModifyCell(cell_resources, relative_cell_id);
 }
 
-void cDeme::SetCellEvent(int x1, int y1, int x2, int y2, int delay, int duration, bool static_pos, int time_to_live, int ID) {
-  cDemeCellEvent demeEvent = cDemeCellEvent(x1, y1, x2, y2, delay, duration, width, GetHeight(), static_pos, time_to_live, this);
-  if(ID != -1)
-    demeEvent.SetEventID(ID);
-  cell_events.Add(demeEvent);
+void cDeme::SetCellEvent(int x1, int y1, int x2, int y2, int delay, int duration, bool static_position, int total_events) {
+  for(int i = 0; i < total_events; i++) {
+    cDemeCellEvent demeEvent = cDemeCellEvent(x1, y1, x2, y2, delay, duration, width, GetHeight(), static_position, this, m_world);
+    cell_events.Add(demeEvent);
+  }
 }
 
-void cDeme::SetCellEventGradient(int x1, int y1, int x2, int y2, int delay, int duration, bool static_pos, int time_to_live) {
+/*void cDeme::SetCellEventGradient(int x1, int y1, int x2, int y2, int delay, int duration, bool static_pos, int time_to_live) {
   cDemeCellEvent demeEvent = cDemeCellEvent(x1, y1, x2, y2, delay, duration, width, GetHeight(), static_pos, time_to_live, this);
   demeEvent.DecayEventIDFromCenter();
   cell_events.Add(demeEvent);
-}
+}*/
 
 int cDeme::GetNumEvents() {
   return cell_events.Size();
 }
 
+void cDeme::SetCellEventSlots(int x1, int y1, int x2, int y2, int delay, int duration, 
+                              bool static_position, int m_total_slots, int m_total_events_per_slot_max, 
+                              int m_total_events_per_slot_min, int m_tolal_event_flow_levels) {
+  assert(cell_events.Size() == 0); // not designed to be used with other cell events
+  assert(m_world->GetConfig().DEMES_MAX_AGE.Get() >= m_total_slots);
+  
+  int flow_level_increment = (m_total_events_per_slot_max - m_total_events_per_slot_min) / (m_tolal_event_flow_levels-1);
+  int slot_length = m_world->GetConfig().DEMES_MAX_AGE.Get() / m_total_slots;
+
+  // setup stats tuples
+
+  for(int i = 0; i < m_total_slots; i++) {
+    int slot_flow_level = flow_level_increment * m_world->GetRandom().GetInt(m_tolal_event_flow_levels) + m_total_events_per_slot_min; // number of event during this slot
+    int slot_delay = i * slot_length;
+    event_slot_end_points.push_back(make_pair(slot_delay+slot_length, slot_flow_level)); // last slot is never reached it is == to MAX_AGE
+
+    for(int k = 0; k < slot_flow_level; k++) {
+      cDemeCellEvent demeEvent = cDemeCellEvent(x1, y1, x2, y2, delay, duration, width, GetHeight(), static_position, this, m_world);
+      demeEvent.ConfineToTimeSlot(slot_delay, slot_delay+slot_length);
+      cell_events.Add(demeEvent);
+    }
+  }
+    
+  // setup stats.flow_rate_tuples
+  std::map<int, flow_rate_tuple>& flowRateTuples = m_world->GetStats().FlowRateTuples();
+
+  for(int i = m_total_events_per_slot_min; i <= m_total_events_per_slot_max; i+=flow_level_increment) {
+    flowRateTuples[i].orgCount.Clear();
+    flowRateTuples[i].eventsKilled.Clear();
+    flowRateTuples[i].attemptsToKillEvents.Clear();
+    flowRateTuples[i].AvgEnergyUsageRatio.Clear();
+    flowRateTuples[i].totalBirths.Clear();
+    flowRateTuples[i].currentSleeping.Clear();
+  }
+}
+
+bool cDeme::KillCellEvent(const int eventID) {
+  eventKillAttemptsThisSlot++;
+
+  if(eventID <= 0)
+    return false;
+  for(int i = 0; i < cell_events.Size(); i++) {
+    cDemeCellEvent& event = cell_events[i];
+    if(event.IsActive() && event.GetEventID() == eventID) {
+      // remove event ID from all cells
+      int eventCell = event.GetNextEventCellID();
+      while(eventCell != -1) {
+        if(event.GetEventID() == m_world->GetPopulation().GetCell(GetCellID(eventCell)).GetCellData()) { // eventID == CellData
+          //set cell data to 0
+          m_world->GetPopulation().GetCell(GetCellID(eventCell)).SetCellData(0);
+          
+        //  TODO // remove energy outflow from these cells
+
+        }
+        eventCell = event.GetNextEventCellID();
+      }
+      event.DeactivateEvent();  //event over
+      eventsKilled++;
+      eventsKilledThisSlot++;
+      eventKillAttempts++;
+      return true;
+    }
+  }
+  return false;
+}
+
 double cDeme::CalculateTotalEnergy() {
   assert(m_world->GetConfig().ENERGY_ENABLED.Get());
     
@@ -405,6 +559,9 @@
       cOrganism* organism = cell.GetOrganism();
       cPhenotype& phenotype = organism->GetPhenotype();
       energy_sum += phenotype.GetStoredEnergy();
+    } else {
+      double energy_in_cell = cell.UptakeCellEnergy(1.0);
+      energy_sum += energy_in_cell * m_world->GetConfig().FRAC_ENERGY_TRANSFER.Get();
     }
   }
   return energy_sum;
@@ -579,7 +736,7 @@
   assert(cell_ids[0] <= absolute_cell_id);
   assert(absolute_cell_id <= cell_ids[cell_ids.GetSize()-1]);
 
-  cPopulation& pop = m_world->GetPopulation();
+//  cPopulation& pop = m_world->GetPopulation();
 
   int relative_cell_id = GetRelativeCellID(absolute_cell_id);
   tArray<double> cell_resources = deme_resource_count.GetCellResources(relative_cell_id);
@@ -606,3 +763,14 @@
 
 } //End AddPheromone()
 
+int cDeme::GetSlotFlowRate() const {
+  vector<pair<int, int> >::const_iterator iter = event_slot_end_points.begin();
+  while(iter != event_slot_end_points.end()) {
+    if(GetAge() <= (*iter).first) {
+      return (*iter).second;
+    }
+    iter++;
+  }
+//  assert(false); // slots must be of equal size and fit perfectally in deme lifetime
+  return 0;
+}

Modified: development/source/main/cDeme.h
===================================================================
--- development/source/main/cDeme.h	2008-06-15 23:58:31 UTC (rev 2647)
+++ development/source/main/cDeme.h	2008-06-16 15:40:36 UTC (rev 2648)
@@ -24,6 +24,8 @@
 #ifndef cDeme_h
 #define cDeme_h
 
+#include <vector>
+
 #include "cDemeCellEvent.h"
 #include "cGermline.h"
 #include "cPhenotype.h"
@@ -32,6 +34,7 @@
 #include "tVector.h"
 #include "cResourceCount.h"
 #include "cStringList.h"
+#include "cDoubleSum.h"
 
 class cResource;
 class cWorld;
@@ -59,7 +62,7 @@
   int cur_org_count; //!< Number of organisms are currently in this deme.
   int last_org_count; 
   int injected_count; //<! Number of organisms that have been injected into this deme
-
+  int birth_count_perslot;
   int _age; //!< Age of this deme, in updates.
   int generation; //!< Generation of this deme
   double total_org_energy; //! total amount of energy in organisms in this deme
@@ -67,6 +70,14 @@
   int gestation_time; // Time used during last generation
   double cur_normalized_time_used; // normalized by merit and number of orgs
   double last_normalized_time_used; 
+  double total_energy_testament; //! total amount of energy from suicide organisms for offspring deme
+  unsigned int eventsKilled;
+  unsigned int eventsKilledThisSlot;
+  unsigned int eventKillAttempts;
+  unsigned int eventKillAttemptsThisSlot;
+  unsigned int consecutiveSuccessfulEventPeriods;
+  int sleeping_count; //!< Number of organisms currently sleeping
+  cDoubleSum energyUsage;
   
   tArray<int> cur_task_exe_count;
   tArray<int> cur_reaction_count;
@@ -93,6 +104,7 @@
   tArray<int> energy_res_ids; //!< IDs of energy resources
   
   tVector<cDemeCellEvent> cell_events;
+  std::vector<std::pair<int, int> > event_slot_end_points; // (slot end point, slot flow rate)
   
   int         m_germline_genotype_id; // Genotype id of germline (if in use)
   tArray<int> m_founder_genotype_ids; // List of genotype ids used to found deme.
@@ -106,9 +118,11 @@
   tVector<cOrgMovementPredicate*> movement_pred_list;  // Movement Predicates
   
 public:
-  cDeme() : _id(0), width(0), cur_birth_count(0), last_birth_count(0), cur_org_count(0), last_org_count(0), 
-            injected_count(0), _age(0), generation(0), total_org_energy(0.0),
-            time_used(0), gestation_time(0), cur_normalized_time_used(0.0), last_normalized_time_used(0.0), 
+  cDeme() : _id(0), width(0), cur_birth_count(0), last_birth_count(0), cur_org_count(0), last_org_count(0), injected_count(0), birth_count_perslot(0),
+            _age(0), generation(0), total_org_energy(0.0),
+            time_used(0), gestation_time(0), cur_normalized_time_used(0.0), last_normalized_time_used(0.0), total_energy_testament(0.0),
+            eventsKilled(0), eventsKilledThisSlot(0), eventKillAttempts(0), eventKillAttemptsThisSlot(0),
+            consecutiveSuccessfulEventPeriods(0), sleeping_count(0),
             avg_founder_generation(0.0), generations_per_lifetime(0.0),
             deme_resource_count(0), m_germline_genotype_id(0) { ; }
   ~cDeme() { ; }
@@ -132,17 +146,22 @@
 
   //! Kills all organisms currently in this deme.
   void KillAll();
+
   void UpdateStats();
   
   int GetBirthCount() const { return cur_birth_count; }
   int GetLastBirthCount() const { return last_birth_count; }
-  void IncBirthCount() { cur_birth_count++; }
+  void IncBirthCount() { cur_birth_count++; birth_count_perslot++;}
 
   int GetOrgCount() const { return cur_org_count; }
   int GetLastOrgCount() const { return last_org_count; }
 
   void IncOrgCount() { cur_org_count++; }
   void DecOrgCount() { cur_org_count--; }
+
+  int GetSleepingCount() const { return sleeping_count; }
+  void IncSleepingCount() { sleeping_count++; }
+  void DecSleepingCount() { sleeping_count--; }
   
   int GetGeneration() const { return generation; }
 
@@ -151,6 +170,13 @@
 
   bool IsEmpty() const { return cur_org_count == 0; }
   bool IsFull() const { return cur_org_count == cell_ids.GetSize(); }
+
+  int GetSlotFlowRate() const;
+  int GetEventsKilled() const { return eventsKilled; }
+  int GetEventsKilledThisSlot() const { return eventsKilledThisSlot;}
+  int GetEventKillAttempts() const { return eventKillAttempts; }
+  int GetEventKillAttemptsThisSlot() const { return eventKillAttemptsThisSlot; }
+  int GetConsecutiveSuccessfulEventPeriods() const { return consecutiveSuccessfulEventPeriods;}
   
   // -= Germline =-
   //! Returns this deme's germline.
@@ -205,11 +231,19 @@
   void Update(double time_step) { deme_resource_count.Update(time_step); }
   int GetRelativeCellID(int absolute_cell_id) { return absolute_cell_id % GetSize(); } //!< assumes all demes are the same size
 
-  void SetCellEvent(int x1, int y1, int x2, int y2, int delay, int duration, bool static_pos, int time_to_live, int ID = -1);
   void SetCellEventGradient(int x1, int y1, int x2, int y2, int delay, int duration, bool static_pos, int time_to_live);
   int GetNumEvents();
+  void SetCellEvent(int x1, int y1, int x2, int y2, int delay, int duration, bool static_position, int total_events);
+  void SetCellEventSlots(int x1, int y1, int x2, int y2, int delay, int duration, 
+                         bool static_position, int m_total_slots, int m_total_events_per_slot_max, 
+                         int m_total_events_per_slot_min, int m_tolal_event_flow_levels);
+
+  bool KillCellEvent(const int eventID);
+  cDemeCellEvent* GetCellEvent(const int i) { return &cell_events[i]; };
   
   double CalculateTotalEnergy();
+  double GetTotalEnergyTestament() { return total_energy_testament; }
+  void IncreaseTotalEnergyTestament(double increment) { total_energy_testament += increment; }
   
   void IncTimeUsed(double merit) 
     { time_used++; cur_normalized_time_used += 1.0/merit/(double)cur_org_count; }
@@ -248,8 +282,6 @@
 
   // --- Pheromones --- //
   void AddPheromone(int absolute_cell_id, double value);
-
-
 };
 
 #endif

Modified: development/source/main/cDemeCellEvent.cc
===================================================================
--- development/source/main/cDemeCellEvent.cc	2008-06-15 23:58:31 UTC (rev 2647)
+++ development/source/main/cDemeCellEvent.cc	2008-06-16 15:40:36 UTC (rev 2648)
@@ -2,28 +2,32 @@
 #include "cDeme.h"
 #include "cWorld.h"
 
-cDemeCellEvent::cDemeCellEvent(int x1, int y1, int x2, int y2, int delay, int duration, int deme_width, int deme_height, bool static_pos, int time_to_live, cDeme* deme) : 
-m_delay(delay)
-, m_duration(duration)
-, m_iter(0)
-, m_deme_width(deme_width)
-, m_deme_height(deme_height)
-, m_time_to_live(time_to_live)
-, m_use_gradient(false)
-, m_active(false)
-, m_static_pos(static_pos)
-, m_dead (false)
-, m_id_set(false)
-, m_deme(deme)
+cDemeCellEvent::cDemeCellEvent(int x1, int y1, int x2, int y2, int delay, int duration, int deme_width, int deme_height, bool static_pos, cDeme* deme, cWorld* world) : 
+  m_delay(delay)
+  , m_duration(duration)
+  , m_iter(0)
+  , m_deme_width(deme_width)
+  , m_deme_height(deme_height)
+  , m_event_width(x2-x1)
+  , m_event_height(y2-y1)
+  , m_active(false)
+  , m_static_pos(static_pos)
+  , m_deme(deme)
+  , m_world(world)
 {
   assert(x1 <= x2);
   assert(y1 <= y2);
   assert(y1 < deme_width && y2 < deme_width);
-  assert(delay >= 0);
+  assert(x1 < deme_height && x2 < deme_height);
+  assert(delay >= -1);
   assert(duration >= 0);
   m_event_cells.ResizeClear((x2-x1+1) * (y2-y1+1));
   int i = 0;
   
+  if(m_delay == -1) {
+    m_delay = m_world->GetRandom().GetInt(m_world->GetConfig().DEMES_MAX_AGE.Get() - m_duration);
+  }
+  
   if(m_static_pos) {
     for(int j = y1; j <= y2; j++) {
       for(int k = x1; k <= x2; k++) {
@@ -49,7 +53,7 @@
   return -1;
 }
 
-void cDemeCellEvent::ActivateEvent(cWorld* m_world) {
+void cDemeCellEvent::ActivateEvent() {
 
   if(m_dead) {
     return;
@@ -72,6 +76,19 @@
     pair<int, int> centerTopRight = make_pair((int)ceil((m_event_width/2.0)), (int)ceil((m_event_height/2.0)));
     center = make_pair(centerBottomleft, centerTopRight);
   }
+  
+  if(!m_static_pos) {
+    //non-static event position
+    int rand_x1 = m_world->GetRandom().GetInt(m_deme_width-m_event_width);
+    int rand_y1 = m_world->GetRandom().GetInt(m_deme_height-m_event_height);
+    int i = 0;
+    for(int j = rand_y1; j <= rand_y1+m_event_height; j++) {
+      for(int k = rand_x1; k <= rand_x1+m_event_width; k++) {
+        m_event_cells[i] = j*m_deme_width+k;
+        i++;
+      }
+    }
+  }
   m_active = true;
 }
 
@@ -157,3 +174,11 @@
   }
   return rp;
 }
+
+// should be called before organisms in deme are running
+void cDemeCellEvent::ConfineToTimeSlot(int min_delay, int max_delay) {
+  assert(!m_active);
+  assert(max_delay > min_delay);
+  
+  m_delay = (m_delay % (max_delay - min_delay)) + min_delay;
+}

Modified: development/source/main/cDemeCellEvent.h
===================================================================
--- development/source/main/cDemeCellEvent.h	2008-06-15 23:58:31 UTC (rev 2647)
+++ development/source/main/cDemeCellEvent.h	2008-06-16 15:40:36 UTC (rev 2648)
@@ -15,13 +15,14 @@
   int m_event_width, m_event_height, m_time_to_live;
   bool m_use_gradient, m_active, m_static_pos, m_dead, m_id_set;
   std::pair<std::pair<int, int>, std::pair<int, int> > center;
-  cDeme* m_deme;
+  cDeme* m_deme; 
+  cWorld* m_world;
   
   std::pair<double, double> GetCenter() const;
   
 public:
-  cDemeCellEvent() { cDemeCellEvent(-1, -1, -1, -1, 0, 0, 0, 0, true, 0, NULL); m_id_set = false;}
-  cDemeCellEvent(int x1, int y1, int x2, int y2, int delay, int duration, int deme_width, int deme_height, bool static_pos, int time_to_live, cDeme* deme);
+  cDemeCellEvent() { cDemeCellEvent(-1, -1, -1, -1, 0, 0, 0, 0, true, NULL, NULL); }
+  cDemeCellEvent(int x1, int y1, int x2, int y2, int delay, int duration, int deme_width, int deme_height, bool static_pos, cDeme* deme, cWorld* world);
   int GetNextEventCellID();
   int GetDelay();
   cDeme* GetDeme() const { return m_deme; }
@@ -38,11 +39,13 @@
   void SetEventID(int ID) { m_eventID = ID; m_id_set = true;}
 
   void DecayEventIDFromCenter() { m_use_gradient = true; }
-  void ActivateEvent(cWorld* m_world);
+  void ActivateEvent();
   void DeactivateEvent();
   void Terminate() { m_dead = true; }
   
   // gradient generators
   double linmap(const double dp, const double ds, const double de, const double rs, const double re) const;
+  
+  void ConfineToTimeSlot(int min_delay, int max_delay);
 };
 #endif

Modified: development/source/main/cOrgInterface.h
===================================================================
--- development/source/main/cOrgInterface.h	2008-06-15 23:58:31 UTC (rev 2647)
+++ development/source/main/cOrgInterface.h	2008-06-16 15:40:36 UTC (rev 2648)
@@ -59,6 +59,9 @@
   virtual cDeme* GetDeme() = 0;
   virtual void SetCellID(int in_id) = 0;
   virtual void SetDemeID(int in_id) = 0;
+  
+  virtual int GetCellData() = 0;
+  virtual void SetCellData(const int newData) = 0;
 
   virtual int GetPrevSeenCellID() = 0;
   virtual int GetPrevTaskCellID() = 0;
@@ -69,8 +72,10 @@
 
   virtual bool Divide(cAvidaContext& ctx, cOrganism* parent, cGenome& child_genome) = 0;
   virtual cOrganism* GetNeighbor() = 0;
+  virtual bool IsNeighborCellOccupied() = 0;
   virtual int GetNumNeighbors() = 0;
   virtual int GetFacing() = 0; //!< Returns the facing of this organism.
+  virtual int GetNeighborCellContents() = 0;
   virtual void Rotate(int direction = 1) = 0;
   virtual void Breakpoint() = 0;
   virtual int GetInputAt(int& input_pointer) = 0;
@@ -93,6 +98,9 @@
   virtual bool UpdateMerit(double new_merit) = 0;
   virtual bool TestOnDivide() = 0;
   virtual bool SendMessage(cOrgMessage& msg) = 0;
+
+  virtual bool BcastAlarm(int jump_jabel, int bcast_range) = 0;
+  virtual void DivideOrgTestamentAmongDeme(double value) = 0;
   
 };
 

Modified: development/source/main/cOrgMovementPredicate.h
===================================================================
--- development/source/main/cOrgMovementPredicate.h	2008-06-15 23:58:31 UTC (rev 2647)
+++ development/source/main/cOrgMovementPredicate.h	2008-06-16 15:40:36 UTC (rev 2648)
@@ -149,8 +149,8 @@
   , m_event_received(false)
   , m_stats_updated(false)
   , m_events(events)
-  , m_total_orgs(1)   // TODO: eventually, want to make this a parameter.  problem is cPopulation::AddDemePred takes only 1 arg
-  , m_total_times(times) {
+  , m_total_times(times)
+  , m_total_orgs(1) {  // TODO: eventually, want to make this a parameter.  problem is cPopulation::AddDemePred takes only 1 arg
 
     m_event_success.clear();
     for(int i = 0; i < m_events.Size(); i++) {

Modified: development/source/main/cOrganism.cc
===================================================================
--- development/source/main/cOrganism.cc	2008-06-15 23:58:31 UTC (rev 2647)
+++ development/source/main/cOrganism.cc	2008-06-16 15:40:36 UTC (rev 2648)
@@ -66,13 +66,14 @@
   , m_sent_value(0)
   , m_sent_active(false)
   , m_test_receive_pos(0)
+  , m_pher_drop(false)
   , m_max_executed(-1)
   , m_is_running(false)
   , m_is_sleeping(false)
   , m_is_dead(false)
+  , killed_event(false)
   , m_net(NULL)
   , m_msg(0)
-  , m_pher_drop(false)
 {
   // Initialization of structures...
   m_hardware = m_world->GetHardwareManager().Create(this);
@@ -673,3 +674,19 @@
   DoOutput(ctx);
 } //End cOrganism::Move()
 
+bool cOrganism::BcastAlarmMSG(cAvidaContext& ctx, int jump_label, int bcast_range) {
+  assert(m_interface);
+  
+  // If we're able to succesfully send an alarm...
+  if(m_interface->BcastAlarm(jump_label, bcast_range)) {
+    // check to see if we've performed any tasks...
+    DoOutput(ctx);
+    return true;
+  }  
+  return false;
+}
+
+void cOrganism::moveIPtoAlarmLabel(int jump_label) {
+  // move IP to alarm_label
+  m_hardware->Jump_To_Alarm_Label(jump_label);
+}

Modified: development/source/main/cOrganism.h
===================================================================
--- development/source/main/cOrganism.h	2008-06-15 23:58:31 UTC (rev 2647)
+++ development/source/main/cOrganism.h	2008-06-16 15:40:36 UTC (rev 2648)
@@ -27,6 +27,7 @@
 #define cOrganism_h
 
 #include <iostream>
+#include <string>
 #include <vector>
 
 #ifndef cCPUMemory_h
@@ -126,6 +127,8 @@
   bool m_is_sleeping;      // Is this organisms sleeping?
   bool m_is_dead;          // Is this organism dead?
 
+  bool killed_event;
+  
   class cNetSupport
   {
   public:
@@ -195,8 +198,10 @@
   // --------  cOrgInterface Methods  --------
   cHardwareBase& GetHardware() { return *m_hardware; }
   cOrganism* GetNeighbor() { return m_interface->GetNeighbor(); }
+  bool IsNeighborCellOccupied() { return m_interface->IsNeighborCellOccupied(); }
   int GetNeighborhoodSize() { return m_interface->GetNumNeighbors(); }
   int GetFacing() { assert(m_interface); return m_interface->GetFacing(); }  // Returns the facing of this organism.
+  int GetNeighborCellContents() const { return m_interface->GetNeighborCellContents(); }
   void Rotate(int direction) { m_interface->Rotate(direction); }
   void DoBreakpoint() { m_interface->Breakpoint(); }
   int GetNextInput() { return m_interface->GetInputAt(m_input_pointer); }
@@ -223,10 +228,12 @@
   int GetPrevTaskCellID() const { return m_interface->GetPrevTaskCellID(); }
   void SetPrevSeenCellID(int id) const { m_interface->SetPrevSeenCellID(id); }
   void SetPrevTaskCellID(int id) const { m_interface->SetPrevTaskCellID(id); }
-  int GetNumTaskCellsReached() const { m_interface->GetNumTaskCellsReached(); }
+  int GetNumTaskCellsReached() const { return m_interface->GetNumTaskCellsReached(); }
   void AddReachedTaskCell() { m_interface->AddReachedTaskCell(); }
-  
 
+  int GetCellData() { return m_interface->GetCellData(); }
+  void SetCellData(const int data) { m_interface->SetCellData(data); }  
+
   // --------  Input and Output Methods  --------
   void DoInput(const int value);
   void DoInput(tBuffer<int>& input_buffer, tBuffer<int>& output_buffer, const int value);
@@ -374,9 +381,17 @@
   }
 
   // -------- BDC Movement ---------
-public:
   void Move(cAvidaContext& ctx);
 
+  
+  /***** context switch********/
+  bool BcastAlarmMSG(cAvidaContext& ctx, int jump_label, int bcast_range);
+  void moveIPtoAlarmLabel(int jump_label);
+  
+  void DivideOrgTestamentAmongDeme(double value) { m_interface->DivideOrgTestamentAmongDeme(value); }
+  
+  void SetEventKilled() { killed_event = true; }
+  bool GetEventKilled() { return killed_event; }
 };
 
 

Modified: development/source/main/cPhenotype.cc
===================================================================
--- development/source/main/cPhenotype.cc	2008-06-15 23:58:31 UTC (rev 2647)
+++ development/source/main/cPhenotype.cc	2008-06-16 15:40:36 UTC (rev 2648)
@@ -87,9 +87,10 @@
   
   // 1. These are values calculated at the last divide (of self or offspring)
   merit                    = in_phen.merit;
-  executionRatio          = in_phen.executionRatio;
+  executionRatio           = in_phen.executionRatio;
   energy_store             = in_phen.energy_store;    
   energy_tobe_applied      = in_phen.energy_tobe_applied;
+  energy_testament         = in_phen.energy_testament;
   genome_length            = in_phen.genome_length;        
   bonus_instruction_count  = in_phen.bonus_instruction_count; 
   copied_size              = in_phen.copied_size;          
@@ -261,9 +262,14 @@
 {
   // Copy divide values from parent, which should already be setup.
   merit           = parent_phenotype.merit;
-  executionRatio = 1.0;
+  if(m_world->GetConfig().INHERIT_EXE_RATE.Get() == 0)
+    executionRatio = 1.0;
+  else 
+    executionRatio = parent_phenotype.executionRatio;
+    
   energy_store    = min(energy_store, (double) m_world->GetConfig().ENERGY_CAP.Get());
   energy_tobe_applied = 0.0;
+  energy_testament = 0.0;
   genome_length   = _genome.GetSize();
   copied_size     = parent_phenotype.child_copied_size;
   executed_size   = parent_phenotype.executed_size;
@@ -413,6 +419,7 @@
   executed_size   = genome_length;
   energy_store    = min(m_world->GetConfig().ENERGY_GIVEN_ON_INJECT.Get(), m_world->GetConfig().ENERGY_CAP.Get());
   energy_tobe_applied = 0.0;
+  energy_testament = 0.0;
   executionRatio = 1.0;
   gestation_time  = 0;
   gestation_start = 0;
@@ -551,8 +558,10 @@
   }
   merit = cur_merit_base * cur_bonus;
   
-  //BB:TODO update energy store
   SetEnergy(energy_store + cur_energy_bonus);
+  m_world->GetStats().SumEnergyTestamentAcceptedByOrganisms().Add(energy_testament);
+  energy_testament = 0.0;
+
   
   genome_length   = _genome.GetSize();
   (void) copied_size;          // Unchanged
@@ -662,7 +671,7 @@
 
   // A few final changes if the parent was supposed to be be considered
   // a second child on the divide.
-  if (m_world->GetConfig().DIVIDE_METHOD.Get() == DIVIDE_METHOD_SPLIT) {
+  if(m_world->GetConfig().DIVIDE_METHOD.Get() == DIVIDE_METHOD_SPLIT) {
     gestation_start = 0;
     cpu_cycles_used = 0;
     time_used = 0;
@@ -826,9 +835,13 @@
   
   energy_store    = clone_phenotype.energy_store;
   energy_tobe_applied = 0.0;
-  executionRatio = 1.0;
-  
-  executionRatio  = clone_phenotype.executionRatio;
+  energy_testament = 0.0;
+
+  if(m_world->GetConfig().INHERIT_EXE_RATE.Get() == 0)
+    executionRatio = 1.0;
+  else 
+    executionRatio = clone_phenotype.executionRatio;
+
   genome_length   = clone_phenotype.genome_length;
   copied_size     = clone_phenotype.copied_size;
   // copied_size     = clone_phenotype.child_copied_size;
@@ -1399,19 +1412,19 @@
   energy_store = max(0.0, min(value, (double) m_world->GetConfig().ENERGY_CAP.Get()));
 }
 
-bool cPhenotype::DoubleEnergyUsage(double energy_req) {
-  if(GetStoredEnergy() < energy_req) {
-    return false;
-  }
+void cPhenotype::DoubleEnergyUsage() {
   executionRatio *= 2.0;
-  return true;
 }
 
 void cPhenotype::HalfEnergyUsage() {
   executionRatio *= 0.5;
 }
 
+void cPhenotype::DefaultEnergyUsage() {
+  executionRatio = 1.0;
+}
 
+
 /**
 Credit organism with energy reward, but only update energy store if APPLY_ENERGY_METHOD = "on task completion" (1)
  */
@@ -1422,6 +1435,8 @@
       energy_tobe_applied += cur_energy_bonus;
     } else if(m_world->GetConfig().APPLY_ENERGY_METHOD.Get() == 1) {
       SetEnergy(energy_store + cur_energy_bonus);
+      m_world->GetStats().SumEnergyTestamentAcceptedByOrganisms().Add(energy_testament);
+      energy_testament = 0.0;
     } else {
       cerr<< "Unknown APPLY_ENERGY_METHOD value " << m_world->GetConfig().APPLY_ENERGY_METHOD.Get();
       exit(-1);
@@ -1432,9 +1447,18 @@
 
 void cPhenotype::ApplyToEnergyStore() {
   SetEnergy(energy_store + energy_tobe_applied);
+  m_world->GetStats().SumEnergyTestamentAcceptedByOrganisms().Add(energy_testament);
+  energy_testament = 0.0;
   energy_tobe_applied = 0.0;
+  energy_testament = 0.0;
 }
 
+void cPhenotype::EnergyTestament(const double value) {
+  assert(value > 0.0);
+  energy_tobe_applied += value;
+  energy_testament += value;
+} //! external energy given to organism
+
 double cPhenotype::ExtractParentEnergy() {
   assert(m_world->GetConfig().ENERGY_ENABLED.Get() > 0);
   // energy model config variables
@@ -1619,8 +1643,9 @@
   }
   merit = cur_merit_base * cur_bonus;
 
-  //BB:TODO update energy store
   SetEnergy(energy_store + cur_energy_bonus);
+  m_world->GetStats().SumEnergyTestamentAcceptedByOrganisms().Add(energy_testament);
+  energy_testament = 0.0;
     
   genome_length   = _genome.GetSize();
   gestation_start = time_used;

Modified: development/source/main/cPhenotype.h
===================================================================
--- development/source/main/cPhenotype.h	2008-06-15 23:58:31 UTC (rev 2647)
+++ development/source/main/cPhenotype.h	2008-06-16 15:40:36 UTC (rev 2648)
@@ -94,7 +94,6 @@
   cMerit merit;             // Relative speed of CPU
   double executionRatio;    //  ratio of current execution merit over base execution merit
   double energy_store;      // Amount of energy.  Determines relative speed of CPU when turned on.
-  double energy_tobe_applied; //Energy that has not yet been added to energy store.
   int genome_length;        // Number of instructions in genome.
   int bonus_instruction_count; // Number of times MERIT_BONUS_INT is in genome.
   int copied_size;          // Instructions copied into genome.
@@ -108,6 +107,8 @@
   // 2. These are "in progress" variables, updated as the organism operates
   double cur_bonus;                           // Current Bonus
   double cur_energy_bonus;                    // Current energy bonus
+  double energy_tobe_applied;                 // Energy that has not yet been added to energy store.
+  double energy_testament;
   int cur_num_errors;                         // Total instructions executed illeagally.
   int cur_num_donates;                        // Number of donations so far
   tArray<int> cur_task_count;                 // Total times each task was performed
@@ -458,10 +459,13 @@
   bool& ChildFertile() { assert(initialized == true); return child_fertile; }
   bool& IsMultiThread() { assert(initialized == true); return is_multi_thread; }
   
-  bool DoubleEnergyUsage(double inst_energy_cost);
+  void DoubleEnergyUsage();
   void HalfEnergyUsage();
+  void DefaultEnergyUsage();
+  
   void RefreshEnergy();
   void ApplyToEnergyStore();
+  void EnergyTestament(const double value); //! external energy given to organism
   double ExtractParentEnergy();
   
   bool operator<(const cPhenotype& rhs) const;

Modified: development/source/main/cPopulation.cc
===================================================================
--- development/source/main/cPopulation.cc	2008-06-15 23:58:31 UTC (rev 2647)
+++ development/source/main/cPopulation.cc	2008-06-16 15:40:36 UTC (rev 2648)
@@ -100,13 +100,13 @@
   if (world->GetVerbosity() > VERBOSE_NORMAL) {
     cout << "Building world " << world_x << "x" << world_y << " = " << num_cells << " organisms." << endl;
     switch(geometry) {
-    case nGeometry::GRID: { cout << "Geometry: Bounded grid" << endl; break; }
-    case nGeometry::TORUS: { cout << "Geometry: Torus" << endl; break; }
-    case nGeometry::CLIQUE: { cout << "Geometry: Clique" << endl; break; }
-    case nGeometry::HEX: { cout << "Geometry: Hex" << endl; break; }
-    default:
-      cout << "Unknown geometry!" << endl;
-      assert(false);
+      case nGeometry::GRID: { cout << "Geometry: Bounded grid" << endl; break; }
+      case nGeometry::TORUS: { cout << "Geometry: Torus" << endl; break; }
+      case nGeometry::CLIQUE: { cout << "Geometry: Clique" << endl; break; }
+      case nGeometry::HEX: { cout << "Geometry: Hex" << endl; break; }
+      default:
+        cout << "Unknown geometry!" << endl;
+        assert(false);
     }
   }
   
@@ -114,7 +114,7 @@
   if (num_demes <= 0) {
     num_demes = 1; // One population == one deme.
   }
-
+  
   // The following combination of options creates an infinite rotate-loop:
   assert(!((m_world->GetConfig().DEMES_ORGANISM_PLACEMENT.Get()==0)
            && (m_world->GetConfig().DEMES_ORGANISM_FACING.Get()==1)
@@ -130,7 +130,7 @@
   
 #ifdef DEBUG
   const int birth_method = m_world->GetConfig().BIRTH_METHOD.Get();
-
+  
   if(num_demes > 1) {
     assert(birth_method != POSITION_CHILD_FULL_SOUP_ELDEST);
   }
@@ -178,23 +178,23 @@
     // We're cheating here; we're using the random access nature of an iterator
     // to index beyond the end of the cell_array.
     switch(geometry) {
-    case nGeometry::GRID:
-      build_grid(&cell_array.begin()[i], &cell_array.begin()[i+deme_size], deme_size_x, deme_size_y);
-      break;
-    case nGeometry::TORUS:
-      build_torus(&cell_array.begin()[i], &cell_array.begin()[i+deme_size], deme_size_x, deme_size_y);
-      break;
-    case nGeometry::CLIQUE:
-      build_clique(&cell_array.begin()[i], &cell_array.begin()[i+deme_size], deme_size_x, deme_size_y);
-      break;
-    case nGeometry::HEX:
-      build_hex(&cell_array.begin()[i], &cell_array.begin()[i+deme_size], deme_size_x, deme_size_y);
-      break;
-    default:
-      assert(false);
+      case nGeometry::GRID:
+        build_grid(&cell_array.begin()[i], &cell_array.begin()[i+deme_size], deme_size_x, deme_size_y);
+        break;
+      case nGeometry::TORUS:
+        build_torus(&cell_array.begin()[i], &cell_array.begin()[i+deme_size], deme_size_x, deme_size_y);
+        break;
+      case nGeometry::CLIQUE:
+        build_clique(&cell_array.begin()[i], &cell_array.begin()[i+deme_size], deme_size_x, deme_size_y);
+        break;
+      case nGeometry::HEX:
+        build_hex(&cell_array.begin()[i], &cell_array.begin()[i+deme_size], deme_size_x, deme_size_y);
+        break;
+      default:
+        assert(false);
     }
   }
-	
+  
   BuildTimeSlicer(0);
   
   // Setup the resources...
@@ -202,7 +202,7 @@
   int global_res_index = -1;
   int deme_res_index = -1;
   int num_deme_res = 0;
-
+  
   //setting size of global and deme-level resources
   for(int i = 0; i < resource_lib.GetSize(); i++) {
     cResource * res = resource_lib.GetResource(i);
@@ -219,7 +219,7 @@
     GetDeme(i).SetDemeResourceCount(tmp_deme_res_count);
     GetDeme(i).ResizeSpatialGrids(deme_size_x, deme_size_y);
   }
-
+  
   for (int i = 0; i < resource_lib.GetSize(); i++) {
     cResource * res = resource_lib.GetResource(i);
     if (!res->GetDemeResource()) {
@@ -247,16 +247,16 @@
       exit(1);
     }
   }
-
+  
 }
 
 void cPopulation::InitiatePop() {
-
+  
   // Load a clone if one is provided, otherwise setup start organism.
   if (m_world->GetConfig().CLONE_FILE.Get() == "-" || m_world->GetConfig().CLONE_FILE.Get() == "") {
     cGenome start_org(0);
     const cString& filename = m_world->GetConfig().START_CREATURE.Get();
-
+    
     if (filename != "-" && filename != "") {
       if (!cGenomeUtil::LoadGenome(filename, m_world->GetHardwareManager().GetInstSet(), start_org)) {
         cerr << "Error: Unable to load start creature" << endl;
@@ -299,7 +299,7 @@
 {
   if (m_world->GetConfig().FASTFORWARD_NUM_ORGS.Get() > 0 && GetNumOrganisms() >= m_world->GetConfig().FASTFORWARD_NUM_ORGS.Get())
   {
-	  return true;
+    return true;
   }
   assert(&parent_organism != NULL);
   
@@ -361,7 +361,7 @@
     // Reset inputs and re-calculate merit if required
     if (m_world->GetConfig().RESET_INPUTS_ON_DIVIDE.Get() > 0){
       environment.SetupInputs(ctx, parent_cell.m_inputs);
-
+      
       int pc_phenotype = m_world->GetConfig().PRECALC_PHENOTYPE.Get();
       if (pc_phenotype){
         cCPUTestInfo test_info;
@@ -404,7 +404,7 @@
     
     //@JEB - we may want to pass along some state information from parent to child
     if ( (m_world->GetConfig().EPIGENETIC_METHOD.Get() == EPIGENETIC_METHOD_OFFSPRING) 
-      || (m_world->GetConfig().EPIGENETIC_METHOD.Get() == EPIGENETIC_METHOD_BOTH) ) {
+         || (m_world->GetConfig().EPIGENETIC_METHOD.Get() == EPIGENETIC_METHOD_BOTH) ) {
       child_array[i]->GetHardware().InheritState(parent_organism.GetHardware());
     }
     
@@ -463,7 +463,7 @@
 {
   assert(in_organism != NULL);
   assert(in_organism->GetGenome().GetSize() >= 1);
-
+  
   in_organism->SetOrgInterface(new cPopulationInterface(m_world));
   
   // If the organism does not have a genotype, give it one!  No parent
@@ -491,7 +491,7 @@
   
   // Setup the inputs in the target cell.
   environment.SetupInputs(ctx, target_cell.m_inputs);
-    
+  
   // Precalculate the phenotype if requested
   int pc_phenotype = m_world->GetConfig().PRECALC_PHENOTYPE.Get();
   if (pc_phenotype){
@@ -508,7 +508,7 @@
     delete test_cpu;
   }
   // Update the archive...
-      
+  
   in_genotype->AddOrganism();
   
   if (old_genotype != NULL) {
@@ -527,7 +527,7 @@
   
   // Keep track of statistics for organism counts...
   num_organisms++;
-
+  
   if (deme_array.GetSize() > 0) {
     deme_array[target_cell.GetDemeID()].IncOrgCount();
   }
@@ -568,7 +568,7 @@
 #ifdef DEBBUG
   int sID, dID, xx1, yy1, xx2, yy2;
 #endif
-
+  
   // Swap inputs between cells to fix bus error when Avidian moves into an unoccupied cell
   environment.SwapInputs(ctx, src_cell.m_inputs, dest_cell.m_inputs);
   
@@ -583,13 +583,13 @@
       actualNeighborhoodSize = 8;
     }
   }
- 
+  
   // Swap cell facings between cells, so that if movement is directed, it continues to be associated with
   // the same organism
   // Determine absolute facing for each cell
   fromFacing = src_cell.GetFacing();
   destFacing = dest_cell.GetFacing();
-
+  
   // Set facing in source cell
   success = 0;
   newFacing = destFacing;
@@ -603,7 +603,7 @@
       break;
     }
   }
-// @DMB this doesn't compile properly -- #ifdef DEBUG
+  // @DMB this doesn't compile properly -- #ifdef DEBUG
 #if 0
   if (!success) {
     sID = src_cell.GetID();
@@ -622,32 +622,32 @@
   }
 #endif 
 
-  // Set facing in destinatiion cell
-  success = 0;
-  newFacing = fromFacing;
-  for(int i = 0; i < actualNeighborhoodSize; i++) {
-    if (dest_cell.GetFacing() != newFacing) {
-      dest_cell.ConnectionList().CircNext();
-      // cout << "MO: dest_cell facing not yet at " << newFacing << endl;
-    } else {
-      // cout << "MO: dest_cell facing successfully set to " << newFacing << endl;
-      success = 1;
-      break;
-    }
+// Set facing in destinatiion cell
+success = 0;
+newFacing = fromFacing;
+for(int i = 0; i < actualNeighborhoodSize; i++) {
+  if (dest_cell.GetFacing() != newFacing) {
+    dest_cell.ConnectionList().CircNext();
+    // cout << "MO: dest_cell facing not yet at " << newFacing << endl;
+  } else {
+    // cout << "MO: dest_cell facing successfully set to " << newFacing << endl;
+    success = 1;
+    break;
   }
+}
 // @DMB this doesn't compile properly -- #ifdef DEBUG
 #if 0
-  if (!success) {
-    sID = src_cell.GetID();
-    dID = dest_cell.GetID();
-    src_cell.GetPosition(xx1,yy1);
-    dest_cell.GetPosition(xx2,yy2);
-    if (1 == abs(xx2-xx1)+abs(yy2-yy1)) {
-      cout << "MO: src: " << sID << "@ (" << xx1 << "," << yy1 << ") dest: " << dID << "@ (" << xx2 << "," << yy2 << "), FAILED to set dest_cell facing to " << newFacing << endl;
-    }
+if (!success) {
+  sID = src_cell.GetID();
+  dID = dest_cell.GetID();
+  src_cell.GetPosition(xx1,yy1);
+  dest_cell.GetPosition(xx2,yy2);
+  if (1 == abs(xx2-xx1)+abs(yy2-yy1)) {
+    cout << "MO: src: " << sID << "@ (" << xx1 << "," << yy1 << ") dest: " << dID << "@ (" << xx2 << "," << yy2 << "), FAILED to set dest_cell facing to " << newFacing << endl;
   }
+}
 #endif
-  
+
 }
 
 void cPopulation::KillOrganism(cPopulationCell& in_cell)
@@ -661,10 +661,10 @@
   m_world->GetStats().RecordDeath();
   
   int cellID = in_cell.GetID();
-
-  if(GetCell(cellID).GetOrganism()->IsSleeping()) {
-    GetCell(cellID).GetOrganism()->SetSleeping(false);
-    m_world->GetStats().decNumAsleep(GetCell(cellID).GetDemeID());
+  
+  if(organism->IsSleeping()) {
+    organism->SetSleeping(false);
+    organism->GetOrgInterface().GetDeme()->DecSleepingCount();
   }
   if(m_world->GetConfig().LOG_SLEEP_TIMES.Get() == 1) {
     if(sleep_log[cellID].Size() > 0) {
@@ -675,19 +675,18 @@
     }
   }
   
-  
   tList<tListNode<cSaleItem> >* sold_items = organism->GetSoldItems();
   if (sold_items)
   {
-	  tListIterator<tListNode<cSaleItem> > sold_it(*sold_items);
-	  tListNode<cSaleItem> * test_node;
+    tListIterator<tListNode<cSaleItem> > sold_it(*sold_items);
+    tListNode<cSaleItem> * test_node;
     
-	  while ( (test_node = sold_it.Next()) != NULL)
-	  {
+    while ( (test_node = sold_it.Next()) != NULL)
+    {
       tListIterator<cSaleItem> market_it(market[test_node->data->GetLabel()]);
       market_it.Set(test_node);
       delete market_it.Remove();
-	  }
+    }
   }
   // Do the lineage handling
   if (m_world->GetConfig().LOG_LINEAGES.Get()) { m_world->GetClassificationManager().RemoveLineageOrganism(organism); }
@@ -761,78 +760,78 @@
 
 void cPopulation::AddSellValue(const int data, const int label, const int sell_price, const int org_id, const int cell_id)
 {
-	// find list under appropriate label, labels more than 8 nops long are simply the same
-	// as a smaller label modded by the market size
-	//int pos = label % market.GetSize();
+  // find list under appropriate label, labels more than 8 nops long are simply the same
+  // as a smaller label modded by the market size
+  //int pos = label % market.GetSize();
   
-	//// id of genotype currently residing in cell that seller live(d) in compared to 
-	//// id of genotype of actual seller, if different than seller is dead, remove item from list
-	//while ( market[pos].GetSize() > 0 && 
-	//	(!GetCell(market[pos].GetFirst()->GetCellID()).IsOccupied() ||
-	//	GetCell(market[pos].GetFirst()->GetCellID()).GetOrganism()->GetID()
-	//	!= 	market[pos].GetFirst()->GetOrgID()) )
-	//{
-	//	market[pos].Pop();
-	//}
+  //// id of genotype currently residing in cell that seller live(d) in compared to 
+  //// id of genotype of actual seller, if different than seller is dead, remove item from list
+  //while ( market[pos].GetSize() > 0 && 
+  //	(!GetCell(market[pos].GetFirst()->GetCellID()).IsOccupied() ||
+  //	GetCell(market[pos].GetFirst()->GetCellID()).GetOrganism()->GetID()
+  //	!= 	market[pos].GetFirst()->GetOrgID()) )
+  //{
+  //	market[pos].Pop();
+  //}
     
-	// create sale item
-	cSaleItem *new_item = new cSaleItem(data, label, sell_price, org_id, cell_id);
+  // create sale item
+  cSaleItem *new_item = new cSaleItem(data, label, sell_price, org_id, cell_id);
   
-	// place into array by label, array is big enough for labels up to 8 nops long
-	tListNode<cSaleItem>* sell_node = market[label].PushRear(new_item);
-	tListNode<tListNode<cSaleItem> >* org_node = GetCell(cell_id).GetOrganism()->AddSoldItem(sell_node);
-	sell_node->data->SetNodePtr(org_node);
+  // place into array by label, array is big enough for labels up to 8 nops long
+  tListNode<cSaleItem>* sell_node = market[label].PushRear(new_item);
+  tListNode<tListNode<cSaleItem> >* org_node = GetCell(cell_id).GetOrganism()->AddSoldItem(sell_node);
+  sell_node->data->SetNodePtr(org_node);
   
-	//:7 for Kolby
+  //:7 for Kolby
 }
 
 int cPopulation::BuyValue(const int label, const int buy_price, const int cell_id)
 {
-	// find list under appropriate label, labels more than 8 nops long are simply the same
-	// as a smaller label modded by the market size
-	//int pos = label % market.GetSize();
+  // find list under appropriate label, labels more than 8 nops long are simply the same
+  // as a smaller label modded by the market size
+  //int pos = label % market.GetSize();
   
-	//// id of genotype currently residing in cell that seller live(d) in compared to 
-	//// id of genotype of actual seller, if different than seller is dead, remove item from list
-	//while ( market[pos].GetSize() > 0 && 
-	//	(!GetCell(market[pos].GetFirst()->GetCellID()).IsOccupied() ||
-	//	GetCell(market[pos].GetFirst()->GetCellID()).GetOrganism()->GetID()
-	//	!= 	market[pos].GetFirst()->GetOrgID()) )
-	//{
-	//	market[pos].Pop();
-	//}
+  //// id of genotype currently residing in cell that seller live(d) in compared to 
+  //// id of genotype of actual seller, if different than seller is dead, remove item from list
+  //while ( market[pos].GetSize() > 0 && 
+  //	(!GetCell(market[pos].GetFirst()->GetCellID()).IsOccupied() ||
+  //	GetCell(market[pos].GetFirst()->GetCellID()).GetOrganism()->GetID()
+  //	!= 	market[pos].GetFirst()->GetOrgID()) )
+  //{
+  //	market[pos].Pop();
+  //}
     
-	// if there's nothing in the list don't bother with rest
-	if (market[label].GetSize() <= 0)
-		return 0;
+  // if there's nothing in the list don't bother with rest
+  if (market[label].GetSize() <= 0)
+    return 0;
   
-	// if the sell price is higher than we're willing to pay no purchase made
-	if (market[label].GetFirst()->GetPrice() > buy_price)
-		return 0;
+  // if the sell price is higher than we're willing to pay no purchase made
+  if (market[label].GetFirst()->GetPrice() > buy_price)
+    return 0;
   
-	// if the buy price is higher than buying org's current merit no purchase made
-	if (GetCell(cell_id).GetOrganism()->GetPhenotype().GetMerit().GetDouble() < buy_price)
-		return 0;
+  // if the buy price is higher than buying org's current merit no purchase made
+  if (GetCell(cell_id).GetOrganism()->GetPhenotype().GetMerit().GetDouble() < buy_price)
+    return 0;
   
-	// otherwise transaction should be completed!
-	cSaleItem* chosen = market[label].Pop();
-	tListIterator<tListNode<cSaleItem> > sold_it(*GetCell(chosen->GetCellID()).GetOrganism()->GetSoldItems());
-	sold_it.Set(chosen->GetNodePtr());
-	sold_it.Remove();
+  // otherwise transaction should be completed!
+  cSaleItem* chosen = market[label].Pop();
+  tListIterator<tListNode<cSaleItem> > sold_it(*GetCell(chosen->GetCellID()).GetOrganism()->GetSoldItems());
+  sold_it.Set(chosen->GetNodePtr());
+  sold_it.Remove();
   
-	// first update sellers merit
-	double cur_merit = GetCell(chosen->GetCellID()).GetOrganism()->GetPhenotype().GetMerit().GetDouble();
-	cur_merit += buy_price;
-	
-	GetCell(chosen->GetCellID()).GetOrganism()->UpdateMerit(cur_merit);
-	
-	// next remove sold item from list in market 
-	//market[pos].Remove(chosen);
+  // first update sellers merit
+  double cur_merit = GetCell(chosen->GetCellID()).GetOrganism()->GetPhenotype().GetMerit().GetDouble();
+  cur_merit += buy_price;
   
+  GetCell(chosen->GetCellID()).GetOrganism()->UpdateMerit(cur_merit);
   
-	// finally return recieve value, buyer merit will be updated if return a valid value here
-	int receive_value = chosen->GetData();
-	return receive_value;
+  // next remove sold item from list in market 
+  //market[pos].Remove(chosen);
+  
+  
+  // finally return recieve value, buyer merit will be updated if return a valid value here
+  int receive_value = chosen->GetData();
+  return receive_value;
 }
 
 void cPopulation::SwapCells(cPopulationCell & cell1, cPopulationCell & cell2)
@@ -938,7 +937,7 @@
       }
       break; 
     case 4: 	// deme fitness = 2^(-deme fitness rank) 
-              // first find all the deme fitness values ...
+                // first find all the deme fitness values ...
     {      
       for (int deme_id = 0; deme_id < num_demes; deme_id++) {
         cDoubleSum single_deme_fitness;
@@ -1067,6 +1066,11 @@
     cDeme & from_deme = deme_array[from_deme_id];
     cDeme & to_deme   = deme_array[to_deme_id];
     
+    
+    ///    ReplaceDeme(cDeme& source_deme, cDeme& target_deme)
+    
+    
+    
     // Do the actual copy!
     for (int i = 0; i < from_deme.GetSize(); i++) {
       int from_cell_id = from_deme.GetCellID(i);
@@ -1098,19 +1102,19 @@
 
 
 /*! Compete all demes with each other based on the given vector of fitness values.
- 
- This form of compete demes uses fitness-proportional selection on a vector of deme
- fitnesses for group selection.  It integrates with the various deme replication options
- used in ReplicateDemes.
- 
- Note: New deme competition fitness functions are added in PopulationActions.cc by subclassing
- cActionAbstractCompeteDemes and overriding cActionAbstractCompeteDemes::Fitness(cDeme&).  (Don't forget
- to register the action and add it to the events file).
- 
- Another note: To mimic the behavior of the other version of CompeteDemes (which is kept around
- for backwards compatibility), change the config option DEMES_REPLICATE_SIZE to be the size of 
- each deme.
- */
+
+This form of compete demes uses fitness-proportional selection on a vector of deme
+fitnesses for group selection.  It integrates with the various deme replication options
+used in ReplicateDemes.
+
+Note: New deme competition fitness functions are added in PopulationActions.cc by subclassing
+cActionAbstractCompeteDemes and overriding cActionAbstractCompeteDemes::Fitness(cDeme&).  (Don't forget
+                                                                                           to register the action and add it to the events file).
+
+Another note: To mimic the behavior of the other version of CompeteDemes (which is kept around
+                                                                          for backwards compatibility), change the config option DEMES_REPLICATE_SIZE to be the size of 
+each deme.
+*/
 void cPopulation::CompeteDemes(const std::vector<double>& fitness) {
   // Each deme must have a fitness:
   assert((int)fitness.size() == deme_array.GetSize());
@@ -1181,6 +1185,7 @@
 3: 'deme-age'  - ...demes who have reached their maximum age
 4: 'birth-count' ...demes that have had a certain number of births.
 5: 'sat-mov-pred'...demes whose movement predicate was previously satisfied
+6: 'events-killed' ...demes that have killed a certian number of events
 
 */
 
@@ -1229,6 +1234,22 @@
         if(!(source_deme.MovPredSatisfiedPreviously())) continue;
         break;
       }
+      case 6: {
+        int currentSlotSuccessful = 0;
+        double kill_ratio = 0.0;
+        
+        if(source_deme.GetSlotFlowRate() == 0) 
+          kill_ratio = 1.0;
+        else
+          kill_ratio = static_cast<double>(source_deme.GetEventsKilledThisSlot()) / static_cast<double>(source_deme.GetSlotFlowRate());
+        
+        if(kill_ratio >= m_world->GetConfig().DEMES_MIM_EVENTS_KILLED_RATIO.Get())
+          currentSlotSuccessful = 1;
+        
+        // Replicate demes that have killed a certain number of event.
+        if(source_deme.GetConsecutiveSuccessfulEventPeriods()+currentSlotSuccessful < m_world->GetConfig().DEMES_MIM_SUCCESSFUL_EVENT_PERIODS.Get()) continue;
+        break;
+      }
       default: {
         cerr << "ERROR: Invalid replication trigger " << rep_trigger
         << " in cPopulation::ReplicateDemes()" << endl;
@@ -1244,70 +1265,72 @@
 */
 void cPopulation::ReplicateDeme(cDeme & source_deme)
 {
-    // Doesn't make sense to try and replicate a deme that *has no organisms*.
-    if(source_deme.IsEmpty()) return;
+  // Doesn't make sense to try and replicate a deme that *has no organisms*.
+  if(source_deme.IsEmpty()) return;
+  
+  // Prevent sterile demes from replicating.
+  if(m_world->GetConfig().DEMES_PREVENT_STERILE.Get() && (source_deme.GetBirthCount() == 0)) {
+    // assumes that all group level tasks cannot be solved by a single organism
+    source_deme.KillAll();
+    return;
+  }
+  
+  //Option to bridge between kin and group selection.
+  if (m_world->GetConfig().DEMES_REPLICATION_ONLY_RESETS.Get())
+  {
+    //Reset deme (resources and births, among other things)
+    bool source_deme_resource_reset = m_world->GetConfig().DEMES_RESET_RESOURCES.Get() == 0;
+    source_deme.DivideReset(source_deme, source_deme_resource_reset);
     
-    // Prevent sterile demes from replicating.
-    if(m_world->GetConfig().DEMES_PREVENT_STERILE.Get() && (source_deme.GetBirthCount() == 0)) {
-      return;
-    }
-    
-    //Option to bridge between kin and group selection.
-    if (m_world->GetConfig().DEMES_REPLICATION_ONLY_RESETS.Get())
-    {
-      //Reset deme (resources and births, among other things)
-      bool source_deme_resource_reset = m_world->GetConfig().DEMES_RESET_RESOURCES.Get() == 0;
-      source_deme.DivideReset(source_deme, source_deme_resource_reset);
-      
-      //Reset all organisms in deme, by re-injecting them?
-      if (m_world->GetConfig().DEMES_REPLICATION_ONLY_RESETS.Get() == 2) {
-        for (int i=0; i<source_deme.GetSize(); i++) {
-          int cellid = source_deme.GetCellID(i);
-          if (GetCell(cellid).IsOccupied()) {          
-            int lineage = GetCell(cellid).GetOrganism()->GetLineageLabel();
-            cGenome genome = GetCell(cellid).GetOrganism()->GetGenome();
-            InjectGenome(cellid, genome, lineage);
-          }
+    //Reset all organisms in deme, by re-injecting them?
+    if (m_world->GetConfig().DEMES_REPLICATION_ONLY_RESETS.Get() == 2) {
+      for (int i=0; i<source_deme.GetSize(); i++) {
+        int cellid = source_deme.GetCellID(i);
+        if (GetCell(cellid).IsOccupied()) {          
+          int lineage = GetCell(cellid).GetOrganism()->GetLineageLabel();
+          cGenome genome = GetCell(cellid).GetOrganism()->GetGenome();
+          InjectGenome(cellid, genome, lineage);
         }
       }
-      return;
     }
+    return;
+  }
+  
+  // Pick a target deme to replicate to, making sure that 
+  // we don't try to replicate over ourself, i.e. DEMES_REPLACE_PARENT 0
+  
+  int target_id = -1;
+  if (m_world->GetConfig().DEMES_PREFER_EMPTY.Get()) {
     
-    // Pick a target deme to replicate to, making sure that 
-    // we don't try to replicate over ourself, i.e. DEMES_REPLACE_PARENT 0
-    
-    int target_id = -1;
-    if (m_world->GetConfig().DEMES_PREFER_EMPTY.Get()) {
-    
-      //@JEB -- use empty_cell_id_array to hold empty demes
-      //so we don't have to allocate a list
-      int num_empty = 0;
-      for (int i=0; i<GetNumDemes(); i++) {
-        if (GetDeme(i).IsEmpty()) {
-          empty_cell_id_array[num_empty] = i;
-          num_empty++;
-        }
-      }  
-      if (num_empty > 0) {
-        target_id = empty_cell_id_array[m_world->GetRandom().GetUInt(num_empty)];
+    //@JEB -- use empty_cell_id_array to hold empty demes
+    //so we don't have to allocate a list
+    int num_empty = 0;
+    for (int i=0; i<GetNumDemes(); i++) {
+      if (GetDeme(i).IsEmpty()) {
+        empty_cell_id_array[num_empty] = i;
+        num_empty++;
       }
+    }  
+    if (num_empty > 0) {
+      target_id = empty_cell_id_array[m_world->GetRandom().GetUInt(num_empty)];
     }
-    
-    // if we haven't found one yet, choose a random one
-    if (target_id == -1) {
-      target_id = source_deme.GetID();
-      const int num_demes = GetNumDemes();
-      while(target_id == source_deme.GetID()) {
-        target_id = m_world->GetRandom().GetUInt(num_demes);
-      }
+  }
+  
+  // if we haven't found one yet, choose a random one
+  if (target_id == -1) {
+    target_id = source_deme.GetID();
+    const int num_demes = GetNumDemes();
+    while(target_id == source_deme.GetID()) {
+      target_id = m_world->GetRandom().GetUInt(num_demes);
     }
-    ReplaceDeme(source_deme, deme_array[target_id]);
+  }
+  ReplaceDeme(source_deme, deme_array[target_id]);
 }
 
 /*! ReplaceDeme is a helper method that handles all the different configuration
 options related to the replacement of a target deme by a source.  It works with
 both CompeteDemes and ReplicateDemes (and can be called directly via an event if
-so desired).
+                                      so desired).
 
 @refactor Replace manual mutation with strategy pattern.
 */
@@ -1319,7 +1342,8 @@
   // used to pass energy to offspring demes (set to zero if energy model is not enabled)
   double source_deme_energy(0.0), deme_energy_decay(0.0), parent_deme_energy(0.0), offspring_deme_energy(0.0);
   if(m_world->GetConfig().ENERGY_ENABLED.Get()) {
-    source_deme_energy = source_deme.CalculateTotalEnergy();
+    source_deme_energy = source_deme.CalculateTotalEnergy() + source_deme.GetTotalEnergyTestament();
+    m_world->GetStats().SumEnergyTestamentAcceptedByDeme().Add(source_deme.GetTotalEnergyTestament());
     deme_energy_decay = 1.0 - m_world->GetConfig().FRAC_ENERGY_DECAY_AT_DEME_BIRTH.Get();
     parent_deme_energy = source_deme_energy * deme_energy_decay * (1.0 - m_world->GetConfig().FRAC_PARENT_ENERGY_GIVEN_TO_DEME_AT_BIRTH.Get());
     offspring_deme_energy = source_deme_energy * deme_energy_decay * m_world->GetConfig().FRAC_PARENT_ENERGY_GIVEN_TO_DEME_AT_BIRTH.Get();
@@ -1359,7 +1383,7 @@
     // mutated germ to ONLY the target's germline.  The source remains unchanged.
     target_deme.ReplaceGermline(source_deme.GetGermline());
     target_deme.GetGermline().Add(next_germ);
-        
+    
     // Germline stats tracking.
     m_world->GetStats().GermlineReplication(source_deme.GetGermline(), target_deme.GetGermline());
     
@@ -1406,12 +1430,12 @@
     target_deme.ReplaceGermline(*new_germline_genotype);
     SeedDeme(source_deme, *new_germline_genotype);
     SeedDeme(target_deme, *new_germline_genotype);
-
+    
   } else {
     // Not using germlines; things are much simpler.  Seed the target from the source.
     target_successfully_seeded = SeedDeme(source_deme, target_deme);
   }
-
+  
   // The source's merit must be transferred to the target, and then the source has
   // to rotate its heritable merit to its current merit.
   if (target_successfully_seeded) target_deme.UpdateDemeMerit(source_deme);
@@ -1448,8 +1472,8 @@
     if (target_successfully_seeded) target_deme.DivideReset(source_deme, target_deme_resource_reset);
     source_deme.DivideReset(source_deme, source_deme_resource_reset);
   }
-
   
+  
   // do our post-replication stats tracking.
   m_world->GetStats().DemePostReplication(source_deme, target_deme);
 }
@@ -1495,13 +1519,13 @@
 */
 bool cPopulation::SeedDeme(cDeme& source_deme, cDeme& target_deme) {
   cRandom& random = m_world->GetRandom();
-
+  
   bool successfully_seeded = true;
-
+  
   // Check to see if we're doing probabilistic organism replication from source
   // to target deme.
   if(m_world->GetConfig().DEMES_PROB_ORG_TRANSFER.Get() == 0.0) {
-  
+    
     //@JEB -- old method is default for consistency! 
     if (m_world->GetConfig().DEMES_SEED_METHOD.Get() == 0) {
       // Here's the idea: store up a list of the genotypes from the source that we
@@ -1518,10 +1542,10 @@
       //       because the cGenotype* from cOrganism::GetGenotype may not live after
       //       a call to cDeme::KillAll.
       std::vector<std::pair<cGenome,int> > xfer; // List of genomes we're going to transfer.
-    
+      
       switch(m_world->GetConfig().DEMES_ORGANISM_SELECTION.Get()) {
         case 0: { // Random w/ replacement (meaning, we don't prevent the same genotype from
-          // being selected more than once).
+                  // being selected more than once).
           while((int)xfer.size() < m_world->GetConfig().DEMES_REPLICATE_SIZE.Get()) {
             int cellid = source_deme.GetCellID(random.GetUInt(source_deme.GetSize()));
             if(cell_array[cellid].IsOccupied()) {
@@ -1543,7 +1567,7 @@
         }
         default: {
           cout << "Undefined value (" << m_world->GetConfig().DEMES_ORGANISM_SELECTION.Get()
-            << ") for DEMES_ORGANISM_SELECTION." << endl;
+          << ") for DEMES_ORGANISM_SELECTION." << endl;
           exit(1);
         }
       }   
@@ -1553,23 +1577,24 @@
       // Clear the demes.
       source_deme.UpdateStats();
       source_deme.KillAll();
-
+      
       target_deme.UpdateStats();
       target_deme.KillAll();
-
+      
       // And now populate the source and target.
       int j=0;
       for(std::vector<std::pair<cGenome,int> >::iterator i=xfer.begin(); i!=xfer.end(); ++i, ++j) {
         int cellid = DemeSelectInjectionCell(source_deme, j);
         InjectGenome(cellid, i->first, i->second);
         DemePostInjection(source_deme, cell_array[cellid]);
-
+        
         cellid = DemeSelectInjectionCell(target_deme, j);
         InjectGenome(cellid, i->first, i->second);
         DemePostInjection(target_deme, cell_array[cellid]);      
+        
       }
     } else /* if (m_world->GetConfig().DEMES_SEED_METHOD.Get() != 0) */{
-    
+      
       // @JEB
       // Updated seed deme method that maintains genotype inheritance.
       
@@ -1577,57 +1602,57 @@
       tArray<cOrganism*> source_founders; // List of organisms we're going to transfer.
       tArray<cOrganism*> target_founders; // List of organisms we're going to transfer.
       
-                  /*
-      // Debug Code
-      cGenotype * original_source_founder_genotype = NULL;
-      if (1) {
-        tArray<int>& source_founders = source_deme.GetFounderGenotypeIDs();
-        if (source_founders.GetSize() > 0) {
-          original_source_founder_genotype = m_world->GetClassificationManager().FindGenotype(source_founders[0]);
-          cout << "Source:" << endl << original_source_founder_genotype->GetGenome().AsString() << endl;
-        }
-        tArray<int>& target_founders = target_deme.GetFounderGenotypeIDs();
-        if (target_founders.GetSize() > 0) {
-          cGenotype * target_founder_genotype = m_world->GetClassificationManager().FindGenotype(target_founders[0]);
-          cout << "Target:" << endl << target_founder_genotype->GetGenome().AsString() << endl;
-        }
-      }
-
-      tArray<int>& source_founders = source_deme.GetFounders();
-      cerr << "Original source genotype ids:" << endl;
-      for(int i=0; i<source_founders.GetSize(); i++) {
-        cerr << source_founders[i] << " ";
-      }
-      cerr << endl;
-  
-      tArray<int>& target_founders = target_deme.GetFounders();
-      cerr << "Original target genotype ids:" << endl;
-      for(int i=0; i<target_founders.GetSize(); i++) {
-        cerr << target_founders[i] << " ";
-      }
-      cerr << endl;
+      /*
+       // Debug Code
+       cGenotype * original_source_founder_genotype = NULL;
+       if (1) {
+         tArray<int>& source_founders = source_deme.GetFounderGenotypeIDs();
+         if (source_founders.GetSize() > 0) {
+           original_source_founder_genotype = m_world->GetClassificationManager().FindGenotype(source_founders[0]);
+           cout << "Source:" << endl << original_source_founder_genotype->GetGenome().AsString() << endl;
+         }
+         tArray<int>& target_founders = target_deme.GetFounderGenotypeIDs();
+         if (target_founders.GetSize() > 0) {
+           cGenotype * target_founder_genotype = m_world->GetClassificationManager().FindGenotype(target_founders[0]);
+           cout << "Target:" << endl << target_founder_genotype->GetGenome().AsString() << endl;
+         }
+       }
+       
+       tArray<int>& source_founders = source_deme.GetFounders();
+       cerr << "Original source genotype ids:" << endl;
+       for(int i=0; i<source_founders.GetSize(); i++) {
+         cerr << source_founders[i] << " ";
+       }
+       cerr << endl;
+       
+       tArray<int>& target_founders = target_deme.GetFounders();
+       cerr << "Original target genotype ids:" << endl;
+       for(int i=0; i<target_founders.GetSize(); i++) {
+         cerr << target_founders[i] << " ";
+       }
+       cerr << endl;
+       
+       // Debug Code
+       //// Count the number of orgs in each deme.
+       int count = 0;
+       for(int i=0; i<target_deme.GetSize(); ++i) {
+         int cell_id = target_deme.GetCellID(i);
+         if(cell_array[cell_id].IsOccupied()) count++;
+       }
+       cout << "Initial orgs in target deme: " << count << endl;
+       
+       count = 0;
+       for(int i=0; i<source_deme.GetSize(); ++i) {
+         int cell_id = source_deme.GetCellID(i);
+         if(cell_array[cell_id].IsOccupied()) count++;
+       }
+       cout << "Initial orgs in source deme: " << count << endl;     
+       */
       
-      // Debug Code
-      //// Count the number of orgs in each deme.
-      int count = 0;
-      for(int i=0; i<target_deme.GetSize(); ++i) {
-        int cell_id = target_deme.GetCellID(i);
-        if(cell_array[cell_id].IsOccupied()) count++;
-      }
-      cout << "Initial orgs in target deme: " << count << endl;
-
-      count = 0;
-      for(int i=0; i<source_deme.GetSize(); ++i) {
-        int cell_id = source_deme.GetCellID(i);
-        if(cell_array[cell_id].IsOccupied()) count++;
-      }
-      cout << "Initial orgs in source deme: " << count << endl;     
-      */
-
       
       switch(m_world->GetConfig().DEMES_ORGANISM_SELECTION.Get()) {
         case 0: { // Random w/ replacement (meaning, we don't prevent the same genotype from
-          // being selected more than once).
+                  // being selected more than once).
           tArray<cOrganism*> founders; // List of organisms we're going to transfer.
           while(founders.GetSize() < m_world->GetConfig().DEMES_REPLICATE_SIZE.Get()) {
             int cellid = source_deme.GetCellID(random.GetUInt(source_deme.GetSize()));
@@ -1656,34 +1681,34 @@
           
           //Die if not >= two organisms. 
           if (source_deme.GetOrgCount() >= 2) {
-          
+            
             //Collect prospective founder organisms into a list
             for (int i=0; i < source_deme.GetSize(); i++) {
               if ( GetCell(source_deme.GetCellID(i)).IsOccupied() ) {
-                  prospective_founders.Push( GetCell(source_deme.GetCellID(i)).GetOrganism() );
+                prospective_founders.Push( GetCell(source_deme.GetCellID(i)).GetOrganism() );
               }
             }
-
+            
             //add orgs alternately to source and target founders until
             //we run out or each reaches DEMES_REPLICATE_SIZE.
             int num_chosen_orgs = 0;
             while( ((target_founders.GetSize() < m_world->GetConfig().DEMES_REPLICATE_SIZE.Get())
-                || (source_founders.GetSize() < m_world->GetConfig().DEMES_REPLICATE_SIZE.Get()))
-                && (prospective_founders.GetSize() > 0) ) {
-
+                    || (source_founders.GetSize() < m_world->GetConfig().DEMES_REPLICATE_SIZE.Get()))
+                   && (prospective_founders.GetSize() > 0) ) {
+              
               int chosen_org = random.GetUInt(prospective_founders.GetSize());
               if (num_chosen_orgs % 2 == 0) {
                 source_founders.Push(prospective_founders.PopPos(chosen_org));
               } else {
                 target_founders.Push(prospective_founders.PopPos(chosen_org));
               } 
-                          
+              
               num_chosen_orgs++;
             }
           }
           break;
         }
-
+          
         case 2: 
         case 3:
         case 4:
@@ -1696,9 +1721,9 @@
           // 4: same as 3: but replication to target fails if only one germ.
           // 5: same as 3: but replication fails and source dies if fewer than two germs.
           tArray<cOrganism*> founders; // List of organisms we're going to transfer.
-
+          
           if (source_deme.GetOrgCount() >= 2) {
-          
+            
             if (m_world->GetConfig().DEMES_DIVIDE_METHOD.Get() != 0) {
               m_world->GetDriver().RaiseFatalException(1, "Germline DEMES_ORGANISM_SELECTION methods 2 and 3 can only be used with DEMES_DIVIDE_METHOD 0.");
             }
@@ -1723,19 +1748,19 @@
             if (m_world->GetVerbosity() >= VERBOSE_ON) cout << "Num prospective founders: " << prospective_founders.GetSize() << endl;
             
             if (prospective_founders.GetSize() < 2) {
-            
+              
               // there were not enough orgs with nonzero germlines
               // pick additional orgs at random without replacement,
               // unless our method forbids this
-
+              
               // leave the founder list empty for method 5
               if (m_world->GetConfig().DEMES_ORGANISM_SELECTION.Get() != 5) {
-              
+                
                 founders = prospective_founders;
                 
                 //do not add additional founders randomly for method 4
                 if (m_world->GetConfig().DEMES_ORGANISM_SELECTION.Get() != 4) {
-                
+                  
                   while(founders.GetSize() < 2) {
                     int cellid = source_deme.GetCellID(random.GetUInt(source_deme.GetSize()));
                     if( cell_array[cellid].IsOccupied() ) {
@@ -1750,15 +1775,15 @@
                 }  
               }
             } else {
-            
-            // pick two orgs based on germline propensities from prospective founders
-
+              
+              // pick two orgs based on germline propensities from prospective founders
+              
               while(founders.GetSize() < 2) {
-              
+                
                 double choice = (m_world->GetConfig().DEMES_ORGANISM_SELECTION.Get() == 2)
-                  ? random.GetDouble( gp_sum.Sum() ) : random.GetDouble( gp_sum.Count() );
-
-
+                ? random.GetDouble( gp_sum.Sum() ) : random.GetDouble( gp_sum.Count() );
+                
+                
                 //cout <<  "Count: " << gp_sum.Count() << endl;
                 
                 // find the next organism to choose
@@ -1776,8 +1801,8 @@
                   // if it wasn't already chosen, then we count down...
                   if (!found) {
                     choice -= (m_world->GetConfig().DEMES_ORGANISM_SELECTION.Get() == 2) 
-                      ? org->GetPhenotype().GetPermanentGermlinePropensity()
-                      : (org->GetPhenotype().GetPermanentGermlinePropensity() > 0);
+                    ? org->GetPhenotype().GetPermanentGermlinePropensity()
+                    : (org->GetPhenotype().GetPermanentGermlinePropensity() > 0);
                   }
                   on++;
                 }
@@ -1792,34 +1817,34 @@
             if (founders.GetSize() > 1) target_founders.Push(founders[1]);       
             
             /*
-            // Debug Code
-            cout << endl;
-            cout << "sum " << gp_sum.Sum() << endl;
-            cout << "min " << min << endl;
-            cout << "choice " << choice << endl;
-            */
-              
+             // Debug Code
+             cout << endl;
+             cout << "sum " << gp_sum.Sum() << endl;
+             cout << "min " << min << endl;
+             cout << "choice " << choice << endl;
+             */
+            
             //cout << "Chose germline propensity " << chosen_org->GetPhenotype().GetLastGermlinePropensity() << endl;
           } else { 
             //Failure because we didn't have at least two organisms...
             //m_world->GetDriver().RaiseFatalException(1, "Germline DEMES_ORGANISM_SELECTION method didn't find at least two organisms in deme.");
           }
-        
-        break;
+          
+          break;
         }  
         default: {
           cout << "Undefined value (" << m_world->GetConfig().DEMES_ORGANISM_SELECTION.Get()
-            << ") for DEMES_ORGANISM_SELECTION." << endl;
+          << ") for DEMES_ORGANISM_SELECTION." << endl;
           exit(1);
         }
       }
       
-
+      
       // We'd better have at *least* one genome.
       // Methods that require a germline can sometimes come up short...
       //assert(source_founders.GetSize()>0);
       //assert(target_founders.GetSize()>0);
-
+      
       // We clear the deme, but trick cPopulation::KillOrganism
       // to NOT delete the organisms, by pretending 
       // the orgs are running. This way we can still create 
@@ -1827,29 +1852,29 @@
       // We also need to defer adjusting the genotype
       // or it will be prematurely deleted before we are done!
       
-     // cDoubleSum gen;
+      // cDoubleSum gen;
       tArray<cOrganism*> old_source_organisms;
       for(int i=0; i<source_deme.GetSize(); ++i) {
         int cell_id = source_deme.GetCellID(i);
-          
+        
         if(cell_array[cell_id].IsOccupied()) {
           cOrganism * org = cell_array[cell_id].GetOrganism();
           old_source_organisms.Push(org);
           org->SetRunning(true);
           org->GetGenotype()->IncDeferAdjust();
           
-         // cout << org->GetPhenotype().GetGeneration()-source_deme.GetAvgFounderGeneration() << " ";
-         // gen.Add(org->GetPhenotype().GetGeneration()-source_deme.GetAvgFounderGeneration());
+          // cout << org->GetPhenotype().GetGeneration()-source_deme.GetAvgFounderGeneration() << " ";
+          // gen.Add(org->GetPhenotype().GetGeneration()-source_deme.GetAvgFounderGeneration());
         }
       }  
       //cout << endl;
       //cout << "Average: " << gen.Average() << endl;
-
       
+      
       tArray<cOrganism*> old_target_organisms;
       for(int i=0; i<target_deme.GetSize(); ++i) {
         int cell_id = target_deme.GetCellID(i);
-          
+        
         if(cell_array[cell_id].IsOccupied()) {
           cOrganism * org = cell_array[cell_id].GetOrganism();
           old_target_organisms.Push(org);
@@ -1868,16 +1893,16 @@
       }
       
       //cout << founders.GetSize() << " founders." << endl;
-
+      
       // Now populate the target (and optionally the source) using InjectGenotype.
       // In the future InjectClone could be used, but this would require the 
       // deme keeping complete copies of the founder organisms when
       // we wanted to re-seed from the original founders.
       for(int i=0; i<target_founders.GetSize(); i++) {
-          int cellid = DemeSelectInjectionCell(target_deme, i);
-          InjectDemeFounder(cellid, *target_founders[i]->GetGenotype(), &target_founders[i]->GetPhenotype());
-          target_deme.AddFounder(*target_founders[i]->GetGenotype(), &target_founders[i]->GetPhenotype());
-          DemePostInjection(target_deme, cell_array[cellid]);
+        int cellid = DemeSelectInjectionCell(target_deme, i);
+        InjectDemeFounder(cellid, *target_founders[i]->GetGenotype(), &target_founders[i]->GetPhenotype());
+        target_deme.AddFounder(*target_founders[i]->GetGenotype(), &target_founders[i]->GetPhenotype());
+        DemePostInjection(target_deme, cell_array[cellid]);
       }
       
       // We either repeat this procedure in the source deme,
@@ -1886,7 +1911,7 @@
       
       // source deme is replaced in the same way as the target
       if (m_world->GetConfig().DEMES_DIVIDE_METHOD.Get() == 0) {    
-
+        
         source_deme.ClearFounders();
         source_deme.UpdateStats();
         source_deme.KillAll();
@@ -1910,7 +1935,7 @@
         tArray<int>& source_founders = source_deme.GetFounderGenotypeIDs();
         tArray<cPhenotype>& source_founder_phenotypes = source_deme.GetFounderPhenotypes();
         for(int i=0; i<source_founders.GetSize(); i++) {
-        
+          
           int cellid = DemeSelectInjectionCell(source_deme, i);
           //cout << "founder: " << source_founders[i] << endl;
           cGenotype * genotype = m_world->GetClassificationManager().FindGenotype(source_founders[i]);
@@ -1927,66 +1952,66 @@
       else {
         m_world->GetDriver().RaiseFatalException(1, "Unknown DEMES_DIVIDE_METHOD");
       }
+      
+      /*
+       // Debug Code
+       //// Count the number of orgs in each deme.
+       count = 0;
+       for(int i=0; i<target_deme.GetSize(); ++i) {
+         int cell_id = target_deme.GetCellID(i);
+         if(cell_array[cell_id].IsOccupied()) count++;
+       }
+       cout << "Final orgs in target deme: " << count << endl;
        
-      /*
-      // Debug Code
-      //// Count the number of orgs in each deme.
-      count = 0;
-      for(int i=0; i<target_deme.GetSize(); ++i) {
-        int cell_id = target_deme.GetCellID(i);
-        if(cell_array[cell_id].IsOccupied()) count++;
-      }
-      cout << "Final orgs in target deme: " << count << endl;
-
-      count = 0;
-      for(int i=0; i<source_deme.GetSize(); ++i) {
-        int cell_id = source_deme.GetCellID(i);
-        if(cell_array[cell_id].IsOccupied()) count++;
-      }
-      cout << "Final orgs in source deme: " << count << endl;
-
-      if (1) {
-        tArray<int>& source_founders = source_deme.GetFounderGenotypeIDs();
-        cGenotype * source_founder_genotype = m_world->GetClassificationManager().FindGenotype(source_founders[0]);
-        tArray<int>& target_founders = target_deme.GetFounderGenotypeIDs();
-        cGenotype * target_founder_genotype = m_world->GetClassificationManager().FindGenotype(target_founders[0]);
-        if (original_source_founder_genotype->GetGenome().AsString() != source_founder_genotype->GetGenome().AsString())
-        {
-          cout << "Original source founder does not equal final source founder!!!!" << endl;
-        }
+       count = 0;
+       for(int i=0; i<source_deme.GetSize(); ++i) {
+         int cell_id = source_deme.GetCellID(i);
+         if(cell_array[cell_id].IsOccupied()) count++;
+       }
+       cout << "Final orgs in source deme: " << count << endl;
+       
+       if (1) {
+         tArray<int>& source_founders = source_deme.GetFounderGenotypeIDs();
+         cGenotype * source_founder_genotype = m_world->GetClassificationManager().FindGenotype(source_founders[0]);
+         tArray<int>& target_founders = target_deme.GetFounderGenotypeIDs();
+         cGenotype * target_founder_genotype = m_world->GetClassificationManager().FindGenotype(target_founders[0]);
+         if (original_source_founder_genotype->GetGenome().AsString() != source_founder_genotype->GetGenome().AsString())
+         {
+           cout << "Original source founder does not equal final source founder!!!!" << endl;
+         }
+         
+         cout << "Source:" << endl << source_founder_genotype->GetGenome().AsString() << endl;
+         cout << "Target:" << endl << target_founder_genotype->GetGenome().AsString() << endl;
+       }
+       
+       // Debug
+       tArray<int>& new_source_founders = source_deme.GetFounders();
+       cerr << "New source genotype ids:" << endl;
+       for(int i=0; i<new_source_founders.GetSize(); i++) {
+         cerr << new_source_founders[i] << " ";
+       }
+       cerr << endl;
+       
+       tArray<int>& new_target_founders = target_deme.GetFounders();
+       cerr << "New target genotype ids:" << endl;
+       for(int i=0; i<new_target_founders.GetSize(); i++) {
+         cerr << new_target_founders[i] << " ";
+       }
+       cerr << endl;
+       */
+      
+      // remember to delete the old target organisms and adjust their genotypes
+      for(int i=0; i<old_target_organisms.GetSize(); ++i) {
+        old_target_organisms[i]->SetRunning(false);
+        cGenotype * genotype = old_target_organisms[i]->GetGenotype();
+        genotype->DecDeferAdjust();
+        m_world->GetClassificationManager().AdjustGenotype(*genotype);
         
-        cout << "Source:" << endl << source_founder_genotype->GetGenome().AsString() << endl;
-        cout << "Target:" << endl << target_founder_genotype->GetGenome().AsString() << endl;
+        // ONLY delete target orgs if seeding was successful
+        // otherwise they still exist in the population!!!
+        if (successfully_seeded) delete old_target_organisms[i];
       }
       
-      // Debug
-      tArray<int>& new_source_founders = source_deme.GetFounders();
-      cerr << "New source genotype ids:" << endl;
-      for(int i=0; i<new_source_founders.GetSize(); i++) {
-        cerr << new_source_founders[i] << " ";
-      }
-      cerr << endl;
-  
-      tArray<int>& new_target_founders = target_deme.GetFounders();
-      cerr << "New target genotype ids:" << endl;
-      for(int i=0; i<new_target_founders.GetSize(); i++) {
-        cerr << new_target_founders[i] << " ";
-      }
-      cerr << endl;
-      */
-              
-      // remember to delete the old target organisms and adjust their genotypes
-        for(int i=0; i<old_target_organisms.GetSize(); ++i) {
-          old_target_organisms[i]->SetRunning(false);
-          cGenotype * genotype = old_target_organisms[i]->GetGenotype();
-          genotype->DecDeferAdjust();
-          m_world->GetClassificationManager().AdjustGenotype(*genotype);
-          
-          // ONLY delete target orgs if seeding was successful
-          // otherwise they still exist in the population!!!
-          if (successfully_seeded) delete old_target_organisms[i];
-        }
-      
       for(int i=0; i<old_source_organisms.GetSize(); ++i) {
         old_source_organisms[i]->SetRunning(false);
         cGenotype * genotype = old_source_organisms[i]->GetGenotype();
@@ -1995,8 +2020,8 @@
         
         // delete old source organisms ONLY if source was replaced
         if ( (m_world->GetConfig().DEMES_DIVIDE_METHOD.Get() == 0)
-          || (m_world->GetConfig().DEMES_DIVIDE_METHOD.Get() == 1) ) {
-        delete old_source_organisms[i];
+             || (m_world->GetConfig().DEMES_DIVIDE_METHOD.Get() == 1) ) {
+          delete old_source_organisms[i];
         }
       }
       
@@ -2011,7 +2036,7 @@
     
     // Kill all the organisms in the target deme.
     target_deme.KillAll();
-
+    
     // Check all the organisms in the source deme to see if they get transferred
     // to the target.
     for(int i=0,j=0; i<source_deme.GetSize(); ++i) {
@@ -2038,8 +2063,8 @@
       //}
     }
   }
-  
-  return successfully_seeded;
+
+return successfully_seeded;
 }
 
 void cPopulation::InjectDemeFounder(int _cell_id, cGenotype& _genotype, cPhenotype* _phenotype)
@@ -2051,8 +2076,8 @@
   // At this point, the cell had better be occupied...
   assert(GetCell(_cell_id).IsOccupied());
   cOrganism * organism = GetCell(_cell_id).GetOrganism();
-
-
+  
+  
   //Now we need to set up the phenotype of this organism...
   if (_phenotype) {
     //If we want founders to have their proper phenotypes
@@ -2060,7 +2085,7 @@
     //organism->SetPhenotype(*_phenotype);
     // Re-initialize the time-slice for this new organism.
     //AdjustSchedule(_cell_id, organism->GetPhenotype().GetMerit());
-
+    
     // For now, just copy the generation...
     organism->GetPhenotype().SetGeneration( _phenotype->GetGeneration() );
     
@@ -2073,12 +2098,12 @@
   }
   
   /* It requires much more than this to correctly implement, do later if needed @JEB
-  //Optionally, set the first organism's merit to a constant value
-  //actually, we need to add so the first organism is seeded this way too...
-  if (m_world->GetConfig().DEMES_DEFAULT_MERIT.Get()) {
-    organism->GetPhenotype().SetMerit( cMerit(m_world->GetConfig().DEMES_DEFAULT_MERIT.Get()) );
-    AdjustSchedule(GetCell(_cell_id), organism->GetPhenotype().GetMerit());
-  }
+    //Optionally, set the first organism's merit to a constant value
+    //actually, we need to add so the first organism is seeded this way too...
+    if (m_world->GetConfig().DEMES_DEFAULT_MERIT.Get()) {
+      organism->GetPhenotype().SetMerit( cMerit(m_world->GetConfig().DEMES_DEFAULT_MERIT.Get()) );
+      AdjustSchedule(GetCell(_cell_id), organism->GetPhenotype().GetMerit());
+    }
   */
 }
 
@@ -2087,8 +2112,8 @@
 Respects all of the different placement options that are relevant for deme replication.
 
 @param sequence The number of times DemeSelectInjectionCell has been called on this deme
-                already.  Used for replicating multiple organisms from the source to the
-                target deme in a sensible fashion.
+already.  Used for replicating multiple organisms from the source to the
+target deme in a sensible fashion.
 */
 int cPopulation::DemeSelectInjectionCell(cDeme& deme, int sequence) {
   int cellid = -1;
@@ -2262,90 +2287,90 @@
 
 
 // Print out statistics about donations
-                  
+
 void cPopulation::PrintDonationStats()
 {
   cDoubleSum donation_makers;
   cDoubleSum donation_receivers;
   cDoubleSum donation_cheaters;
-
+  
   cDoubleSum edit_donation_makers;
   cDoubleSum edit_donation_receivers;
   cDoubleSum edit_donation_cheaters;
-
+  
   cDoubleSum kin_donation_makers;
   cDoubleSum kin_donation_receivers;
   cDoubleSum kin_donation_cheaters;
-
+  
   cDoubleSum threshgb_donation_makers;
   cDoubleSum threshgb_donation_receivers;
   cDoubleSum threshgb_donation_cheaters;
-
+  
   cDoubleSum quanta_threshgb_donation_makers;
   cDoubleSum quanta_threshgb_donation_receivers;
   cDoubleSum quanta_threshgb_donation_cheaters;
-
+  
   cStats& stats = m_world->GetStats();
-
+  
   cDataFile & dn_donors = m_world->GetDataFile("donations.dat");
   dn_donors.WriteComment("Info about organisms giving donations in the population");
   dn_donors.WriteTimeStamp();
   dn_donors.Write(stats.GetUpdate(), "update");
-
-
+  
+  
   for (int i = 0; i < cell_array.GetSize(); i++)
-    {
-      // Only look at cells with organisms in them.
-      if (cell_array[i].IsOccupied() == false) continue;
-      cOrganism * organism = cell_array[i].GetOrganism();
-      const cPhenotype & phenotype = organism->GetPhenotype();
-   
-      // donors & receivers in general
-      if (phenotype.IsDonorLast()) donation_makers.Add(1);       //found a donor
-      if (phenotype.IsReceiverLast()){
-        donation_receivers.Add(1);                              //found a receiver
-        if (phenotype.IsDonorLast()==0){
-          donation_cheaters.Add(1);                             //found a receiver whose parent did not give
-        }
+  {
+    // Only look at cells with organisms in them.
+    if (cell_array[i].IsOccupied() == false) continue;
+    cOrganism * organism = cell_array[i].GetOrganism();
+    const cPhenotype & phenotype = organism->GetPhenotype();
+    
+    // donors & receivers in general
+    if (phenotype.IsDonorLast()) donation_makers.Add(1);       //found a donor
+    if (phenotype.IsReceiverLast()){
+      donation_receivers.Add(1);                              //found a receiver
+      if (phenotype.IsDonorLast()==0){
+        donation_cheaters.Add(1);                             //found a receiver whose parent did not give
       }
-      // edit donors & receivers
-      if (phenotype.IsDonorEditLast()) edit_donation_makers.Add(1);       //found a edit donor
-      if (phenotype.IsReceiverEditLast()){
-        edit_donation_receivers.Add(1);                              //found a edit receiver
-        if (phenotype.IsDonorEditLast()==0){
-          edit_donation_cheaters.Add(1);                             //found a edit receiver whose parent did...
-        }                                                              //...not make a edit donation
-      }
-
-      // kin donors & receivers
-      if (phenotype.IsDonorKinLast()) kin_donation_makers.Add(1);       //found a kin donor
-      if (phenotype.IsReceiverKinLast()){
-        kin_donation_receivers.Add(1);                              //found a kin receiver
-        if (phenotype.IsDonorKinLast()==0){
-          kin_donation_cheaters.Add(1);                             //found a kin receiver whose parent did...
-        }                                                              //...not make a kin donation
-      }
-
-      // threshgb donors & receivers
-      if (phenotype.IsDonorThreshGbLast()) threshgb_donation_makers.Add(1); //found a threshgb donor
-      if (phenotype.IsReceiverThreshGbLast()){
-        threshgb_donation_receivers.Add(1);                              //found a threshgb receiver
-        if (phenotype.IsDonorThreshGbLast()==0){
-          threshgb_donation_cheaters.Add(1);                             //found a threshgb receiver whose parent did...
-        }                                                              //...not make a threshgb donation
-      }
-
-      // quanta_threshgb donors & receivers
-      if (phenotype.IsDonorQuantaThreshGbLast()) quanta_threshgb_donation_makers.Add(1); //found a quanta threshgb donor
-      if (phenotype.IsReceiverQuantaThreshGbLast()){
-        quanta_threshgb_donation_receivers.Add(1);                              //found a quanta threshgb receiver
-        if (phenotype.IsDonorQuantaThreshGbLast()==0){
-          quanta_threshgb_donation_cheaters.Add(1);                             //found a quanta threshgb receiver whose parent did...
-        }                                                              //...not make a quanta threshgb donation
-      }
-
     }
-
+    // edit donors & receivers
+    if (phenotype.IsDonorEditLast()) edit_donation_makers.Add(1);       //found a edit donor
+    if (phenotype.IsReceiverEditLast()){
+      edit_donation_receivers.Add(1);                              //found a edit receiver
+      if (phenotype.IsDonorEditLast()==0){
+        edit_donation_cheaters.Add(1);                             //found a edit receiver whose parent did...
+      }                                                              //...not make a edit donation
+    }
+    
+    // kin donors & receivers
+    if (phenotype.IsDonorKinLast()) kin_donation_makers.Add(1);       //found a kin donor
+    if (phenotype.IsReceiverKinLast()){
+      kin_donation_receivers.Add(1);                              //found a kin receiver
+      if (phenotype.IsDonorKinLast()==0){
+        kin_donation_cheaters.Add(1);                             //found a kin receiver whose parent did...
+      }                                                              //...not make a kin donation
+    }
+    
+    // threshgb donors & receivers
+    if (phenotype.IsDonorThreshGbLast()) threshgb_donation_makers.Add(1); //found a threshgb donor
+    if (phenotype.IsReceiverThreshGbLast()){
+      threshgb_donation_receivers.Add(1);                              //found a threshgb receiver
+      if (phenotype.IsDonorThreshGbLast()==0){
+        threshgb_donation_cheaters.Add(1);                             //found a threshgb receiver whose parent did...
+      }                                                              //...not make a threshgb donation
+    }
+    
+    // quanta_threshgb donors & receivers
+    if (phenotype.IsDonorQuantaThreshGbLast()) quanta_threshgb_donation_makers.Add(1); //found a quanta threshgb donor
+    if (phenotype.IsReceiverQuantaThreshGbLast()){
+      quanta_threshgb_donation_receivers.Add(1);                              //found a quanta threshgb receiver
+      if (phenotype.IsDonorQuantaThreshGbLast()==0){
+        quanta_threshgb_donation_cheaters.Add(1);                             //found a quanta threshgb receiver whose parent did...
+      }                                                              //...not make a quanta threshgb donation
+    }
+    
+  }
+  
   dn_donors.Write(donation_makers.Sum(), "parent made at least one donation");
   dn_donors.Write(donation_receivers.Sum(), "parent received at least one donation");
   dn_donors.Write(donation_cheaters.Sum(),  "parent received at least one donation but did not make one");
@@ -2361,7 +2386,7 @@
   dn_donors.Write(quanta_threshgb_donation_makers.Sum(), "parent made at least one quanta_threshgb_donation");
   dn_donors.Write(quanta_threshgb_donation_receivers.Sum(), "parent received at least one quanta_threshgb_donation");
   dn_donors.Write(quanta_threshgb_donation_cheaters.Sum(),  "parent received at least one quanta_threshgb_donation but did not make one");
-
+  
   dn_donors.Endl();
 }
 // Copy a single indvidual out of a deme into a new one (which is first purged
@@ -2435,17 +2460,17 @@
 }
 
 void cPopulation::CheckImplicitDemeRepro(cDeme& deme) {
-
+  
   if (GetNumDemes() <= 1) return;
   
   if (m_world->GetConfig().DEMES_REPLICATE_CPU_CYCLES.Get() 
-    && (deme.GetTimeUsed() >= m_world->GetConfig().DEMES_REPLICATE_CPU_CYCLES.Get())) ReplicateDeme(deme);
+      && (deme.GetTimeUsed() >= m_world->GetConfig().DEMES_REPLICATE_CPU_CYCLES.Get())) ReplicateDeme(deme);
   else if (m_world->GetConfig().DEMES_REPLICATE_TIME.Get() 
-    && (deme.GetNormalizedTimeUsed() >= m_world->GetConfig().DEMES_REPLICATE_TIME.Get())) ReplicateDeme(deme); 
+           && (deme.GetNormalizedTimeUsed() >= m_world->GetConfig().DEMES_REPLICATE_TIME.Get())) ReplicateDeme(deme); 
   else if (m_world->GetConfig().DEMES_REPLICATE_BIRTHS.Get() 
-    && (deme.GetBirthCount() >= m_world->GetConfig().DEMES_REPLICATE_BIRTHS.Get())) ReplicateDeme(deme); 
+           && (deme.GetBirthCount() >= m_world->GetConfig().DEMES_REPLICATE_BIRTHS.Get())) ReplicateDeme(deme); 
   else if (m_world->GetConfig().DEMES_REPLICATE_ORGS.Get() 
-    && (deme.GetOrgCount() >= m_world->GetConfig().DEMES_REPLICATE_ORGS.Get())) ReplicateDeme(deme);      
+           && (deme.GetOrgCount() >= m_world->GetConfig().DEMES_REPLICATE_ORGS.Get())) ReplicateDeme(deme);      
 }
 
 // Print out all statistics about individual demes
@@ -2460,13 +2485,32 @@
   PrintDemeMutationRate();
   PrintDemeResource();
   PrintDemeInstructions();
-    
+  
   if(m_world->GetConfig().ENERGY_ENABLED.Get() == 1) {
     PrintDemeSpatialEnergyData();
     PrintDemeSpatialSleepData();
   }
 }
 
+void cPopulation::PrintDemeTestamentStats(const cString& filename) {
+  cStats& stats = m_world->GetStats();
+  
+  cDataFile& df = m_world->GetDataFile(filename);
+  df.WriteTimeStamp();
+  df.Write(m_world->GetStats().GetUpdate(), "Update");
+  df.Write(stats.SumEnergyTestamentToDemeOrganisms().Average(),     "Energy Testament to Deme Organisms");
+  df.Write(stats.SumEnergyTestamentToFutureDeme().Average(),        "Energy Testament to Future Deme");
+  df.Write(stats.SumEnergyTestamentToNeighborOrganisms().Average(), "Energy Testament to Neighbor Organisms");
+  df.Write(stats.SumEnergyTestamentAcceptedByDeme().Average(),      "Energy Testament Accepted by Future Deme");
+  df.Write(stats.SumEnergyTestamentAcceptedByOrganisms().Average(), "Energy Testament Accepted by Organisms");
+  df.Endl();
+  
+  
+  stats.SumEnergyTestamentToDemeOrganisms().Clear();
+  stats.SumEnergyTestamentToFutureDeme().Clear();
+  stats.SumEnergyTestamentToNeighborOrganisms().Clear();
+}
+
 void cPopulation::PrintDemeDonor() {
   cStats& stats = m_world->GetStats();
   const int num_demes = deme_array.GetSize();
@@ -2474,12 +2518,12 @@
   df_donor.WriteComment("Num orgs doing doing a donate for each deme in population");
   df_donor.WriteTimeStamp();
   df_donor.Write(stats.GetUpdate(), "update");
-
+  
   for (int deme_id = 0; deme_id < num_demes; deme_id++) {
     cString comment;
     const cDeme & cur_deme = deme_array[deme_id];
     cDoubleSum single_deme_donor;
-
+    
     for (int i = 0; i < cur_deme.GetSize(); i++) {
       int cur_cell = cur_deme.GetCellID(i);
       if (cell_array[cur_cell].IsOccupied() == false) continue;
@@ -2504,7 +2548,7 @@
     cString comment;
     const cDeme & cur_deme = deme_array[deme_id];
     cDoubleSum single_deme_fitness;
-
+    
     for (int i = 0; i < cur_deme.GetSize(); i++) {
       int cur_cell = cur_deme.GetCellID(i);
       if (cell_array[cur_cell].IsOccupied() == false) continue;
@@ -2524,12 +2568,12 @@
   df_gest.WriteComment("Average gestation time for each deme in population");
   df_gest.WriteTimeStamp();
   df_gest.Write(stats.GetUpdate(), "update");
-
+  
   for (int deme_id = 0; deme_id < num_demes; deme_id++) {
     cString comment;
     const cDeme & cur_deme = deme_array[deme_id];
     cDoubleSum single_deme_gest_time;
-
+    
     for (int i = 0; i < cur_deme.GetSize(); i++) {
       int cur_cell = cur_deme.GetCellID(i);
       if (cell_array[cur_cell].IsOccupied() == false) continue;
@@ -2557,7 +2601,7 @@
     df_inst.WriteComment(comment);
     df_inst.WriteTimeStamp();
     df_inst.Write(stats.GetUpdate(), "update");
-        
+    
     tArray<cIntSum> single_deme_inst(num_inst);
     
     const cDeme & cur_deme = deme_array[deme_id];
@@ -2586,12 +2630,12 @@
   df_life_fit.WriteComment("Average life fitnesses for each deme in the population");
   df_life_fit.WriteTimeStamp();
   df_life_fit.Write(stats.GetUpdate(), "update");
-
+  
   for (int deme_id = 0; deme_id < num_demes; deme_id++) {
     cString comment;
     const cDeme & cur_deme = deme_array[deme_id];
     cDoubleSum single_deme_life_fitness;
-
+    
     for (int i = 0; i < cur_deme.GetSize(); i++) {
       int cur_cell = cur_deme.GetCellID(i);
       if (cell_array[cur_cell].IsOccupied() == false) continue;
@@ -2611,12 +2655,12 @@
   df_merit.WriteComment("Average merits for each deme in population");
   df_merit.WriteTimeStamp();
   df_merit.Write(stats.GetUpdate(), "update");
-
+  
   for (int deme_id = 0; deme_id < num_demes; deme_id++) {
     cString comment;
     const cDeme & cur_deme = deme_array[deme_id];
     cDoubleSum single_deme_merit;
-
+    
     for (int i = 0; i < cur_deme.GetSize(); i++) {
       int cur_cell = cur_deme.GetCellID(i);
       if (cell_array[cur_cell].IsOccupied() == false) continue;
@@ -2637,12 +2681,12 @@
   df_mut_rates.WriteTimeStamp();
   df_mut_rates.Write(stats.GetUpdate(), "update");
   cDoubleSum total_mut_rate;
-
+  
   for (int deme_id = 0; deme_id < num_demes; deme_id++) {
     cString comment;
     const cDeme & cur_deme = deme_array[deme_id];
     cDoubleSum single_deme_mut_rate;
-
+    
     for (int i = 0; i < cur_deme.GetSize(); i++) {
       int cur_cell = cur_deme.GetCellID(i);
       if (cell_array[cur_cell].IsOccupied() == false) continue;
@@ -2663,12 +2707,12 @@
   df_receiver.WriteComment("Num orgs doing receiving a donate for each deme in population");
   df_receiver.WriteTimeStamp();
   df_receiver.Write(stats.GetUpdate(), "update");
-
+  
   for (int deme_id = 0; deme_id < num_demes; deme_id++) {
     cString comment;
     const cDeme & cur_deme = deme_array[deme_id];
     cDoubleSum single_deme_receiver;
-
+    
     for (int i = 0; i < cur_deme.GetSize(); i++) {
       int cur_cell = cur_deme.GetCellID(i);
       if (cell_array[cur_cell].IsOccupied() == false) continue;
@@ -2678,7 +2722,7 @@
     comment.Set("Deme %d", deme_id);
     df_receiver.Write(single_deme_receiver.Sum(), comment);
   }
-    df_receiver.Endl();
+  df_receiver.Endl();
 }
 
 void cPopulation::PrintDemeResource() {
@@ -2688,10 +2732,10 @@
   df_resources.WriteComment("Avida deme resource data");
   df_resources.WriteTimeStamp();
   df_resources.Write(stats.GetUpdate(), "update");
-
+  
   for (int deme_id = 0; deme_id < num_demes; deme_id++) {
     cDeme & cur_deme = deme_array[deme_id];
-
+    
     cur_deme.UpdateDemeRes();
     cResourceCount res = GetDeme(deme_id).GetDemeResourceCount();
     for(int j = 0; j < res.GetSize(); j++) {
@@ -2715,10 +2759,10 @@
     cDataFile& df = m_world->GetDataFile(tmpfilename);
     cString UpdateStr = cStringUtil::Stringf( "deme_%07i_energy_%07i = [ ...", i, update );
     df.WriteRaw(UpdateStr);
-
+    
     int gridsize = m_world->GetPopulation().GetDeme(i).GetSize();
     int xsize = m_world->GetConfig().WORLD_X.Get();
-
+    
     // write grid to file
     for (int j = 0; j < gridsize; j++) {
       cPopulationCell& cell = m_world->GetPopulation().GetCell(cellID);
@@ -2740,13 +2784,13 @@
   cString tmpfilename = cStringUtil::Stringf( "deme_spacial_resource_%s.m", tmpResName );
   cDataFile& df = m_world->GetDataFile(tmpfilename);
   cString UpdateStr = cStringUtil::Stringf( "deme_%07i_%s_%07i = [ ...", deme_id, static_cast<const char*>(res.GetResName(i)), m_world->GetStats().GetUpdate() );
-
+  
   df.WriteRaw(UpdateStr);
-
+  
   cSpatialResCount sp_res = res.GetSpatialResource(i);
   int gridsize = sp_res.GetSize();
   int xsize = m_world->GetConfig().WORLD_X.Get();
-
+  
   for (int j = 0; j < gridsize; j++) {
     df.WriteBlockElement(sp_res.GetAmount(j), j, xsize);
   }
@@ -2764,10 +2808,10 @@
   for(int i = 0; i < m_world->GetPopulation().GetNumDemes(); i++) {
     cString UpdateStr = cStringUtil::Stringf( "deme_%07i_sleep_%07i = [ ...", i, update);
     df.WriteRaw(UpdateStr);
-
+    
     int gridsize = m_world->GetPopulation().GetDeme(i).GetSize();
     int xsize = m_world->GetConfig().WORLD_X.Get();
-
+    
     // write grid to file
     for (int j = 0; j < gridsize; j++) {
       cPopulationCell cell = m_world->GetPopulation().GetCell(cellID);
@@ -2791,12 +2835,12 @@
   df_task.WriteComment("Num orgs doing each task for each deme in population");
   df_task.WriteTimeStamp();
   df_task.Write(stats.GetUpdate(), "update");
-
+  
   for (int deme_id = 0; deme_id < num_demes; deme_id++) {
     cString comment;
     const cDeme & cur_deme = deme_array[deme_id];
     tArray<cIntSum> single_deme_task(num_task);
-
+    
     for (int i = 0; i < cur_deme.GetSize(); i++) {
       int cur_cell = cur_deme.GetCellID(i);
       if (cell_array[cur_cell].IsOccupied() == false) continue;
@@ -2825,16 +2869,16 @@
   << "#  3+: founder genotype ids" << endl << endl;
   
   for(int i=0; i<deme_array.GetSize(); i++) {
-  
+    
     if(deme_array[i].IsEmpty()) continue;
     
     tArray<int>& deme_founders = deme_array[i].GetFounderGenotypeIDs();   
-      
+    
     fp << i << " " << deme_founders.GetSize();    
     for(int j=0; j<deme_founders.GetSize(); j++) {  
       fp << " " << deme_founders[j];
     }
-  
+    
     fp << endl;
   }
 }
@@ -2874,10 +2918,10 @@
 		int gen_id = organism->GetGenotype()->GetID();	
 		if (m_world->GetConfig().TRACK_CCLADES.Get() > 0)
 		{
-			if (m_world->GetClassificationManager().IsCCladeFounder(gen_id))
-			{	
-				organism->SetCCladeLabel(gen_id);
-			}
+                  if (m_world->GetClassificationManager().IsCCladeFounder(gen_id))
+                  {	
+                    organism->SetCCladeLabel(gen_id);
+                  }
 		}
 }
 
@@ -2895,11 +2939,11 @@
   assert(parent_cell.IsOccupied());
   
   const int birth_method = m_world->GetConfig().BIRTH_METHOD.Get();
-
+  
   // @WRE carrying capacity handling
   /* Pick and kill an organism here if needed
-   * and then enter choices for birth method handling.
-   */
+    * and then enter choices for birth method handling.
+    */
   if ((0 < m_world->GetConfig().BIOMIMETIC_K.Get()) &&
       (num_organisms >= m_world->GetConfig().BIOMIMETIC_K.Get())) {
     // Measure temporary variables
@@ -2924,14 +2968,14 @@
     }
     KillOrganism(cell_array[max_msrndx]);
   }
-
+  
   //@AWC -- decide wether the child will migrate to another deme -- if migrating we ignore the birth method.  
   if ((m_world->GetConfig().MIGRATION_RATE.Get() > 0.0) //@AWC -- Pedantic test to maintain consistancy.
       && m_world->GetRandom().P(m_world->GetConfig().MIGRATION_RATE.Get())) {
-
+    
     //cerr << "Attempting to migrate with rate " << m_world->GetConfig().MIGRATION_RATE.Get() << "!" << endl;
     int deme_id = parent_cell.GetDemeID();
-         
+    
     //get another -unadjusted- deme id
     int rnd_deme_id = m_world->GetRandom().GetInt(deme_array.GetSize()-1);
     
@@ -2974,7 +3018,7 @@
   // the cases. For now, a bunch of if's that return if they handle.
   
   if (birth_method == POSITION_CHILD_FULL_SOUP_RANDOM) {
-   
+    
     // Look randomly within empty cells first, if requested
     if (m_world->GetConfig().PREFER_EMPTY.Get()) {
       int num_empty_cells = UpdateEmptyCellIDArray();
@@ -2983,7 +3027,7 @@
         return GetCell(empty_cell_id_array[out_pos]);
       } 
     }
-
+    
     int out_pos = m_world->GetRandom().GetUInt(cell_array.GetSize());
     while (parent_ok == false && out_pos == parent_cell.GetID()) {
       out_pos = m_world->GetRandom().GetUInt(cell_array.GetSize());
@@ -3005,6 +3049,8 @@
     return PositionDemeRandom(parent_cell.GetDemeID(), parent_cell, parent_ok);
   }
   else if (birth_method == POSITION_CHILD_PARENT_FACING) {
+    const int deme_id = parent_cell.GetDemeID();
+    deme_array[deme_id].IncBirthCount();
     return parent_cell.GetCellFaced();
   }
   else if (birth_method == POSITION_CHILD_NEXT_CELL) {
@@ -3141,8 +3187,8 @@
 }
 
 void cPopulation::PositionEnergyUsed(cPopulationCell & parent_cell,
-                                tList<cPopulationCell> & found_list,
-                                bool parent_ok)
+                                     tList<cPopulationCell> & found_list,
+                                     bool parent_ok)
 {
   // Start with the parent organism as the replacement, and see if we can find
   // anything equivilent or better.
@@ -3171,78 +3217,78 @@
 // This function handles PositionChild() when there is migration between demes
 cPopulationCell& cPopulation::PositionDemeMigration(cPopulationCell& parent_cell, bool parent_ok)
 {
-    //cerr << "Attempting to migrate with rate " << m_world->GetConfig().MIGRATION_RATE.Get() << "!" << endl;
-    int deme_id = parent_cell.GetDemeID();
+  //cerr << "Attempting to migrate with rate " << m_world->GetConfig().MIGRATION_RATE.Get() << "!" << endl;
+  int deme_id = parent_cell.GetDemeID();
+  
+  // Position randomly in any other deme
+  if (m_world->GetConfig().DEMES_MIGRATION_METHOD.Get() == 0) {  
     
-    // Position randomly in any other deme
-    if (m_world->GetConfig().DEMES_MIGRATION_METHOD.Get() == 0) {  
-                    
-      //get another -unadjusted- deme id
-      int rnd_deme_id = m_world->GetRandom().GetInt(deme_array.GetSize()-1);
-      
-      //if the -unadjusted- id is above the excluded id, bump it up one
-      //insures uniform prob of landing in any deme but the parent's
-      if(rnd_deme_id >= deme_id) rnd_deme_id++;
-      
-      //set the new deme_id
-      deme_id = rnd_deme_id;
-    }
+    //get another -unadjusted- deme id
+    int rnd_deme_id = m_world->GetRandom().GetInt(deme_array.GetSize()-1);
     
-    //Position randomly in an adjacent deme in neighborhood (assuming torus)
-    //Extremely hacked DEMES_NUM_X config setting simulates grid
-    else if (m_world->GetConfig().DEMES_MIGRATION_METHOD.Get() == 1) {
+    //if the -unadjusted- id is above the excluded id, bump it up one
+    //insures uniform prob of landing in any deme but the parent's
+    if(rnd_deme_id >= deme_id) rnd_deme_id++;
     
-      //get a random eight-neighbor
-      int dir = m_world->GetRandom().GetInt(8);
-      
-      // 0 = NW, 1=N, continuing clockwise....
+    //set the new deme_id
+    deme_id = rnd_deme_id;
+  }
+  
+  //Position randomly in an adjacent deme in neighborhood (assuming torus)
+  //Extremely hacked DEMES_NUM_X config setting simulates grid
+  else if (m_world->GetConfig().DEMES_MIGRATION_METHOD.Get() == 1) {
     
-      // Up one row
-      if (m_world->GetConfig().DEMES_NUM_X.Get() == 0) {
-          m_world->GetDriver().RaiseFatalException(1, "DEMES_NUM_X must be non-zero if DEMES_MIGRATION_METHOD 1 used.");
-      }
-      int x_size = m_world->GetConfig().DEMES_NUM_X.Get();
-      int y_size = (int) (m_world->GetConfig().NUM_DEMES.Get() / x_size);
-
-      assert(y_size * x_size == m_world->GetConfig().NUM_DEMES.Get());
-
-      int x = deme_id % x_size;
-      int y = (int) (deme_id / x_size);
-
-      if ( (dir == 0) || (dir == 1) || (dir == 2) ) y--;
-      if ( (dir == 5) || (dir == 6) || (dir == 7) ) y++;
-      if ( (dir == 0) || (dir == 3) || (dir == 5) ) x--;
-      if ( (dir == 2) || (dir == 4) || (dir == 7) ) x++;
-      
-      //handle boundary conditions...
-      
-      x = (x + x_size) % x_size;
-      y = (y + y_size) % y_size;
-
-      //set the new deme_id
-      deme_id = x + x_size * y;
-
-      assert(deme_id > 0);
-      assert(deme_id > 0);
-    }
+    //get a random eight-neighbor
+    int dir = m_world->GetRandom().GetInt(8);
     
-    //Random deme adjacent in list
-    else if (m_world->GetConfig().DEMES_MIGRATION_METHOD.Get() == 2) {
-
-      //get a random direction to move in deme list
-      int rnd_deme_id = m_world->GetRandom().GetInt(1);
-      if (rnd_deme_id == 0) rnd_deme_id = -1;
-      
-      //set the new deme_id
-      deme_id = (deme_id + rnd_deme_id + GetNumDemes()) % GetNumDemes();
+    // 0 = NW, 1=N, continuing clockwise....
+    
+    // Up one row
+    if (m_world->GetConfig().DEMES_NUM_X.Get() == 0) {
+      m_world->GetDriver().RaiseFatalException(1, "DEMES_NUM_X must be non-zero if DEMES_MIGRATION_METHOD 1 used.");
     }
+    int x_size = m_world->GetConfig().DEMES_NUM_X.Get();
+    int y_size = (int) (m_world->GetConfig().NUM_DEMES.Get() / x_size);
     
-    // TODO the above choice of deme does not respect PREFER_EMPTY
-    // i.e., it does not preferentially pick a deme with empty cells if they are 
-    // it might make sense for that to happen...
+    assert(y_size * x_size == m_world->GetConfig().NUM_DEMES.Get());
     
-    // Now return an empty cell from the chosen deme
-    return PositionDemeRandom(deme_id, parent_cell, parent_ok); 
+    int x = deme_id % x_size;
+    int y = (int) (deme_id / x_size);
+    
+    if ( (dir == 0) || (dir == 1) || (dir == 2) ) y--;
+    if ( (dir == 5) || (dir == 6) || (dir == 7) ) y++;
+    if ( (dir == 0) || (dir == 3) || (dir == 5) ) x--;
+    if ( (dir == 2) || (dir == 4) || (dir == 7) ) x++;
+    
+    //handle boundary conditions...
+    
+    x = (x + x_size) % x_size;
+    y = (y + y_size) % y_size;
+    
+    //set the new deme_id
+    deme_id = x + x_size * y;
+    
+    assert(deme_id > 0);
+    assert(deme_id > 0);
+  }
+  
+  //Random deme adjacent in list
+  else if (m_world->GetConfig().DEMES_MIGRATION_METHOD.Get() == 2) {
+    
+    //get a random direction to move in deme list
+    int rnd_deme_id = m_world->GetRandom().GetInt(1);
+    if (rnd_deme_id == 0) rnd_deme_id = -1;
+    
+    //set the new deme_id
+    deme_id = (deme_id + rnd_deme_id + GetNumDemes()) % GetNumDemes();
+  }
+  
+  // TODO the above choice of deme does not respect PREFER_EMPTY
+  // i.e., it does not preferentially pick a deme with empty cells if they are 
+  // it might make sense for that to happen...
+  
+  // Now return an empty cell from the chosen deme
+  return PositionDemeRandom(deme_id, parent_cell, parent_ok); 
 }
 
 // This function handles PositionChild() by returning a random cell from the entire deme.
@@ -3252,7 +3298,7 @@
   
   const int deme_size = deme_array[deme_id].GetSize();
   cDeme& deme = deme_array[deme_id];
-
+  
   // Look randomly within empty cells first, if requested
   if (m_world->GetConfig().PREFER_EMPTY.Get()) {
     
@@ -3262,7 +3308,7 @@
       return GetCell(empty_cell_id_array[out_pos]);
     } 
   }
-
+  
   int out_pos = m_world->GetRandom().GetUInt(deme_size);
   int out_cell_id = deme.GetCellID(out_pos);
   
@@ -3286,7 +3332,7 @@
   // all cells in the cPopulation when it was created. Using functions
   // that resize it (like Push) will slow this code down considerably.
   // Instead, we keep track of how much of this memory we are using.
-      
+  
   // Look at all cells
   if (deme_id == -1) { 
     for (int i=0; i<cell_array.GetSize(); i++) {
@@ -3295,7 +3341,7 @@
   }
   // Look at a specific deme
   else {
-	cDeme& deme = deme_array[deme_id];
+    cDeme& deme = deme_array[deme_id];
     for (int i=0; i<deme.GetSize(); i++) {
       if (GetCell(deme.GetCellID(i)).IsOccupied() == false) empty_cell_id_array[num_empty_cells++] = deme.GetCellID(i);
     }
@@ -3320,11 +3366,11 @@
   cPopulationCell& cell = GetCell(cell_id);
   assert(cell.IsOccupied()); // Unoccupied cell getting processor time!
   cOrganism* cur_org = cell.GetOrganism();
-
+  
   cell.GetHardware()->SingleProcess(ctx);    
   
   if (cur_org->GetPhenotype().GetToDelete() == true) delete cur_org;
-
+  
   m_world->GetStats().IncExecuted();
   resource_count.Update(step_size);
   
@@ -3332,7 +3378,7 @@
   if (GetNumDemes() > 1)
   {
     for(int i = 0; i < GetNumDemes(); i++) GetDeme(i).Update(step_size);
-  
+    
     cDeme & deme = GetDeme(GetCell(cell_id).GetDemeID());
     deme.IncTimeUsed(cur_org->GetPhenotype().GetMerit().GetDouble());
     CheckImplicitDemeRepro(deme);
@@ -3345,7 +3391,7 @@
   assert(step_size > 0.0);
   assert(cell_id < cell_array.GetSize());
   assert(m_world->GetHardwareManager().SupportsSpeculative());
-
+  
   // If cell_id is negative, no cell could be found -- stop here.
   if (cell_id < 0) return;
   
@@ -3373,15 +3419,15 @@
   }
   
   if (cur_org->GetPhenotype().GetToDelete() == true) delete cur_org;
-
+  
   m_world->GetStats().IncExecuted();
   resource_count.Update(step_size);
- 
-   // Deme specific
+  
+  // Deme specific
   if (GetNumDemes() > 1)
   {
     for(int i = 0; i < GetNumDemes(); i++) GetDeme(i).Update(step_size);
-  
+    
     cDeme & deme = GetDeme(GetCell(cell_id).GetDemeID());
     deme.IncTimeUsed(cur_org->GetPhenotype().GetMerit().GetDouble());
     CheckImplicitDemeRepro(deme);
@@ -3392,12 +3438,12 @@
 // Loop through all the demes getting stats and doing calculations
 // which must be done on a deme by deme basis.
 void cPopulation::UpdateDemeStats() {
-
+  
   // bail early to save time if there are no demes
   if (GetNumDemes() == 1) return ;
-
+  
   cStats& stats = m_world->GetStats();
-
+  
   stats.SumDemeAge().Clear();
   stats.SumDemeBirthCount().Clear();
   stats.SumDemeOrgCount().Clear();
@@ -3406,11 +3452,14 @@
   stats.SumDemeGestationTime().Clear();
   stats.SumDemeNormalizedTimeUsed().Clear();
   stats.SumDemeMerit().Clear();
-
+  
   stats.SumDemeGenerationsPerLifetime().Clear();
-
+  
   stats.ClearNumOccupiedDemes();
-
+  
+  stats.SumDemeEventsKilled().Clear();
+  stats.SumDemeAttemptsToKillEvents() .Clear();
+  
   for(int i = 0; i < GetNumDemes(); i++) {
     cDeme& deme = GetDeme(i);
     if(deme.IsEmpty())  // ignore empty demes
@@ -3423,15 +3472,18 @@
     stats.SumDemeBirthCount().Add(deme.GetBirthCount());
     stats.SumDemeOrgCount().Add(deme.GetOrgCount());
     stats.SumDemeGeneration().Add(deme.GetGeneration());
-
+    
     stats.SumDemeLastBirthCount().Add(deme.GetLastBirthCount());
     stats.SumDemeLastOrgCount().Add(deme.GetLastOrgCount());
-
+    
     stats.SumDemeGestationTime().Add(deme.GetGestationTime());
     stats.SumDemeNormalizedTimeUsed().Add(deme.GetLastNormalizedTimeUsed());
     stats.SumDemeMerit().Add(deme.GetDemeMerit().GetDouble());
     
     stats.SumDemeGenerationsPerLifetime().Add(deme.GetGenerationsPerLifetime());
+    
+    stats.SumDemeEventsKilled().Add(deme.GetEventsKilled());
+    stats.SumDemeAttemptsToKillEvents().Add(deme.GetEventKillAttempts());
   }
 }
 
@@ -3983,11 +4035,11 @@
         current_cell += 1;
       }
     }
-
-// @DMB - This seems to be debugging output...
-//    cout << (*it).id_num << " " << (*it).parent_id << " " << (*it).genotype->GetParentID() << " "
-//         << (*it).genotype->GetNumOffspringGenotypes() << " " << (*it).num_cpus << " " << (*it).genotype->GetNumOrganisms() << endl;
     
+    // @DMB - This seems to be debugging output...
+    //    cout << (*it).id_num << " " << (*it).parent_id << " " << (*it).genotype->GetParentID() << " "
+    //         << (*it).genotype->GetNumOffspringGenotypes() << " " << (*it).num_cpus << " " << (*it).genotype->GetNumOrganisms() << endl;
+    
     if (soup_full) {
       cout << "Warning: Too many organisms in population file, remainder ignored" << endl;
       break;
@@ -4062,7 +4114,7 @@
   InjectGenome(cell_id, genome, lineage_label);
   cPhenotype& phenotype = GetCell(cell_id).GetOrganism()->GetPhenotype();
   phenotype.SetNeutralMetric(neutral);
-    
+  
   if (merit > 0) phenotype.SetMerit(cMerit(merit));
   AdjustSchedule(GetCell(cell_id), phenotype.GetMerit());
   
@@ -4070,7 +4122,7 @@
   
   if (GetNumDemes() > 1) {
     cDeme& deme = deme_array[GetCell(cell_id).GetDemeID()];
-
+    
     // If we're using germlines, then we have to be a little careful here.
     // This should probably not be within Inject() since we mainly want it to
     // apply to the START_CREATURE? -- @JEB
@@ -4096,16 +4148,22 @@
       }
       
       GetCell(cell_id).GetOrganism()->GetPhenotype().SetPermanentGermlinePropensity
-        (m_world->GetConfig().DEMES_FOUNDER_GERMLINE_PROPENSITY.Get());
-        
-        
+      (m_world->GetConfig().DEMES_FOUNDER_GERMLINE_PROPENSITY.Get());
+      
+      
       if (m_world->GetConfig().DEMES_FOUNDER_GERMLINE_PROPENSITY.Get() >= 0.0) {
-         GetCell(cell_id).GetOrganism()->GetPhenotype().SetPermanentGermlinePropensity
-          ( m_world->GetConfig().DEMES_FOUNDER_GERMLINE_PROPENSITY.Get() );
+        GetCell(cell_id).GetOrganism()->GetPhenotype().SetPermanentGermlinePropensity
+        ( m_world->GetConfig().DEMES_FOUNDER_GERMLINE_PROPENSITY.Get() );
       }
-
+      
     }
   }
+  else if(m_world->GetConfig().DEMES_USE_GERMLINE.Get() == 2) {
+    //find the genotype we just created from the genome, and save it
+    cDeme& deme = deme_array[GetCell(cell_id).GetDemeID()];
+    cGenotype * genotype = m_world->GetClassificationManager().FindGenotype(genome, lineage_label);
+    deme.ReplaceGermline(*genotype);
+  }
 }
 
 void cPopulation::InjectParasite(const cCodeLabel& label, const cGenome& injected_code, int cell_id)
@@ -4226,7 +4284,7 @@
   cAvidaContext& ctx = m_world->GetDefaultContext();
   
   cOrganism* new_organism = new cOrganism(m_world, ctx, new_genotype->GetGenome());
-	
+  
   //Coalescense Clade Setup
   new_organism->SetCCladeLabel(-1);  
   
@@ -4262,25 +4320,25 @@
   
   // Activate the organism in the population...
   ActivateOrganism(ctx, new_organism, cell_array[cell_id]);
-
+  
   // Log the injection of this organism if LOG_INJECT is set to 1 and
   // the current update number is >= INJECT_LOG_START
   if ( (m_world->GetConfig().LOG_INJECT.Get() == 1) &&
        (m_world->GetStats().GetUpdate() >= m_world->GetConfig().INJECT_LOG_START.Get()) ){
-
-      cString tmpfilename = cStringUtil::Stringf("injectlog.dat");
-      cDataFile& df = m_world->GetDataFile(tmpfilename);
-
-      int update = m_world->GetStats().GetUpdate();
-      int orgid = new_organism->GetID();
-      int deme_id = m_world->GetPopulation().GetCell(cell_id).GetDemeID();
-      int facing = new_organism->GetFacing();
-      const char *orgname = (const char *)new_genotype->GetName();
-
-      cString UpdateStr = cStringUtil::Stringf("%d %d %d %d %d %s", update, orgid, cell_id, deme_id, facing, orgname);
-      df.WriteRaw(UpdateStr);
+    
+    cString tmpfilename = cStringUtil::Stringf("injectlog.dat");
+    cDataFile& df = m_world->GetDataFile(tmpfilename);
+    
+    int update = m_world->GetStats().GetUpdate();
+    int orgid = new_organism->GetID();
+    int deme_id = m_world->GetPopulation().GetCell(cell_id).GetDemeID();
+    int facing = new_organism->GetFacing();
+    const char *orgname = (const char *)new_genotype->GetName();
+    
+    cString UpdateStr = cStringUtil::Stringf("%d %d %d %d %d %s", update, orgid, cell_id, deme_id, facing, orgname);
+    df.WriteRaw(UpdateStr);
   }
-
+  
 }
 
 
@@ -4329,7 +4387,7 @@
   assert(cell_id >= 0 && cell_id < cell_array.GetSize());
   
   cAvidaContext& ctx = m_world->GetDefaultContext();
-      
+  
   // Do mutations on the child genome, but restore it to its current state afterward.
   cGenome save_child = parent.ChildGenome();
   parent.GetHardware().Divide_DoMutations(ctx);
@@ -4337,12 +4395,12 @@
   parent.GetHardware().Divide_TestFitnessMeasures(ctx);
   parent.ChildGenome() = save_child;
   cOrganism* new_organism = new cOrganism(m_world, ctx, child_genome);
-
+  
   // Set the genotype...
   assert(parent.GetGenotype());  
   cGenotype* new_genotype = m_world->GetClassificationManager().GetGenotype(child_genome, parent.GetGenotype(), NULL);
   new_organism->SetGenotype(new_genotype);
-    
+  
   // Setup the phenotype...
   new_organism->GetPhenotype().SetupOffspring(parent.GetPhenotype(),child_genome);
   
@@ -4365,7 +4423,7 @@
   
   // Activate the organism in the population...
   ActivateOrganism(ctx, new_organism, cell_array[cell_id]);  
-
+  
 }
 
 
@@ -4425,7 +4483,7 @@
   //implementing a very poor man's hash...
   tArray<int> phenotypes;
   tArray<int> phenotype_counts;
-    
+  
   for (int i = 0; i < cell_array.GetSize(); i++) {
     // Only look at cells with organisms in them.
     if (cell_array[i].IsOccupied() == false) continue;
@@ -4444,7 +4502,7 @@
     }
     ids.insert(id);
     complete.insert(key);
-
+    
     // add one to our count for this key
     int k;
     for(k=0; k<phenotypes.GetSize(); k++)
@@ -4459,7 +4517,7 @@
       phenotypes.Push(id);
       phenotype_counts.Push(1);
     }
-
+    
     // go through again to calculate Shannon Diversity of task counts
     // now that we know the total number of tasks done
     double shannon_diversity = 0;
@@ -4550,7 +4608,7 @@
   phenotype.SetMerit( cMerit(new_merit) );
   phenotype.SetLifeFitness(new_merit/phenotype.GetGestationTime()); 
   if (new_merit <= old_merit) {
-	  phenotype.SetIsDonorCur(); }  
+    phenotype.SetIsDonorCur(); }  
   else  { phenotype.SetIsReceiver(); } 
   AdjustSchedule(GetCell(cell_id), phenotype.GetMerit());
   
@@ -4567,7 +4625,7 @@
 void cPopulation::AddBeginSleep(int cellID, int start_time) {
   sleep_log[cellID].Add(make_pair(start_time,-1));
 }
-  
+
 void cPopulation::AddEndSleep(int cellID, int end_time) {
   pair<int,int> p = sleep_log[cellID][sleep_log[cellID].Size()-1];
   sleep_log[cellID].RemoveAt(sleep_log[cellID].Size()-1);
@@ -4583,14 +4641,14 @@
     if (cell.IsOccupied())
     {
       cPhenotype & p =  cell.GetOrganism()->GetPhenotype();
-
+      
       // Don't continue if the time used was zero
       if (p.GetTrialTimeUsed() != 0)
       {
         // Correct gestation time for speculative execution
         p.SetTrialTimeUsed(p.GetTrialTimeUsed() - cell.GetSpeculativeState());
         p.SetTimeUsed(p.GetTimeUsed() - cell.GetSpeculativeState());
-
+        
         cell.GetOrganism()->NewTrial();
         cell.GetOrganism()->GetHardware().Reset();
         
@@ -4607,21 +4665,21 @@
 }
 
 /*
-  CompeteOrganisms
-  
-   parents_survive => for any organism represented by >=1 child, the first created is the parent (has no mutations)
-   dynamic_scaling => rescale the time interval such that the geometric mean of the highest fitness versus lower fitnesses
-                      equals a time of 1 unit
-*/
+ CompeteOrganisms
+ 
+ parents_survive => for any organism represented by >=1 child, the first created is the parent (has no mutations)
+ dynamic_scaling => rescale the time interval such that the geometric mean of the highest fitness versus lower fitnesses
+ equals a time of 1 unit
+ */
 
 void cPopulation::CompeteOrganisms(int competition_type, int parents_survive)
 {
   NewTrial();
-
+  
   double total_fitness = 0;
   int num_cells = GetSize();
   tArray<double> org_fitness(num_cells); 
-
+  
   double lowest_fitness = -1.0;
   double average_fitness = 0;
   double highest_fitness = -1.0;
@@ -4630,14 +4688,14 @@
   double highest_fitness_copied = -1.0;
   int different_orgs_copied = 0;
   int num_competed_orgs = 0;
-
+  
   int num_trials = -1;
   
   int dynamic_scaling = 0; 
-
+  
   if (competition_type==3) dynamic_scaling = 1;
   else if  (competition_type==4) dynamic_scaling = 2;
-    
+  
   // How many trials were there? -- same for every organism
   // we just need to find one...
   for (int i = 0; i < num_cells; i++) 
@@ -4663,12 +4721,12 @@
   if (num_trials == 0) return;
   
   if (m_world->GetVerbosity() > VERBOSE_SILENT) cout << "==Compete Organisms==" << endl;
-
+  
   tArray<double> min_trial_fitnesses(num_trials);
   tArray<double> max_trial_fitnesses(num_trials);
   tArray<double> avg_trial_fitnesses(num_trials);
   avg_trial_fitnesses.SetAll(0);
-
+  
   bool init = false;
   // What is the min and max fitness in each trial
   for (int i = 0; i < num_cells; i++) 
@@ -4714,7 +4772,7 @@
       cPhenotype& p = GetCell(i).GetOrganism()->GetPhenotype();
       //Don't need to reset trial_fitnesses because we will call cPhenotype::OffspringReset on the entire pop
       tArray<double> trial_fitnesses = p.GetTrialFitnesses();
-
+      
       //If there are no trial fitnesses...use the actual fitness.
       if (trial_fitnesses.GetSize() == 0)
       {
@@ -4733,11 +4791,11 @@
           { 
             fitness += log(trial_fitnesses[t]); 
           }
-          fitness /= (double)trial_fitnesses.GetSize();
+            fitness /= (double)trial_fitnesses.GetSize();
           fitness = exp( fitness );
-        break;
-  
-        //Product
+          break;
+          
+          //Product
         case 5:
           //Treat as logs to avoid overflow when multiplying very large fitnesses
           fitness = 0;
@@ -4745,29 +4803,29 @@
           { 
             fitness += log(trial_fitnesses[t]); 
           }       
-          fitness = exp( fitness );
-        break;
-         
-        //Geometric Mean of normalized values
+            fitness = exp( fitness );
+          break;
+          
+          //Geometric Mean of normalized values
         case 1:
           fitness = 1.0;        
           for (int t=0; t < trial_fitnesses.GetSize(); t++) 
           { 
-             fitness*=trial_fitnesses[t] / max_trial_fitnesses[t]; 
+            fitness*=trial_fitnesses[t] / max_trial_fitnesses[t]; 
           }
-          fitness = exp( (1.0/((double)trial_fitnesses.GetSize())) * log(fitness) );
-        break;
-        
-        //Arithmetic Mean
+            fitness = exp( (1.0/((double)trial_fitnesses.GetSize())) * log(fitness) );
+          break;
+          
+          //Arithmetic Mean
         case 2:
           fitness = 0;
           for (int t=0; t < trial_fitnesses.GetSize(); t++) 
           { 
             fitness+=trial_fitnesses[t]; 
           }
-          fitness /= (double)trial_fitnesses.GetSize();
-        break;
-      
+            fitness /= (double)trial_fitnesses.GetSize();
+          break;
+          
         default:
           m_world->GetDriver().RaiseFatalException(1, "Unknown CompeteOrganisms method");
       }
@@ -4780,7 +4838,7 @@
     } // end if occupied
   }
   average_fitness = total_fitness / num_competed_orgs;
- 
+  
   //Rescale by the geometric mean of the difference from the top score and the average
   if ( dynamic_scaling == 1 ) {
     double dynamic_factor = 1.0;
@@ -4807,13 +4865,13 @@
         dynamic_factor += log(org_fitness[i]);
       }
     }
-        
+    
     cout << "Scaling factor = " << dynamic_factor << endl;
     if (num_org > 0) dynamic_factor = exp(dynamic_factor / (double)num_org);
     cout << "Scaling factor = " << dynamic_factor << endl;
     
     total_fitness = 0;
-
+    
     for (int i = 0; i < num_cells; i++) {
       if ( GetCell(i).IsOccupied() ) {
         org_fitness[i] /= dynamic_factor;
@@ -4854,7 +4912,7 @@
   // calling that twice would erase this information before it could potentially be output between NewTrial and CompeteOrganisms events.
   for (int i = 0; i < num_cells; i++) {
     if (m_world->GetVerbosity() >= VERBOSE_DETAILS) cout << "Cell " << i << " has " << org_count[i] << " copies in the next generation" << endl;  
-
+    
     if (org_count[i] > 0) {
       different_orgs_copied++;
       cPhenotype& p = GetCell(i).GetOrganism()->GetPhenotype();
@@ -4903,7 +4961,7 @@
     
     is_init[to_cell_id] = true;
   }
-
+  
   if (!parents_survive)
   {
     // Now create children from remaining cells into themselves
@@ -4936,15 +4994,15 @@
 }
 
 /* This routine is designed to change values in the resource count in the 
-   middle of a run.  This is designed to work with cActionChangeEnvironment
-   routine BDB 22-Feb-2008 */
+middle of a run.  This is designed to work with cActionChangeEnvironment
+routine BDB 22-Feb-2008 */
 
 void cPopulation::UpdateResourceCount(const int Verbosity) {
   const cResourceLib & resource_lib = environment.GetResourceLib();
   int global_res_index = -1;
   int deme_res_index = -1;
   int num_deme_res = 0;
-
+  
   //setting size of global and deme-level resources
   for(int i = 0; i < resource_lib.GetSize(); i++) {
     cResource * res = resource_lib.GetResource(i);
@@ -4956,7 +5014,7 @@
     cResourceCount tmp_deme_res_count(num_deme_res);
     GetDeme(i).SetDemeResourceCount(tmp_deme_res_count);
   }
-
+  
   for (int i = 0; i < resource_lib.GetSize(); i++) {
     cResource * res = resource_lib.GetResource(i);
     if (!res->GetDemeResource()) {
@@ -4984,5 +5042,5 @@
       exit(1);
     }
   }
-
+  
 }

Modified: development/source/main/cPopulation.h
===================================================================
--- development/source/main/cPopulation.h	2008-06-15 23:58:31 UTC (rev 2647)
+++ development/source/main/cPopulation.h	2008-06-16 15:40:36 UTC (rev 2648)
@@ -227,6 +227,7 @@
   
   // Deme-related stats methods
   void PrintDemeAllStats();
+  void PrintDemeTestamentStats(const cString& filename);
   void PrintDemeDonor();
   void PrintDemeFitness();
   void PrintDemeGestationTime();

Modified: development/source/main/cPopulationInterface.cc
===================================================================
--- development/source/main/cPopulationInterface.cc	2008-06-15 23:58:31 UTC (rev 2647)
+++ development/source/main/cPopulationInterface.cc	2008-06-16 15:40:36 UTC (rev 2648)
@@ -46,7 +46,14 @@
   return &m_world->GetPopulation().GetDeme(m_deme_id);
 }
 
+int cPopulationInterface::GetCellData() {
+  return m_world->GetPopulation().GetCell(m_cell_id).GetCellData();
+}
 
+void cPopulationInterface::SetCellData(const int newData) {
+  m_world->GetPopulation().GetCell(m_cell_id).SetCellData(newData);
+}
+
 bool cPopulationInterface::Divide(cAvidaContext& ctx, cOrganism* parent, cGenome& child_genome)
 {
   assert(parent != NULL);
@@ -62,6 +69,11 @@
   return cell.ConnectionList().GetFirst()->GetOrganism();
 }
 
+bool cPopulationInterface::IsNeighborCellOccupied() {
+  cPopulationCell & cell = m_world->GetPopulation().GetCell(m_cell_id);
+  return cell.ConnectionList().GetFirst()->IsOccupied();
+}
+
 int cPopulationInterface::GetNumNeighbors()
 {
   cPopulationCell & cell = m_world->GetPopulation().GetCell(m_cell_id);
@@ -77,6 +89,11 @@
 	return cell.GetFacing();
 }
 
+int cPopulationInterface::GetNeighborCellContents() {
+  cPopulationCell & cell = m_world->GetPopulation().GetCell(m_cell_id);
+  return cell.ConnectionList().GetFirst()->GetCellData();
+}
+
 void cPopulationInterface::Rotate(int direction)
 {
   cPopulationCell & cell = m_world->GetPopulation().GetCell(m_cell_id);
@@ -258,3 +275,63 @@
   return true;
 }
 
+
+bool cPopulationInterface::BcastAlarm(int jump_label, int bcast_range) {
+  bool successfully_sent(false);
+  cPopulationCell& scell = m_world->GetPopulation().GetCell(m_cell_id);
+  assert(scell.IsOccupied()); // This organism; sanity.
+
+  const int ALARM_SELF = m_world->GetConfig().ALARM_SELF.Get(); // does an alarm affect the sender; 0=no  non-0=yes
+  
+  if(bcast_range > 1) { // multi-hop messaging
+    cDeme& deme = m_world->GetPopulation().GetDeme(GetDemeID());
+    for(int i = 0; i < deme.GetSize(); i++) {
+      int possible_receiver_id = deme.GetCellID(i);
+      cPopulationCell& rcell = m_world->GetPopulation().GetCell(possible_receiver_id);
+    
+      if(rcell.IsOccupied() && possible_receiver_id != GetCellID()) {
+        //check distance
+        pair<int, int> sender_pos = deme.GetCellPosition(GetCellID());
+        pair<int, int> possible_receiver_pos = deme.GetCellPosition(possible_receiver_id);
+        int hop_distance = max( abs(sender_pos.first  - possible_receiver_pos.first),
+                              abs(sender_pos.second - possible_receiver_pos.second));
+        if(hop_distance <= bcast_range) {
+          // send alarm to organisms
+          cOrganism* recvr = rcell.GetOrganism();
+          assert(recvr != NULL);
+          recvr->moveIPtoAlarmLabel(jump_label);
+          successfully_sent = true;
+        }
+      }
+    }
+  } else { // single hop messaging
+    for(int i = 0; i < scell.ConnectionList().GetSize(); i++) {
+      cPopulationCell* rcell = scell.ConnectionList().GetPos(i);
+      assert(rcell != NULL); // Cells should never be null.
+
+      // Fail if the cell we're facing is not occupied.
+      if(!rcell->IsOccupied())
+        continue;
+      cOrganism* recvr = rcell->GetOrganism();
+      assert(recvr != NULL);
+      recvr->moveIPtoAlarmLabel(jump_label);
+      successfully_sent = true;
+    }
+  }
+  
+  if(ALARM_SELF) {
+    scell.GetOrganism()->moveIPtoAlarmLabel(jump_label);
+  }
+  return successfully_sent;
+}
+
+void cPopulationInterface::DivideOrgTestamentAmongDeme(double value){
+  cDeme* deme = GetDeme();
+  for(int i = 0; i < deme->GetSize(); i++) {
+    cPopulationCell& cell = deme->GetCell(i);
+    if(cell.IsOccupied()) {
+      cOrganism* org = cell.GetOrganism();
+      org->GetPhenotype().EnergyTestament(value/deme->GetOrgCount());
+    }
+  }
+}

Modified: development/source/main/cPopulationInterface.h
===================================================================
--- development/source/main/cPopulationInterface.h	2008-06-15 23:58:31 UTC (rev 2647)
+++ development/source/main/cPopulationInterface.h	2008-06-16 15:40:36 UTC (rev 2648)
@@ -65,6 +65,9 @@
   cDeme* GetDeme();
   void SetCellID(int in_id) { m_cell_id = in_id; }
   void SetDemeID(int in_id) { m_deme_id = in_id; }
+  
+  int GetCellData();
+  void SetCellData(const int newData);
 
   int GetPrevSeenCellID() { return m_prevseen_cell_id; }
   int GetPrevTaskCellID() { return m_prev_task_cell; }
@@ -75,8 +78,10 @@
 
   bool Divide(cAvidaContext& ctx, cOrganism* parent, cGenome& child_genome);
   cOrganism* GetNeighbor();
+  bool IsNeighborCellOccupied();
   int GetNumNeighbors();
   int GetFacing(); // Returns the facing of this organism.
+  int GetNeighborCellContents();
   void Rotate(int direction = 1);
   void Breakpoint() { m_world->GetDriver().SignalBreakpoint(); }
   int GetInputAt(int& input_pointer);
@@ -100,7 +105,9 @@
   bool TestOnDivide();
   //! Send a message to the faced organism.
   bool SendMessage(cOrgMessage& msg);
+  bool BcastAlarm(int jump_label, int bcast_range);
   
+  void DivideOrgTestamentAmongDeme(double value);
 };
 
 

Modified: development/source/main/cResourceCount.cc
===================================================================
--- development/source/main/cResourceCount.cc	2008-06-15 23:58:31 UTC (rev 2647)
+++ development/source/main/cResourceCount.cc	2008-06-16 15:40:36 UTC (rev 2648)
@@ -492,8 +492,8 @@
   }
 }
 
-void cResourceCount::ReinitializeResources(){
+void cResourceCount::ReinitializeResources(double additional_resource){
   for(int i = 0; i < resource_name.GetSize(); i++) {
-    Set(i, resource_initial[i]);
+    Set(i, resource_initial[i]+additional_resource);
   }
 }

Modified: development/source/main/cResourceCount.h
===================================================================
--- development/source/main/cResourceCount.h	2008-06-15 23:58:31 UTC (rev 2647)
+++ development/source/main/cResourceCount.h	2008-06-16 15:40:36 UTC (rev 2648)
@@ -105,7 +105,7 @@
   double Get(int id) const;
   void ResizeSpatialGrids(int in_x, int in_y);
   cSpatialResCount GetSpatialResource(int id) { return spatial_resource_count[id]; }
-  void ReinitializeResources();
+  void ReinitializeResources(double additional_resource);
   cString GetResName(int id) { return resource_name[id]; }
 };
 

Modified: development/source/main/cStats.cc
===================================================================
--- development/source/main/cStats.cc	2008-06-15 23:58:31 UTC (rev 2647)
+++ development/source/main/cStats.cc	2008-06-16 15:40:36 UTC (rev 2648)
@@ -46,6 +46,7 @@
 #include <cfloat>
 #include <numeric>
 #include <cmath>
+#include <sstream>
 
 
 cStats::cStats(cWorld* world)
@@ -227,9 +228,6 @@
 
   genotype_map.Resize( m_world->GetConfig().WORLD_X.Get() * m_world->GetConfig().WORLD_Y.Get() );
 
-  numAsleep.Resize(m_world->GetConfig().NUM_DEMES.Get());
-  numAsleep.SetAll(0);
-
   if(m_world->GetConfig().NUM_DEMES.Get() == 0) {
     relative_pos_event_count.ResizeClear(m_world->GetConfig().WORLD_X.Get(), m_world->GetConfig().WORLD_Y.Get()); 
     relative_pos_pred_sat.ResizeClear(m_world->GetConfig().WORLD_X.Get(), m_world->GetConfig().WORLD_Y.Get());
@@ -601,8 +599,51 @@
   df.Write(sum_deme_gestation_time.Average(),               "Gestation Time");
   df.Write(sum_deme_normalized_time_used.Average(),         "Time Used (normalized by org fitness)");
   df.Write(sum_deme_generations_per_lifetime.Average(),     "Generations between current and last founders");
+  df.Write(sum_deme_events_killed.Average(),                "Events killed");
+  df.Write(sum_deme_events_kill_attempts.Average(),         "Attempts to kill event");
+  
+  df.Endl();
+}
 
+void cStats::PrintFlowRateTuples(const cString& filename) {
+  cDataFile& df = m_world->GetDataFile(filename);
+
+  df.WriteComment("Flow Rate Tuples");
+  df.WriteTimeStamp();
+
+  df.Write(m_update,                                        "Update");
+  // write each tuple
+  for(map<int, flow_rate_tuple>::iterator iter = flow_rate_tuples.begin(); iter != flow_rate_tuples.end(); iter++) {
+    ostringstream oss;
+    oss << "flow rate " << (*iter).first;
+    string flow_rate_str(oss.str());
+    string flow_rate_pop_size_str(flow_rate_str+" deme pop size");
+    string flow_rate_events_killed_str(flow_rate_str+" events killed");
+    string flow_rate_events_attempted_to_kill_str(flow_rate_str+" events attempted to kill");
+    string flow_rate_exe_ratio_str(flow_rate_str+" exe ratio");
+    string flow_rate_total_births_str(flow_rate_str+" total births");
+    string flow_rate_total_sleeping_str(flow_rate_str+" total sleeping");
+    
+    df.Write((*iter).first, flow_rate_str.c_str());
+    df.Write((*iter).second.orgCount.Average(), flow_rate_pop_size_str.c_str());
+    df.Write((*iter).second.eventsKilled.Average(), flow_rate_events_killed_str.c_str());
+    df.Write((*iter).second.attemptsToKillEvents.Average(), flow_rate_events_attempted_to_kill_str.c_str());
+    df.Write((*iter).second.AvgEnergyUsageRatio.Average(), flow_rate_exe_ratio_str.c_str());
+    df.Write((*iter).second.totalBirths.Average(), flow_rate_total_births_str.c_str());
+    df.Write((*iter).second.currentSleeping.Average(), flow_rate_total_sleeping_str.c_str());
+    
+  }
   df.Endl();
+
+  // reset all tuples
+  for(map<int, flow_rate_tuple >::iterator iter = flow_rate_tuples.begin(); iter != flow_rate_tuples.end(); iter++) {
+    (*iter).second.orgCount.Clear();
+    (*iter).second.eventsKilled.Clear();
+    (*iter).second.attemptsToKillEvents.Clear();
+    (*iter).second.AvgEnergyUsageRatio.Clear();
+    (*iter).second.totalBirths.Clear();
+    (*iter).second.currentSleeping.Clear();
+  }
 }
 
 void cStats::PrintErrorData(const cString& filename)
@@ -1152,9 +1193,12 @@
   df.WriteComment("total number of organisms sleeping" );
   
   df.Write( GetUpdate(), "update" );
-    
-  for( int i=0; i < numAsleep.GetSize(); i++ ){
-    df.Write(numAsleep[i], cStringUtil::Stringf("DemeID %d", i));
+  
+  cPopulation& pop = m_world->GetPopulation();
+  int numDemes = pop.GetNumDemes();
+  
+  for( int i=0; i < numDemes; i++ ){
+    df.Write(pop.GetDeme(i).GetSleepingCount(), cStringUtil::Stringf("DemeID %d", i));
   }
   df.Endl();
 }
@@ -1313,10 +1357,6 @@
   m_deme_births.Add(source_deme.GetBirthCount());
   m_deme_merit.Add(source_deme.GetHeritableDemeMerit().GetDouble());
   m_deme_generation.Add(source_deme.GetGeneration());
-
-  // reset #orgs. sleeping in demes
-  numAsleep[source_deme.GetID()]=0;
-  numAsleep[target_deme.GetID()]=0;
 }
 
 

Modified: development/source/main/cStats.h
===================================================================
--- development/source/main/cStats.h	2008-06-15 23:58:31 UTC (rev 2647)
+++ development/source/main/cStats.h	2008-06-16 15:40:36 UTC (rev 2648)
@@ -77,6 +77,15 @@
 class cDeme;
 class cGermline;
 
+struct flow_rate_tuple {
+  cIntSum orgCount;
+  cIntSum eventsKilled;
+  cIntSum attemptsToKillEvents;
+  cDoubleSum AvgEnergyUsageRatio;
+  cIntSum totalBirths;
+  cIntSum currentSleeping;
+};
+
 class cStats
 {
 #if USE_tMemTrack
@@ -269,7 +278,7 @@
   double max_competition_copied_fitness;  
   int num_orgs_replicated;
 
-  tArray<int> numAsleep;
+//  tArray<int> numAsleep;
   
   // simple deme stats
   cIntSum sum_deme_age;
@@ -284,6 +293,18 @@
   cDoubleSum sum_deme_generations_per_lifetime;
   int m_num_occupied_demes;
 
+  cIntSum sum_deme_events_killed;
+  cIntSum sum_deme_events_kill_attempts;
+  
+  cDoubleSum EnergyTestamentToFutureDeme;
+  cDoubleSum EnergyTestamentToNeighborOrganisms;
+  cDoubleSum EnergyTestamentToDemeOrganisms;
+  cDoubleSum EnergyTestamentAcceptedByOrganisms;
+  cDoubleSum EnergyTestamentAcceptedByDeme;
+  
+  //(event flow rate, (deme pop size, events killed))
+  std::map<int, flow_rate_tuple > flow_rate_tuples;
+
   // deme predicate stats
   tMatrix<int> relative_pos_event_count;
   tMatrix<int> relative_pos_pred_sat;
@@ -435,6 +456,17 @@
   cDoubleSum& SumDemeMerit()   { return sum_deme_merit; }
   cDoubleSum& SumDemeGenerationsPerLifetime()   { return sum_deme_generations_per_lifetime; }
 
+  cIntSum& SumDemeEventsKilled()          { return sum_deme_events_killed; }  
+  cIntSum& SumDemeAttemptsToKillEvents()          { return sum_deme_events_kill_attempts; }
+  
+  cDoubleSum& SumEnergyTestamentToFutureDeme() { return EnergyTestamentToFutureDeme;}
+  cDoubleSum& SumEnergyTestamentToNeighborOrganisms() { return EnergyTestamentToNeighborOrganisms; }
+  cDoubleSum& SumEnergyTestamentToDemeOrganisms() { return EnergyTestamentToDemeOrganisms; }
+  cDoubleSum& SumEnergyTestamentAcceptedByOrganisms() { return EnergyTestamentAcceptedByOrganisms; }
+  cDoubleSum& SumEnergyTestamentAcceptedByDeme() { return EnergyTestamentAcceptedByDeme; }
+  
+  std::map<int, flow_rate_tuple >&  FlowRateTuples() { return flow_rate_tuples; }
+
 #if INSTRUCTION_COUNT
   void ZeroInst();
 #endif
@@ -478,6 +510,17 @@
   const cDoubleSum& SumDemeMerit()  const  { return sum_deme_merit; }
   const cDoubleSum& SumDemeGenerationsPerLifetime() const  { return sum_deme_generations_per_lifetime; }
 
+  const cIntSum& SumDemeEventsKilled() const          { return sum_deme_events_killed; }
+  const cIntSum& SumDemeAttemptsToKillEvents() const  { return sum_deme_events_kill_attempts; }
+  
+  const cDoubleSum& SumEnergyTestamentToFutureDeme() const { return EnergyTestamentToFutureDeme;}
+  const cDoubleSum& SumEnergyTestamentToNeighborOrganisms() const { return EnergyTestamentToNeighborOrganisms; }
+  const cDoubleSum& SumEnergyTestamentToDemeOrganisms() const { return EnergyTestamentToDemeOrganisms; }
+  const cDoubleSum& SumEnergyTestamentAcceptedByOrganisms() const { return EnergyTestamentAcceptedByOrganisms; }
+  const cDoubleSum& SumEnergyTestamentAcceptedByDeme() const { return EnergyTestamentAcceptedByDeme; }
+
+  const std::map<int, flow_rate_tuple >&  FlowRateTuples() const { return flow_rate_tuples; }
+
   void IncResamplings() { ++num_resamplings; }  // @AWC 06/29/06
   void IncFailedResamplings() { ++num_failedResamplings; }  // @AWC 06/29/06
 
@@ -650,10 +693,10 @@
 
   int GetNumSenseSlots();
 
-  int getNumAsleep(int demeID) { return numAsleep[demeID]; }
+/*  int getNumAsleep(int demeID) { return numAsleep[demeID]; }
   void incNumAsleep(int demeID) { numAsleep[demeID]++; }
   void decNumAsleep(int demeID) { numAsleep[demeID]--; }
-
+*/
   double GetAveSpeculative() const { return (m_spec_num) ? ((double)m_spec_total / (double)m_spec_num) : 0.0; }
   int GetSpeculativeWaste() const { return m_spec_waste; }
 
@@ -669,6 +712,7 @@
   // Public calls to output data files (for events)
   void PrintAverageData(const cString& filename);
   void PrintDemeAverageData(const cString& filename);
+  void PrintFlowRateTuples(const cString& filename);
   void PrintErrorData(const cString& filename);
   void PrintVarianceData(const cString& filename);
   void PrintDominantData(const cString& filename);

Modified: development/source/main/cTaskLib.cc
===================================================================
--- development/source/main/cTaskLib.cc	2008-06-15 23:58:31 UTC (rev 2647)
+++ development/source/main/cTaskLib.cc	2008-06-16 15:40:36 UTC (rev 2648)
@@ -27,6 +27,7 @@
 #include "cTaskLib.h"
 
 #include "cArgSchema.h"
+#include "cDeme.h"
 #include "cEnvReqs.h"
 #include "tHashTable.h"
 #include "cTaskState.h"
@@ -411,6 +412,11 @@
   else if (name == "movebetweenevent")
     NewTask(name, "Move to a target area", &cTaskLib::Task_MoveBetweenMovementEvent);  
 
+  // event tasks
+  if(name == "move_to_event")
+    NewTask(name, "Moved into cell containing event", &cTaskLib::Task_MoveToEvent);
+  else if(name == "event_killed")
+    NewTask(name, "Killed event", &cTaskLib::Task_EventKilled);
   
   // Make sure we have actually found a task  
   if (task_array.GetSize() == start_size) {
@@ -2971,7 +2977,7 @@
   cOrgInterface* iface = ctx.GetOrgInterface();
   int prev_target = deme.GetRelativeCellID(iface->GetPrevTaskCellID());
 
-  int cellid = ctx.GetOrgInterface()->GetCellID();
+//  int cellid = ctx.GetOrgInterface()->GetCellID();
 
   // NOTE: as of now, orgs aren't rewarded if they touch a target more than
   //   once in a row.  Could be useful in the future to have fractional reward
@@ -3007,3 +3013,21 @@
   return 0.0;
 }
 
+double cTaskLib::Task_MoveToEvent(cTaskContext& ctx) const {
+  cDeme* deme = ctx.GetOrganism()->GetOrgInterface().GetDeme();
+  int cell_data = ctx.GetOrganism()->GetOrgInterface().GetCellData();
+  if(cell_data <= 0)
+    return 0.0;
+    
+  for(int i = 0; i < deme->GetNumEvents(); i++) {
+    if(deme->GetCellEvent(i)->GetEventID() == cell_data)
+      return 1.0;
+  }
+  return 0.0;
+}
+
+double cTaskLib::Task_EventKilled(cTaskContext& ctx) const {
+  if(ctx.GetOrganism()->GetEventKilled())
+    return 1.0;
+  return 0.0;
+}

Modified: development/source/main/cTaskLib.h
===================================================================
--- development/source/main/cTaskLib.h	2008-06-15 23:58:31 UTC (rev 2647)
+++ development/source/main/cTaskLib.h	2008-06-16 15:40:36 UTC (rev 2648)
@@ -293,6 +293,9 @@
   double Task_MoveToMovementEvent(cTaskContext& ctx) const;
   double Task_MoveBetweenMovementEvent(cTaskContext& ctx) const;
 
+  // movement
+  double Task_MoveToEvent(cTaskContext& ctx) const;
+  double Task_EventKilled(cTaskContext& ctx) const;
 };
 
 




More information about the Avida-cvs mailing list