library HandleCounter initializer Init

   globals
      integer handles = 1
      leaderboard HandleBoard
      real period = 1
   endglobals
   
   function Update takes nothing returns nothing
      local integer i = 0
      local integer id
      local location array P
      local real result=0
      
      loop
      exitwhen i >= 50
         set i = i + 1
         set P[i] = Location(0,0)
         set id = GetHandleId(P[i])
         set result = result + (id-0x100000)
      endloop
      set result = result/i-i/2
      
      loop
          call RemoveLocation(P[i])
          set P[i] = null
          exitwhen i <= 1
          set i = i - 1
      endloop
      call LeaderboardSetItemValue(HandleBoard,0,(R2I(result)-handles)*R2I(period))
      set handles = R2I(result)
   endfunction


   private function Periodic takes nothing returns nothing
      set HandleBoard = CreateLeaderboard()
      call LeaderboardSetLabel(HandleBoard, "Handles per second")
      call PlayerSetLeaderboard(GetLocalPlayer(),HandleBoard)
      call LeaderboardDisplay(HandleBoard,true)
      call LeaderboardAddItem(HandleBoard,"leakage",0,Player(0))
      call LeaderboardSetSizeByItemCount(HandleBoard,1)
      call Update()
      call TimerStart(GetExpiredTimer(),period,true,function Update)
   endfunction


   private function Init takes nothing returns nothing
      call TimerStart(CreateTimer(),0,false,function Periodic)
   endfunction

endlibrary
