MODULE T19;

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); *)
        Storage.ALLOCATE( ptr^.b,Strings.Length(str));
        IF ptr <> NIL THEN
            MemUtils.MemCopy(SYSTEM.ADR(str),Strings.Length(str), ptr^.b);
            (* ptr^.len := ptr^.len + llen; *)
            ptr^.len := Strings.Length(str);
        END;
    END abAppend;

BEGIN
    abufInit(abufPtr);


    str := " Bonjour les petits amis!";
    Storage.ALLOCATE(abufPtr^.b, Strings.Length(str));
    
    (* MemUtils.MemCopy(SYSTEM.ADR(str),Strings.Length(str), abufPtr^.b);  
    abufPtr^.len := Strings.Length(str); *)
    abAppend(abufPtr, str);

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

    abFree(abufPtr);
END T19.