module tt_um_rejunity_z80 (
    input  wire [7:0] ui_in,    // Dedicated inputs
    output wire [7:0] uo_out,   // Dedicated outputs
    input  wire [7:0] uio_in,   // IOs: Input path
    output wire [7:0] uio_out,  // IOs: Output path
    output wire [7:0] uio_oe,   // IOs: Enable path (active high: 0=input, 1=output)
    input  wire       ena,      // will go high when the design is enabled
    input  wire       clk,      // clock
    input  wire       rst_n     // reset_n - low to reset
);

    // We have to multiplex the 16 bits of (A) address bus and 8 control signals into
    // the 8 output pins that are available in TinyTapeout.
    wire  [7:0] ctrl_signals;
    wire [15:0] addr_bus;

    // Use mux_control to select between the address bus and control signals
    //   [00] --- {A0 - A7} 
    //   [01] --- {A8 - A15}
    //   [1?] --- control signals {m1_n, mreq_n, iorq_n, rd_n, wr_n, rfsh_n, halt_n, busak_n}

    // reg [1:0] clk_counter;
    // always @(posedge clk)
    //     clk_counter <= (rst_n) ? clk_counter + 1 : 0;
    // wire z80_clk = (rst_n) ? clk_counter[1:0] == 0: clk; // Z80 clock is pulsed once every 4 TinyTapeout clock cycles

    // assign uo_out = (clk_counter[0] == 0) ? ctrl_signals :
    //                 (clk_counter[1] == 0) ? addr_bus[7:0] :
    //                                         addr_bus[15:8];

    wire z80_clk = clk;
    wire [1:0] mux_control = ui_in[7:6];
    assign uo_out = (mux_control[1] == 1) ? ctrl_signals :
                    (mux_control[0] == 0) ? addr_bus[7:0] :
                                            addr_bus[15:8];

    // reg [7:0] mux_out;
    // assign uo_out = mux_out;
    // always @(*) begin
    //     case(ui_in[7:6])
    //         2'd0:  mux_out = addr_bus[7:0];
    //         2'd1:  mux_out = addr_bus[15:8];
    //         2'd2:  mux_out = ctrl_signals;
    //         2'd3:  mux_out = ctrl_signals;
    //     endcase
    // end
    
    wire doe; // Data Output Enable
    assign uio_oe  = {8{doe}}; // (active high: 0=input, 1=output)

    z80 z80 (
        .clk     (z80_clk),
        .cen     (ena),
        .reset_n (rst_n),
        .wait_n  (ui_in[0]),
        .int_n   (ui_in[1]),
        .nmi_n   (ui_in[2]),
        .busrq_n (ui_in[3]),
        .di      (uio_in),
        .dout    (uio_out),
        .doe     (doe),
        .A       (addr_bus),
        .m1_n    (ctrl_signals[0]),
        .mreq_n  (ctrl_signals[1]),
        .iorq_n  (ctrl_signals[2]),
        .rd_n    (ctrl_signals[3]),
        .wr_n    (ctrl_signals[4]),
        .rfsh_n  (ctrl_signals[5]),
        .halt_n  (ctrl_signals[6]),
        .busak_n (ctrl_signals[7])
    );
endmodule