module step_cpu(input wire [9:0] SW, input wire [3:0] KEY, output wire [9:0] LEDR);
    reg [7:0] high_byte, low_byte;
    always @(posedge KEY[1] or negedge KEY[3])
        if (!KEY[3]) high_byte <= 0; else high_byte <= SW[7:0];
    always @(posedge KEY[2] or negedge KEY[3])
        if (!KEY[3]) low_byte <= 0; else low_byte <= SW[7:0];

    wire [15:0] view;
    wire done, busy;
    course_cpu core(KEY[0], KEY[3], SW[9], {high_byte, low_byte}, SW[2:0], view, done, busy);
    assign LEDR = {done, busy, SW[8] ? view[15:8] : view[7:0]};
endmodule

module course_cpu(input wire clk, reset_n, run, input wire [15:0] data_in,
                  input wire [2:0] probe, output wire [15:0] view, output wire done, busy);
    localparam FETCH=0, EXECUTE=1, CALCULATE=2, WRITE_BACK=3;
    localparam MOVE=0, MOVE_TOP=1, ADD=2, SUBTRACT=3;
    reg [1:0] phase;
    reg [15:0] ir, accumulator, result;
    reg [15:0] registers [0:7];
    wire [2:0] op = ir[15:13];
    wire [2:0] destination = ir[11:9];
    wire [15:0] operand = ir[12] ? {7'b0, ir[8:0]} : registers[ir[2:0]];
    reg [15:0] bus_value;
    integer index;

    always @* begin
        case (phase)
            EXECUTE: begin
                case (op)
                    MOVE: bus_value = operand;
                    MOVE_TOP: bus_value = {ir[7:0], 8'h00};
                    default: bus_value = registers[destination];
                endcase
            end
            CALCULATE: bus_value = operand;
            WRITE_BACK: bus_value = result;
            default: bus_value = data_in;
        endcase
    end
    assign view = registers[probe];
    assign busy = phase != FETCH;
    assign done = (phase == EXECUTE && (op == MOVE || op == MOVE_TOP)) || phase == WRITE_BACK;

    always @(posedge clk or negedge reset_n) begin
        if (!reset_n) begin
            phase <= FETCH;
            ir <= 0;
            accumulator <= 0;
            result <= 0;
            for (index = 0; index < 8; index = index + 1) registers[index] <= 0;
        end else begin
            case (phase)
                FETCH: if (run) begin ir <= bus_value; phase <= EXECUTE; end
                EXECUTE: begin
                    case (op)
                        MOVE, MOVE_TOP: begin registers[destination] <= bus_value; phase <= FETCH; end
                        ADD, SUBTRACT: begin accumulator <= bus_value; phase <= CALCULATE; end
                        default: phase <= FETCH;
                    endcase
                end
                CALCULATE: begin
                    result <= op == SUBTRACT ? accumulator - bus_value : accumulator + bus_value;
                    phase <= WRITE_BACK;
                end
                WRITE_BACK: begin registers[destination] <= bus_value; phase <= FETCH; end
            endcase
        end
    end
endmodule
