library ieee;
use ieee.std_logic_1164.all;

entity spi_clkmon is

  port (
    clk_i               : in  std_logic;
    rst_in              : in  std_logic;
    sck_i               : in  std_logic;
    csn_i               : in  std_logic;
    clock_polarity_i    : in  std_logic;
    clock_phase_i       : in  std_logic;
    clock_rising_o      : out std_logic;
    sample_data_o : out std_logic;
    change_data_o : out std_logic);

end entity spi_clkmon;

architecture a1 of spi_clkmon is
  signal changing : std_logic;

  signal sample_data : std_logic;
  signal change_data : std_logic;

  signal curr_sck : std_logic;
  signal next_sck : std_logic;

begin  -- architecture a1

  set_curr_sck: process (clk_i) is
  begin  -- process set_curr_sck
    if rising_edge(clk_i) then          -- rising clock edge
      if rst_in = '0' or csn_i = '1' then -- synchronous reset (active low)
        curr_sck <= '0';
      else
        curr_sck <= next_sck;
      end if;
    end if;
  end process set_curr_sck;

  next_sck <= sck_i when clock_polarity_i = '0' else not sck_i;

  changing <= '1' when next_sck /= curr_sck else '0';
  sample_data <= '1' when curr_sck = clock_phase_i and changing = '1' else '0';
  change_data <= '1' when curr_sck /= clock_phase_i and changing = '1' else '0';

  clock_rising_o <= sample_data;
  sample_data_o <= sample_data;
  change_data_o <= change_data;

end architecture a1;
