------------------------------------------------------------------------------
--                                  G P S                                   --
--                                                                          --
--                       Copyright (C) 2011, AdaCore                        --
--                                                                          --
-- GPS is free software;  you can  redistribute it  and/or modify it  under --
-- terms of the  GNU General Public License as published  by the Free Soft- --
-- ware  Foundation;  either version 3,  or (at your option) any later ver- --
-- sion.  GNAT is distributed in the hope that it will be useful, but WITH- --
-- OUT 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 GNAT; see file COPYING3.  If not, go to --
-- http://www.gnu.org/licenses for a complete copy of the license.          --
--                                                                          --
------------------------------------------------------------------------------

with MI.Lexer;    use MI.Lexer;
with MI.Parser;   use MI.Parser;

with Ada.Text_IO; use Ada.Text_IO;

package body Read_File_Helper is

   -------------
   -- MI_Open --
   -------------

   function MI_Open (File_Name : String) return Stream_Access
   is
      File         : File_Type;
   begin
      Open (File, In_File, File_Name);
      return Stream (File);
   end MI_Open;

   --------------
   -- MI_Parse --
   --------------

   procedure MI_Parse
     (Stream : Stream_Access;
      Result : out Record_List)
   is
      Tokens : Token_List;
   begin
      Tokens := Build_Tokens (Stream);
      Build_Records (Tokens, Result);
   end MI_Parse;

   -----------------------------
   -- MI_Extract_First_Record --
   -----------------------------

   procedure MI_Extract_First_Record
     (Result : Record_List;
      Rec    : out MI_Record_Access)
   is
      Cursor : constant Record_Lists.Cursor := Record_Lists.First (Result);
   begin
      if not Record_Lists.Has_Element (Cursor) then
         raise Helper_Error with "no MI_Record found";
      end if;

      Rec := Record_Lists.Element (Cursor);
   end MI_Extract_First_Record;

   -------------------------
   -- MI_Get_First_Record --
   -------------------------

   function MI_Get_First_Record (File_Name : String) return MI_Record_Access
   is
      Stream   : constant Stream_Access := MI_Open (File_Name);
      Rec_List : Record_List;
      Rec      : MI_Record_Access;

   begin
      MI_Parse (Stream, Rec_List);
      MI_Extract_First_Record (Rec_List, Rec);
      return Rec;
   end MI_Get_First_Record;

end Read_File_Helper;
