Programmers' Workshop

by Leigh Edwards


Welcome to a new series of articles on programming, primarily in OPL (Organiser 
Programming Language) with very occasional forays into Operating System calls.
In picking up the mantle for this column from Andrew Baldwin I was faced with a 
problem (apart from keeping up the excellent standards).

My dilemma was: At what level to pitch it? The beginner, expert or at some
vague middle ground? I didn't want to bore the experienced reader or baffle the 
beginner, but I could run the risk of doing both.

So my chosen approach will be as follows:

1. To assume that every reader has got access to an OPL programming manual as 
supplied by Psion, or at least the text of it, which is available in electronic 
form (see the references near the end of this article).

2. All readers have read the manual and have at least some experience of OPL.

3. To pick a key aspect of programming. Attempt to clarify and in particular 
extend the coverage provided in the OPL programming manual. I'll make
occasional references to chapters in the OPL Programming manual although some
repetition will be unavoidable. Wherever possible I'll include illustrative
code examples to demonstrate the concepts under discussion and hopefully show 
new or useful aspects for problem solving.

I hope the majority of programmers will find something of interest and may be 
something new in amongst my scribblings. Feedback on this column would be
welcome, particularly on suggestions for future topics or questions about
previous articles (see the references at the end).

So, where shall we start?

I think variables, constants, arguments (of the friendly function kind),
parameters and use of memory would be a good place to begin.

OPL only allows four types of variable: Integers, long integers, floating point 
and strings (see Chapter 2) which can be a little restrictive. In some 
languages, such as C, there are many more types and you can even define names 
for new ones based on the standard types or combinations of them. Each type
of variable uses a different amount of memory and since OPL is translated, 
instead of compiled like C, the variable names take up memory too.

			bytes used
Integer                        2
Long integer                   4
Floating point                 8
String(len)                 len + 2

Variable names will consume as many bytes as the name length, up to a maximum 
name length of eight characters. The two extra bytes for strings hold the 
maximum length and the actual length of the string concerned, and they are 
stored in memory immediately before any characters actually in the
string. For example:

PROC test:
  GLOBAL namestr$(12)
  namestr$ = "Palmtop"
ENDP

Would use eight bytes for the string name and nine bytes for the string data. 
The maximum length byte would equal 12 and the actual length byte would 
equal 7. The memory containing the string would hold the decimal values: 
12,7,80,97,108,109,116,111,112
Since one byte can only hold values up to 255 this explains why OPL strings are 
limited to a maximum size of 255.


Array variables are slightly different

Numeric array variables have two bytes that store the number of elements in the 
array, i.e. its size, stored just before the values for each of the array 
items.

So an integer array declared as follows:

GLOBAL myint%(20) would take 42 bytes of memory.


String arrays are slightly different again

Again the first two bytes of memory hold the size of the array, i.e. the total 
number of strings, followed by a byte holding the maximum size that any string 
element could be. Each of the strings are then stored following the same 
pattern. The first byte holds the actual length of the string, followed by
the characters in that string. Each string in the array follows on in the same 
way until the end of the array is reached.

Variables that are declared directly following each other occupy continuous 
memory, following the storage patterns outlined above of course. Using the 
ADDR() function it is possible to get the address at which a variable is stored 
in memory.

You may be wondering by now how this information could be of value to you. 
Bear with me a little longer and all will become clear.


Good Programming Practice

Almost any program of reasonable size and complexity should be split into 
Procedures that are `called' as required. This approach has many benefits 
including:
1.      Splitting a complex problem down into small manageable chunks, 
	each of which can be written and tested individually.
2.      Allows sections of code to be made general purpose, avoiding 
	duplication of similar code.
3.      Procedures from one program can easily be re-used in others with 
	similar needs.

When a procedure is used a number of parameters are included in the calling 
statement. It is the variability of the parameters which allows the procedure 
to be made general purpose. For example you might have a procedure that 
calculates the sale price of an item based on the trade value, profit
margin and tax rate. You would pass the values in as parameters and the
procedure would return the price the customer pays. But what if you want the
procedure to return the sale price, the tax amount and the amount of profit.
The usual solution in OPL is to use global variables for the other two return
values, but this approach can have a number of disadvantages:

1.      Global variables are visible and modifiable outside of the procedures 
	in which they are normally used. This can lead to bugs which are 
	difficult to find.
2.      They hold their value between procedure calls and a previous value may 
	be used inappropriately.
3.      They make procedures less general because they rely on variables which 
	must be declared outside of themselves.
4.      Each additional global takes more memory and may slow programmes down.

Some of the disadvantages can be reduced by declaring globals as near to their 
point of reference as possible. For example, if a global is declared in the
very first procedure of a program then all other parts of the program can see
and modify it. If it is declared inside a lower level procedure instead,
then only that procedure, or any others that are called by it, can see the 
variable (including any other procedures that they may call and so on down). 
Hiding essential globals in this way can save a lot of anguish and head 
scratching later.


Some value at last

Here's an alternative approach to using globals for passing back multiple 
values from a procedure by combining the ADDR() function with the appropriate 
the POKE command. To take up my previous example of sale price calculation 
again.

PROC price:
  LOCAL tradep,taxrate,markup
  LOCAL custp,profit,taxamnt
  taxrate = .175 REM tax rate may vary depending on product
  markup = .2    REM profit margin may vary depending on product
  PRINT "Trade price ?", REM ask for the trade price
  INPUT tradep           REM get the trade price from sales person
  REM call salesp: to return the customers price
  REM and pass the memory addresses of the taxamnt and
  REM profit local variables so salesp: can pass the values back 
  custp = salesp:(tradep,markup,taxrate,ADDR(taxamnt),ADDR(profit))
  PRINT "Customer price",custp REM show the results
  PRINT "Sales tax",taxamnt
  PRINT "Profit",profit
  GET
  RETURN 0
ENDP

PROC salesp:(tp,mu,txr,txadd%,prftadd%)
  REM txadd% and prftadd% are integer values which hold the
  REM addresses of the floating point variables to be modified

  POKEF prftadd%,tp*mu         REM poke in the value of profit
  POKEF txadd%,(tp*(1+mu))*txr REM poke in the value of sales tax
  RETURN (tp*(1+mu))*(1+txr)   REM return the customer price
ENDP


If you wish to use types other than floating point variables you will obviously 
have to substitute the appropriate POKE command (see Chapter 13) for the ones 
in the example.


More problems solved

You cannot pass an array as a parameter to a procedure, but using this approach 
you could pass the address of the first element of the array and access its 
elements using the corresponding PEEK and POKE commands e.g.

For an integer array a%(12)

ADDR(a%()) will return the address of the first element and ADDR(a%(12)) will 
give the address of the last element. You can use PEEKW(ADDR(a%(9)) to read the 
integer value in the 9th element and POKEW(ADDR(a%(9)),200 to store the integer 
value 200 in the 9th element of array a%(). Easy when you know how isn't it?

Ever wished you could use byte variables instead of integers? You could 
declare a long string or an array of integers, find its address using ADDR() 
and then use the PEEKB and POKEB to access the individual bytes. 
Note, if you use a string PEEKB(ADDR(str$)) will return the length byte of the
string. You need to use PEEKB(ADDR(str$)+1) to get the first byte of the string
If you're keeping track of array element addresses by incrementing or 
decrementing the value you should use the UADD and USUB functions (only on the 
3a) to avoid integer overflow errors.

Similarly if you really need a string longer than 255 bytes, you could declare 
a big integer array and away you go.

Next time I'll delve further into memory and explore some options for a 
substitute DATA statement found in the BASIC language. But before I go, one 
last word on numeric variables and program size and speed. Always use integer 
variables, unless you're likely to go out of range (see Chapter 2), then
choose a long integer and only use floating point variables where necessary. 
Run the following bit of code, note the number of seconds and then add on an & 
character to all occurrences of the ctr variable. Translate and run it, note 
the seconds again then replace the & with % and try again.


PROC loops:
  LOCAL ctr
  LOCAL tim1&,tim2&
  PRINT "looping"
  tim1& = int(hour)*3600+minute*60+second
  WHILE ctr < 10000
    ctr = ctr + 1
  ENDWH
  tim2& = int(hour)*3600+minute*60+second
  PRINT tim2&-tim1&,"seconds"
  GET
  RETURN 0
ENDP


References:

All chapter numbers refer to the OPL Programming manual available from Psion. 
The text of the manual and OPL examples can be obtained on-line as oplman.zip 
from a number of sources including:
CIX - Psion conference, files topic, in the flist.
Compuserve Palmtop forum, Psion programming library 19.
From http://www.nwt.com
Or for on-line viewing at 
http://www.primate.wisc.edu/people/dubois/psion/oplman/psion.html

The author can be contacted via e-mail using ple@cix.compulink.co.uk or 
Compuserve 100533,1726 or via Palmtop magazine.



Programmers' Workshop

by Leigh Edwards

Last time I discussed the four types of OPL variables, how they are stored in 
memory, how to pass back more than one value from a procedure call, plus the
effects of variables on memory storage and speed of program execution.
In this issue I'll finish the theme of variables by discussing: conversion 
between variable types, dynamic allocation of memory for variables, an 
alternative method of returning multiple values from a procedure, an 
equivalent to the DATA keyword found in the Basic language.


Varying Your Variables

With the three numeric types - integer, long integer and floating-point
you can assign any type to any other, and the value on the right-hand 
side will be converted to the variable type on the left-hand side. However 
you must be aware of rounding down and possible errors due to numeric 
overflow or sign changes. For example:

LOCAL I% REM integer
LOCAL L& REM long integer
LOCAL F  REM floating-point
F = 5.99
I% = F     REM I% will be converted to 5
F = -5.99
I% = F     REM I% will be converted to -5 not 6
L& = 70000 REM This value is OK for a long integer,
I% = L&    REM but this will cause an overflow error
F = L&     REM No problem here floats can hold
	   REM bigger values than long integers

Obviously conversions by direct assignment will not cause problems for the 
following: 
Integer to long integer, integer to floating-point,  long integer to 
floating-point. Although direct assignment works, there is a specific function 
to convert an integer or long integer to floating point i.e.  f=FLT(x&).

For floating-point to integer or long integer, use the INT() function. To 
trim the fractional part (digits after the decimal point) from a floating-point 
number and obtain a floating-point result, use the INTF() function. If you 
convert by directly assigning a floating-point value to an integer or long 
integer, the fractional part will automatically be discarded, providing the 
converted value is no too large.

For integer to string (ASCII character) conversion use a$=CHR$(x%), which is 
suitable for integers of 255 or less, this function will not work for long
integers, they have to be assigned to a integer variable first.
To get the complete string representation of an integer, long integer or 
floating-point value e.g. for formatted output purposes say, use FIX$() or 
GEN$().
The NUM$() function will return just the integer part (i.e. the digits before 
the decimal point) of a floating-point number rounded up to the nearest whole 
number, although pointless, using the NUM$() function with integers or long 
integers will not cause errors. 
The SCI$() function is used to convert any number to a string in scientific 
format.

For string to integer use ASC() for a single character string, or the first 
character of a string e.g. if a$="Palmtop" then a%=ASC(a$) would set a% equal
to 80. To find the ASCII code for any printable character use the % operator.
e.g. a%=%x will set a% to equal 120, the ASCII code for `x'.

When converting a string to integer, long integer or floating-point - for a 
string which contain a valid mathematical expression, the r=EVAL(a$) function 
will return the numeric result of the expression in a$ in r%, r& or r. The 
string can contain any maths function or operator. If the string just contains 
valid numeric characters e.g. "3.142" use the r=VAL(a$) function. 
If the string contains a floating-point number, but the variable to 
receive the value is an integer e.g. r%=VAL("223.03"), only the digits before 
the decimal point will be converted (assuming the number is within range).

To convert integers into hexadecimal format use the HEX$() function. To specify 
hex constants put a $ symbol in front of the value e.g. a%=$FF would make 
a% = 255 decimal. Use the & symbol for long integer constants.
A crafty way of converting hexadecimal strings back to decimal is to put a 
$ symbol at the start of the string and use the EVAL() function.
For example if a$ = "1FF", then:

a$="$"+a$
r%=EVAL("a$")

would result in r% = 511 decimal. Again be careful about errors due to overflow 
and the sign of resultant values. Use a & symbol to convert long integer 
values.

To manipulate parts of strings, the LEFT$(), RIGHT$() and MID$() functions are 
available, but an easy way to trim a string to the desired length is as 
follows:

LOCAL f$(130)
....
f$=PARSE$(.....) REM parse$ gets full path and file name
POKEB ADDR(f$),7 REM poke length byte to 7 for node & drive
		 REM info only e.g. f$ = "LOC::M:"

Sometimes when calling EPOC operating system functions which have string 
parameters, you must pass them as so called `zero terminated' this is easily
achieved e.g. a$ = a$ + CHR$(0).

I'll leave it as an exercise for the reader to work out how to get just the
fractional part of a floating-point number (I can see at least two ways to 
do this).


Variable Amounts of Variables

Occasionally you may not know how much space your program will need to store a 
set of values. For example, a database sorting routine where you do not know 
how many records might be involved in the sort. One solution would be to set 
a limit on the program and declare an array size at the maximum number of 
records that can be sorted. This is not ideal for many reasons e.g. it will 
use more memory than is necessary on average, the program may fail at the 
outset due to lack of available memory even though the user may not wish to 
sort records and the amount of memory will vary depending on the type of data
to be sorted. The best way of avoiding these problems is to dynamically 
allocate memory when the sort function is invoked by the user. The ALLOC() 
keyword can be used to reserve an amount of memory of sufficient size (in bytes) 
to sort the number of records selected. If insufficient memory is available to 
meet the ALLOC() request then the value returned by the call is set to zero.
Otherwise the address of the block of memory is returned and data can be stored 
using the appropriate POKEx commands and retrieved using the corresponding 
PEEKx functions. When the work is done all of the memory can be released using 
the FREEALLOC() command.


A Little Hidden Magic

When any program (process) is started an area of memory, called the process 
data segment, is allocated to it by the operating system. A block of that
memory is reserved for the so called reserved or `magic' statics, most are used 
to manage the process, but a block of fourteen bytes can safely be used by the
program itself. They are like special global variables and are available from 
anywhere in the code - hence `magic' and retain their values - hence `static'
for the lifetime of the program. They are always found at the same addresses 
i.e. 0x28 - 0x35 (40 - 53 decimal), (the statics, treated as seven integer 
length values, are usually referred to by the names DatApp1 - DatApp7).

So this gives two alternative approaches to passing back multiple values from a 
procedure. Return values could be stored and retrieved using the magic static 
locations i.e. using the POKEx commands and the appropriate PEEKx functions. 
There is enough memory for fourteen bytes values, seven integers, three long
integers, but only one floating-point value (eight bytes each).
Alternatively, the statics could be used indirectly i.e. to hold the addresses 
of the variables to be modified by the procedure, which could then be used in
the POKEx or PEEKx statements. Since the address of a variable in memory is
always an integer value this allows the addresses of up to seven variables of
any type to be held. The first method is fairly straight forward, but the
indirect method is a little more obscure so I think an example is required.

PROC price:
  LOCAL tradep,taxrate,markup
  LOCAL custp,profit,taxamnt
  POKEW 40,ADDR(taxamnt) REM put address of variables in the
  POKEW 42,ADDR(profit)  REM magic static memory locations
  taxrate =.175 REM tax rate may vary depending on product
  markup = 0.2  REM profit margin may vary
  PRINT "Trade price ?", REM ask the sales person
  INPUT tradep           REM for the trade price
  REM call salesp: to return the customers
  REM price, the memory addresses of the taxamnt
  REM and profit variables are in the magic statics
  REM so salesp: can directly modify them using POKEF
  custp=salesp:(tradep,markup,taxrate)
  PRINT "Customer price",custp REM show the results
  PRINT "Sales tax",taxamnt
  PRINT "Profit",profit
  GET
  RETURN 0
ENDP

PROC salesp:(tp,mu,txr)
  REM the magic statics at address 40 & 42 hold
  REM the addresses of tax and profit
  REM of the other 2 floating point variables to be modified
  REM use PEEKW to get the address held in each magic static
  POKEF PEEKW(40),(tp*(1+mu))*txr REM poke in the value of
  POKEF PEEKW(42),tp*mu           REM sales tax & profit
  RETURN (tp*(1+mu))*(1+txr) REM return the customer price
ENDP

If you wish to use variable types other than floating point you will obviously 
have to substitute the POKEF commands used above for the variant appropriate to
your variables types (see Chapter 13).


Lets Get Basic

Now, suppose you wish store some constant data in your program code as per the 
DATA statement in the Basic language. There is no equivalent to DATA in OPL, so 
you may be forced to use a data file. Although file handling is relatively 
easy, it is not always the simplest or most appropriate method. If each byte in
the data is equivalent to a displayable character then you could use a literal
string, if not the next best alternative is to use an array. The type of array 
used and how you fill it will depend upon the type of data, and how you intend
to use it or read it out. If you need individual bytes of data which will be
read using PEEKB you could use an integer array, for example:

LOCAL data%(10)
data%(1) = $EB3A
data%(2) = $55E8
etc. to fill the array.

However the 8086 class processor used in the Series 3 stores integers in 
reversed order in memory, so the above example would result in the bytes stored 
in the following order of increasing memory location 3A,EB,E8,55.
If you intend to read the data as integers using PEEKW then each integer will 
be returned directly as entered.

Similarly if you use a long integer array, which is more efficient to fill,
then to get the data in the following byte order: EB,3A,55,E8,95,00,83,EC, you
would have to initialise it using:

LOCAL data&(10)
data&(1) = &E8553AEB
data&(2) = &EC830095
etc.
 
i.e. Below the left four columns give individual bytes; the right column is 
the bytes reorganised as long words.
EB  3A  55  E8   E8553AEB
95  00  83  EC   EC830095

If you intend to read the data as long integers using PEEKL then each long 
integer will be returned directly as entered.


Well done to those who persevered and are still hanging in there, things will 
get a little lighter next time when I'll be taking the lid off OVAL - see
elsewhere in this issue for a brief taster.

References:
Any chapter numbers refer to the OPL Programming manual from Psion, the text 
of which is on-line as oplman.zip from a number of sources e.g.
CIX - Psion conference, files topic- in the flist. Compuserve Palmtop A forum, 
library 19. 
From http://www.nwt.com, or for on-line viewing at 
http://www.primate.wisc.edu/people/dubois/psion/oplman/psion.html
The author can be contacted via e-mail using ple@cix.compulink.co.uk or 
Compuserve 100533,1726 or via Palmtop magazine.
