/* 
 * File:        abs.s
 * Description: Computes absolute value.
 */

        .arch armv8-a

        .global main 

        .text
        .align  2
main:
        stp     fp, lr, [sp,-16]!       // Set up the stack frame
        mov     fp, sp
        
        adr     x0, prompt              // Pass the prompt string
        bl      printf                  // Call printf

        adr     x0, infmt               // Pass the input format in x0
        adr     x1, x                   // Pass the address of x in x1
        bl      scanf                   // Call scanf

        adr     x0, x                   // Move x into x0
        ldr     x0, [x0]                
        mov     x1, x0                  // Put a copy of x into x1
        bl      abs                     // Call abs

        mov     x2, x0                  // Put the return value from abs into x2
        
        adr     x0, outfmt              // Pass the output format in x0
        bl      printf                  // Call printf
        
        mov     x0, #0                  // Put the return value for main into x0
        ldp     fp, lr, [sp], 16        // Pop the frame pointer and link register
        ret                             // Return from main
        
        
abs:                                    // The abs function
        stp     fp, lr, [sp,-16]!       // Set up the stack frame
        mov     fp, sp

        cmp     x0, #0                  // Check if x0 is positive
        bge     done                    
        neg     x0, x0                  // Negate x0

done:
        ldp     fp, lr, [sp], 16        // Return from abs
        ret                             
        
        .data                           // Start of data segment
        .align  3                       // Align on an address divisible by 8

x:      .quad  0                        // The first integer

        .section .rodata
        
prompt:   .string "Enter an integer: "  // Prompt string
infmt:    .string "%ld"                 // Scanf format
outfmt:   .string "|%ld| = %ld\n"       // Printf format
