package testprocs;

import simulator.*;
import scripting.*;
import modules.color.*;
import modules.hierarchy.*;
import modules.neighborset.*;
import modules.gradient.*;
import utils.*;
import java.awt.*;
import java.util.*;
import java.io.*;

public class HExperiments implements ProcessorModule {
  static final String script = "modules.color.ColorModule\nmodules.gradient.ActiveGradient\nmodules.neighborset.NeighborSet\nmodules.hierarchy.Hierarchy\ntestprocs.HExperiments";

  public static void main (String argv[]) {
    try {
      //System.out.print("Output file name? [out.txt] ");
      //StreamTokenizer(new BufferedReader(new InputStreamReader(is)));
      out = new PrintWriter(new FileWriter("out.txt"),true);
      out.println("Flux sampled once per timestep.");
    } catch(Exception e) {
      System.out.println("failure: "+e);
    }
    
    for(int i=0;i<10;i++) {
      exptid=i;
      out.println("Experiment "+i);

      CommunicationsModel comm = new PerfectCommunicationsModel();
      ProcessorFactory pf = new ScriptProcFactory(script);
      Simulator sim = new Simulator(comm,pf,2000,0.04);
      
      // and... run!
      sim.setPaused(false);
      sim.run();
      
      cleanup(); // between sims palette cleansing
    }
  }


  static void cleanup() { // between sims palette cleansing
    flux=0; initiator=Double.NaN;
  }

  public Symbol getName() { return Symbol.GetSymbol("HExtProc"); }
  public void link(PortedProcessor p) {
    pp = p;
    pp.addClockListener(this);
    hm = (Hierarchy)p.getModule("Hierarchy");
  }

  PortedProcessor pp; ActiveGradient ag; ColorModule cm; Hierarchy hm;

  static double initiator=Double.NaN;
  boolean ruler=false;
  public void init() {
    if(Double.isNaN(initiator)) {
      initiator=pp.getUID(); ruler=true; System.out.println("Starting...");
    }
  }
  static PrintWriter out;
  static int exptid=0;

  public static int level = 0;
  public static int flux = 0;
  boolean myflux=false;
  public boolean signalEvent(Symbol name,Object data) {
    boolean dirty = false;
    if(name==PortedProcessor.kClock) {
      int t = ((Integer)data).intValue();
      
      boolean newflux = hm.getStability()==0;
      if(newflux!=myflux) { myflux=newflux; if(myflux) flux++; else flux--; }
      if(ruler) {
        if(t%5==0) System.out.println("t="+t);
        out.println(exptid+"\t"+t+"\t"+flux);
        if(t==700) Simulator.kludgeterm=true;
      }
    }
    return dirty;
  }

}


