module namco163_mixed (
	input         clk,
	input         ce,
	input   [3:0] submapper,
	input         enable,
	input         wren,
	input  [15:0] addr_in,
	input   [7:0] data_in,
	output  [7:0] data_out,
	input  [15:0] audio_in,
	output [15:0] audio_out,
	// savestates              
	input       [63:0]  SaveStateBus_Din,
	input       [ 9:0]  SaveStateBus_Adr,
	input               SaveStateBus_wren,
	input               SaveStateBus_rst,
	input               SaveStateBus_load,
	output      [63:0]  SaveStateBus_Dout,
	
	input         Savestate_MAPRAMactive,    
	input  [6:0]  Savestate_MAPRAMAddr,     
	input         Savestate_MAPRAMRdEn,    
	input         Savestate_MAPRAMWrEn,    
	input  [7:0]  Savestate_MAPRAMWriteData,
	output [7:0]  Savestate_MAPRAMReadData
);

reg disabled;

always@(posedge clk) begin
if (!enable) begin
	disabled <= 1'b0;
end else if (SaveStateBus_load) begin
	disabled <= SS_MAP1[0];
end else if (ce) begin
	if(wren & addr_in[15:11]==5'b11100)           //E000..E7FF
		disabled<=data_in[6];
	end
end

assign SS_MAP1_BACK[0]    = disabled;
assign SS_MAP1_BACK[63:1] = 63'b0; // free to be used

//sound
wire [10:0] n163_out;

namco163_sound n163
(
	clk, ce, enable, wren, addr_in, data_in, data_out, n163_out,
	// savestates
	SaveStateBus_Din, 
	SaveStateBus_Adr,
	SaveStateBus_wren,
	SaveStateBus_rst,
	SaveStateBus_load,
	SaveStateBus_wired_or[1],
	Savestate_MAPRAMactive,
	Savestate_MAPRAMAddr,     
	Savestate_MAPRAMRdEn,    
	Savestate_MAPRAMWrEn,    
	Savestate_MAPRAMWriteData,
	Savestate_MAPRAMReadData
);

//pdm #(10) pdm_mod(clk20, saturated, exp6);
wire [9:0] saturated=n163_out[9:0] | {10{n163_out[10]}};    //this is still too quiet for the suggested 47k resistor, but more clipping will make some games sound bad
wire [15:0] audio = {1'b0, saturated, 5'b0};
wire [16:0] audio_mix = (!enable | disabled) ? {audio_in, 1'b0} : (submapper==5) ? (audio_in>>>2) + audio : (submapper==4) ? (audio_in>>>1) + audio : audio_in + audio;
assign audio_out = audio_mix[16:1];

// savestates
localparam SAVESTATE_MODULES    = 2;
wire [63:0] SaveStateBus_wired_or[0:SAVESTATE_MODULES-1];
wire [63:0] SS_MAP1;
wire [63:0] SS_MAP1_BACK;	
wire [63:0] SaveStateBus_Dout_active = SaveStateBus_wired_or[0] | SaveStateBus_wired_or[1];
	
eReg_SavestateV #(SSREG_INDEX_SNDMAP5, 64'h0000000000000000) iREG_SAVESTATE_MAP1 (clk, SaveStateBus_Din, SaveStateBus_Adr, SaveStateBus_wren, SaveStateBus_rst, SaveStateBus_wired_or[0], SS_MAP1_BACK, SS_MAP1);  

assign SaveStateBus_Dout = enable ? SaveStateBus_Dout_active : 64'h0000000000000000;

endmodule