
-- set up values used by the handler functions

local ccScale = 1.0/127.0
local ccScale1 = 1.0/128.0
local ccScale2 = 0.5/63.0

local ccMap = {}
local avoids = { 
	[1] = true,		-- mod wheel
	[7] = true,		-- volume
	[10] = true,	-- pan
	[64] = true,	-- sustain
	[99] = true,	-- NPRN
	[98] = true,	-- NPRN
	[6] = true,		-- NPRN
	[38] = true,	-- NPRN
}
local cc = -1
for i=0,getNumParameters()-1 do
	if isParameterUsed( i ) then
		cc = cc + 1
		while avoids[cc] do
			cc = cc + 1
		end
		ccMap[ cc ] = i
--		print( cc, getParameterName( i ) )
	end
end

-- define the handler functions

-- set most parameters via CC messages
local function handleCC( channel, cc, value )
	-- look up the cc in the table
	local param = ccMap[ cc ]
	if param then
		local minv, maxv = getParameterMinMax( param )
		local unit = getParameterUnit( param )

		-- scale the value
		if minv < 0 and maxv > 0 then
			if value <= 64 then
				value = value * ccScale1
			else
				value = 0.5 + ( value - 64 ) * ccScale2
			end
		else
			if unit	== 23 then
				-- 23 == beats
			else
				value = value * ccScale
			end
		end

		-- offset the value
		if unit == 8 then
			-- hertz
			-- log2( x ) == log( x ) / log( 2 ) == log( x ) * 1.4426950409
			value = minv * math.pow( 2.0, math.log( maxv/minv ) * 1.4426950409 * value )
		elseif unit == 23 then
			-- beats
			value = value + 1
		elseif unit == 2 then
			-- boolean
			value = ( value > 0 ) and 1 or 0
		elseif unit == 1 then
			-- indexed
			value = minv + ( maxv - minv ) * value
			value = math.floor( value + 0.5 )
		else
			value = minv + ( maxv - minv ) * value
		end

		setParameter( param, value )
	end
end

-- set up the MIDI events we're interested in

requestAllCC( handleCC )
