.data

# Coefficients of the polynomial a^2c + bx + c
input_a:    .word 1     # a
input_b:    .word 0     # b
input_c:    .word -2    # c

.text

# -----------------------------------------------------------------------------
# main:
#
# Entry point
#
# Args:
#   N/A
#
# Returns:
#   N/A
# -----------------------------------------------------------------------------
main:
    # Compute the roots
    lw          a0, input_a
    lw          a1, input_b
    lw          a2, input_c
    jal         quadratic_roots
    # Print the results
    li          a7, 3           # Print double
    ecall
    li          a7, 11          # Print char
    li          a0, '\n'        # a0 <- '\n'
    ecall
    li          a7, 3           # Print double
    fmv.d       fa0, fa1
    ecall
    # Exit
    li          a7, 10          # Exit without errors
    ecall

# -----------------------------------------------------------------------------
# quadratic_roots:
#
# Compute the roots of ax^2 + bx + c.
#
# Args:
#   a0: a
#   a1: b
#   a2: c
#
# Returns:
#   fa0: Root 1
#   fa1: Root 2
# -----------------------------------------------------------------------------
quadratic_roots:
    # Convert the inputs to floats
    fcvt.d.w    ft0, a0         # ft0 <- float(a)
    fcvt.d.w    ft1, a1         # ft1 <- float(b)
    fcvt.d.w    ft2, a2         # ft2 <- float(c)
    # Compute the portions of the formula
    li          t0, 2           # t0 <- 2
    fcvt.d.w    ft7, t0         # ft7 <- 2.0
    fmul.d      ft0, ft0, ft7   # ft0 <- 2a
    fmul.d      ft3, ft0, ft2   # ft3 <- 2a * c
    fmul.d      ft3, ft3, ft7   # ft3 <- 2a * c * 2 = 4ac
    fmul.d      ft4, ft1, ft1   # ft4 <- b^2
    fsub.d      ft4, ft4, ft3   # ft4 <- b^2 - 4ac
    fsqrt.d     ft4, ft4        # ft4 <- sqrt(b^2 - 4ac)
    # Compute the roots
    li          t0, -1
    fcvt.d.w    ft6, t0         # ft6 <- -1
    fmul.d      fa0, ft1, ft6   # fa0 <- -b
    fmv.d       fa1, fa0        # fa1 <- -b
    fsub.d      fa0, fa0, ft4   # fa0 <- -b - sqrt(b^2 - 4ac)
    fadd.d      fa1, fa1, ft4   # fa0 <- -b + sqrt(b^2 - 4ac)
    fdiv.d      fa0, fa0, ft0
    fdiv.d      fa1, fa1, ft0
    ret
