// Debug Montgomery reduction step by step
use crypto::fieldq

fn main() {
    // Test fq_mont_reduce on a known value
    // fq_to_mont(42) = fq_mont_reduce(42 * 1353)
    let a = 42 * fq_mont_r2()
    println("a = 42 * R2 = " + int_to_str(a))

    let aq = a * fq_qinv()
    println("a * QINV = " + int_to_str(aq))

    let t_raw = bit_and(aq, 65535)
    println("low 16 bits = " + int_to_str(t_raw))

    let mut t = t_raw
    if t >= 32768 { t = t - 65536 }
    println("signed t = " + int_to_str(t))

    let tq = t * fq_q()
    println("t * Q = " + int_to_str(tq))

    let diff = a - tq
    println("a - t*Q = " + int_to_str(diff))

    let low_check = bit_and(diff, 65535)
    println("(a - t*Q) & 0xFFFF = " + int_to_str(low_check) + " (should be 0)")

    let result = shr(diff, 16)
    println(">> 16 = " + int_to_str(result))

    // Now test round-trip
    let mont = fq_mont_reduce(a)
    println("")
    println("fq_mont_reduce(" + int_to_str(a) + ") = " + int_to_str(mont))
    let back = fq_mont_reduce(mont)
    println("fq_mont_reduce(" + int_to_str(mont) + ") = " + int_to_str(back))
    println("Expected: 42")

    // Simple: what's QINV * Q mod R?
    println("")
    let check = bit_and(fq_qinv() * fq_q(), 65535)
    println("QINV * Q mod R = " + int_to_str(check) + " (must be 1)")
}
