module apb_if_mem (

// APB interface
input clk,
input rst_n,
input PSEL,
input PENABLE,
input PWRITE,
input wire [31:0] PADDR,
input wire [31:0] PWDATA,

output PREADY,
output PSLVERR,
output wire [31:0] PRDATA,

// downstream logic interface
input wire [31:0] rdData,
input wire pReady,
output wire csn,
output wire rdn,
output wire wrn,
output reg sel,
output wire [31:0] addr,
output wire [31:0] wrData
);

reg ack;
assign csn = ~(PSEL & ~&PADDR[15:12]);
assign rdn = PWRITE;
assign wrn = ~PWRITE;
assign addr = {12'b0,PADDR[19:0]};
assign wrData = PWDATA;

assign PREADY = pReady | ack;
assign PSLVERR = 1'b0;
assign PRDATA = ack ? {30'h0,sel} : rdData;

always @ (posedge clk or negedge rst_n)
    if (~rst_n)
        sel = 1'b0;
    else if (PSEL & PWRITE & &PADDR[15:12])
        sel = PWDATA[0];

always @ (posedge clk or negedge rst_n)
    if (~rst_n)
        ack = 1'b0;
    else if (PSEL & PENABLE)
        ack = 1'b0;
    else if (PSEL & &PADDR[15:12])
        ack = 1'b1;
endmodule
