global _start
;On considère le fichier contenant le personnel comme deja existant
;https://www.tutorialspoint.com/assembly_programming/assembly_file_management.htm

section .data
msg: db "WAK !", 10
len: equ $-msg
file: db "test.txt", 0
lenfile: equ $-file
out: dw 0
buffer : db 0
name_buffer : db 0
name_len : equ $-name_buffer
age_buffer : db 0
age_len : equ $-age_buffer
space :db ' '
break : db 10

section .text
_start:
    ;ouverture fichier
    mov eax, 5
    mov ebx, file
    mov ecx, 0x441            ;append/write/create if not existent
    mov edx, 0777o          ;la totale
    int  80h
    mov esi,eax

    cmp eax,0
    jbe end ;erreur ouverture

    mov  esi, eax

    ;ecriture fichier
    ;mov eax, 4
    ;mov ebx, esi
    ;mov ecx, msg
    ;mov edx, len
    ;int 80h

    cmp eax,0
    jbe close ;erreur ecriture


    ;fermer fichier
    mov eax, 6
    mov ebx, esi
    int 80h


    ;ouverture fichier
    mov eax, 5
    mov ebx, file
    mov ecx, 0            ;read only
    mov edx, 0777o          ;la totale
    int  80h
    mov esi,eax

    cmp eax,0
    jbe end ;erreur ouverture

    mov  esi, eax

    mov edi,0                   ;ICI COMMENCE LE LISTAGE
    jmp read_list

echo:
    ;lecture
    mov eax, 3
    mov ebx, esi
    mov ecx, buffer
    mov edx, 1
    int 80h

    ;test si erreur
    cmp eax,0
    jbe close


    ;affichage
    mov eax, 4
    mov ebx, 1
    mov ecx, buffer
    mov edx, 1
    int 80h

    jmp echo

read_list :
    ;lecture
    mov eax, 3
    mov ebx, esi
    mov ecx, buffer
    mov edx, 1
    int 80h

    ;test si erreur
    cmp eax,0
    jbe close

    cmp byte [buffer], ','
    je inc_compt

output_list :
    ;affichage
    mov eax, 4
    mov ebx, 1
    mov ecx, buffer
    mov edx, 1
    int 80h

    jmp read_list

inc_compt:
    inc edi

    mov eax, 4
    mov ebx, 1
    mov ecx, space
    mov edx, 1
    int 80h

    mov eax,edi
    mov bl,3
    div bl
    cmp edx,0
    je break_line
    jmp read_list

break_line :
    mov eax, 4
    mov ebx, 1
    mov ecx, break
    mov edx, 1
    int 80h

    mov eax,edi
    mov edx,0
    mov bl,2
    div bl



close:
    ; close the file
   mov eax, 6
   mov ebx, esi
   int  80h 

   jmp end
end:
    mov eax, 1
    xor ebx, ebx
    int 80h
