.text
.global _main
.extern _printf
.extern _atoi

_main:
    // Save callee-saved registers
    stp x19, x20, [sp, #-16]!
    stp x21, x22, [sp, #-16]!
    stp x23, x24, [sp, #-16]!
    stp x29, x30, [sp, #-16]!
    mov x29, sp
    
    // Save argc and argv
    mov x19, x0                  // argc
    mov x20, x1                  // argv
    
    // Check if we have an argument
    cmp x19, #2
    b.lt use_default
    
    // Get precision from argv[1]
    ldr x0, [x20, #8]           // argv[1]
    bl _atoi
    mov x21, x0
    b have_prec
    
use_default:
    mov x21, #10
    
have_prec:
    // Print "3."
    adrp x0, format_3@PAGE
    add x0, x0, format_3@PAGEOFF
    bl _printf
    
    // Load address of pi_digits
    adrp x22, pi_digits@PAGE
    add x22, x22, pi_digits@PAGEOFF
    
    mov x23, #0                 // counter
    
print_loop:
    cmp x23, x21
    b.ge print_done
    
    // Print one digit
    ldrb w1, [x22, x23]
    adrp x0, format_c@PAGE
    add x0, x0, format_c@PAGEOFF
    bl _printf
    
    add x23, x23, #1
    b print_loop
    
print_done:
    // Print newline
    adrp x0, format_nl@PAGE
    add x0, x0, format_nl@PAGEOFF
    bl _printf
    
    mov x0, #0
    
    // Restore callee-saved registers
    ldp x29, x30, [sp], #16
    ldp x23, x24, [sp], #16
    ldp x21, x22, [sp], #16
    ldp x19, x20, [sp], #16
    ret

.section __TEXT,__cstring
format_3:
    .asciz "3."
format_c:
    .asciz "%c"
format_nl:
    .asciz "\n"
pi_digits:
    .asciz "14159265358979323846264338327950288419716939937510582097494459230781640628620899862803482534211706798214808651328230664709384460955058223172535940812848111745028410270193852110555964462294895493038196"
