
library ieee;
use ieee.std_logic_1164.all;

entity STRETCH is
  port (X, CLK, RST : in std_logic;
        Z : out std_logic);
end STRETCH;

architecture STRETCH of STRETCH is
  type STATE is (S0, S1, S2, S3, S4, S5, S6, S7, S8);
  signal CURRENT_STATE, NEXT_STATE : STATE;
  signal TEMP : std_logic;
begin
  process(X, CURRENT_STATE)
  begin
    case CURRENT_STATE is
      when S0 => if (X = '0') then
                   NEXT_STATE <= S1;
                 else
                   NEXT_STATE <= S2;
                 end if;
      when S1 => TEMP <= X;
                 NEXT_STATE <= S3;
      when S2 => TEMP <= X;
                 NEXT_STATE <= S4;
      when S3 => if (TEMP <= '0') then
                   NEXT_STATE <= S5;
                 else 
                   NEXT_STATE <= S6;
                 end if;
      when S4 => if (TEMP <= '0') then
                   NEXT_STATE <= S5;
                 else 
                   NEXT_STATE <= S6;
                 end if;
      when S5 => NEXT_STATE <= S7;
      when S6 => NEXT_STATE <= S8;
      when S7 => if (X = '0') then
                   NEXT_STATE <= S1;
                 else
                   NEXT_STATE <= S2;
                 end if;
      when S8 => if (X = '0') then
                   NEXT_STATE <= S1;
                 else
                   NEXT_STATE <= S2;
                 end if;
    end case;
  end process;
  process(CLK, RST)
  begin
    if (RST = '1')
      then CURRENT_STATE <= S0;
    elsif (CLK'event and CLK = '1') then
      CURRENT_STATE <= NEXT_STATE;
    end if;
  end process;
  process(CURRENT_STATE)
  begin
    case CURRENT_STATE is
      when S0|S1|S3|S5|S7 => Z <= '0';
      when S2|S4|S6|s8 => Z <= '1';
    end case;
  end process;
end STRETCH;


