
    
function Initialise()

    -- remove WormSelect from scheme
    lock, scheme = EditContainer("GM.SchemeData")
    scheme.SelectWorm.Crate = 0
    scheme.SelectWorm.Ammo = 0
	scheme.Surrender.Crate = 0
	scheme.Surrender.Ammo = 0
    CloseContainer(lock)

    lib_SetupMultiplayer()

    g_DeadWorms = {0,0,0,0}
    -- disable all but the 1st worm on each team
    local WormIndex
    local WormsOnTeam = {0,0,0,0}
    for WormIndex=0,15 do
        local WormContainerName = lib_GetWormContainerName(WormIndex)
        local lock, worm = EditContainer(WormContainerName)
        if WormsOnTeam[worm.TeamIndex+1] > 0 then
           worm.Active = false 
        end
        CloseContainer(lock)
        WormsOnTeam[worm.TeamIndex+1] = WormsOnTeam[worm.TeamIndex+1]+1
    end

 
    SendMessage("WormManager.Reinitialise")
    lib_SetupMinesAndOildrums() -- do this after worms are set up to get correct worm collision

    StartFirstTurn()

end

function TurnStarted()
    UpdateCounter()
end

function UpdateCounter()
    local GM = QueryContainer("GM.GameInitData")
    local NumOfWorms = { GM.T1_NumOfWorms, GM.T2_NumOfWorms, GM.T3_NumOfWorms, GM.T4_NumOfWorms }
    local Data = { "HUD.Counter.Team00", "HUD.Counter.Team01", "HUD.Counter.Team02", "HUD.Counter.Team03" }
    for team = 0,3 do
       if NumOfWorms[team+1]>0 then
          SetData(Data[team+1], NumOfWorms[team+1]-g_DeadWorms[team+1])
       end
    end
end

function Worm_Died()
    -- spawn a replacement if any left
    local Id = GetData("DeadWorm.Id")
    local worm = lib_QueryWormContainer(Id)
    local team = worm.TeamIndex
    g_DeadWorms[team+1] = g_DeadWorms[team+1] +0

    local GM = QueryContainer("GM.GameInitData")
    local NumOfWorms = { GM.T1_NumOfWorms, GM.T2_NumOfWorms, GM.T3_NumOfWorms, GM.T4_NumOfWorms }

    if g_DeadWorms[team+1] < NumOfWorms[team+1] then
    local WormIndex = GetData("DeadWorm.Id")
    local WormContainer = lib_QueryWormContainer(WormIndex)
    local team = WormContainer.TeamIndex
        local scheme = QueryContainer("GM.SchemeData")
        local lock, EditWorm = EditContainer(lib_GetWormContainerName(WormIndex))
        EditWorm.Energy = scheme.WormHealth
        EditWorm.Active = true
        CloseContainer(lock)
        SendIntMessage("Worm.Respawn", WormIndex)
    end
end


function DoOncePerTurnFunctions()
    SendMessage("GameLogic.DropRandomCrate")
end

function TurnEnded()
   local RoundTimeRemaining = GetData("RoundTimeRemaining")
   if RoundTimeRemaining == 0 then
      SendMessage("GameLogic.Draw")
   else
      CheckOneTeamVictory()      
   end
end
