
package cz.karry.dop.core.alu;


import cz.karry.dop.core.Signal;
import cz.karry.dop.core.SignalListener;

/**
 *
 * @author karry
 */
class Czm implements SignalListener{

    
    private Signal czm;
    private Signal cin;
    private Signal cf;
    private Signal ci0;
    private Signal ucf;
    private Signal clk;
    private Signal ecw;
    private Signal reset;
    private boolean dTmpValue;
    private boolean dValue;


    //     Czm(core.getSignal(Core.RESET), core.getSignal(Core.CLK), core.getSignal(Core.UCF), core.getSignal(Core.ECW), core.getSignal(Core.CI0), flags.getCFSignal() );
    
    public Czm(Signal reset, Signal clk, Signal ucf, Signal ecw, Signal ci0, Signal cf) {
        cin = new Signal(Alu.CIN);
        czm = new Signal(Alu.CZM);
        
        this.reset = reset;
        this.clk = clk;
        this.ucf = ucf;
        this.ecw = ecw;
        this.ci0 = ci0;
        this.cf = cf;
        
        ci0.addSignalListener(this);
        cf.addSignalListener(this);
        reset.addSignalListener(this);
        czm.addSignalListener(this);
        clk.addSignalListener(this);
    }

    Signal getCin() {
        return cin;
    }

    Signal getCzm() {
        return czm;
    }

    public void signalChangePerformed(Signal signal, boolean active) {
        if ((signal == ci0) && (!czm.isActive())){
            cin.setState(ci0.isActive());
        }
        if ((signal == cf) && (czm.isActive())){
            cin.setState(cf.isActive());
        }
        if (signal == czm){
            if (active){
                cin.setState(cf.isActive());
            }else{
                cin.setState(ci0.isActive());
            }
        }
        
        if (signal == clk){
            if (active){ // rising edge
                if ( ucf.isActive() ){
                    dTmpValue = true;
                }else if ((!ucf.isActive()) && (!ecw.isActive())){
                    dTmpValue = czm.isActive();
                }else{
                    dTmpValue = false;
                }
            }else{ // faling edge
                dValue = dTmpValue;
                czm.setState(dValue);
            }
        }
        
        if ((signal == reset) && active){
            dValue = false;
            dTmpValue = false;
            czm.setState(false);
        }
    }

}
