#!/usr/bin/ksh93

########################################################################
#                                                                      #
#               This software is part of the ast package               #
#                 Copyright (c) 2008-2012 Roland Mainz                 #
#                      and is licensed under the                       #
#                 Eclipse Public License, Version 1.0                  #
#                    by AT&T Intellectual Property                     #
#                                                                      #
#                A copy of the License is available at                 #
#          http://www.eclipse.org/org/documents/epl-v10.html           #
#         (with md5 checksum b35adb5213ca9657e911e9befb180842)         #
#                                                                      #
#                                                                      #
#                 Roland Mainz <roland.mainz@nrubsig.org>              #
#                                                                      #
########################################################################

#
# Copyright (c) 2008, 2012, Roland Mainz. All rights reserved.
#

#
# funcplot - small shell-based function plotter
#

# Solaris needs /usr/xpg6/bin:/usr/xpg4/bin because the tools in /usr/bin are not POSIX-conformant
export PATH='/usr/xpg6/bin:/usr/xpg4/bin:/bin:/usr/bin'

# Make sure all math stuff runs in the "C" locale to avoid problems
# with alternative # radix point representations (e.g. ',' instead of
# '.' in de_DE.*-locales). This needs to be set _before_ any
# floating-point constants are defined in this script).
if [[ "${LC_ALL-}" != '' ]] ; then
	export \
		LC_MONETARY="${LC_ALL}" \
		LC_MESSAGES="${LC_ALL}" \
		LC_COLLATE="${LC_ALL}" \
		LC_CTYPE="${LC_ALL}"
		unset LC_ALL
fi
export LC_NUMERIC='C'


function fatal_error
{
	print -u2 "${progname}: $*"
	exit 1
}

# Get terminal size and put values into a compound variable with the integer
# members "columns" and "lines"
function get_term_size
{
	nameref rect=$1
    
	rect.columns=${ tput cols ; } || return 1
	rect.lines=${ tput lines ; }  || return 1
    
	return 0
}

function usage
{
	OPTIND=0
	getopts -a "${progname}" "${funcplot_usage}" OPT '-?'
	exit 2
}

# program start
# (be carefull with builtins here - they are unconditionally available
# in the shell's "restricted" mode)
builtin basename
builtin sum

typeset progname="${ basename "${0}" ; }"

# terminal size rect
typeset -C termsize=(
	integer columns=-1
	integer lines=-1
)

get_term_size termsize || fatal_error $"Could not get terminal size."

typeset -r funcplot_usage=$'+
[-?\n@(#)\$Id: funcplot (Roland Mainz) 2008-11-27 \$\n]
[-author?Roland Mainz <roland.mainz@nrubsig.org>]
[+NAME?funcplot - simple shell function plotter]
[+DESCRIPTION?\bfuncplot\b is a small calculator application which
	prints the results of ISO C99 math expressions read from either
	arguments or stdin if no arguments are given.]
[+SEE ALSO?\bksh93\b(1),\bceil\b(3M), \bcopysign\b(3M), \bcos\b(3M), 
	\bcosh\b(3M), \berf\b(3M), \berfc\b(3M), \bexp\b(3M), 
	\bexp2\b(3M), \bexpm1\b(3M), \bfabs abs\b(3M), \bfdim\b(3M), 
	\bfinite\b(3M), \bfloor int\b(3M), \bfma\b(3M), \bfmax\b(3M), \bfmin\b(3M), 
	\bfmod\b(3M), \bfpclassify\b(3M), \bhypot\b(3M), \bilogb\b(3M), 
	\bisfinite\b(3M), \bisgreater\b(3M), \bisgreaterequal\b(3M), \bisinf\b(3M), 
	\bisless\b(3M), \bislessequal\b(3M), \bislessgreater\b(3M), \bisnan\b(3M), 
	\bisnormal\b(3M), \bissubnormal\b(3M), \bisunordered\b(3M), \biszero\b(3M), 
	\blgamma\b(3M), \blog\b(3M), \blog1p\b(3M), \blog2\b(3M), 
	\blogb\b(3M), \bnearbyint\b(3M), \bnextafter\b(3M), \bnexttoward\b(3M), 
	\bpow\b(3M), \bremainder\b(3M), \brint\b(3M), \bround\b(3M), 
	\bscalb\b(3M), \bscalbn\b(3M), \bsignbit\b(3M), \bsin\b(3M), 
	\bsinh\b(3M), \bsqrt\b(3M), \btan\b(3M), \btanh\b(3M), 
	\btgamma\b(3M), \btrunc\b(3M)]
'
while getopts -a "${progname}" "${funcplot_usage}" OPT ; do 
#	printmsg "## OPT=|${OPT}|, OPTARG=|${OPTARG}|"
	case "${OPT}" in
		*)	usage ;;
	esac
done
shift $(( OPTIND-1 ))

typeset -C plotdata=(
	float minx
	float maxx
	float stepx
	typeset func
	integer width
	integer height
)

float scale_x

plotdata.minx=-5.
plotdata.maxx=+5.
plotdata.stepx=0.05
plotdata.func="cos(x) "
(( plotdata.width=termsize.columns ))
(( plotdata.height=termsize.lines ))

float -a x_values
float -a y_values
integer i=0

# create calculation function
# (we do this to make sure the shell compiles this function instead of
# interpreting it over and over again)
unset -f do_calc
(
cat <<EOF
function do_calc
{
	set -o errexit
	
	for (( x=plotdata.minx ; x < plotdata.maxx ; x+=plotdata.stepx )) ; do
		(( x_values[i]=x        ))
		(( y_values[i++]=${plotdata.func} ))
	done
	return 0
}
EOF
) | source /dev/stdin || fatal_error $"Could not compile function."

do_calc || fatal_error $"Calculation error"

(( numsteps=${#y_values[*]}-1 ))

# get minimum+maximum values of the values in y_values
float miny=-0.001 maxy=+0.001
for ((i=0 ; i <= numsteps ; i++)) ; do
	(( isnormal(y_values[i]) )) || continue
	(( miny=fmin(miny, y_values[i]) ))
	(( maxy=fmax(maxy, y_values[i]) ))
done

(( scale_x=(plotdata.width  / 1.2) / (plotdata.maxx - plotdata.minx) ))
(( scale_y=(plotdata.height / 1.2) / (maxy          - miny)          ))

printf $"%d y values, scale_x=%f scale_y=%f miny=%f maxy=%f\n" numsteps scale_x scale_y miny maxy

float xv yv
typeset ch

for ((i=0 ; i <= numsteps ; i++)) ; do
	(( xv=x_values[i] , yv=y_values[i] ))

	ch="#"
	
	if ! (( isnormal(yv) )) ; then
		if (( isnan(yv) )) ; then
			ch="N"
			yv=0
		elif (( isinf(yv) )) ; then
			if (( yv >= 0 )) ; then
				ch=">"
				(( yv=maxy ))
			else
				ch="<"
				(( yv=miny ))
			fi
		# this should use |iszero()| once ksh93 on Solaris has it
		elif (( yv == +0 || yv == -0 )) ; then
			ch="0"
		else
			ch="X" # this should not happen (but does since we do not catch |issubnormal()&co.|)
			(( yv=0 ))
		fi
	fi
	
	(( x=int(xv*scale_x + plotdata.width  / 2.) ))
	(( y=int(yv*scale_y + plotdata.height / 2.) ))
	
	(( x >=plotdata.width )) && continue
	(( y >=plotdata.height )) && continue
	(( x <0 )) && continue
	(( y <0 )) && continue

	tput cup $(( plotdata.height-y )) $(( x ))
	printf "${ch}"
done

# exiting - put cursor below grapth
tput cup $((termsize.lines-2)) 0
print "\ndone."

exit 0

# EOF.
