--------------------------------
-- Ivan Levashew aka OCTAGRAM --
--         Barnaul, 2009-2010 --
--------------------------------

with System; use System;
with Interfaces; use Interfaces;
with System.Storage_Elements; use System.Storage_Elements;
with Turbo_Private.Bits; use Turbo_Private.Bits;

procedure Turbo_Private.Memory.Fill_Byte_Fallback
  (Target : Address; Amount : Unsigned_Addr; Item : Unsigned_8)
is
   pragma Preelaborate;

   Buffer_Size : constant := 4096;
   type Buffer_Type is new Storage_Array (0 .. Buffer_Size - 1);

   Buffer : Buffer_Type := (others => Storage_Element (Item));

   -- Amount > 0 !
   procedure Mini_Fill (Target : Address; Amount : Storage_Count) is
      Target_Array : Buffer_Type;
      for Target_Array'Address use Target;
      pragma Import (C, Target_Array);
   begin
      Target_Array (0 .. Amount - 1) := Buffer (0 .. Amount - 1);
   end Mini_Fill;

   Amount_Div : constant Unsigned_Addr := Amount / Buffer_Size;
   Amount_Mod : constant Unsigned_Addr := Amount mod Buffer_Size;

begin

   if Amount <= 0 then
      return;
   end if;

   if Amount_Div >= 1 then
      for i in 0 .. Amount_Div - 1 loop
         Mini_Fill (Target + i * Buffer_Size, Buffer_Size);
      end loop;
   end if;

   if Amount_Mod >= 1 then
      Mini_Fill (Target + Amount_Div * Buffer_Size,
                 Storage_Count (Amount_Mod));
   end if;

end Turbo_Private.Memory.Fill_Byte_Fallback;
