-- set no waveform = noise
--[[
Notes:
poke(0xFF8C) --16: state
poke(0xFF9C) --72: regs
poke(0xFFE4) --256: waves
]]--
return function(R)
	R.noise={}

    -- ch:0-4
    -- pos:0-31
    -- v:0-1
    R.noise.setWaveU=function(ch,pos,v)
	    poke4(0x1FF3C+36*ch+pos,(v*15)//1)
    end

	-- data is a table of values (should have max 32 entries)
    R.noise.setWaveUs=function(ch,data)
		for i=1,#data do
			R.noise.setWaveU(ch,i-1,data[i])
		end
    end

	R.noise.getWaveUs=function(ch)
	    local w={}
		for pos=0,31 do
			w[pos+1]=peek4(0x1FF3C+36*ch+pos)/15
		end
		return w
    end

	-- ch: 0-3
	-- pitch: 0-4095
	R.noise.setFreq=function(ch,freq)
		freq=freq//1
		poke4(0x1FF3A+ch*36,(freq>>8)&15)
		poke(0xFF9C+ch*18,freq&255)
	end

	-- ch: 0-3
	-- vol4: 0-1
	R.noise.setVolU=function(ch,vol)
		poke4(0x1FF3B+ch*36,(vol*15)//1)
	end

	-- ch: 0-3	
	R.noise.getVolU=function(ch)
		return peek4(0x1FF3B+ch*36)/15
	end

	--[[
	These were in documentation, but I couldn't get them working with just a quick prodding:
	-- NB Check this works...
	R.noise.setVolL=function(ch,vol)
		poke4(0x1FF30+ch*2,(vol*15)//1)
	end
	
	-- NB Check this works...
	R.noise.setVolR=function(ch,vol)
		poke4(0x1FF31+ch*2,(vol*15)//1)
	end
	--]]

	R.noise.getFreqA=function()
		return 440
	end
	
	R.noise.addFreqSemis=function(freq,semis)
		return freq*(2^(1/12))^semis
	end

	R.noise.makeWaveUSin=function()
		local w={}
		for pos=0,31 do
			w[pos+1]=.5+math.sin(math.pi*2*pos/32)/2
		end
		return w
	end

	R.noise.makeWaveUSquare=function()
		local w={}
		for pos=0,31 do
			w[pos+1]=pos/32<.5 and 0 or 1
		end
		return w
	end

	R.noise.makeWaveUSaw=function()
		local w={}
		for pos=0,31 do
			w[pos+1]=pos/15
		end
		return w
	end

	R.noise.makeWaveUTriangle=function()
		local w={}
		for pos=0,31 do
			w[pos+1]=(pos<16) and pos/15 or (31-pos)/15
		end
		return w
	end

	R.noise.makeWaveUPulse=function()
		local w={}
		for pos=0,31 do
			w[pos+1]=(pos%16<2) and 0 or 1
		end
		return w
	end
end
