-------------------------------------------------------------------------------
-- (C) Altran Praxis Limited
-------------------------------------------------------------------------------
--
-- The SPARK toolset is free software; you can redistribute it and/or modify it
-- under terms of the GNU General Public License as published by the Free
-- Software Foundation; either version 3, or (at your option) any later
-- version. The SPARK toolset is distributed in the hope that it will be
-- useful, but WITHOUT ANY WARRANTY; without even the implied warranty of
-- MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU General
-- Public License for more details. You should have received a copy of the GNU
-- General Public License distributed with the SPARK toolset; see file
-- COPYING3. If not, go to http://www.gnu.org/licenses for a complete copy of
-- the license.
--
--=============================================================================

with Ada.Unchecked_Deallocation;

package body Log_Files
is

   procedure Initialize (File_Set : out Log_File_Set)
   is
   begin
      for I in File_Set'Range loop
         File_Set (I).In_Use := False;
         --  No initial value available for the File_Type component.
      end loop;
   end Initialize;

   procedure Open (File_Name : in     String;
                   Index     :    out Positive;
                   File_Set  : in out Log_File_Set)
   is
      procedure Set_Next_Free
      is
      begin
         Index := 1;
         while File_Set (Index).In_Use loop
            Index := Index + 1;
         end loop;
      end Set_Next_Free;
   begin
      Set_Next_Free;
      File_Set (Index).FT := new Ada.Text_IO.File_Type;
      Ada.Text_IO.Create (File_Set (Index).FT.all,
                          Ada.Text_IO.Out_File,
                          File_Name);
      File_Set (Index).In_Use := True;
   end Open;

   procedure Close (Index    : in     Positive;
                    File_Set : in out Log_File_Set)
   is
      procedure Free is new Ada.Unchecked_Deallocation (Ada.Text_IO.File_Type, Ada_Text_IO_File_Type_Ptr);
   begin
      Ada.Text_IO.Close (File_Set (Index).FT.all);
      Free (File_Set (Index).FT);
      File_Set (Index).In_Use := False;
   end Close;

   function File_Type (Index    : Positive;
                       File_Set : Log_File_Set) return access Ada.Text_IO.File_Type
   is
   begin
      return File_Set (Index).FT;
   end File_Type;

end Log_Files;
