-- Procedure Tail is basic Tail command.
-- Date := "2023-04-29" ; 
-- Version := "1.0.0" ; 
-- Obtain the line 'line' with command : tail line FILE.
-- Obtain the 'Lasts' lines with command : tail -lasts File

with ada.wide_text_io;
use ada.wide_text_io;
with Ada.Command_Line;
use Ada.Command_Line;

procedure Tail is
   
   Line_Count : Natural := 0;
   
   Tail_Line : constant Integer := Integer'Value(Argument(1));
   
   Filename : constant String := Argument(Argument_Count);
   
   File : File_Type;
begin
   
   Open(File, In_File, Filename, Form => "WCEM=8");
   while not End_Of_File(File) loop
      declare
	 Line : constant Wide_String := Get_Line(File);
      begin
	 Line_Count := Line_Count + 1;
      end;
   end loop;
   Close(File);
   if Tail_Line <= Line_Count then
      if Tail_Line > 0 then
	 declare
	    File_Index : Natural := 0;
	 begin
	    Open(File, In_File, Filename, Form => "WCEM=8");
	    while not End_Of_File(File) loop
	       declare
		  Line : constant Wide_String := Get_Line(File);
	       begin
		  
		  File_index := File_index + 1;
		  if File_Index >= Tail_Line then		     
		     Put(Line);
		     if not End_Of_File(File) then
		     New_Line;
		  end if;
		  end if;
		  
	       end;
	    end loop;
	    Close(File);
	 end;
      else

	 declare
	    File_Index : Natural := 0;
	 begin
	    Open(File, In_File, Filename, Form => "WCEM=8");
	    while not End_Of_File(File) loop
	       declare
		  Line : constant Wide_String := Get_Line(File);
	       begin
		  
		  
		  if File_Index >= (Line_Count - abs(Tail_Line)) then
		     Put(Line);
		     if not End_Of_File(File) then
			New_Line;
		     end if;
		  end if;
		  
		  File_index := File_index + 1;
	       end;
	    end loop;
	    Close(File);
	 end;
      end if;
   end if;
end Tail;