library ieee;
use ieee.std_logic_1164.all;
use ieee.numeric_std.all;

entity morse_fsm is
    generic (UNIT_CYCLES : positive := 25000000);
    port (CLOCK_50 : in std_logic;
          SW : in std_logic_vector(9 downto 0);
          KEY : in std_logic_vector(3 downto 0);
          LEDR : out std_logic_vector(9 downto 0));
end entity;

architecture rtl of morse_fsm is
    type phase_type is (idle, dot, dash_first, dash_middle, dash_last, gap);
    type letter_table is array(0 to 7) of unsigned(3 downto 0);
    type length_table is array(0 to 7) of natural range 1 to 4;
    constant pattern : letter_table := ("0010", "0001", "0101", "0001", "0000", "0100", "0011", "0000");
    constant size : length_table := (2, 4, 4, 3, 1, 4, 3, 4);
    signal phase : phase_type;
    signal key_meta, key_sample, previous : std_logic;
    signal bits : unsigned(3 downto 0);
    signal remaining : natural range 0 to 3;
    signal ticks : natural range 0 to UNIT_CYCLES - 1;
begin
    LEDR <= "0000000000" when phase = idle or phase = gap else "0000000001";
    process(CLOCK_50, KEY)
        variable choice : natural range 0 to 7;
    begin
        if KEY(0) = '0' then
            key_meta <= '1'; key_sample <= '1'; previous <= '1';
            phase <= idle; bits <= (others => '0'); remaining <= 0; ticks <= 0;
        elsif rising_edge(CLOCK_50) then
            key_meta <= KEY(1); key_sample <= key_meta; previous <= key_sample;
            if phase = idle then
                if previous = '1' and key_sample = '0' then
                    choice := to_integer(unsigned(SW(2 downto 0)));
                    bits <= shift_right(pattern(choice), 1); remaining <= size(choice) - 1;
                    if pattern(choice)(0) = '1' then phase <= dash_first; else phase <= dot; end if;
                    ticks <= 0;
                end if;
            elsif ticks < UNIT_CYCLES - 1 then
                ticks <= ticks + 1;
            else
                ticks <= 0;
                case phase is
                    when dot | dash_last =>
                        if remaining = 0 then phase <= idle; else phase <= gap; end if;
                    when dash_first => phase <= dash_last; -- TODO: measure the dash.
                    when dash_middle => phase <= dash_last;
                    when gap =>
                        if bits(0) = '1' then phase <= dash_first; else phase <= dot; end if;
                        bits <= shift_right(bits, 1); remaining <= remaining - 1;
                    when idle => null;
                end case;
            end if;
        end if;
    end process;
end architecture;
