LIBRARY IEEE;
USE IEEE.STD_LOGIC_1164.ALL;
USE IEEE.STD_LOGIC_MISC.ALL;

ENTITY MEM_LOADS_MASKING IS

	PORT( 
		ALU_LSBS: IN  STD_LOGIC_VECTOR(1  DOWNTO 0);
		U	: IN  STD_LOGIC;
		OPCODE  : IN  STD_LOGIC_VECTOR(1  DOWNTO 0);
		MEM_VAL : IN  STD_LOGIC_VECTOR(31 DOWNTO 0);
		OUTPUT  : OUT STD_LOGIC_VECTOR(31 DOWNTO 0)
	    );
		 
END MEM_LOADS_MASKING;

ARCHITECTURE DATAFLOW OF MEM_LOADS_MASKING IS
	
	--  Bytes
	-- +-------------------+
	-- |  A |  B |  C |  D |  
	-- +-------------------+

	BEGIN
			 -- SIGNED LOAD BYTE
	OUTPUT <= 	(31 DOWNTO 8  => MEM_VAL( 7)) & MEM_VAL(7  DOWNTO 0  ) WHEN (OPCODE = "00" AND ALU_LSBS = "00" AND U = '0' ) ELSE -- BYTE: D LSB
			(31 DOWNTO 8  => MEM_VAL(15)) & MEM_VAL(15 DOWNTO 8  ) WHEN (OPCODE = "00" AND ALU_LSBS = "01" AND U = '0' ) ELSE -- BYTE: C
			(31 DOWNTO 8  => MEM_VAL(23)) & MEM_VAL(23 DOWNTO 16 ) WHEN (OPCODE = "00" AND ALU_LSBS = "10" AND U = '0' ) ELSE -- BYTE: B
			(31 DOWNTO 8  => MEM_VAL(31)) & MEM_VAL(31 DOWNTO 24 ) WHEN (OPCODE = "00" AND ALU_LSBS = "11" AND U = '0' ) ELSE -- BYTE: A MSB
			 -- SIGNED LOAD HALF
			(31 DOWNTO 16 => MEM_VAL(15)) & MEM_VAL(15 DOWNTO 0  ) WHEN (OPCODE = "01" AND ALU_LSBS(1) = '0' AND U = '0' ) ELSE -- HALF: DC
			(31 DOWNTO 16 => MEM_VAL(31)) & MEM_VAL(31 DOWNTO 16 ) WHEN (OPCODE = "01" AND ALU_LSBS(1) = '1' AND U = '0' ) ELSE -- HALF: AB
			 -- UNSIGNED LOAD BYTE
			(31 DOWNTO 8  => '0') & MEM_VAL(7  DOWNTO 0  ) WHEN (OPCODE = "00" AND ALU_LSBS = "00" AND U = '1' ) ELSE -- BYTE: D LSB
			(31 DOWNTO 8  => '0') & MEM_VAL(15 DOWNTO 8  ) WHEN (OPCODE = "00" AND ALU_LSBS = "01" AND U = '1' ) ELSE -- BYTE: C
			(31 DOWNTO 8  => '0') & MEM_VAL(23 DOWNTO 16 ) WHEN (OPCODE = "00" AND ALU_LSBS = "10" AND U = '1' ) ELSE -- BYTE: B
			(31 DOWNTO 8  => '0') & MEM_VAL(31 DOWNTO 24 ) WHEN (OPCODE = "00" AND ALU_LSBS = "11" AND U = '1' ) ELSE -- BYTE: A MSB
			 -- UNSIGNED LOAD HALF
			(31 DOWNTO 16 => '0') & MEM_VAL(15 DOWNTO 0  ) WHEN (OPCODE = "01" AND ALU_LSBS(1) = '0' AND U = '1' ) ELSE -- HALF: DC
			(31 DOWNTO 16 => '0') & MEM_VAL(31 DOWNTO 16 ) WHEN (OPCODE = "01" AND ALU_LSBS(1) = '1' AND U = '1' ) ELSE -- HALF: DC
			 -- LOAD WORD
			 MEM_VAL;
			   
END DATAFLOW;