import lyng.time

val WORK_SIZE = 500
val THREADS = 1

fn piSpigot(iThread: Int, n: Int) {
    var piIter = 0
    var pi = List.fill(n) { 0 }
    val boxes = n * 10 / 3
    var reminders = List.fill(boxes) { 2 }
    var heldDigits = 0
    for (i in 0..<n) {
        var carriedOver = 0
        var sum = 0
        for (j in (boxes - 1) downTo 0) {
            val denom = j * 2 + 1
            reminders[j] *= 10
            sum = reminders[j] + carriedOver
            val quotient = sum / denom
            reminders[j] = sum % denom
            carriedOver = quotient * j
        }
        reminders[0] = sum % 10
        var q = sum / 10
        if (q == 9) {
            ++heldDigits
        } else if (q == 10) {
            q = 0
            for (k in 1..heldDigits) {
                var replaced = pi[i - k]
                if (replaced == 9) {
                    replaced = 0
                } else {
                    ++replaced
                }
                pi[i - k] = replaced
            }
            heldDigits = 1
        } else {
            heldDigits = 1
        }
        pi[piIter] = q
        ++piIter
    }

    var res = ""
    for (i in (n - 8)..<n) {
        res += pi[i]
    }

    println(iThread.toString() + ": " + res)
    res
}

for( r in 0..100 ) {
    val t0 = Instant()

    println("piBench (lyng): THREADS = " + THREADS + ", WORK_SIZE = " + WORK_SIZE)
    for (i in 0..<THREADS) {
        piSpigot(i, WORK_SIZE)
    }

    val dt = Instant() - t0

    println("all done, dt = ", dt)
    delay(800)
}