#!/bin/bash
set -ueo pipefail

# This script interactively processes input lines:
#   * number is pushed on stack,
#   * operator (+, -, *, /) pops two operands and pushes result,
#   * empty line removes last number from stack (or exits if empty)

# At first, it may seem less intuitive than usual way of counting,
# but after getting used to it,
# keeping intermediate results on stack while performing subcalculations
# is much more natural than using parentheses in interactive calculations.


while true; do
	# print stack
	clear
	echo "+---postfix-calc---+"
	for val; do
		printf "| %16d |\n" "$val"
	done | tac
	echo -n ':'

	# read or break
	read line || break

	# process line
	case "$line" in
		+|-|'*'|'/')
			[ "$#" -ge 2 ] || continue
			res=$(( $2 $line $1 ))
			shift 2
			set -- "$res" "$@";;
		'')
			[ "$#" -ge 1 ] || exit
			shift;;
		*)
			[[ "$line" =~ ^-?[0-9]+$ ]] || continue
			set -- "$line" "$@";;
	esac
done
echo
