require "util"

palfade = {
    original = {},
    reddish = {},
} local me = palfade

function me.init()
    for i=1,32 do
        me.reddish[i] = {r=me.original[i].r, g=me.original[i].g, b=me.original[i].b}
    end
end

function me.reddish_limit(r, g, b)
    local t = util.luminance(r, g, b) / 255

    local R = 255 * t
    local G = g * (1 - t)
    local B = b * (1 - t)

    return R, G, B
end

function me.fade_reddish_color(r, g, b, f)
    local ff = math.min(1, f+util.luminance(r,g,b))
    local R = math.floor(r*ff)
    local G = math.floor(g*f)
    local B = math.floor(b*f)

    return R, G, B
end

function me.fade_reddish(f)
    for i=1,32 do
        local r, g, b = me.fade_reddish_color(me.original[i].r, me.original[i].g, me.original[i].b, f)
        me.reddish[i].r, me.reddish[i].g, me.reddish[i].b = r, g, b
        pal.color(i-1,r,g,b)
    end
end

function me.fade_red(f)
    for i=1,32 do
        local r = math.floor(me.reddish[i].r + (255-me.reddish[i].r)*f)
        local g = math.floor(me.reddish[i].g - (me.reddish[i].g)*f)
        local b = math.floor(me.reddish[i].b - (me.reddish[i].b)*f)
        pal.color(i-1,r,g,b)
    end
end

function me.fade_white(f)
    for i=1,32 do
        local r = math.floor(me.reddish[i].r + (255-me.reddish[i].r)*f)
        local g = math.floor(me.reddish[i].g + (255-me.reddish[i].g)*f)
        local b = math.floor(me.reddish[i].b + (255-me.reddish[i].b)*f)
        pal.color(i-1,r,g,b)
    end
end

function me.restore()
    pal.set(me.original)
end
