with GNATCOLL.Projects; use GNATCOLL.Projects;
with GNATCOLL.Traces;   use GNATCOLL.Traces;
with GNATCOLL.Utils;    use GNATCOLL.Utils;
with GNATCOLL.VFS;      use GNATCOLL.VFS;

with Ada.Command_Line;  use Ada.Command_Line;
with Ada.Text_IO;       use Ada.Text_IO;
with GNAT.Strings;      use GNAT.Strings;

procedure Main is

  Target         : String_Access := new String'("");
  RTS            : String_Access := new String'("");
  Prj            : String_Access;
  Autogpr_Name   : constant Virtual_File := Create ("auto.cgpr");
  Autogpr        : String_Access;
  Lines          : String_List_Access;

  Args : Natural := Argument_Count;

  Env : Project_Environment_Access;
  Tree : Project_Tree;
  Root : Project_Type;
  Sources  : File_Array_Access;
  Success  : Boolean;
begin
  if Args = 0 then
     Put_Line ("No project file specified");
     return;
  end if;

  Prj := new String'(Argument (1));
  if Args > 1 then
     RTS := new String'(Argument(2));
  end if;
  if Args > 2 then
     Target := new String'(Argument(3));
  end if;

  GNATCOLL.Traces.Parse_Config_File;
  Initialize (Env);
  Env.Set_Target_And_Runtime (Target.all, RTS.all);

  Autogpr_Name.Delete (Success => Success);
  Set_Config_File (Env.all, Autogpr_Name);
  Set_Automatic_Config_File (Env.all, True);

  Tree.Load (Create (+Prj.all), Env);

  Sources := Tree.Root_Project.Source_Files (Recursive => True);

  for S in Sources'Range loop
     Put_Line ("Source: " & Sources (S).Display_Base_Name);
  end loop;

  Put_Line ("system.ads is "
     & Tree.Create ("system.ads").Display_Full_Name);

  --  Check the contents of auto.cgpr (since it will be deleted on
  --  exit)

  Autogpr := Autogpr_Name.Read_File;
  if Autogpr = null then
     Put_Line ("No " & Autogpr_Name.Display_Full_Name);
  else
     Lines := Split (Autogpr.all, On => ASCII.LF);

     --  Assume third line is the gprconfig line
     Put_Line (Lines (Lines'First + 2).all);

     --  Now look for the Target info
     for L of Lines.all loop
        if Starts_With (L.all, "   for Target") then
           Put_Line (L.all);
           exit;
        end if;
     end loop;
  end if;

end Main;
