#!/bin/sh

#######################################################
#     Bash CALCulator 2
#######################################################
#
#
#    FILE: bashcalc2.sh
# VERSION: 1.1
#    DATE: 06-19-2006
#
#  AUTHOR: Crouse - Please visit bashscripts.org and usalug.org
#
#  Z2 cosmetics: dronz#zipit
########################################################

header ()
{
clear
echo "\033[1;33;42m          CALCULATOR          ";
echo "      Help: H then Enter      ";
echo "------------------------------\033[49m\033[0m";
}

calc ()
{
header
# Reset scale to 4 after Clear or Help.
scale="scale=4"
while true
do read -p "" bashcalc;
       case "$bashcalc" in
       q|Q|1|quit|exit|$'\e') clear ; exit ;;
       c|C|+) calc ;;
       h|H|"'"|help|"?") 
          clear
          echo ""
          echo " [H] then Enter = this HELP"
          echo " [C] then Enter = clear screen"
          echo " [Q] then Enter = quit"
          echo ""
          echo " For simple calculations, "
          echo " type your keyboard as usual."
          echo " Allowed: 1234567890 . + - * /"
          echo " SHIFT then , or . are  (  )"
          echo " ALT then SHIFT then ; is  ^ "
          echo ""
          read -p  " Type Enter" temp;
          clear
          echo ""
          echo " For heavy calculations,"
          echo " toggle to the red chars:"
          echo " SHIFT then SPACE = toggle ALT"
          echo " SHIFT then ; = ^ = power"
          echo " SHIFT then J or K = (  )"
          echo " CTRL and . = dec. point"
          echo ""
          echo " Last calculation is stored in"
          echo "         /tmp/calc "
          echo ""
          read -p  " Type Enter" temp;
          calc
          ;;

       # Change the decimal scale if you like...
       scale*) scale="${bashcalc}" ;;

       # Reuse previous result if we start with an operator.
       # To use a negative number start with a space first.
       -*) bashcalc="${result}${bashcalc}" ;;
       +*) bashcalc="${result}${bashcalc}" ;;
       /*) bashcalc="${result}${bashcalc}" ;;
       "*"*) bashcalc="${result}${bashcalc}" ;;
       "%"*) bashcalc="${result}${bashcalc}" ;;
       "^"*) bashcalc="${result}${bashcalc}" ;;

       # Just in case I cant remember the math fns...
       # Reuse previous result if we start with a fn.
       sqrt) bashcalc="sqrt(${result})" ;;
       sin) bashcalc="s(${result})" ;;
       atan) bashcalc="a(${result})" ;;
       ln) bashcalc="l(${result})" ;;
       exp) bashcalc="e(${result})" ;;
       # ...
       # We could do many calculator key fns like this.

       esac

  result=$(echo " ${scale}; ${bashcalc} " | bc -l )
  echo ${result}
  echo "------------------------------";
  echo "${bashcalc} =" > /tmp/calc ; 
  echo "${result}" >> /tmp/calc ;
done
}

# Program run starts here
calc

exit 0
