PAC

Section: User Commands (1)
Updated:
Index Return to Main Contents
 

NAME

pac - panel calculator  

SYNOPSIS

pac  

DESCRIPTION

pac is an interactive calculator, resembling a ``panel'' or ``page'' editor. The interface is simple: the user enters numbers and arithmetic operators, pac displays the result. Alternate capabilities to the CALCULATOR include an ASCII to decimal to octal to hexadecimal converter ATOI, a checkbook balancer TOTAL, a loan payment and amortization program LOAN, an editor for the expandable ``conversions data base'' NEWCONVERSION, time of day CLOCK; as well as session recording to files. Operating the alternate capabilities is intuitively obvious and is helped along by the format of the display.

The pac panel is a screen 23 lines by 78 characters, partitioned by inverse video borders into subwindows. The CALCULATOR is a rectangle 4 lines deep by 44 characters wide, located in the upper left corner of the panel, simulating a hand-held calculator: echoing numbers and operators typed to the first three lines, displaying the evaluated result in the fourth line upon RETURN. Control characters, shown along the borders as first characters of mnemonics, provide immediate state switching to and from alternate tools.  

LINE EDITING

A selected function comes to life with the cursor in the home position of a subwindow managed by the function. The user directs input to this portion of the screen under the control of a primitive line editor.

Normally the typed characters are echoed and contribute to the input string. Characters which the tool is not equipped to deal with are not echoed, and are ignored by the editor. Control characters (also not echoed) select alternate tools, or provide exit from the program. A number of keys are commands to the line editor only, allowing cursor positioning and input correction. The editor keys and their effect may vary slightly, depending on the currently active pac tool.

The first character echoed to a line, normally erases the previous input string. In the CALCULATOR function, the line editing = key restores the old input string for editing. A string beginning with the # character is considered a comment. Comments are helpful if the user is recording the session, or for annotating scripts. Another line editing character specific to the CALCULATOR window is the pipe (|), which brings the cursor to the left edge of the following window line.

If the input string reaches the right line boundary, additional characters overwrite the rightmost character, except in the CALCULATOR function where the three lines of the input window conceptually form a single string. Typing RETURN triggers the interpretation of the input string. Regardless of the cursor position at the time of RETURN, all data on the line is evaluated. If the user did not type characters prior to RETURN, a repeat of the previous string, or a tool-specific default string is the assumed input.

A summary of the edit keys is always visible in an inverse video bar running vertically in the center of the screen. Editing characters include DELETE and BACKSPACE, both of which delete characters under the cursor and move bytes at the right of the cursor to the left.

Control-C in the CALCULATOR function, SPACE in the checkbook balancer function, clear a line from the cursor to its end; in the checkbook balancer function a Control-C clears (zeroes) the entire window. Straight brackets [ ] move the the cursor non-destructively to the left or right. In the CALCULATOR function, curly braces { } move the cursor to the line above or below, while the ``greater than'' sign > switches to insert mode: characters already to the right of the cursor are pushed further to the right with each new character added. The ``less than'' sign <, the ESCAPE key or a RETURN end the insert mode.  

CALCULATOR OPERATION

Input begins at the top left byte of the CALCULATOR window, and may consist of multiple statements separated by semicolons. After RETURN, the input is broken down to a list of tokens. Compound tokens contain one or more alphanumeric characters, underscores and periods; simple tokens are single, non-alphanumeric characters from the set:

; % + - * / ^ ( ) \ ' ? ! #

A subset of simple tokens are the math operators %, + or -, * or /, ^ (in increasing order of operator precedence). The percent sign stands for the ``modulo'' operation, the asterisk stands for multiplication, the circumflex for exponentiation. Only integer exponents are allowed.

Tokens are delimited by commas or spaces, by the appearance of the next simple token, or by the end of the input line.

Numbers are a subset of compound tokens, formed entirely from the digits 0-9, the hexadecimal digits a-f or A-F, and the period character.

During parsing, commas and spaces are removed, and successive numbers are concatenated to form a single number.

The resulting token list is passed to the interpreter, which evaluates each token in a normal, left-to-right sequence. A pac lookup table is searched for a match to the token. A match proves the token to be a pac control word, processed immediately. This preprocessing may affect other tokens to the left or right of the control word; and in most cases the affected tokens (including the control word) are replaced by a single number.

If the token does not match a control word, any lower case a-f characters of the token are upcased.

From the interpreter, the string is passed to the bc calculator through an inter-process pipe. Bc evaluates the math expression, and returns the result to pac for formatting and display. pac prints the result in the fourth (bottom) line of the CALCULATOR window.

The precision variable controls the number of digits printed to the right of a decimal point. This variable can be set with the precision n or pr n command; n values may range from 0 to 32. Results with greater than precision fractional digits are rounded. Fractions too small to show up within the precision range cause an underflow error. User selectable number formatting and justification controls the final appearance of the result.

Examples of CALCULATOR input:

12.785 + s --- add 12.785 and stack variable s 12.785 + s; sto j --- as above; copy result into j f + a --- add hex numbers (dec15 + dec10) p + q --- add stack variables p and q 3.3^4 --- the fourth power of 3.3 27^ (-3) --- 1 / 19683 7! - 99 --- factorial of 7, minus 99 (-5) * 40 --- using the unary minus (998 micro + .000002)mega --- 1000 32/(16/(8/(4/(m * 2/m)))) --- 8 (if stack variable m not equal 0) +10 --- add 10 to the previous result -10 --- subtract 10 from the previous result - 60 / 3 --- subtract 20 from the previous result * 5 --- multiply previous result by 5

pac stores results as digit strings, on 17 lines of screen display. Each of the strings is a pac variable. The first of these strings, CURRES, is the result shown in the CALCULATOR window. CURRES is updated continuously and is the result of the most recently evaluated expression. This value can be referenced by the \ (backslash) character: 9 + \ adds CURRES and 9. Any operator that unsuccessfully looks for an operand to its left, will automatically reference CURRES (as in the last four ``Examples of CALCULATOR input'' above). Syntax errors clear CURRES to zero.

The other 16 strings constitute the user stack, a rectangular area directly below the CALCULATOR window. The 16 lines of the stack are labeled by the letters h to w in the left inverse video border. These labels are also pac tokens, and can be input to the CALCULATOR instead of typing the string contained in a stack cell. New results are automatically ``pushed'' on the stack, unless the pac command stack off prohibits this.

pac key words for explicitly manipulating stack contents are clr, dup, pop, pll, psh, sto, swp. These operators can be input to the CALCULATOR regardless of whether the stack is on or off. A stack operator normally references the single-character stack label immediately following the operator. For example, pop m removes the number contained in m, and moves all stack strings located below m up one position; clr p substitutes the number in stack cell p with zero. If a stack label is not given, CURRES is the subject of the stack operation, except that clr, replaces the value of each stack variable with 0.

The pac keyword ibase (abbreviated version: ib) followed by an integer or a variable in the range of 2 through 16, can select an input base other than decimal. The command

ib 2; 1011 0100 0010

as an example, results in the decimal display of ``2882''.

The effect of the ib command lasts from the time it was first encountered in the input, to the end of the input string; then pac automatically reverts to the original input base. To permanently change the input base, the command staybase on (abbreviated version: sb) should be issued. The effect of staybase on lasts until a staybase off commands cancels it. Output radix is similarly controlled by the obase n (or ob n) command for n values 2-16; and staybase effects the permanence of input and output radices in tandem.

Some useful CALCULATOR operators are:

the bitwise operations
and or xor not twoscomp (abbr.:tc)
the percent operations
pplus pminus pdiff pversus pequal pof (abbr.: pp pm pd pv pe po)
the conversion operator
to

Examples:

Add 6.5 percent to 3500:      3500 pplus 6.5 ---  3727.5
Percentage increase from 3300 to 3500:       3300 pdiff 3500---  6.06
If 4778 is 100%, what % is 2389:             4778 pversus 2389---  50
What is 75% of 4000:          75 pof 4000    ---  3000
If 40% of a sum is 50, what is the sum:      40 pequal 50---  125
Convert 1225 inches to centimeters:          1225 to cm---  3111.5

The pac tokens sin(x), cos(x), exp(x), log(x), arct(x) are used as substitutes for the bc ``s(x), c(x), e(x), l(x), a(x)'' functions, respectively. Input values and results are radians.  

CALCULATOR ENVIRONMENT

Environment control operators are used to customize the CALCULATOR to the user's liking. As with the other pac tokens, a certain redundancy is apparent in naming the variables: two-character abbreviations are generally accepted as input tokens.

When exiting pac, an attempt is made to write a ``.pacrc'' file in the user's home directory, unless the dontsave command expressly forbids this. In the .pacrc file, pac keeps a record of the current panel environment. The file also contains the sixteen stack strings, and the up-to-date ``units conversions list'' described under EDITING THE CONVERSIONS LIST, with any modifications effected by the user. Subsequent calls to pac begin by reading and resetting internal parameters from the file data.

To the right of the stack, the narrower GLOBALS window lists the environment control operators and their current values. The state-switching Control-G character overlays the GLOBALS window with a STATUS OPTIONS window, which shows the abbreviated name of each control operator token, followed by the values that this operator may assume. A second Control-G toggles the STATUS OPTIONS window display back to GLOBALS, unless the execution of a CALCULATOR string has already caused the re-display of the GLOBALS window.

The variables justify, format, hardform, and autotime control the format of the pac display screen, and control the format of the file records. The command justify left (abbreviated: ju le) instructs pac to position the leftmost digit of the result in the bottom leftmost position of the CALCULATOR window. Conversely, justify right (abbreviated: ju ri) specifies that the rightmost digit of the result be placed in the bottom rightmost CALCULATOR window position. As a special case of justify right, justify fix outputs the result in a fixed decimal point format. In fixed justification, the number of digits displayed to the right of the decimal point is constant: the value of the precision variable (0 through 32). The format space or format comma (abbreviated: sp and cm) command specifies that CURRES values are to be displayed with spaces or commas respectively, between groups of digits; this makes it easier to read long strings.

The hardform command controls the format of a recording file which can be opened for writing with the Control-F (File) character, or for appending with the Control-P (Postpend) character. The user is prompted for a file name; ``hardcopy'' is the default. Having opened the file, a new Control-F or Control-P will close it, otherwise the file will record calculator transactions until the exit from pac. The command hardform verbose (abbreviated: ver) resets to the default file output format, saving both input and results, with records separated by horizontal lines of dashes. The commands hardform terse (te) and hardform xterse (xt) specify successively denser session recording.

The command: autoconv automatically applies the selected unit conversion formula to each new evaluation (CURRES) prior to displaying the result. For example, a list of dollar figures may be converted to pounds just by entering each dollar value.

The macro command: init resets the format, hardform, ibase, obase, justify, precision, stack, staybase, and autoconv parameters to their default values.

The special combination help [token] (or its abbreviated form ? [token]) overlays the stack area with a portion of the token list, highlighting the selected token. To the right of each token of the list, a very brief summary of the token action is printed. Stack display resumes at the first subsequent stack activity.  

ASCII CONVERSIONS

Directly to the right of the CALCULATOR window, a small rectangle provides immediate conversion between ASCII characters and their decimal, octal, or hexadecimal values, on a per-character basis. The window is titled ATOI, and initially contains the following prompts:

^ A  asc
^ D  dec
^ O  oct
^ X  hex

The characters preceded by the caret ^ stand for the control characters which cause temporary transition from the CALCULATOR state to the ATOI window. Control-A prompts the user to enter any character on the top line of the ATOI window, and immediately displays the decimal, octal, and hex equivalents of this character beneath the input. Context then returns to the CALCULATOR. Control-D similarly, prompts for a decimal value in the top line, in the 0-127 range. Following a RETURN, the ASCII equivalent of the decimal value, as well as the octal and hexadecimal versions are printed. Control-O prompts for an octal number between \000 and \177; Control-X prompts for a hexadecimal value between 0x0 and 0x7f. Values out of the ASCII range are ignored, and the cursor stays on the first line of the ATOI window until a legal value is selected.  

AMORTIZATION

Control-L (LOAN) changes context and moves the cursor to the loan amortization window below ATOI. A second Control-L returns the user to the previous context. The top three lines of the LOAN window are labeled ``AMT'', ``%'', and ``YRS'' in the inverse video border to the left. The user is expected to input a decimal string as the ``loan amount'' (principal) on the ``AMT'' line, an amortization (percent) rate in the second line, and the life term of the loan (in years) on the third line. Up to two digits past the decimal point are significant for both the principal and the life term values, three digits past the decimal point are significant for the percent rate.

When all three lines contain non-zero values, the monthly payment on the proposed loan is immediately displayed in the fourth line of the window, and the cursor wraps back to the first line. The user can now repeatedly adjust the amount, rate, or term values in an infinite loop, by simply typing over the old values. Each change causes an immediate update of the monthly payment figure.

To dump the actual monthly amortization schedule to a file, Control-B moves the cursor to the last line of the LOAN window, where the month/year date of the first payment is entered; then the user is prompted for a file name on the bottom of the screen. The amortization file creation involves substantial floating point math and string formatting, and takes a few seconds to complete.

The author has gleaned the amortization algorithm from examining actual bank loan printouts. While the pac method duplicates the bank samples exactly, different methods of rounding may possibly be employed by other lending institutions, resulting in minor discrepancies between the two sets of figures.  

CHECKBOOK BALANCER

Cashier's lists, checkbook tallies, score keeping, and a number of book keeping activities involve entering and summing values in columnar format. Control-T switches pac to the TOTAL window directly overlaying the CONVERSIONS list. Initially, the TOTAL window consists of 19 lines of zero values, and a bottom ``total'' line. The lines are labeled in the right inverse video border by the lower case letters a through s, and the ``total'' line is labeled by t. As the user types in decimal values (followed by RETURN) the cursor advances to the next lower line, and the entered values are automatically summed to ``total''.

At each RETURN, the most recently typed value is re-formatted right justified, with the number of fractional digits dictated by the user environment' precision value. Negative values are subtracted from the total. The line may also contain a single * or @ character, to effect price multiplication by item count. As an example, ``64 @ 9.17'' is immediately converted to ``586.88''.

When nineteen items have already been entered and the cursor is in line s, the input window wipes itself clean and copies the current total to the top line. The cursor is then positioned at the beginning of the second line, and the entry process can continue indefinitely. It is convenient to refer to this paging event as a ``subtotal''. At subtotal, as well as at the exit from the TOTAL function, the current total is pushed into stack cell h (the top visible element of the user stack on the left side). If the user stack is on, its elements are shifted down one line, potentially retaining a sequence of subtotal values. The calculator CURRES value is not affected by subtotals; the user must explicitly reference the appropriate stack cells to transfer values to the CALCULATOR window for input.

Similarly to the ``hardcopy'' file used for keeping an automatic record of CALCULATOR activities, a separate ``hardtotal'' file may be opened for write or append while the checkbook balancer is active. ``Hardtotal'' is supplied as the default file name, unless the user types in another name. The file continues receiving snapshots of the entire TOTAL window at every subtotal (except receiving only the subtotal values if the pac hardform variable is set to xterse), and a final snapshot on exit from the TOTAL window.

TOTAL interprets decimal numbers only. In addition to digits, + - * @ and the normal line editing characters, the TOTAL line editor also accepts the letters a through t and A through T. The lower case letters cause the value in the corresponding line to be replicated in the line of the cursor (t replicates the current total). Upper case alphabetics A through S relocate the cursor to the line labeled by the corresponding lower case letter; input then continues from this line. When the cursor is relocated this way, the digit string already in the line is not cleared; the new input will be prepended to it. A space typed clears the line from the cursor to its end. Upper case T forces a stack push of the current total, and the snapshot of the window written to an open ``hardtotal'' file. The # character is again a comment delimiter, signaling the editor to ignore it and any further input until the RETURN. A second Control-T provides return to the previous context. A ``hardtotal'' file may be explicitly closed prior to exiting TOTAL, or it may be left open, awaiting recording of further TOTAL activities. Even after exiting TOTAL, the window remains visible over the CONVERSIONS list until a CALCULATOR conversion takes place.  

EDITING THE CONVERSIONS LIST

Unit conversion operations of the CALCULATOR are based on a conversions data base, shadowed from a static list into dynamically allocated memory at initialization, and modifiable by the user. The NEWCONVERSION editor for the conversions database is entered with a Control-N, typically to add new conversions defined by the user, but occasionally to remove existing conversions, or to alter current conversion factors. pac conversions are unidirectional, converting from units A to units B. Separate conversions must be defined to convert from dollars to pounds, and from pounds to dollars, for example. An altered exchange rate between the dollar and the pound may prompt the user to update the dollar-to-pound and pound-to-dollar formulae.

Editing the conversions data base begins in a temporary window overlaying the CALCULATOR window. The user is prompted to select between adding, removing or altering a conversion. Next the user enters a key up to three characters long.

If the removal or the alteration of an existing conversion is selected, the ``conversion keys list'' is searched for a matching key; the key may be re-entered on error until a match is found. When changing an already existing conversion, the user enters a new key (up to three bytes long) as the altered key value. For the pound-to-dollar conversion, let's assume the key us. A new conversion key is inserted in the key list in alphabetical order. A thirteen characters long reference label is typed in next (typically a ``from-units to-units'' pair), as a visual reminder of the meaning of the key. In our example, this may simply be pound dollar.

The new formula is entered at the bottom inverse video bar. The character set of the formula is limited to digits, math operators + - * / ^ %, decimal point, left and right parentheses, and the backslash character \. Normal line editing characters may be used to correct errors. All numbers are assumed to be decimal. Given the exchange rate of 1.75 dollars to the pound, the ``X pounds = Y dollars'' equation could be stated as ``Y = X * 1.75'' and entered as

\ * 1.75

into the data base. When the formula is invoked in a later CALCULATOR conversion such as ``900 to us'', the backslash standing for X in the solution, will be substituted by ``900'', followed by the multiplication by the constant to get the new (converted) value. Though the conversion list is stored in decimal format, during calculations the constant strings are automatically re-cast into the input radix in effect. The converse operation: dollars to pounds, would have a different key, a different label, and the following conversion formula:

\ / 1.75

More complex formulae are feasible; the formula need not start with a backslash; multiple backslashes may occur. Having finished with the editing of the conversion, the most recently added conversion is shown selected in the center of the CONVERSIONS window. Context reverts to the calling tool.  

CLOCK

Control-K installs a date/hour/minute clock in the right corner of the top inverse video border. Time is kept in a twelve-hour format; a period following the minutes denotes PM. The clock operates asynchronously and without affecting the rest of the program. A second Control-K turns off the clock. The pac environment variable autotime may be enabled, with the effect that the clock appears automatically on entry to the program.  

EXIT

Control-E resets the terminal to cooked mode, writes the .pacrc file (containing the pac environment variables, stack, and the conversion list) in the user's HOME directory; and returns the user to the shell. The cursor is moved to the line below the pac screen. From the CALCULATOR function, either quit or exit has the same effect. The action of the TAB character (Control-I) or the equivalent token bye is different in that the CALCULATOR stack is cleared (all 0 values are saved in the .pacrc file), and the screen is cleared as well.  

BUGS

Physical constants are defined to a few digits of precision only, not to the 32 digits maximum capability of the calculator. There is no guarantee as to the accuracy of the constant definitions; the program must be re-compiled to make improvements or changes.

Parentheses are passed through the preprocessor to bc instead of being handled immediately. For this reason, one should avoid using pac operators (multi-byte non-numeric words, and the factorial operator !) inside open parentheses. Also, logical (bit) and percent operators should not directly precede a left parenthesis.

These same pac operators may force partial evaluations of the input string, often changing CURRES faster than it is possible to visually update the result. Explicit use of the CURRES token BACKSLASH is therefore discouraged, except during the editing of conversion formulae.

Though pac traps error messages from bc, if the operating system is running with a broken or incorrectly compiled/linked bc, the buggy executable may ``surprize'' the pac process by deadlocking the pipes.

Due to its interactive nature, pac is not optimized for speed; shell scripts are slow.


 

Index

NAME
SYNOPSIS
DESCRIPTION
LINE EDITING
CALCULATOR OPERATION
CALCULATOR ENVIRONMENT
ASCII CONVERSIONS
AMORTIZATION
CHECKBOOK BALANCER
EDITING THE CONVERSIONS LIST
CLOCK
EXIT
BUGS

This document was created by man2html, using the manual pages.
Time: 20:20:51 GMT, November 26, 2024