library ieee;
use ieee.std_logic_1164.all;


entity MAE is 
	port(
		clk : in std_logic;
		reset : in std_logic;
		fin_tempo : in std_logic;
		fin_1 : in std_logic;
		fin_0 : in std_logic;
		tr_bit : in std_logic;
		load : out std_logic;
		shift : out std_logic;
		start_tempo : out std_logic;
		go_1 : out std_logic;
		go_0 : out std_logic
		
	);
end MAE;



architecture behaviour of MAE is
	type state is (Start, LecReg, Send0, Send1, Tempo);
	signal cs, fs : state;
	--signal cpt : integer range 0 to 51 := 0;

begin
	process(clk, reset)
	variable   cpt : INTEGER RANGE 0 TO 101;
	begin
		if reset = '1' then 
			fs <= Start;
			load <= '0';
			shift <= '0';
			start_tempo <= '0';
			go_0 <= '0';
			go_1 <= '0';
			cpt := 0;
			
		elsif rising_edge(clk) then

			if cs = Start then
				load <= '1';
				fs <= LecReg;

			elsif cs = LecReg then
			    load <= '0';
				if tr_bit = '1' then
					fs <= Send1;
				else
					fs <= Send0;
				end if;
				shift <= '1';
				cpt := cpt + 1;

			elsif cs = Send0 then
			    shift <= '0';
				go_0 <= '1';
				if fin_0 = '1' then
					go_0 <= '0';
					if cpt >= 101 then -- on doit normalement en compter 51, mais ça marche pas par contre 101 c'est nickel
						fs <= Tempo;
					else
						fs <= LecReg;
					end if;
				end if;
				
			elsif cs = Send1 then
			    shift <= '0';
				go_1 <= '1';
				if fin_1 = '1' then
					go_1 <= '0';
					if cpt >= 101 then
						fs <= Tempo;
					else
						fs <= LecReg;
					end if;
				end if;

			elsif cs = Tempo then
				start_tempo <= '1';
				if fin_tempo = '1' then
					start_tempo <= '0';
					cpt := 0;
					fs <= Start;
				end if;
			end if;

			cs <= fs;

		end if;
	end process;
end behaviour;