BEGIN {
stack[0] = 0
stack_p = 0
print rpn_calc("3 19 + -2 /")
print rpn_calc("3 19 + -2 / +")
print rpn_calc("1 2 + 3 4 5 sum")
print rpn_calc("5 4 - exp")
print rpn_calc("1 2.0 +")
print rpn_calc("12 5 /")
print rpn_calc("2 3 4 prod")
}
function rpn_calc(str, i, n, q, ql, t) {
ql = split(str, q)
if (! is_integer(q[1])) return 0
n = q[1]
init()
for(i = 2; i <= ql; i++) {
t = q[i]
if (is_integer(t)) {
push(n)
n = t
}
else if (t == "+") {
if (empty()) return 0
n += pop()
}
else if (t == "-") {
if (empty()) return 0
n = pop() - n
}
else if (t == "*") {
if (empty()) return 0
n *= pop()
}
else if (t == "/") {
if (empty()) return 0
n = int(pop() / n)
}
else if (t == "exp") {
}
else if (t == "sum") {
while(! empty()) {
n += pop()
}
}
else if (t == "prod") {
while(! empty()) {
n *= pop()
}
}
else {
return "error"
}
}
return n
}
function is_integer(s) {
return match(s, /^-?(0|[1-9][0-9]*)$/)
}
function init( n) {
stack_p = 0
}
function push(n) {
stack[stack_p++] = n
}
function empty( n) {
return (stack_p < 1);
}
function pop( n) {
return (empty() ? 0 : stack[--stack_p])
}
QkVHSU4gewogICAgc3RhY2tbMF0gPSAwCglzdGFja19wID0gMAoKCXByaW50IHJwbl9jYWxjKCIzIDE5ICsgLTIgLyIpCglwcmludCBycG5fY2FsYygiMyAxOSArIC0yIC8gKyIpCglwcmludCBycG5fY2FsYygiMSAyICsgMyA0IDUgc3VtIikKCXByaW50IHJwbl9jYWxjKCI1IDQgLSBleHAiKQoJcHJpbnQgcnBuX2NhbGMoIjEgMi4wICsiKQoJcHJpbnQgcnBuX2NhbGMoIjEyIDUgLyIpCglwcmludCBycG5fY2FsYygiMiAzIDQgcHJvZCIpCn0KCmZ1bmN0aW9uIHJwbl9jYWxjKHN0ciwgIGksIG4sIHEsIHFsLCB0KSB7CgoJcWwgPSBzcGxpdChzdHIsIHEpCglpZiAoISBpc19pbnRlZ2VyKHFbMV0pKS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