library ieee;
use ieee.std_logic_1164.all;

entity run_states is
    generic (invert_a : std_logic := '0');
    port (clock, reset_n, sample : in std_logic;
          states : out std_logic_vector(8 downto 0));
end entity;

architecture rtl of run_states is
    signal state, following : std_logic_vector(8 downto 0);
    signal start, start_zero, start_one : std_logic;
begin
    start <= state(0) xor invert_a;
    start_zero <= start or state(5) or state(6) or state(7) or state(8);
    start_one <= start or state(1) or state(2) or state(3) or state(4);
    following(0) <= invert_a;
    following(1) <= not sample and start_zero;
    following(2) <= not sample and state(1);
    following(3) <= not sample and state(2);
    following(4) <= not sample and state(3); -- TODO: keep a match across an overlapping zero
    following(5) <= sample and start_one;
    following(6) <= sample and state(5);
    following(7) <= sample and state(6);
    following(8) <= sample and (state(7) or state(8));

    process(clock)
    begin
        if rising_edge(clock) then
            if reset_n = '0' then
                state <= (0 => not invert_a, others => '0');
            else
                state <= following;
            end if;
        end if;
    end process;
    states <= state;
end architecture;

library ieee;
use ieee.std_logic_1164.all;

entity one_hot_runs is
    port (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 board of one_hot_runs is
    signal ordinary, modified, visible_state : std_logic_vector(8 downto 0);
begin
    first : entity work.run_states generic map ('0') port map (KEY(0), SW(0), SW(1), ordinary);
    second : entity work.run_states generic map ('1') port map (KEY(0), SW(0), SW(1), modified);
    visible_state <= ordinary when SW(2) = '0' else modified;
    LEDR <= (visible_state(4) or visible_state(8)) & visible_state;
end architecture;
