module mux_heap(
	input clk, resetn,

	output            mux_heap_valid,
	input             mux_heap_ready,
	output     [31:0] mux_heap_addr ,
	output     [31:0] mux_heap_wdata,
	output     [ 3:0] mux_heap_wstrb,
	input      [31:0] mux_heap_rdata,

	input    	      BUS_valid,
	output reg        BUS_ready,

	input             DMA_heap_valid,
	output            DMA_heap_ready,
	input      [31:0] DMA_heap_addr ,
	input      [31:0] DMA_heap_wdata,
	input      [ 3:0] DMA_heap_wstrb,
	output     [31:0] DMA_heap_rdata, 

	input             CPU_heap_valid,
	output            CPU_heap_ready,
	input      [31:0] CPU_heap_addr ,
	input      [31:0] CPU_heap_wdata,
	input      [ 3:0] CPU_heap_wstrb,
	output     [31:0] CPU_heap_rdata
);

	// reg BUS_valid_m1;
	always @(posedge clk) begin
		if (!resetn) begin
			// reset
			BUS_ready <= 0;
			// BUS_valid_m1 <= 0;
		end else begin
			// BUS_valid_m1 <= BUS_valid;
			if ((BUS_valid == 1) && (CPU_heap_valid == 0)) begin
				BUS_ready <= 1;
			end else if (BUS_valid == 0) begin
				BUS_ready <= 0;
			end
		end
	end

	assign mux_heap_valid = BUS_ready ? DMA_heap_valid : CPU_heap_valid;
	assign mux_heap_addr  = BUS_ready ? DMA_heap_addr  : CPU_heap_addr ;
	assign mux_heap_wdata = BUS_ready ? DMA_heap_wdata : CPU_heap_wdata;
	assign mux_heap_wstrb = BUS_ready ? DMA_heap_wstrb : CPU_heap_wstrb;

	assign DMA_heap_ready = BUS_ready ? mux_heap_ready : 0;
	assign CPU_heap_ready = BUS_ready ? 0 : mux_heap_ready;

	assign DMA_heap_rdata = BUS_ready ? mux_heap_rdata : 0;
	assign CPU_heap_rdata = BUS_ready ? 0 : mux_heap_rdata;

endmodule