	TITLE "Stack on LCELL";
	PARAMETERS (
        WIDTH = 16,
        DEPTH = 8
);
SUBDESIGN Stack (
	CLK	: input;
	DI[WIDTH-1..0] : input; 
	DO[WIDTH-1..0] : output;
	CMD[1..0]	: input;
)
VARIABLE
	REGS[DEPTH-1..0][WIDTH-1..0] : DFFE;
	CMDR[5..0]	: NODE;
BEGIN
	CASE CMD[] IS
		WHEN 0 => CMDR[] = B"000000"; -- NOP
		WHEN 1 => CMDR[] = B"111111"; -- PUSH
		WHEN 2 => CMDR[] = B"000111"; -- POP
		WHEN 3 => CMDR[] = B"111001"; -- SWAP_TOP
	END CASE;

	REGS[][].clk	= CLK;
	REGS[0][].ena	= CMDR0;
	REGS[1][].ena	= CMDR1;
	REGS[DEPTH-1..2][].ena	= CMDR2;
	DO[] = REGS[0][];

	IF CMDR3 THEN
		REGS[0][] = DI[];
	ELSE
		REGS[0][] = REGS[1][];
	END IF;
	
	IF CMDR4 THEN
		REGS[1][] = REGS[0][];
	ELSE
		REGS[1][] = REGS[2][];
	END IF;
	FOR i IN 2 TO DEPTH-2 GENERATE
	IF CMDR5 THEN
		REGS[i][] = REGS[i-1][];
	ELSE
		REGS[i][] = REGS[i+1][];
	END IF;
	END GENERATE;
	
	IF CMDR5 THEN
		REGS[DEPTH-1][] = REGS[DEPTH-2][];
	ELSE
		REGS[DEPTH-1][] = 0;
	END IF;
END;
