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
file: db "test.txt", 0
lenfile: equ $-file
out: dw 0
coma : db ','
buffer : db 0



section .text
_start:

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

    xor edi,edi
    push edi ;On push 0 dans la pile pour la position du plus jeune
    mov edi,512
    push edi ;Age du plus jeune
    mov edi, 1
    push edi ;Position actuel
    xor edi,edi
    push edi ;Age actuelle


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

    ;test si erreur
    cmp eax,0
    jbe continue

    cmp byte [buffer], ','
    je inc_compt
    jmp read_list

inc_compt:
    inc edi
    xor eax,eax
    xor edx,edx
    pop eax
    pop edx
    inc edx
    push edx
    push eax
    and edi,1 ;Modulo 2
    cmp edi,0
    je init_toInt
    jmp read_list

init_toInt :
    xor ebx,ebx
    mov ebx,10d

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

loop_toInt :
    pop eax ;Récupère age en cours de calcul
    mov ebx,10
    xor ecx,ecx
    mov cl,[buffer] 
    sub ecx, '0' ;Transforme char en sa valeur int
    mul ebx ;Multiplier eax par 10 
    add eax,ecx
    push eax

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

    ;test si erreur
    cmp eax,0
    jbe continue

    cmp byte [buffer], 10
    je test_plus_jeune
    jmp loop_toInt

test_plus_jeune :
    pop eax
    pop edx
    pop edi
    push edi
    inc edx
    push edx
    push eax
    cmp eax,edi
    jbe est_plus_jeune
    jmp read_list

est_plus_jeune :
    xor eax,eax
    pop ebx
    pop eax
    pop edx
    pop edx
    push eax
    push ebx ;
    xor eax,eax
    push eax
    xor ebx,ebx
    push ebx
    jmp read_list

continue : 
    pop eax
    pop ebx
    pop ecx ; Age plus jeune
    pop edx  ; Position plus jeune

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

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