`timescale 1ns/1ps
module test_morse;
    reg clk=0;
    reg [3:0] keys=15;
    reg [9:0] sw=0;
    wire [9:0] lights;
    integer selected_letter = 0;
    integer unit_number = 0;
    morse_sender #(.UNIT_CYCLES(5)) dut(clk, sw, keys, lights);
    always #1 clk=~clk;
    task cycles;
        input integer n;
        begin repeat (n) @(negedge clk); end
    endtask
    task check;
        input expected;
        begin
            if (lights !== {9'b0,expected}) begin
                $display("FAIL letter %c, unit %0d: expected LEDR0=%b, observed LEDs=%b",
                         8'd65 + selected_letter, unit_number, expected, lights);
                $finish;
            end
        end
    endtask
    task send;
        input integer choice, length;
        input [15:0] timeline;
        integer step, k;
        begin
            selected_letter=choice; unit_number=0;
            sw=choice; keys[1]=0; cycles(3);
            // Hold KEY1 through E and its following silence.
            if (choice != 4) keys[1]=1;
            for (step=0; step<length; step=step+1) begin
                unit_number=step+1;
                check(timeline[step]);
                // Change the selection during transmission to check the captured letter.
                if (step==1) sw=7-choice;
                for (k=0;k<4;k=k+1) begin cycles(1); check(timeline[step]); end
                cycles(1);
            end
            unit_number=length+1;
            repeat (10) begin check(0); cycles(1); end
            keys[1]=1; cycles(3); check(0);
        end
    endtask
    initial begin
        #0.4; keys[0]=0; #0.1; check(0); cycles(3); keys[0]=1; cycles(5);
        send(0, 5, 16'b11101);
        send(1, 9, 16'b101010111);
        send(2, 11, 16'b10111010111);
        send(3, 7, 16'b1010111);
        send(4, 1, 16'b1);
        send(5, 9, 16'b101110101);
        send(6, 9, 16'b101110111);
        send(7, 7, 16'b1010101);
        selected_letter=1; unit_number=1;
        sw=1; keys[1]=0; cycles(3); check(1);
        #0.2; keys[0]=0; #0.1; check(0); keys[1]=1; cycles(3); keys[0]=1; cycles(8); check(0);
        send(4,1,1);
        $display("PASS A-H, five clock edges per unit, latched selection, one letter per press, asynchronous reset and restart"); $finish;
    end
endmodule
