library IEEE;
use IEEE.STD_LOGIC_1164.ALL;
use ieee.numeric_std.all;

entity sqrt is
    port(
        sync_in : in std_logic;
        clk : in std_logic;
        number : in signed (31 downto 0);
        sqrt : out signed (15 downto 0);
        sync_out : out std_logic);
end sqrt;

architecture Behavioral of sqrt is
    signal num  : signed(31 downto 0);  
    signal a : signed(31 downto 0);  
    signal b : signed(31 downto 0) := (others => '0'); 
    signal i : integer := 17;
begin
    
   process (clk)     
   begin
      if (rising_edge(clk)) then
        if (sync_in='1') then
          b(30) <= '1';
          b(29 downto 0) <= (others => '0');
          num  <= number;
          a <= (others=>'0');
          i <= 0;
        end if; 
        if (i < 16) then
           if (num >= a+b) then
              num   <= num - (a+b);
              a  <= a/2 + b;
           else
              a  <= a/2;
           end if;
           b <= b/4;
           i <= i + 1;
           sync_out <= '0';
        elsif (i = 16) then
           sqrt <= resize(a,16);
           sync_out <= '1';
           i <= i + 1;
        else
           sync_out <= '0';    
        end if;        
      end if;  
   end process;

end Behavioral;
