-- Fill page with random color based on the current 4 colors, The alpha channel as well
--@TBCONFIG STYLE: Replace, 2,Black,White,User Hue
--@TBCONFIG SLIDER: Hue, 50
--@TBCONFIG SLIDER: Threshold, 1

local uHue = sliderVal1 * 360
local uThreshold  = sliderVal2

function hueSame(x, y, hue)
local h,s,l = get_hsl(x,y)
local hueLo = uHue - 360 *  uThreshold
local hueHi = uHue + 360 *  uThreshold
	if hueLo >= 0 and hueHi <= 360 then
		if h >= hueLo and h <= hueHi then 
			return true
		end
	elseif hueLo <= 0 and hueHi <= 360 then -- wrap around
		if h >= (360 + hueLo) and h <= hueHi then 
			return true
		end	
	elseif hueLo >= 0 and hueHi >= 360 then -- wrap around
		if h >=  hueLo and h <= (hueHi - 360) then 
			return true
		end	
	end
end

function ColorsSame(x, y, origR, origG, origB)
local  a, b, c
local tol =  uThreshold
local thisR, thisG, thisB = get_rgb(x, y)		-- get the exact color
	-- apply a tolerance of 1% to allow for aliasing effects
	a = CheckTolerance(thisR, origR, tol)
	b = CheckTolerance(thisG, origG, tol)
	c = CheckTolerance(thisB, origB, tol)
	if a == true and b == true and c == true then
		return true
	else
		return false
	end
	
end
function CheckTolerance(a, b, tol)
local  p
	if b > a then 
	p = a; a = b; b = p  -- swap over so that a is always larger (or equal)
	end
	if a > b then 
		p = (a - b) / a
	else
		p = 0 
	end
	if p < tol then 
		return true
	else
		return false
	end
end

local clearAlpha
for y = 0, height - 1 do
  for x = 0, width - 1 do
	clearAlpha = false
	if styleVal1 == 1 then -- black
		if ColorsSame(x, y, 0, 0, 0) then clearAlpha = true end 
	elseif styleVal1 == 2 then -- white
		if ColorsSame(x, y, 1, 1, 1) then clearAlpha = true end 
	else  -- hue
		if hueSame(x, y, hue) then clearAlpha = true end 
	end
	
	if clearAlpha == true then 
	    local r, g, b = get_rgb(x, y)
		set_rgba(x, y, r, g, b, 0) 
	end 	
  end
end