-------------------------------------------------------------
-- MSS copyright 2015
-- Filename:  S1_TO_P8_CONVERSION.VHD
-- Author: Alain Zarembowitch / MSS
-- Version: 0
-- Date last modified: 8/9/15
-- Inheritance: n/a
--
-- description:   1-bit serial conversion to 8-bit parallel 
-- Key conversion rule is that MSb is transmitted first.     
-- Optional start of frame is aligned always MSb
---------------------------------------------------------------
library IEEE;
use IEEE.STD_LOGIC_1164.ALL;
use IEEE.NUMERIC_STD.ALL;

entity S1_TO_P8_CONVERSION is
    Port ( 
		--// CLK, RESET
		CLK: in std_logic;
		SYNC_RESET: in std_logic;

		--// 1-bit serial input signals
		DATA1_IN: in std_logic;  
		SAMPLE1_CLK_IN: in std_logic;
		SOF1_IN: in std_logic;
		EOF1_IN: in std_logic;
			-- optional start of frame and end of frame

		--// 8-bit parallel output signals
		DATA8_OUT: out std_logic_vector(7 downto 0);
		SAMPLE8_CLK_OUT: out std_logic;
		SOF8_OUT: out std_logic;
		EOF8_OUT: out std_logic
		
	);
end entity;

architecture Behavioral of S1_TO_P8_CONVERSION is
--------------------------------------------------------
--      COMPONENTS
--------------------------------------------------------
--------------------------------------------------------
--     SIGNALS
--------------------------------------------------------   
signal DATA8: std_logic_vector(7 downto 0) := (others => '0');
signal BIT_CNTR: unsigned(2 downto 0) := (others => '1');
signal SAMPLE8_CLK: std_logic := '0';
signal SOF8_FLAG: std_logic := '0';
signal EOF8_FLAG: std_logic := '0';


--------------------------------------------------------
--      IMPLEMENTATION
--------------------------------------------------------
begin
               
INPUT_BIT_CNTR: process(CLK)
begin
	if rising_edge(CLK) then       
		if(SYNC_RESET = '1') then
			BIT_CNTR <= (others => '1');
			DATA8 <= (others => '0');
			SAMPLE8_CLK <= '0';
		
		elsif(SAMPLE1_CLK_IN = '1') then
			DATA8(7 downto 1) <= DATA8(6 downto 0);
			DATA8(0) <= DATA1_IN;
			
			if(SOF1_IN = '1') then
				BIT_CNTR <= (others => '0');
			else
				BIT_CNTR <= BIT_CNTR + 1;
			end if;
			
			if(BIT_CNTR = 6) then
				SAMPLE8_CLK <= '1';
			else
				SAMPLE8_CLK <= '0';
			end if;	
		else
			SAMPLE8_CLK <= '0';
		end if;
	end if;
end process;
DATA8_OUT <= DATA8;
SAMPLE8_CLK_OUT <= SAMPLE8_CLK;

SOF_GEN: process(CLK)
begin
	if rising_edge(CLK) then       
		if(SYNC_RESET = '1') then
			SOF8_FLAG <= '0';
		elsif(SOF1_IN = '1') then
			SOF8_FLAG <= '1';
		elsif(SAMPLE8_CLK = '1') then
			SOF8_FLAG <= '0';
		end if;
	end if;
end process;
SOF8_OUT <= SAMPLE8_CLK and SOF8_FLAG;


EOF_GEN: process(CLK)
begin
	if rising_edge(CLK) then       
		if(SYNC_RESET = '1') then
			EOF8_FLAG <= '0';
		elsif(EOF1_IN = '1') then
			EOF8_FLAG <= '1';
		elsif(SAMPLE8_CLK = '1') then
			EOF8_FLAG <= '0';
		end if;
	end if;
end process;
EOF8_OUT <= SAMPLE8_CLK and EOF8_FLAG;
                        
end Behavioral;
