-- sends a train to its next station if its in automatic
function toNextStation(t)
    local l = 0
    for _ in pairs(t.schedule.records) do l = l + 1 end

    if not t.manual_mode and l > 1 then
        local s = t.schedule
        s.current = math.fmod(s.current, l) + 1
        t.schedule = s
        t.manual_mode = false
        return true
    end
    return false
end


script.on_event("go-to-next-station", function(event)
    local player = game.players[event.player_index]
    -- 2 alternatives: player is mousing over train or inside a train.
    if player.selected and player.selected.train then
        if toNextStation(player.selected.train) then return end
    end

    if player.vehicle and player.vehicle.train then
        if toNextStation(player.vehicle.train) then return end
    end
end)