local function calculate_bucket(bucket, data) -- This is per bucket

    if type(bucket) ~= "number" then bucket = tonumber(bucket) end

    local affected_tickers = {}

    for _, ticker in ipairs(data) do
        if ticker.frequency == bucket then
            table.insert(affected_tickers, ticker)
        end
    end

    -- Prevent division by 0
    if (#affected_tickers == 0) then
        -- We should never reach this code. If there are members of the bucket,
        -- then there must be affected ticker.
        minetest.log("error",
                     "[yl_ticker] globalstep division by zero, no members of bucket = " ..
                         dump(bucket))
        return
    end

    -- Let's calculate the distance
    local distance = bucket / #affected_tickers

    local n = 0
    for _, ticker in ipairs(affected_tickers) do
        ticker._next_runtime = os.time() + n * distance
        n = n + 1
    end

end

local delta = 1
local timer = 0

local gs = function(dtime)

    timer = timer + dtime
    if timer <= delta then return end
    timer = timer - delta

    -- payload
    local success, data = yl_ticker.list()
    if ((success == false) or (data == nil)) then
        return false, "Could not retrieve list"
    end

    local current_time = os.time()
    local affected_bucket = {}

    -- Check if any ticker should be displayed
    for _, ticker in pairs(data) do
        -- Check if any ticker needs to be removed from the list due to runtime expired.
        if ((type(ticker.runtime) == "number") and
            (current_time >= (ticker.creation_date + ticker.runtime))) then
            yl_ticker.delete(ticker.id)
        elseif current_time >= (ticker._next_runtime or 0) then

            if (type(ticker._next_runtime) ~= "number") then
                table.insert(affected_bucket, ticker.frequency)
            else
                local a_success, message =
                    yl_ticker.say(ticker.id, "*")
                if (a_success == false) then
                    minetest.log("error",
                                 "[yl_ticker] globalstep cannot send to target, message = " ..
                                     dump(message) .. " : ticker = " ..
                                     dump(ticker))
                    return
                end
                ticker._next_runtime =
                    ticker._next_runtime +
                        (ticker.frequency or 3600)
            end

            yl_ticker.log(os.date("!%H:%M:%S", os.time()) .. "=" ..
                                     tostring(ticker.id))
        end
    end

    -- If there were any tickers that had no _next_runtime, then we need to recalculate their bucket
    for _, bucket in ipairs(affected_bucket) do
        calculate_bucket(bucket, data)
    end
end

minetest.register_globalstep(gs)
