/*
 * Created on Apr 4, 2005
 *
 * TODO To change the template for this generated file go to
 * Window - Preferences - Java - Code Style - Code Templates
 */
package ps6.v2;

import java.util.ArrayList;

import ps6.Message;

/**
 * @author knorton
 *
 * TODO To change the template for this generated type comment go to
 * Window - Preferences - Java - Code Style - Code Templates
 */
public abstract class Gate {
	protected ArrayList 		connects = null;
	private Message[]		results = null;
	private boolean			doDamp = false;
	
	public Gate() {
		this.connects = new ArrayList();
	}
	
	public void damp() {
		this.doDamp = true;
	}
	
	protected Connector getConnector(int ix) {
		return (Connector)this.connects.get(ix);
	}
	
	public void connect(Connector c) {
		this.connects.add(c);
	}
	
	public abstract void update();
	
	public void setResult(Message[] msgs) {
		this.results = msgs;
	}
	
	private static Message average(Message a, Message b) {
		return new Message(
			(a.getP(0)+b.getP(0))/2.0,
			(a.getP(1)+b.getP(1))/2.0);
	}
	
	public void commit() {
		if (this.doDamp)
			for (int i=0;i<this.results.length;i++)
				this.results[i] = average(this.results[i],this.getConnector(i).receive(this));
		
		for (int i=0;i<this.connects.size();i++)
			((Connector)this.connects.get(i)).send(this,this.results[i]);
	}
}
