-------------------------------------------------------------------------------
-- Company:
-- Engineer:
--
-- Create Date:    13:28:47 05/16/2014
-- Design Name:
-- Module Name:    counter - Behavioral
-- Project Name:
-- Target Devices:
-- Tool versions:
-- Description:
--
-- Dependencies:
--
-- Revision:
-- Revision 0.01 - File Created
-- Additional Comments:
--
-------------------------------------------------------------------------------
library IEEE;
use IEEE.STD_LOGIC_1164.ALL;
use IEEE.STD_LOGIC_ARITH.ALL;
use IEEE.STD_LOGIC_UNSIGNED.ALL;

-- Uncomment the following library declaration if using
-- arithmetic functions with Signed or Unsigned values
--use IEEE.NUMERIC_STD.ALL;

-- Uncomment the following library declaration if instantiating
-- any Xilinx primitives in this code.
--library UNISIM;
--use UNISIM.VComponents.all;

entity counter is
  port (
    CLK : in  std_logic;
    RESET : in  std_logic;
    CE : in  std_logic;
    UP_DW : in  std_logic;
    CARRY : out std_logic;
    DOUT : out std_logic_vector (3 downto 0)
  );
end counter;

architecture Behavioral of counter is

signal COUNT : std_logic_vector(3 downto 0);

begin

process (CLK) begin
  if CLK='1' and CLK'event then
    if RESET='1' then 
      COUNT <= (others => '0');
    elsif CE='1' then
      if UP_DW='1' then
        if COUNT = "1001" then
          COUNT <= "0000";
        else
          COUNT <= COUNT + 1;
        end if;
      else
        if COUNT = "0000" then
          COUNT <= "1001";
        else
          COUNT <= COUNT - 1;
        end if;
      end if;
    end if;
  end if;
end process;

process (COUNT, CE, UP_DW) begin
  if(UP_DW = '1') then
    if(COUNT = "1001" and CE =  '1') then
      CARRY <= '1';
    else
      CARRY <= '0';
    end if;
  else
    if(COUNT = "0000" and CE = '1') then
      CARRY <= '1';
    else
      CARRY <= '0';
    end if;
  end if;
end process;

DOUT <= COUNT;

end Behavioral;

