#!/usr/bin/mawk -f

BEGIN {
print "mu-bc 0.01 (3 apr 1999) by Andrea Manzini <linux@netbusiness.it>"
print "For details, type help; to quit, press CTRL+D"
prompt()
}

END {
  print "Bye!"
}

/(HELP)|(help)/ {help();next}
/(LET)|(let) +[A-Za-z]+/ {assign($2);next}
/(DEL)|(del) +[A-Za-z]+/ {del($2);next}
/./ {eval($0)}

function help()
{
print "Enter any algebric expression. You can use + - * / % ^ () operators."
print "Valid math functions are: int(), sin(), cos(), exp(), log(), rand(), sqrt()"
print "You can assign variables to the last result with the command LET <var> and"
print "then use variables in expressions. To delete variables, type DEL <var>." 
prompt()
}

function del(varname)
{
delete VAR[varname]
print varname " deleted."
prompt()
}

function assign(varname)
{
VAR[varname]=LST
print varname "=" LST " now."
prompt()
}

function eval(expr)
{ 
  CMD= "BEGIN{" 
  for(v in VAR) {
    CMD= CMD v "=" VAR[v] ";" 
  }
  CMD=CMD "print(" expr ")}"
  CMD=sprintf("/usr/bin/mawk '%s' > /tmp/mubc",CMD)
  system(CMD)
  getline LST < "/tmp/mubc"
  close("/tmp/mubc")
  print LST
  prompt()
}

function prompt()
{
  T=ORS
  ORS=""
  print "> "
  getline < /dev/stdin
  ORS=T
}
