library ieee;
use ieee.std_logic_1164.all;
use ieee.std_logic_unsigned.all;

entity pulses is port (
	clk, reset, etr, enw: in std_logic;
	plsttl, v_pulse: in std_logic_vector(1 downto 0);
	pulse_out: out std_logic_vector(1 downto 0);
	add: in std_logic_vector(1 downto 0);
	grp: in std_logic_vector(4 downto 0);
	db_in: in std_logic_vector(13 downto 0);
	db_out: out std_logic_vector (15 downto 0);
	delay_0, delay_1: out std_logic_vector(6 downto 0)
);
end pulses ;

architecture arch of pulses is
signal pulse_reg0, pulse_reg1: std_logic_vector(13 downto 0);
signal pulse_in: std_logic_vector(1 downto 0);
signal conta_0, conta_1: std_logic_vector(7 downto 0);
signal q0_0, q0_1, q1_0, q1_1: std_logic;
signal ps1, ps2, psync: std_logic_vector(1 downto 0);

begin

pulse_in <= v_pulse or plsttl;
delay_0 <= pulse_reg0 (6 downto 0);
delay_1 <= pulse_reg1 (6 downto 0);

db_out <= "00" & pulse_reg0 when etr='0' and grp(2)='1' and add=3 else (others => 'Z'); --11
db_out <= "00" & pulse_reg1 when etr='0' and grp(3)='1' and add=0 else (others => 'Z'); --12

process (clk, reset)
begin
	if reset='1' then
	  pulse_reg0 <= ( others => '0');
	  pulse_reg1 <= ( others => '0');
	elsif clk'event and clk='1' then
	  if enw='1' then 
	    if grp(2)='1' and add=3 then --11
	      pulse_reg0 <= db_in;
	    end if;
	    if grp(3)='1' and add=0 then --12
	      pulse_reg1 <= db_in;
	    end if;
	  end if;
	end if;
end process; 


process (clk, reset)
begin
	if reset='1' then
	  conta_0 <= (others => '1');
	elsif clk'event and clk='1' then
	  if psync(0)='1' then
	    conta_0 <= '0' & pulse_reg0(13 downto 7);
	  elsif conta_0(7)='0' then
	    conta_0 <= conta_0 - 1;
	  end if;
	end if;
end process;

process (clk, reset)
begin
	if reset='1' then
	  conta_1 <= (others => '1');
	elsif clk'event and clk='1' then
	  if psync(1)='1' then
	    conta_1 <= '0' & pulse_reg1(13 downto 7);
	  elsif conta_1(7)='0' then
	    conta_1 <= conta_1 - 1;
	  end if;
	end if;
end process;

process (clk, reset)
begin
	if reset='1' then
	  q0_0 <= '1';
	  q0_1 <= '1';
	elsif clk'event and clk='1' then
	  if psync(0)='1' then
	    q0_0 <= '0';
	    q0_1 <= '0';
	  else
	    q0_1 <= q0_0;
	    q0_0 <= conta_0(7);
	  end if;
	end if;
end process;

process (clk, reset)
begin
	if reset='1' then
	  q1_0 <= '1';
	  q1_1 <= '1';
	elsif clk'event and clk='1' then
	  if psync(1)='1' then
	    q1_0 <= '0';
	    q1_1 <= '0';
	  else
	    q1_1 <= q1_0;
	    q1_0 <= conta_1(7);
	  end if;
	end if;
end process;

pulse_out(0) <= conta_0(7) and not q0_1;
pulse_out(1) <= conta_1(7) and not q1_1;

psync <= ps1 and not ps2;
process (clk, reset)
begin
	if reset='1' then
	  ps1 <= "00";
	  ps2 <= "00";
	elsif clk'event and clk='1' then
	  ps1 <= pulse_in;
	  ps2 <= ps1;
	end if;
end process;

end arch;
	
