MODULE T20;

IMPORT FIO, Storage, SYSTEM, Strings, MemUtils, libc;
IMPORT NumberIO;

TYPE
    abufType            = RECORD
                            b   : SYSTEM.ADDRESS;
                            len : CARDINAL;
                          END;
    abufTypePtr         = POINTER TO abufType;

VAR
    abufPtr     : abufTypePtr;
    str         : ARRAY [0..100] OF CHAR;
    i           : CARDINAL;

PROCEDURE abufInit(VAR ptr : abufTypePtr);
    BEGIN
        Storage.ALLOCATE(ptr,SYSTEM.TSIZE(abufType) );
        ptr^.b := NIL;
        ptr^.len := 0;
    END abufInit;

 PROCEDURE abFree (VAR ptr : abufTypePtr);

    BEGIN
        Storage.DEALLOCATE(ptr^.b, ptr^.len);
        Storage.DEALLOCATE(ptr,SYSTEM.TSIZE(abufType));
    END abFree;

PROCEDURE abAppend (VAR ptr : abufTypePtr; str: ARRAY OF CHAR );

        VAR
            llen : CARDINAL;
    BEGIN
        llen := Strings.Length(str);
        IF ptr <> NIL THEN
            Storage.REALLOCATE( ptr^.b,ptr^.len + llen);
            MemUtils.MemCopy(SYSTEM.ADR(str),llen, SYSTEM.ADDADR(ptr^.b,ptr^.len));
            ptr^.len := ptr^.len + llen;
        END;
    END abAppend;

BEGIN
    abufInit(abufPtr);

    str := " Bonjour les petits amis!";
    abAppend(abufPtr, str);

    str := " coucou";
    abAppend(abufPtr, str);

    (* writing the string in the terminal *)
    libc.write(FIO.StdOut,abufPtr^.b,abufPtr^.len);

    abFree(abufPtr);
END T20.