/*
 * To change this template, choose Tools | Templates
 * and open the template in the editor.
 */

package cz.karry.dop.core.alu;

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

/**
 *
 * @author karry
 */
class Adder implements BusListener, SignalListener{
    private Bus bus1;
    private Bus bus2;
    private Bus sum;
    private Signal cin;
    private Signal carry;
    private Signal overflow;

    public Adder(Bus bus1, Bus bus2, Bus sum, Signal cin, Signal carry, Signal overflow) {
        this.bus1 = bus1;
        this.bus2 = bus2;
        this.sum = sum;
        
        this.cin = cin;
        this.carry = carry;
        this.overflow = overflow;
        
        cin.addSignalListener(this);
        bus1.addBusListener(this);
        bus2.addBusListener(this);
        
        add();
    }

    public void busChangePerformed(Bus bus, int value) {
        add();
    }

    public void signalChangePerformed(Signal signal, boolean active) {
        add();
    }

    private void add() {
        int value = bus1.getValue() + bus2.getValue();
        if (cin.isActive()){
            value ++;
        }
            
        carry.setState((value & 0x10000) == 0x10000);
        // boolean cy15 = (value & 0x8000) == 0x8000;
        // overflow.setState(cy15 != carry.isActive()); // cy15 XOR cy16
        overflow.setState( ((value & 0x8000) == 0x8000) != carry.isActive()); // cy15 XOR cy16
        
        this.sum.setValue(value & 0xffff);
    }

}
