-- $Id: except.gnat,v 1.0 2003/06/11 12:06:00 dada Exp $
-- http://dada.perl.it/shootout/
-- Ada 95 code by C.C.

with Text_IO, Ada.Strings.Fixed, Ada.Command_Line;

procedure Except is
   High_Exception : exception;
   Low_Exception  : exception;
   Low            : Integer := 0;
   High           : Integer := 0;

   procedure Blowup (K : Integer) is
      pragma Inline (Blowup);
   begin
      case 1 = (K mod 2) is
         when False => raise High_Exception;
         when True  => raise Low_Exception;
      end case;
   end Blowup;

   procedure Low_Function (K : Integer) is
      pragma Inline (Low_Function);
   begin
      Blowup (K);
   exception
      when Low_Exception => Low := Low + 1;
   end Low_Function;

   procedure High_Function (K : Integer) is
      pragma Inline (High_Function);
   begin
      Low_Function (K);
   exception
      when High_Exception => High := High + 1;
   end High_Function;

   procedure Some_Function (K : Integer) is
      pragma Inline (Some_Function);
   begin
      High_Function (K);
   exception
      when others => Text_IO.Put_Line ("We shouldn't get here");
   end Some_Function;

   function L_Trim (Source : String; Side : Ada.Strings.Trim_End :=
               Ada.Strings.Left) return String renames Ada.Strings.Fixed.Trim;
   N        : Natural := 0;
begin
   begin
      N := Natural'Value (Ada.Command_Line.Argument (1));
   exception
      when Constraint_Error => null;
   end;
   for K in reverse 0 .. N - 1 loop
      Some_Function (K);
   end loop;
   Text_IO.Put_Line ("Exceptions: HI=" & L_Trim (Natural'Image (High)) &
            " / LO=" & L_Trim (Natural'Image (Low)));
end Except;