package body Graphs is
   procedure Append (Nodes : in out Links.Arena; L : in out List; Value : Integer) is
      Added : Links.Handle;
   begin
      Links.Insert (Nodes, (Value => Value, Previous => L.Last, Next => Links.No_Handle), Added);
      if Links.Valid (Nodes, L.Last) then
         declare
            Before : Link := Links.Element (Nodes, L.Last);
         begin
            Before.Next := Added;
            Links.Replace_Element (Nodes, L.Last, Before);
         end;
      else
         L.First := Added;
      end if;
      L.Last := Added;
   end Append;

   function Sum_Forward (Nodes : Links.Arena; L : List) return Long_Long_Long_Integer is
      Sum : Long_Long_Long_Integer := 0;
      At_Node : Links.Handle := L.First;
   begin
      --  a list over 16 slots has at most 16 nodes: the walk stops after that many steps
      for Step in 1 .. 16 loop
         pragma Loop_Invariant (Sum in -2 ** 63 * Long_Long_Long_Integer (Step - 1) .. 2 ** 63 * Long_Long_Long_Integer (Step - 1));
         exit when not Links.Valid (Nodes, At_Node);
         Sum := Sum + Long_Long_Long_Integer (Links.Element (Nodes, At_Node).Value);
         At_Node := (if Links.Element (Nodes, At_Node).Next >= 0 then Links.Element (Nodes, At_Node).Next else 0);
      end loop;
      return Sum;
   end Sum_Forward;

   function Count_Backward (Nodes : Links.Arena; L : List) return Natural is
      Count : Natural := 0;
      At_Node : Links.Handle := L.Last;
   begin
      for Step in 1 .. 16 loop
         pragma Loop_Invariant (Count < Step);
         exit when not Links.Valid (Nodes, At_Node);
         Count := Count + 1;
         At_Node := (if Links.Element (Nodes, At_Node).Previous >= 0 then Links.Element (Nodes, At_Node).Previous else 0);
      end loop;
      return Count;
   end Count_Backward;

   function Depth (Nodes : Trees.Arena; H : Trees.Handle) return Natural is
      Steps : Natural := 0;
      At_Node : Trees.Handle := H;
   begin
      for Step in 1 .. 16 loop
         pragma Loop_Invariant (Steps < Step);
         exit when not Trees.Valid (Nodes, At_Node) or else Trees.Element (Nodes, At_Node).Parent = 0;
         Steps := Steps + 1;
         At_Node := (if Trees.Element (Nodes, At_Node).Parent >= 0 then Trees.Element (Nodes, At_Node).Parent else 0);
      end loop;
      return Steps;
   end Depth;
end Graphs;
