// Top module that interfaces the ALU and BASYS3 board components

`timescale 1ns / 1ps

module top(
  input       clk,                          // Clock input
  input [15:0] SW,                          // Input switches
  input       BTNL, BTNR, BTNU, BTND, BTNC, // Input buttons

  output CA, CB, CC, CD, CE, CF, CG, DP, // 7-segment display segments
  output [3:0]  AN,          // 7-segment display anodes
  output [15:0] LED       // LED outputs to show the result
);

// Global wire definitions
wire reset;

assign reset = BTNC; // Active high reset from center button

// 7 -segment display decoder instance
wire [3:0] hex3, hex2, hex1, hex0;

seg7display seg7_inst(
  .x_l    ({hex3, hex2, hex1, hex0}),
  .clk    (clk),
  .reset  (reset),
  .a_to_g ({CG, CF, CE, CD, CC, CB, CA}),
  .an_l   (AN),
  .dp_l   (DP)
);

logic [15:0] RegA, RegB;
logic [5:0] op_code;

always_ff @(posedge clk or posedge reset) begin
    if (reset) begin
        RegA <= 16'b0;
        RegB <= 16'b0;
        op_code <= 6'b0;
    end else begin
        if (BTNU) begin
            RegA <= SW;
        end
        if (BTNR) begin
            RegB <= SW;
        end
        if (BTND) begin
            op_code <= SW[5:0];
        end
    end
end

logic [15:0] RegB_shifted;
shifter shifter_inst (
    .in(RegB),
    .shift_op(op_code[1:0]),
    .out(RegB_shifted)
);

// ALU instance
wire [15:0] alu_result;
wire Z, N, V, C;
ALU alu_inst (
  .A      (RegA),
  .B      (RegB_shifted),
  .C_in   (op_code[5]), // Carry input for ADDC and SUBC
  .op     (op_code[4:2]),
  .Y      (alu_result),
  .status ({Z, N, V, C})
);


// Connect ALU result to LEDs
assign LED[15:0] = {12'b0, Z,N,V,C};
assign {hex3, hex2, hex1, hex0} = alu_result;

endmodule