with ada.text_io; 
 use ada.text_io;

procedure concurrency_demo is

    protected type shared_buffer is
        procedure put (item : in character);
        function get return character;
        function is_empty return boolean;
        procedure remove_first; 
    private 
        buffer : string(1 .. 10) := (others => ' ');
        count  : natural := 0;
    end shared_buffer;

    protected body shared_buffer is
        procedure put(item : in character) is
        begin
            if count < buffer'length then
                buffer(count + 1) := item;
                count := count + 1;
            end if;
        end put;

        function get return character is
        begin
            if count > 0 then
                return buffer(1);
            else
                return ' ';
            end if;
        end get;

        procedure remove_first is
        begin
            if count > 0 then
                for i in 1 .. count - 1 loop
                    buffer(i) := buffer(i + 1);
                end loop;
                count := count - 1;
            end if;
        end remove_first;

        function is_empty return boolean is
        begin
            return count = 0;
        end is_empty;
    end shared_buffer;

    my_buffer : shared_buffer;

    -- producer task: adds data to the buffer
    task type producer is
        entry start;
        entry done;
    end producer;

    task body producer is
        a   : integer   := character'pos('a');
        ch  : character := character'val(a);
    begin
        accept start;
        put_line("producer: starting");
        for i in 1 .. 5 loop
            my_buffer.put(ch);
            put_line("producer: added " & ch);
            ch := character'val(a + i);
        end loop;
      
      -- wait here for the main program to call p.done
      accept done; 
    end producer;

    -- consumer task: retrieves data from the buffer
    task type consumer is
        entry start;
        entry done;
    end consumer;

   task body consumer is
   begin
      accept start;
      put_line("consumer: starting");
      for i in 1 .. 5 loop
         while my_buffer.is_empty loop
            null; 
         end loop;
         declare
            item : character := my_buffer.get;
         begin
            put_line("consumer: got " & item);
            my_buffer.remove_first;
         end;
      end loop;
      
    -- wait here for the main program to call c.done
        accept done; 
    end consumer;

    p : producer;
    c : consumer;

begin
    p.start;
    c.start;

    -- wait for tasks to finish by accepting their "done" entry
    p.done;
    c.done;

    put_line("all tasks completed.");
end concurrency_demo;
