library ieee;
use ieee.std_logic_1164.all;

entity shift_register is

  generic (
    SIZE : natural);

  port (
    clk_i      : in  std_logic;
    rst_in     : in  std_logic;
    lsbfirst_i : in  std_logic;
    shift_i    : in  std_logic;
    sd_i       : in  std_logic;
    sd_o       : out std_logic;
    latch_i    : in  std_logic;
    data_i     : in  std_logic_vector(SIZE - 1 downto 0);
    data_o     : out std_logic_vector(SIZE - 1 downto 0));

end entity shift_register;

architecture a1 of shift_register is
  signal next_register : std_logic_vector(SIZE - 1 downto 0);
  signal curr_register : std_logic_vector(SIZE - 1 downto 0);
begin  -- architecture a1

  set_data: process (clk_i) is
  begin  -- process set_data
    if rising_edge(clk_i) then          -- rising clock edge
      if rst_in = '0' then              -- synchronous reset (active low)
        curr_register <= (others => '0');
      else
        curr_register <= next_register;
      end if;
    end if;
  end process set_data;

  next_register <= data_i when latch_i = '1' else
                   curr_register(SIZE - 2 downto 0) & sd_i when shift_i = '1' and lsbfirst_i = '0' else
                   sd_i & curr_register(SIZE - 1 downto 1) when shift_i = '1' else
                   curr_register;

  sd_o <= curr_register(SIZE - 1);
  data_o <= curr_register;

end architecture a1;
