with Globals;

package body Protected_Counters is

  protected body Protected_Counter is
    procedure Reset(N: in Integer) is
    begin
      Count := N;
    end Reset;
    procedure Next(N: out Integer) is
    begin
      N := Count;
      Count := Count+1;
    end Next;
  end Protected_Counter;

  protected body Protected_Task_Counter is
    procedure Reserve(N: in out Natural) is
      use Globals;
    begin
      if Count<NTasks then
        N := Integer'Min(NTasks-Count,N);
        Count := Count+N;
      else
        N := 0;
      end if;
    end Reserve;
    procedure Free(N: in Natural) is
    begin
      Count := Count-N;
    end Free;
  end Protected_Task_Counter;

  function Reserve_Tasks(NMax: Natural; Allow: Boolean := True) return Natural is
    use Globals;
  begin
    if not Allow then return 0; end if;
    if NMax=0 then return 0; end if;
    if NTasks=1 then return 0; end if;
    declare
      N: Natural := NMax;
    begin
      Task_Counter.Reserve(N);
      return N;
    end;
  end Reserve_Tasks;

  procedure Free_Tasks(N: in Natural) is
  begin
    if N>0 then Task_Counter.Free(N); end if;
  end Free_Tasks;

end Protected_Counters;
