-- @description RTL Auto Color Tracks by Keyword
-- @author Rockettree Labs
-- @version 1.0
-- @about Scans track names and assigns standard mixing colors based on keywords (Drums, Bass, Guitars, Vocals, etc.)

local color_map = {
    {"KICK", 255, 0, 0},      -- Red
    {"SNARE", 255, 100, 0},   -- Orange
    {"HAT", 255, 150, 0},     -- Light Orange
    {"TOM", 200, 50, 0},      -- Dark Orange
    {"DRUM", 255, 50, 0},     -- Orange/Red
    {"BASS", 0, 100, 255},    -- Blue
    {"GTR", 0, 255, 100},     -- Green
    {"GUITAR", 0, 255, 100},  -- Green
    {"VOX", 200, 0, 255},     -- Purple
    {"VOCAL", 200, 0, 255},   -- Purple
    {"BGV", 150, 0, 255},     -- Dark Purple
    {"KEYS", 255, 200, 0},    -- Yellow
    {"SYNTH", 255, 200, 0},   -- Yellow
    {"FX", 0, 255, 255},      -- Cyan
    {"BUSS", 100, 100, 100},  -- Gray
    {"BUS", 100, 100, 100},   -- Gray
    {"MASTER", 50, 50, 50},   -- Dark Gray
    {"VERB", 0, 150, 255},    -- Light Blue
    {"DELAY", 0, 150, 255}    -- Light Blue
}

reaper.Undo_BeginBlock()

local num_tracks = reaper.CountTracks(0)

for i = 0, num_tracks - 1 do
    local track = reaper.GetTrack(0, i)
    local _, name = reaper.GetSetMediaTrackInfo_String(track, "P_NAME", "", false)
    local upper_name = string.upper(name)
    
    for j = 1, #color_map do
        local keyword = color_map[j][1]
        local r = color_map[j][2]
        local g = color_map[j][3]
        local b = color_map[j][4]
        
        if string.find(upper_name, keyword) then
            -- Reaper expects colors in OS-dependent format. 
            -- reaper.ColorToNative(r,g,b) does this, ORing with 0x1000000 forces the color to stick
            local color = reaper.ColorToNative(r, g, b) | 0x1000000
            reaper.SetTrackColor(track, color)
            break -- stop matching once we find the first keyword
        end
    end
end

reaper.TrackList_AdjustWindows(false)
reaper.UpdateArrange()
reaper.Undo_EndBlock("RTL: Auto Color Tracks by Keyword", -1)
