AiphaBasic. TM User's Manual

©-1977 ALPHA MICROSYSTEMS ALLRIGHTSRESERVED p

I would like to express my thanks to the followingpeople for their assistance in the developrient ofAiphaBasic: Mike Roach for debugging and suggestions on implementation of new features Paul Allen Eelstein for the trig package and advanced mathematical assistance Bob Hitchcock for operator and applications oriented suggestions and scaled arithmetic the myriad of users who pointed out problems in the earlier versions (scirtetiniesnot so tactfully) and most of all to Carolyn without whom much of thismay never have been accomplished.

Dick Wilcox

'AMOS','AiphaBasic', and'AM—lOO'

aretrademarks of products aix) software of

ALPHAMICRDSYSTFjS Irvine, CA 92714

©1977 —ALPHAMICR)SYSTEI.IS

ALPHA MICRD 17881-F Sky Park North Irvine, CA 92714 INDEX

INTDUCTIQN '10 ALPHABASIC PAGE 1 ALPHABASIC GENERAL INFORMATION PAGE 3 INTERACTIVE VS CCMPILER MODES PAGE 6 RUNNING BASIC PRAMS PAGE 7

ALPHABASIC VARIABLES PAGE 9 DATA FORMMS PAGE 11 ALPHABASIC EXPRESSIONS PAGE 13 ELMER CASE CHARACTERS PAGE 15 SUBSTRING MODIFIERS PAGE 16

MEMORY MAPPII)G SYSTEM PAGE 18

INTERACTIVE CCtIMAND SUMMARY PAGE 27 PRCRN4 STATFIIENIS PAGE 31 BASIC FUNCTIONS PAGE 37

FORMATTED OUTPUT VIA PRINT USINGSTATEMENTS PAGE 41 SCALED ARITHMETIC PAGE 43

ALPHABASIC FILE I/O SYSTEM PAGE 45 FILE I/O STATEMENTS PAGE 47

CALL It3G EXTERNAL ASSEMBLY LANGUAGESUBtYPINE5 PAGE 51 ERDR TRAPPING PAGE 54 SYSTEMS FUNCTIONS PAGE 57 EXPANDED TAB FUNCTIONS (SCREEN CONTROL) PAGE 59 FORMATTED NUMERIC DATA VIA THE "USING"MODIFIER PAGE 60

PRCCESSING INDEXED SEQUENTIAL FILES PAGE 61

CHAINING TO OTHER PR(XRAMS AND SYSTEMS PAGE 68

Note:This manual reflects Aiphasasicversion 3.3 release C INTRODUCTION 10 ALPHABASIC

Alphasasicis an extension of the popular BASIC language with severalfeatures not found in other implementations.These features not only enhance the performance of traditional uses of the language but also make business applicationseasier to program. COBOL users will find the I/O processing convenient for data manipulation while thememory mapping system will entice the programmers who wish to linkup their own external routines. Floating point hardware in the processor is fullysupported making AlphaBasic fasterfor mathematical computations thanany other BASIC currently implemented in a microprocessor system. AlphaBasic runs in one of two modes.Interactive mode operates in the traditionalmanner whereby the user creates, alters, and tests hisprogram which resides totally in memory. This mode is convenient for the creation and debugging of new programs or the dynamicalteration of exisitng programs. mode is more useful forprograms which are to be put into productive use or for testing programs which are too large to fit inmemory in the interactive mode.In compiler mode, the user compiles theprogram and stores the compiled object codeon the disk.During the actual running of the compiled program, only the object code and a minimal run—tineexecution package need be in memory thereby conservingspace and increasing run speed. The compiler and the runtime packageare both written in reentrant code so that they may optionally be shared by allusers running or debugging programs. The object programs created by the compilerare also totally reentrant and sharable thereby further reducingmemory requirements if it is desired to allow several users to run the same program. Data formats supported include floatingpoint, string, binary and unformatted All variables. data formats may besimple variables or array structures. In addition, theuniquememory mapping system allows the user to specify the orderingof variables in prearranged groupingsfor more efficient processing. This system is similar to the dataformatting capabilities of the COBOL language and lends itself nicely to businessapplications where the manipulation of formatted data structures is of primeconcern.Mvanced compiler techniques have been used in allareas to give a truly commercial grade processingsystem which may be easily integrated intoa series of programs not limited to the BASIC language.If the user is runninga large number of BASIC tasks in a timesharing environment, therun—time package is fully reentrant andmay be includedin the resident monitor fora further increase in memory efficiency. The compiled object programs are also totally reentrant andsharablefor users whoare running the same applicationprograms. Variable names are not limitedto the conventional single character and single digit format but may beany number of alphanumeric characters in length,as long as the first character is alphabetic.This is accomplished by usinga dynamic tree structure for the storage ofreserved words and variablenames within the compiler and isanotherfeature which makes Aiphasasic ideallysuited for business applications.Since the source code is compiledand need not be in memory when the program is eventuallyrun, the length of the variable name is not a significant concern.Label names may also be used to identify points in the program for CCYJO and GOSUBbranches.Label names are alphanumeric and help

1 to clarify the program structurewhen used with meaningful definitions. The following sections will describeAlphaBasic features and operations.It is assumed that the reader is familiar withconventional BASIC language concepts. This initial description isnot meant as a tutorial to the novice butrather as an informational packet which will listthe supported functions of conventional BASIC and give more detailed study norm. only to those areas that differ franthe In all cases, AiphaBasic has beendesigned to support allfeaturesof conventionalBASIC which is currently inuse in the microprocessor field. those few areas where In no mention is made here of a feature which isnormally considered standard, it is probablydue to lack of space (or possibly time) lack of during theinitial writing of this description. The reader is encouraged to contact his local dealerto clear up anyspecificquestions that may arise until such timeasmore comprehensive documentation isgenerated on AlphaBasic.

2 ALPHABASIC GENERAL INFORMATION

This section will attempt to explain the general differencesencountered in the AiphaBasic compiler system and to list the currently implementedfeatures or problems and limitations that are known to exist at this time.

COMPILER OPERATION The user initiates the AlphaBasic compiler functionby entering the command BASIC while in monitor coninand mode.Once the compiler has been located and loaded into RAM it will print the READYmessage and await user input.Although the system is a compiler in actual operation ithas been designed to look as much like the popular interpreters thatare currently on the market.The system is interactive in nature and theuser may enter his source program and edit it on a line number basis just like the interpretive versions.No fancy editing techniques are yet available and each linemust be changed by entering the line number and the entire new line.Line numbers must be in the range of 1—65534 to be valid.The source text is built up inmemory as it is entered and is automatically kept in numericalsequence.Multiple lines (terminated by line—feed instead of carriage—return)are not supported at this time but will be in the future.No syntax checking is performed when the line is enteredother than validation of the line number. When the user enteres the RUN commandthe source program is compiled in its entirety and syntax errors reported.The resulting object code is also stored in memory which results ina much greater initial memory requirement.If no errors were detected the object code is thenexecuted with no direct reference to the source code anymore.Any further editing of the source code will switch to automatically force recompilation set a entered. when the next RUN command is

The user may store the compiled objectprogram on disk by using the SAVE command with the explicit extension "RUN"appended to the program name.This saved program may then later be executed withoutrecompilation by use of the monitor RUN connarxi which callsupon the runtthe package only.

MULTIPLE STATEMENT LINES The system supports multiplestatement lines by using colons to separate the statements.The normal rules apply suchas REM and DATA statements cannot contain other statementson the same line. multiple statement lines. Immediate mode commands may also be

IMMEDIATEMDDE COMMNDS

All linestypedintoAlphabasic by the user will be consideredfor immediate execution ifno line number preceeds the command. Systemcoinliands result in immediateinterpretation and execution andare considered those commands which result in a system fucntion butare not ever included in the text of a program itself.Normal program statementsmay be entered without a line number in which

3 case they will be compiledas a single line program and executed. thenimmediately Certain coninands are consideredillegal in inrnediate mode andthe user is advised that no errormessages are currently implemented toprevent the user fruit inadvertantly attemptingto execute these commands.In sane instances the execution of thesecommands will result in completesystem destruction which means you must reboot the entireoperating system. corrected in a future release. This malady will be

VARIABLENAMES

Variable names are not limited to a single letter ora letter and a digit as in conventional BASIC implementations. A variable name may contain alphanumericcharacters as long anynumberof also be used in variable as the first one is alpha A—Z.Apostrophes may names to improve clarity. Mappedvariables are defined by an explicit typecode and therefore do not follow the standard conventionof using a dollar sign forstring variables. Normal consideredfloating point variables (non—mapped)variables are in unless they are terminated bya dollar sign which case theyare considered string variables.Subscripting follows the standard conventions ofother BASIC's by enclosingthe subscripts within parenthesis.Some examples of legalvariables follow:

A

NUMBER STRIN3$ MASTER' INVENIORY' RECORD HEADER1 Mct4' ALWAYS 'LIKED' YOU'BEST Z1234567

PRCERPI4 LABELS

Aiphasasicallows the use ofprogram labels to identify points A program label iscomposed of 1 or more alphanumeric in the program. first must be alphaA—z. characters of which the Apostrophes may also beused within labels for clarity. Labels, when used, must be the first itxneon a line and must be terminated bya colon (:). Alabel may be followed the same line by a program statementon or it may betheonly item on the line. linenumbers for (IO and Labels operate similarto document ostJs statements and makethe program easierto - Anexample of labelusage follows: 10 START' PIfl3RAM: 20 INPUT"ENTER TWO NUMBERSTO GET SUM:",A,B 30PRINTA;"+";B;"="A+B 40IF A+B<>0 QYIO SUM'NOP'ZEWJ 50PRINT "SUM IS ZERD" 60 aaoSTART'PiY3RAr4 70 SUM'NOr'ZERJ:PRINT "SUM IS N(YI' ZERD" 80 0310 START'PWYRAJ4 90 END

4 MEMORY ALLCCATICZ%J

The compiler systemallocatesmemory dynamically during editing, compiling,and executionof the user program.Currently there is no check made to insurethat the user is not running out ofmemory in his allocated partition andchancesare prettygood that memory overrun will resultin a system crash. We realize that this is a grave restriction and there are several technicalreasons why this condition is not checked for andreported as an error. I will not bore you with the gory details on this except tOinsureyou that itwill be implemented ina future production relase ofAlphaBasic.In the meantime you can kinda keeptabs on memory usage with the MEM(X)function which will deliver back varioususages of memory duringprogram developuent.See the section on functions for detailon this. more

EXPANDEDSOURCE'IEXT MODE

klphaflasic normally scans the source text in expanded mode(version3.2) which dictates that reservedwords (verbs, functions,connands, etc) be terminated by a space or a character that is illegalin variable names. and variables to begin with This allows labels reserved words.In other words, the variablename PRIN'ThIASTER will not be interpretedas PRINT ?.WSTER in expanded mode.In this mode the statement FOR A=l'ID 10 cannot be writtenas FORA=lI%Jl0.There are two commandswhich the user may applyto switch back and forth between expanded modes: normal and

EXPAND Isets syntaxscannerto expanded mode NOEXPAND Isets syntaxscannerto normalmode AlphaBasic initializes itself in the expanded mode. Note that the mode in which a program is compiled has nothing to do whatsoever with theresultant object code which is generated eitherin size or execution speed.

5 INTERACTIVE VS C)MPILER MJDES

AlphaBasic may berun in one of two modes of execution.Interactive mode deals directly with theuser on a one—for—one basis allowingditect editing of the source program in memory and testingof that program in a debug mode.This is the mode that most BASICinterpreters operate in and theone that most users of BASIC are already familiar with.In addition to the normal commandsthere are saiie unique features that make AlphaBasicmore useful in a debug mode. In interactive mode the entirecanpiler as well as the usersource program must be stored in memory foroperation.Editing of the source program takesplace in the conventionalmanner by typing each line with its line number first.Lines are kept in sequence autanatically bythe internal editing routines.Each time a change is made in the sourceprogram a switch is set which indicates that the program must be reccmpiled before itcan be executed.Any time the user enters a command which results inprogram execution (RUN, CONT, or single—step) this switch is tested and ifset, the program is cctnpiled inmemory and the object code generated in itsown special area of memory also. that is then executed by the It is this object code during interactive operations.run—time package which also must be inmemory Ccwmands which do not havea line number are considered immediate mode caiimands and are executed inuiediately.Actually, the statement is canpiled and execution isapplied against the currently existingset of defined variables. New variables are defined as required by immediate mode commands. Certain commands are meaningless in immediate mode andare therefore not allowed etc). (FOR, NEXT, Multi—statement linesare lines which contain more thanonecommand separatedby colons and are allowedinimmediate modeaswell as in the source program.

A uniquefeature which is very useful fordebugging is the single—step ccnmand. Each time the line—feed keyis entered with no dataon the line, thenext instructionin the program is listed andthen executed.Control is then returned to the user terminal forinspection of variablesor alteration of the source program before continuingexecution. source program results in recanpilation Note that any alteration of the actually executed. before the single—step coninand is

Calipiler mode differs franinteractive mode in that theprogram is canpiled first and then the objectcode is stored on disk witha special save coninand. The object code may then berun at any time in the future requiring thatonly the run time package be inmemory along with the object code itself.Neither the canpiler propernor the program source code is requiredfor execution in canpiler mode resulting ina large cutback in memoEy requirement.This mode is also ideal for sequentialautanatic processing of multipleprograms within a system structure.IN this mode, BASIC programsmay be freely mixed with assembly languageprograms for maximan efficiency andflexibility.

6 RUNNING BASIC PX3RAM5

AlphaBasic supports the ability to compileand run programswithout reread thesource having to program by saving thecompiledcode on disk andusingthe runtime package torun that code at anylatertime. components in the compiler system There are twomain named BASIC.P3 andRUN. PRG. These programs reside inthe system library (CSKO:[1,4J)and are called into memory required. as they are BASIC.P is thecompilerandcontainsthecodewhich scans the source program in memory andcreates All the runnable object program also inmemory. system ccrnmands suchas LIST, tOAD, SAVE,etc. are also processed in this program. RUN.PR3is the runtime package and containsthe code andsubroutines which perform the actualexecution of the compiled objectcode from memory. This object codecan be fran the compilation phase duringinteractive program development or it can be fromthe direct loading of the disk. a saved object code file on

Theruntisne package (RUN.PRG) isfree—standing andmay run without referencing thecompiler program (BASIC.pwJ). The compiler, however, will first insure the that runtime package is present inmemory and loadit if necessary since it draws uponseveral of the internal runtimeroutines during compilation.The user may optionallybuild his monitor with the runtimepackage resident for sharing by all users. Those users which thenruninthe interactive mode will also benefit since BASIC. Pwill locate RUN. PH in the monitormemory andnothave to load itagain into the usermemory.The compiler itself may also be includedin the monitor but due to the sizeof it this is not normally doneunless the majority ofthe users will be doingprogram development and testing (suchas a school trainingprogramteaching BASIC) 'It run in the interactive mode(the mode most familiar tous due to other versions of BASIC)the user types the conirtand "BASIC"on his terminal and the compiler and runtimeprograms are both located and loaded intomemory as required.The LOAD connarid may then beused to load source programs into for editing, compilationand test. memory the source program The SAVE command may be usedto save either or the compiled object programon disk for later use.Source programs have the extension "RAE" whilecompiled object programs have the extension "RUN". Note that there is noway to recover the source text fran the compiledobject code so the normal ruleis to save both of them eitheron the same or different disks.Running in the interactive mode alwaysinvolves the compilation and running ofa source program which is in memory andnever includes running a saved objectcode program directly. To run a compiled program the user must be in monitor mode.Monitor mode may be entered from the interactivecompiler mode above by exiting thecompiler via the BYE command typedon the terminal.Once the monitor mode is obtained theuser enters the RUN coimiand followedby the name of the objectprogram to be run. The runtime package is located(and loaded from disk i necessary)and then started.The runtime package then initializesuser memory and locates the user program specified in the RUN calunand.This program has the extension "RUN"and may be either in memory alreadyor be loaded from the user diskarea.Loading of the program isautomatic by the runtime package ifthe program is not in memory.The program is then executedand continues until the endor until aborted by theuser typing a control—c on his terminal.

7 Note that the WIN commandserves two different functions the user is in monitor depending on whether mode or in interactiveBASIC mode. In monitor mode the RUN command is used toexecute a compiled BASICprogram which has been previously storedon disk or loaded into memory PAYL will run the PAYROL.pjy explicitly.The coninand RUN mode without compiled program andthen exit back to monitor ever enterirg the compiler itself.In interactive BASIC mode the P13W command will compileand run the currentsource program which theuser is editing and testing. The user should note thesedifferences. tchile we are on the subjectof running sourceprograms versus compiled object programs,there is one more restriction that the user should note. The CHAIN statement causesone program to terminate executionand turn control over to the next program in sequence.This chained program must bea compiled object program or it will not be found.There is no mechanism to loada source program and then compile it forthe CHAIN statement'suse.The object program module may, however, be already inmemory or it may be on disk in whichcase it will be loaded automatically.If the chained program isalready in memory there will be ho wait time due to loadingfrom the disk.The object program modulemay be doaded into memory by themonitor LOAD command (different WAD command). from the AlphaBasic

Note also that the compiledobject program is totallyreentrant and sharable between severalusers so that any programs thatare commonly used as either complete programs or chained linksmay be stored in monitor memory for high—speed access.

8 ALPHABASIC VARIABLEs

Variablenames may be any number of unique limitedto a single character alphanumeric characters andare not or character—digit pairasin other versions BASIC. The first character of the of name must be alphabetic andthevariable name must not beginwithanyreserved word used in BASIC. usedin variable names to improve Apostrophes may also be clarity. Mapped variables may takeon any type formatregardless of thename terminator. type Unmapped variablesassumethe code as in other versions ofBASIC. String variables are specifiedby appending a dollar signto the name and integer variablesare specified by appending a percent signto the name. more detail on these options. Refer to the section on data formatsfor

NUMERIC VARIABLES The normal mode of processingmathematical variables (as opposedto string variables) is in 11—digitaccuracy which might be termed "single—and—one—half" precision compared to normallyaccepted standards.This is due to the hardware floating point instructionswhich are implemented in theWD—16 microprocessor chip set used in the AM—lOt)computer.Integer and binary variablesare also considered numeric variables butare always converted to floating point format prior to performing mathematicaloperations on them.All printing of math variables is done under normal.BASIC format with the significance being under user control from 1to 11 digits. variable set up this value. The SIGNIFICANCE statement is usedto

STRING VARIABLES AlphaBasic supports string variables in bothsingle andarraymodes. The memory that is allocated for eachstring variable is the number ofbytes representing the maximum size that thestring is allowed to expandto.Each string is variable in size within thismaximum limit and a null byte isstored at the end of each string to indicateits current actual size.At the start of each compilation the default sizeto be used for strings is 10 charactersmaximum. The STPSIZ statementmay be used within the program to alterthe value to be used for all new stringvariables which follow.Future releases of the compiler syntax will allow individualstring definitions to have theirown size specificationwithout the need to changethis default value. String variablesare manipulated in the samemanner as in other versions of BASIC and may be concatenatedby use of the plus sign betweentwo strings. String variablesmay be assigned values by enclosingstring literals in quotes. Stringfunctions such as LEFT$, RIGHT$, MID$, etc. are implementedto assist in manipulating portions ofstrings or substrings. In addition, a powerful substring modifiermay be used to operate on portions expressions. of strings within A seperate section is devotedto this uniqueoptionof AlphaBasic. Unformatted variables are also considered string variableswhen they are used in expressions or printed. Be careful with this one! If the is mapped to contain unformattedvariable subfields which are not instring format, it will cause

9 some very strange results whenprinted or used in expressions.This is because no conversions are performedon the subfields of an unformatted variable;it is used in its entiretyexactly as it appears inmemory.

VARI ABLE ARRAYS

Arrays may be numericor string variables and are allocateddynamically during execution when the DIMstatement is encountered in theprogram.During execution if no DIM statementhas been encountered when the first thearray is made, a default reference to array size of 10 elements for each subscriptlevel isused.This means that all DIMstatements must be executed in the prior to any actualreferences to the array. program Arraysmay be any number oflevels deep but practicality dictatessome reasonablelimit of 20 or so. Each level is referenced bya subscript value starting with element 1 andextendingto element N. Once an array has been dimensionedby a DIM statement itmay not be redimensioned by a subsequent DIM statement in the sameprogram.At ho time may the number of subscriptsvary in any of the references to any element inthe array.The number of subscripts in each element reference mustalso match the number of subscripts in the corresponding DIM statement whichdefined the array size.

10 DATA FORMATS

AiphaBasichas been designed with other language the goal of flexibility in interfacing with• processors within the AMOS operatingsystem and primarily aimed towards assembly languageprograms where the data frana BASIC program must be manipulated ina way that is either infeasibleor inefficient for another BASIC program to do.In order to accanplish thisgoal, the data formats must be clearly defined andunderstandable by theuser who wishes this information. Data will normally be outputto one or more disk files to bepassed on to another BASIC programor to an assembly languageprogram for further reduction or processing.Data may also be output ina print image format for printing by theoperating system print spooler required job. It is our intention to provide all information on the internalformats andworkingsof AlphaBasic so that the user will find the task of interfacing thesoftwareoutputs to be straightforward. This initial description isnot meant to be the final result of the internal documentation effort, but merelyanintroductionto the designtheory behind the canpiler. All variables inuse by the application programare stored in a dynamically alterable area within theuser program area.The areas that change during programexecution are those whichare set aside for arrays and variable size strings. Simple variables do not changeposition once they are assigned positions. storage Assignment of storage isnormally done as each variable is encountered in the sourceprogram. The user has the option of overiding assignmentby the memory mapping this system which will be described later.Each variable is assignedas one of the following data formattypes and once assigned, may not be changedwithin the sameprogram.

FL/DATING POINT — allnumeric variables are assignedas this type unless otherwise specified in theprogram. Thestandard precision inuse by this systemwould probably be called "single—and—one—hf"since it lies midway between what has beenaccepted as single and doubleprecision formats. reason for this is that the hardwarefloating point instructions The thisformat and so we may all work in as well make use of the extra precisionwherever possible. Floating point numbers occupy six bytes of storage andare in the same format as dictated by the hardware instructions FADD,FSUB, FMUL,FDIV,arid FOIl'. Of the 48 bits inuse for each 6—byte variable, signfor the mantissa. the high order bit is the The next 8 bits representthesignedexponent in excess—l28 notation givinga range of approximately 2.9*lO_39 thru l.7*l0"38. The remaining 39 bits contain the mantissa which isnormalized with an implied high—order bit of one. This gives an effective40—bit mantissa which results in an accuracy of 11 significant digits.

STRING — used for the storage of alphanumerictext data. String variables may be assigned fixed lengthsfor efficiency and speed vary ormay be left to dynamically in size as the datachanges.Fixed length string variablesrequire one byte of storage for eachcharacter and may be fixed inposition using the memory mapping system.Dynamic length string variablesmay not be mapped into memory since their positionmay shift during execution. to the user if it is absolutely Miindexing scheme is defined an external routine. necessary for him to locate these stringswith

11 BINARY —binaryvariables are similar to integer variables in other implementations of BASIC.A binary variable may be frau 1 to S bytes in length and may be signed when all 5 bytes are specified.When less than 5 bytes are specified for the size (in a MAP statement) the binary value may be loaded as a negative number but will always be returned as a positive number of full magnitude with the upper bit (preloaded as the sign) taking on its specific• value in the equivalent positive binary variable.For instance, a 1—byte binary may be loaded with positive numbers from 0 thru 255 (decimal) or negative numbers fran —l thru —128 but the negative numbers will be returned as the positive values of 128 thru 255 respectively.Only 5—byte binary variables will return the original sign and value when loaded with a negative number. Binary variables may be used in expressions but they are slower than floating point variables because they are always converted first to floating point format before any mathematical operations are performed on them.Binary variables are useful in integer and logical (Boolean) operations or for storing values in small amounts of memory (floating point numbers always take 6 bytes of memory regardless of their values).Alllogicaloperations performedwithin expressions(AND, OR, XOR, NOT etc.) cause the values to be first converted to signed5—byte binary format before the logical operation is performed.The value —1 represents a 40—bit mask of all ones and it is this value which is returned as the result of any relational comparison between two expressions or variables.

INTFX3ER —integervariables and constants are specified by appending the variable name with a percent sign (%) which is the standard convention inuse by other BASIC's.AlphaBasic generates floating point variables and performs automatic integer truncation for all integer variables specified in thismanner. Integer constants are generated as their equivalent floating point values and are included only for compatibility with existing program structures.Since integer variables are effectively floating point variables withan additional INTconversionperformed, they are actually slower than regularfloating point variables. This is opposite from most other BASIC's which usually store integer variables as 2—byte signed values and perform special integer arithmeticon them. True integer variables may be defined by using the MAP statement and the "B" binary type code.

UNFORMATTED— definesa fixed size area of storage used to contain absolute unformatted data which may be in any of the above formats.This format will normally be used in the mapping system to define contiguous storage which is subdivided into multiple variables of different formats.No conversion ever takes place when moving data to and from this format.Unformatted variables are treated as string variables when used in expressions.

*Notethat dtamic length string variables are not yet implemented.

12 ALPHABASIC EXPRESSIONS

Expressions in AlphaBasic follow the same format used by other popular versions of BASIC.Parentheses are used to designate hierarchy within expression terms and the normal mathematical hierarchy prevails in the absence of parentheses. The following mathematical operators are recognized by AlphaBasic:

+ unaryplus or addition — unaryminus or subtraction * multiplication / division raise to power ** raiseto power string literal NOT logical not AND logical and OR logical or XOR logical xor EQV logical equivalence MIN minimum value MAX maximum value = equal less than > greater than <> unequal >< unequal it unequal <= lessthan or equal =< lessthan or equal >= greaterthan or equal => greaterthan or equal

OPERAWR PRECEDENCE The precedence of operators determines thesequence in which mathematical operationsare performedwhenevaluating an expression that does not have overriding parenthesis todictate hierarchies.AlphaBasic uses the followingoperator precedence:

exponentiation unary plus and minus multiplication and division addition and subtraction relational operations (comparisons) logical AND, OR, XOR, EQV, MIN, MX logical NOT

MODE INDEPENDENCE

Expressions may contain arty mixture of variable types and constants inany arrangement. AlphaBasic performs autanatic string and numeric conversions as

13 necessary to insure the result is in the proper format.For example, if two strings are multiplied together they will first be automatically converted to numeric format before the multiplication takes place.If the result is then to k / becomea string it will be reconverted back to string format before the assignment is performed.In other words, the statement P4 = * "345"is perfectly legal and will work correctly.This is a powerful feature which can save much programming effort when used correctly. Thereis an ambiguous situation which arises fran this modeindependence. The plussymbol (+)is used both as an addition operator for numeric operations and as a concatenation operator for string operations.The value of 34+5 is equal to 39 but the value of "34"+"5" is equal to the string "345".The operation of the plus symbol is unambiguaous in its operation but may take a little thought to figure out its exact usage in all situations.A few examples might help. If the first operand is numeric and the second is string we convert the second to numeric and perform addition.

34 +"5"equals 39 If the first operand is string and the second operand is numeric we convertthe second to string and perform concatenation.

"34"+5equals"345" The above two examples apply only when we are not "expecting" a particular type of variable or term.This generally occurs only in afirst level PRINT expression. Atother times we are expecting a specifictype of variable and the conversion of the first variable will beperformed priorto inspecting the operator (plus sign). The operation ofthe plus sign is then implicitly specified by the result of the first first variable.Take the following example:

5* "34" + 4 Themultiplication operator (*)forces us to expect a numeric term to follow. The "34" string is therefore immediately converted to numeric 34 and multiplied by the 5.The plus sign then performs numeric addition instead concatenation.The result is in numeric format andwillbe converted if its destination is a string.

If this approach seems confusing youshouldtry a few examples of your ownon the system to seewhatthe results are.Remember, anypotentially ambiguous expressionmay always be forced to one or the other typebyuse of the Sm and VALfunctions.

14 TflER CPSE CBARACTE

Beginningwith release 3.1 Alphaflasic supports lower case letters (a—z)in both the input source program and in the runtime execution of programs.The line editorbuilt into the interactive system willnow accept andstoresource input textin lower case characters if desired. Lower case letters when used within variable names and labels will be unique and separate from the corresponding upper case letters. In other words, the variable "a" is separate from the variable"A" andthe variable "Tom" is separate fran the variables "9DM" and "torn". Lower case letters may be used as the first character of a variable name or program label just as upper case lettersmay be. Reserved words are treated somewhat differently from the above system.When a reserved word is expected, the syntax parser temporarily translates all lower case letters to upper case and then checks for a reserved word match.If the word is not a reserved word the translation is not retained and the lower case letters are used for variable name matches.The following statements are all considered to be identical:

FOR A =120 100 STEP 2 For A =1To 100 Step 2 For A =1to 100 step 2 for A =1to 100 step 2 Lower case letters used within string literals (inside quotes) will be retained and printed as lower case.Lower case letters which are entered into string variables by means of the INPUT statement will also be retained as lower case letters.The entire string processing system now supports lower case characters.

Note that alllowercase characters are considered greater than anyupper case characterdue to their position in the ASCII colating sequence. 2b assist in processingand comparing input which contains lower case letters the UCS(X) function has been implemented.This function will return a string which is identical to the argument string (X) with all lower case characters being translated to upper case.The inverse function LCS(X) will return a stUng with all upper case characters being translated to lower case.

15 SUBSTRU3 MODIFIERS

Alphasasic supports a unique method of manipulating substrings.A substring is defined as a portion of an existing string which may be as snail as a single character or as large as the entire string.Substring modifiers allow the substring to be defined in terms of character positions within the string, relative to either the left or right end of the string.The length of the substring is defined either in terms of its beginning arid ending positions or in terms of its beginning position and its length.

Substringsare defined by referencing the desired string followed by the substring modifier.The substring modifier is twonumeric arguments enclosed within square brackets. The substring modifier takes on twodistinctformats:

[beginning—position ,ending—position] [beginning—position; substring—length]

Thefirst format defines thesubstring in terms of itsbeginningandending positionswithin the string and uses a comma to separate the two arguments. The second format defines the substring in terms of its beginning position within the string and its length using a semicolon to separate the arguments. The second format basically performs the same functionas the MID$ function. Thebeginning andending positions may are defined as character positions within thestring relative to either the left or right end. A positive value represents the character position relative to the left end of the string with character position 1 representing the first (leftmost) position. A negative value represents the character position relative to the right end of the string with character position —l representing the last (rightmost) position. Assume the following string has the letters ABCDEF in it. The positions are defined in termsof positions 1 through 6 (left—relative) or positions —l through —6 (right—relative)

A B C D E F (6 characters within main string) 1 2 3 4 5 6 (left—relative position values) —6—5 —4 —3 —2 —l (right—relative position values) Allowing negative values for right—relative positions providesthe ability to pick out digits within a numeric string without havingto calculate the total size of the string first and then work fran the left. The substring—length argument used by the second formatmay also take on negative values for a more flexible format.Normally the length is a positive value which represents the number of characters countingthe beginning position and incrementing the index to the left.A negative length causes the index to move to the right and returns a substring whose last character is theone marked by the beginning—position argument.Confusing?Perhaps a few examples may clarify the use of substring modifiers.Assume the main string is A$ and it contains the above example of "ABCDEF".The following substrings will be returned:

A$[2,4] equals BCD A$[2;4] equals BCDE

16 A$[3,3] equals C A$[3;31 equals CDE A$[—3,—2] equals DE A$[3,—2] equals CDE A$[3;—2] equals BC A$[—3;—2] equals CD A$[4;l) equals C A$[4;—l] equals C

Any position values or length values which would cause thesubstring to overflow outof either endofthe main string will be truncated at the string end. A$[3,l0] equals CDEF A$[—14,34] equals ABCDEF

The main string to which the substring modifier is applied is actually any expression and need not be a defined single string variable.

=(A$+B$+C$),[2;lO] =("ABLE"+A$4-"34")[4,101

The modeindependence feature allows substring modifiers to be applied to numericexpressions.A string is returned but ifthedestination is a numeric variable anotherconversion will be made on the substring to return a numeric value.

Q =(AB)[2,5] PRINP X[3,4]

Substringmodifiers may be applied to subscripted variables or expressions containing subscripted variables. The substring modifiers are independent functions not to be confused with subscripts.

=A$(3,4)[2,5] =(A$(l)+B$(3))[—5,31

Substringmodifiers return a string value.These may be used the same as strings in expressions.

=P4+B$[2;5]+(A$[2,2]+C$)[—5;—3]

Substring modifiers may be applied to theleftside of an assignment in order to alter a ubstring within a string variable.Only that portion of the string definedby the substring modifier will be changed.The other characters in the string will not be altered.This may not be applied to numeric variables. A$[2,4] = Inthe above example, if A$ had contained "ABCDEF" before the assignment was executed the result in P4 would be "AQRSEF".

17 MEMORY MAPPING SYSTEM

AlphaBasic derives much of its versatility and speed from the fact that it is a true compiler in its execution mode.Memory storage is allocated during compilation for all defined variables in an area that is contiguous and predictable.All variables are referenced by the compiled program code through an indexing scheme.Each variable in the working storage area contains an item in the index area which contains all information needed to define and locate that variable.The working storage area therefore contains only the pure variables themselves without any associated or intervening descriptive information. The index area is a separate entity physically located before the working storage area in memory.

The allocation of the variable storage area for anyprogramis predictable and normally done as each variable is encountered during compilation.Since this schemeis not easily followed by the user, a different method must be derived which can override normalallocationprocesses for those users who wish to have the variables allocated in a predetermined manner. The disk I/O system also requiresthat the variables used be' in a specific relationship to each other when used in the more advanced modes.The MAP statement has been incled in AlphaBasic for the purpose of allocating variables ina specific manner. MAP statements are non—executable at run time but merely direct the compiler in the definition and allocation of the referenced variables.Each M7\P statement contains a unique variable name to which the statement applies.When the compiler encounters this statement it allocates the next contiguousspace in working storage as required and assigns it to that variablename.The type of the variable is also specified in this statement andmay be used to override the standard naming conventions of BASIC.All variables not defined in a MAP statement will then automatically be assigned storage insequence for total compatibility with existing standards. As has been noted previously, this memory mapping system is primarily required for advanced disk I/O techniques and to assist in linking with assemblylanguage routines.Special functions are provided to deliver the absolute addresses of these areas as parameters during assembly routine calls.By knowing the layout of the variables in memory, the user need onlypass the base address of the area to the routine and the routine can then reference all needed variables by indexing techniques.The mapping system does have another distinct advantage to thesophisticated prograninerinthe allocation of arrays. WiththeMAP statementthe user has the ability to override the standardarray allocation scheme and force the allocation to proceed ina more flexible manner. Conventional BASIC arrays are allocated in contiguousmemory for each subscripted variable encountered.AlphaBasic allows several variables to be combined in a single contiguous array whichcan provide efficiency in the manipulation of associated data structures.

MAPSTATEMENT FORMAT Briefly, the MAP statement has the followingsyntax: MAPn variable—name(dimensions), type, size, value, origin

18 (3 MAPn represents the hierarchy of the mapped variable fornesting purposes within other variables of a higher level.It must be within the range of MP3P1 through MAR16. As each mapped variable is assigned it will be automatically included as a part of those variables with a higher level.Level numbers are actually backward with MARl being the highest level and MAR16 being the lowest (or innermost) level in the nesting scheme.Levels need not be sequential as they areassigned. That is, a MAP5statementmay immediately follow a MAP2statement withouthaving dunmy MAP3arid MAP4 statementsintervening if desired. This nesting scheme closely parallels the data division format in the (DBOL language.

To eliminate potential allocation problems all MARllevelvariables will be forcedto begin on aneven address. This allows insuring that certain binary andfloating point variables will begin on word boundaries if desired for assembly language subroutine processing.The AM—ba instruction set performs most efficiently when word data is aligned on word boundaries.Also, floating pointvariables will always be aligned to word boundaries.

VARIABLENAME The variable—name is the name to be given the variable for referencing within theprogram and must follow the rules for Alphaeasic variables. Since the type may be explicitly specified, the user need not follow the normal conventions such as requiring that the string variable names be followed by a dollar—sign for identification. If the variable name is followed by a set of subscripts within parenthesis then the variable will be assigned as an array with the dimensions specified by the subscripts just as if a DIMENSION statement had been used to assign the array. For example, the statement MAP1 A,F assigns a single floating point variable called "A" but the statement MAP1 A(5,lO),F assigns a floating point array with 50 elements in it (5 X 10) just as if the statement DIM A(5,l0) had been executed. Note that since these mapped arrays are assigned memory at compile time and not at run time, the subscripts must be decimal numbers instead of variables.

TYPE CODE

The type code is a single character code which specifies the type of variable to be mapped into memory. The following variable types are implemented in AlphaBasic:

X —unformattedabsolute data variable S —stringvariable F —floatingpoint variable B —binaryunsigned numeric variable

If no explicit type code is entered, unformatted data (type X)is assumed.

Unformatted data is absolute in memory and is usually only used to reference a group of other variables as one unit. Until more specific details on data handling are determined, unformatted data variables should only be moved to other unformatted data variables. For all practical purposes, unformatted data variables are treated like string variables except that they are not terminated by a null byte, only by the explicit size of the variable.

19 String variables are terminated either by the explicit size of thevariable or by a null byte (0)if the string is shorter thantheallocated size. Movinga longstring to a short one truncates allcharacterswhich will not fit into the newstring variable. Movingashort string to a long one causes the remainder of the long variable to befilledwith null (0) bytes sothatthe actual data sizeof the string will be preserved for concatenation and printing purposes. Floating point variables are the normal numeric variables used for mathematical calculations.AiphaBasic supports only one—and—one—half precision floating point variables which require 6 bytes of memory each and give 11—12 digits of precision. Floating point variables must beginon an evenaddress andthe MAP statementprocessor will leave a blank byte between anyfloatingpoint variable andthevariable it follows in memory if that variable ended on an oddaddress. This probably would only cause concern during the mappingofrecord structures for I/O transfers.

Binary variables may range in size from1—5bytes giving fran 8—39 bits of binaryunsigned numeric data or 40 bits of binary signed data.This is handy for the storage of snall integer data such as flags in a single byte or for the storage of memory references as word values with a range of up to 65535 in two bytes. Binary variables are manipulated just like floating point variables with conversions to and fran the floating point format being automatic for calculations. Since all binary variables are converted to floating point format before performing any arithmetic calculations, binary arithmetic is actually slower than normal floating point arithmetic and is used mainly for compacting data into files and arrays where the floating point size of 6 bytes is inefficient,when conversions from floating point to binary are done, any data that will not fit within the defined size of the target variable will merely be lost with no error message given.Range checks, where required, are the responsibility of the programiter prior to moving a floating point number to a binary variable area.The best way to understand this is to play with a few examples in irediate mode. Please take note that the use of binary numeric variables is not allowed in some instances.FOR—NEXT loops may not use a binary variable as the target variable although they may be used in the FPCM, '10 and STEP value expressions.The record number key in a random mode OPEN statement must be floating point als. The result variable of a ICOKUP statement must be floating point.

SIZE

The size parameter in the MAP statement is optional but ifused,itmustbe a decimal number specifying the number of bytes in the variable.If itisomitted itwilldefault to 0 for unformatted and string types, 6 for floating point types, and 2 for binary types.The size parameter of floating point variables must be 6 or omitted.

VALUE An initial value may be given to any mapped variable by including any valid expression inthevalue parameter.This value may be a numeric constant, a string constant, or a complete expression including variables. Remember,

20 however, that the expression is resolved when the MAP statement is executed at runtime and the current value of any variable within the value expression is the one used to calculate the assignment result.MAP statements may be executed more than once if it is desired to reload the initial values. Note that if the size parameter is omitted (such as for floating point variables) but the value parameter is used there must be an extra conina to indicate the missing size parameter. MAP1 PI,F,,3.14159 MAP1HOLIIDAY,S,lO,"CHRISIt4AS"

Thefirst example preloads the value 3.14159 into thefloatingpoint variable called P1. The second example preloads the letters CHRISThASintothe string variablecalled HOLIDAY.

ORIGIN In some instances it may be deirable to redefine records or array areas in different formats so that they occupy the same memory area.For instance, a file may contain several different record formats with the first byte of the record containing a type code for that record format.The origin parameter will allow you to redefine the record area in the different formats to be expected. when the record is read into the area the type code in the first byte can be used to execute the proper routine for the record type.Each different routine can access the record in a different format by the different variable names in that format.All record formats actually occupy the same area in memory.This feature directly parallels the "redefine" verb in the COBOL language data division. Normally, a MAP statement causes allocation of memory to begin at the point wherethe last variable with the same level number left off. The origin parameter allows this to be modified so that allocation will beginback atthe base of some previously defined variable and therefore overlay thesame memory area. If the new variable is snaller than the previousone (or the exact same size) it will be totally contained within the previous one. f it is larger than the previous one it will spill over into newly allocatedmemory or possibly into another variable area of the same level depending on whether there were more variables following it. (Play with this one a while to get the hang of it)

The origin parameter must be the last parameteron the line and takes the format @TAG where TAG is a previously defined mapped variableon the same map level. If size and value parameters are not included in this statement theymay be omitted with no dummy comas if desired.

The following statements define threeareas which all occupy the same 48—byte memory area but which may be referenced in three different ways:

100 MPPl ARJAY 110 P4AP2 INDEX(8),F 200 MAP1 ADDRESS,@ARRAY 210 MAP2 STREET,S,24 220 MAP2 CITY,S,14

21 230 MP3P2 STATE,S,4 300MPPl IflJBLE'ABRAY, @ARRAY 310 MAP2 UNIT(6) 320 MAP3 CODE,B,2 330 MAP3 RESULT,F Statements 100—100 define an array with 8 floating point elements for a totalof 48 bytes in memory.Statements 200—230 define an area with three string variables in it for a total of 42 bytes.Normally this area would follow the 48—byte ARRTY area in memory but the origin parameter in statement 200 causes it tooverlay the first 42 bytes of the ARRAYareainstead, Statements 300—330. define another array area of a different format with 6 elements, each element beingcanposed ofone 2—byte binary variable (CODE) and one floating point variable(RESULT). The origin parameter in statement 300 also causes this area tooverlay the ARRAYarea exactly. Caution: The above schemeallow variablesto be referenced in a different formatthan whenthey were entered into memory. If you load the 8 elements INDEX(l) through INDEX(S) with floating point values and then reference the variable STPEEYI'asa string you will get the first four floating point variables,INDEX(l) through INDEX(4),which will look very strange in string format!

EXAMPLES The following two statements produce identical arrays:

100DIM kl(l0) 110 MAP1Al(l0),F

Bothstatementsproduce arrays containing ten floating point variables referenced as Al(l) thru Al(lO). Statement 110, however, will define its placement in memory in relation to other mapped variables. Similarly, the two statements at 300 and 310 produce the same two—dimensional array as the statement at 200:

200 DIM B1(5,20) 300 MAP1BX(5) 310 MAP281(20),F

Inspect the following statements:

400 DIM Cl(lO) 410 DIM 01(10) 500 MA.PlOC(l0) 510 MAP2 C1,F 520 MAP2Dl,F

The statements at 400 and410produce twoarrayseach with ten variables. The statements at 500, 510 and 520 produce one array with twenty variables in it. Thevariables will still bereferenced as Cl(1) thru C1(10) and D1(l) thru Dl(10) but their placement in memory is quite different.The Cl variables will beinterlaced with theDlvariables gWingCl(l), D1(l), C].(2), 01(2), C1(3),

22 Cl(lO), D1(lO).There arealso ten unformatted variables CX(l) thru CX(1O) whicheach contain the repective pairs of Cl—Dl variables in tandem. Referencing one of these CX variables will reference a 12—byte unformatted item cartposedoftheCl—Dlpair of the same subscript.This typeofformatting would be useful in sophisticated techniques only. Thefollowing define a more canpiex area:

100MAP1 ARRAY! 110 MAP2 UNITX(5) 120 MAP3 SIZA,B,2 130 MPJP3 SIZB,B,2 140 MAP3 NItYT,F 150 MAP3FLThG(10) ,B,l 160 MAP3 CNANE,S,20 170 MA.P2IOTAL,F 180MAP! THING,F 190 MAP1 WORK1,X,40

Thearea that is allocatedbythe abovestatements requires a total of252 bytes of contiguousmemory storage. A total of 3 levels are represented in various formats. Statement 100 defines a level 1 unformatted areacalledARRAY! which is subdivided into two level 2 items.Statement 110 defines the first of these which is an area called UNITX. Theoptional dimension indicates that 5 of these identical areas exist which must bereferenced in the programby the subscripted variable names UNITX(l) thru UWITX(5).Each one of these areas is then further subdivided into five level 3 items (statements 120—160).Since the level 2 is subscripted because it occurs 5 times, so must each of the level 3 items be subscripted.There are 5 variables named SIZA(1) thru SIZA(S) occuring once in each of the respective variables UNITx(1) thru UNITX(5). Thesame holds true for the variables SIZB, N'Iclr, and CNJME.Statement 150, however, creates a special case since it contains a dimension also.Normally this would create an area of 10 sequential bytes referenced as FLAG (1)thru FLAG(lO). Inour example, however, this 10—byte area will occuronce in each of the higher level areas of UNITX(1) thru UNITX(5).This implicitly then defines a double—subscripted variable ranging from FLAG(].,1) thru FLAG(5,lO).Statement 170causes the allocation to return to level 2 where one floating point variable is allocated. Thetotal storage requirement for the level 1 variable ARRAY1canes out to 206 bytes as follows:40 bytes for each of the five areas UNITX(1) thru tJNITX(5) plus 6 bytes for the one variable IYYTAL.Notice that since 'IOTAL starts a new level 2 it does not occur 5 times as do the level 3 items which canprise UNITX(l) thru UNITX(5). Following the above mess in memory cane two more variables defined in statements • 180 and 190.THING is a normal floating point variable which occupies 6 bytes andWDRK1is an unformatted area whose size is 40 bytes.Note that since WDRK1 was not subdivided into one or more level 2 items a size clause was required to explicitly define its storage requirements.'Ibtal storage used by theabove series of statements (100—190)is 252 bytes.

Notethat the variable UNITX(1) refers to the 40—byteitemcanprisedof the variables(in order) SIZA(1) , SIZB(l) , NTOP(l) , FLPG(l,l)thru FL1G(1,l0) ,and CNANE(l). Moving the variable UNITX(1)to another area such as WDRK1 will

23 transfer the entire 40—bytes with no conversions of any data.fl can be seen that although this mapping system includes advanced prograutning practices, it provides the user with a degree of flexibility never before offered in a BASIC language implementation.

USING THE MAP STATEMENTS Map statments may be used in immediate mode as a learning tool to see how the variables are allocated.They are not designed to be practical in the ininediate mode, however, and are best used by putting them into a program file and ccrnpiling the program.In the ininediate mode, if an error occurs in the syntax of the statement, the variable will have already been added to the tree and you will not be able to repeat the map statement again. MAP statements should normally come at the beginning of the program before any references to the variables being mapped.Ifa reference is made to the variable before it is mapped (such as LET A=5.8)the variable will be assigned by the normal variable allocation routines arid the MAP statement will then give an error since the variable is already defined.rs a convenience, all MAP1 statements force allocation to the next even byte boundary so that binary word data can be assigned properly if desired. Due to the canplexity of the syntax checking used for the MAP statement, no syntax analysis is performed on them until the program is canpiled (unless the MAP statement is used in the inuediate mode).If you wish to check the syntax of your progress during the entering of a group of MAP statementsyou may force ccxnpilation and syntax checking of your partialprogram with the Ct(4PILE ccxnmand. This will indicate your progress so far and also define all mapped variables up to this point so that you may interrogate then with the "@"cam'iand described in the followingsection.

LOCATINGVARIABLES DURING DEBUGGING Since the mapping scheme is new and fairly ccxnplexto understand fully, a conmarid has been implemented which will assistyou in locating the mapped variables and in understanding the allocation techniques used by theAlphaeasic memory mapping system.It is valid only as a system caunarid and has no meaning if used within a program text.The cc*umand has the general format of an atsign (@) followed by a variable name.If the variable name is not followed by a subscript, the system will search for the requested variable and printout all parameters about the variable for you on the terminal.This may actually be two definitionssincethe variable "A" may actually be two different variables,one which is a single floating point number andonewhich is a subscripted array. The information returned about the variable will be thetype of variable (string, binary, etc), the dimensions of thearray if the variable is indeed an array, the size of the variable in bytes, and the offset to the variable fran the base of the memory area used to allocate all variables.If you enter a reserved word (such as @PmRT) the system will tellyouthatthe name is a reserved word.Pemember that the current system will not allowyou to begin a variable name with a reserved wordso that PRINTSUM is also considered a reserved word at this time.

24 The general format of the definition line which is returned by the system is:

fmemory—type} {variable—type} {diiuensions}, {SIZEn},{location}

Memory—typeis the method of allocation used for the variable being defined. FIXED variablesare those which have not been defined by a W'JP statement and wereallocated automatically by the compiler when they were referenced in the program. Thisis the normalmethodused by other BASIC versions to allocate variables. DYNAMICvariablearrays are those arrays which were allocated by a DIM statement or by a default reference to a subscripted variable. MAP1through MAP16 variables andvariablearrays are those which were defined in a MAP statement.

Variable—typeis the typeofthe variable andmaybe UNFOPMATPED,STRING, Ft/DATINGPOINT,orBINARY.

If thevariableis an array the dimensions will be listed after the variable typecodein the format ARRAY(n,n,n)where n,n,n are the values of the subscripts in use by the array.If the array is dynamic and has not been allocated yet the subscript v4ues will be replaced by the letter "X" to indicate that they are not known at this point.Remember that any variable defined in a MAPstatementwhich is in a lower level to another variable will inheritallsubscriptsfrom that higher level variable.

The size of the variable will be given in bytes. In the case of arrays, the size will represent the size of each single element within the array.

The location of the variable is a little tricky to explain since it is actually an offset to the base of a storage area set aside for the allocation of user variables. As each new variable or array is allocated it will be assigned a locationwhich is relative to the base of this storage area.The location information is givenhere to help you understand the relative placement of the variablesin the mapping system and does not represent the actual memory locations which they occupy.There are two distinct areas in use for variables andthus the offsets of the variables will be to one of these two areas. All FIXEDand MAP1 through MAP16 variables are allocated in the fixed storage area while all DYNAMIC arrays are allocated in the dynamic array storage area. As dynamic arrays are dimensioned andredimensionedtheir position may shift around relative to one another andrelativeto the dynamic storage area base. Variables in the fixed storage area will never change position relative to each otheror to the storage area base.

Arraylocation information is given only pertinent to the base of the array itself which is the location of the first element within the array.The actual range of locations used by the array may or may not be contiguous in memory depending on whether overlapped dimensioning techniques are beingusedin the MAP statements. Simple (non—array) variables are defined as a location range which tells exactly where the entire variable lies within the storage area. If you want to find out where a particular element of an array is located you may follow the variable—name by the particular subscript values (decimal numbers only) of the element you wish to locate, given the twocommands:

@A(4,l2)

25 The first cctmnand liiigiveinformation about the array "A" while the second coitrnani will define the exact location of element A(4,12) within the array "A".

Keep in mind that this "@"commandis to assist you in following the allocation of variables, particularly in more complex mapping schemes.A few minutes at the terminal with immediate mode MAP statements followed by "@"commandswill help you see how the mapping scheme works.

26 Itfl'ERA.CTIVE (DMMAND SUMMARY

WheneverAiphaBasic is not either compiling or executing a programit will be in interactive canmand mode which means it is waiting for a command fromthe user terminal to initiate sane action.The action taken depends on the type of• input enteredby theuserwhich will fall into one of the following maincategories:

1.Edit commandwhichbegins with a valid source line number 2. Program statement for immediate execution (no line number) 3. Interactive system coninandresultingin a controlled action

Editcommandswill allow the creation andediting ofa source program in memory on a single line basis. The line number must be first followed by the program statement which will d the line to the source format in proper numerical sequence. If the line contains only the line number, the line will bedeleted fromthe program.No fancy character editing commands are implemented in this version. Program statements without line numbers result in the immediate compilation and execution of the statement entered.These program statements will be covered in anothersection. The remainder of this section will briefly list theavailable interactive commands and the corresponding action performed.

NEW This command clears out all current source code, object code, user symbols and variables.It effectively initializes the compiler to accept new source program statements or imrrgnediate mode statements.

LIST

Thesource program (if any) is listed in numerical sequence on the user terminal. If no line numbers follow the LIST commandthe entireprogram will be listed. The listing may be abortedbyentering control—c on the terminal which will return the user to interactive command mode. If one line number follows the LIST commandonlythat line number will be listed. If the commandis followed by two line numbers separated by a comma, space or other non—numeric character, only those lines which fall within the range boundedbythe two numberswill be listed.

DELETE The DELETE command is used to delete groups of source lines from the program text.If the command is followed by a single line number, only that line will be deleted.If the command is followed by two line numbers separated by a comma, space or other non—numeric character, all lines of text which fall betweenthetwo linenumbers inclusive will be deleted from the text.

27 SAVE The entire source program is saved on the disk in the user's file area.The usermustenter the name of the program (1—6 characters) following the SAVE command. The program will be saved with the extension "BAS" and will be in ASCII format which may be listed or edited with the normal system programs outside of AlphaBasic.If a previous version of the program (same name) already exists onthe disk in the current user's file area that program will first be deletedbefore the new program is saved.No backup file will be automatically created.In actual practice, the program name may be a full system file specification if desired. The SAVE command may also be used to save the compiled object program ondisk for laterrunning withoutrecompilation. ¶LD save the object program the user enters the programname followed bythe explicit extension "RJN" whichcauses theprogram to be compiled if necessary andthenthe object program to be saved on disk. The following twoexamples willshow how the SAVEcatimandis used to save first the source program andthentheobjectprogram:

SAVE PAYDL (saves source as PAYJCL.BAS) SAVE PAYROL.RUN (saves object as PAYK)L.RIJN)

LOAD

Thespecifiedprogramwhose name must follow the LOAD commandislocated on disk in the current user'sfile area and then loadedintomemory for editingor execution. This is the reverse of the save function above.The program is expected to be in ASCII format with the default extension "BAS" unless explicitlyentered as otherwise. If the program cannot be located an error message will result. In actual practice, the program name may be a full file specifier if desired.

The load command does not clear the text buffer before it loads the requested file and therefore may be used to concatenate or merge several programs or subroutines together to be saved as a single program. The separate routines must not duplicate line numbers in the other routines that they are to be merged with or else the new line numbers will overlay the old ones just as if the file had been edited in fran the user terminal. The NEW cc'nznand should be used prior to any load command if it is desired to insure that the text buffer is clear.

CY4PILE

The current source program in memory is compiled and the objectcode builtup in another area of memory. Control then returns to interactive camiand mode. The compiled program is not executed. Compilation effectively sets all variables to zero and deletes all variables that may have been generated as a direct result of immediate mode commands.

28 JN This is the normal way to initiate the running of the existing program in memory. A check is first made to see if the program has been compiled since the last editing change to the source code and if it has not been, an automatic compilation phase takes place to insure the object code is up to date.All variables are reset to zero (strings are reset to null) and the compiled object code is then executed.Execution may be interrupted at any time by typing a - control—con the user terminal.This control—c status is tested only at the beginning of each new source line so multiple statement lines will not be interrupted until all statements on that line have been completed.

CONT The execution of the program is continued from wherever it last left off.This is normally done after a control—c interrupt, a program STOP statement, a breakpoint interrupt, or a single—step sequence.A program may not be continued afterithas come to the end of the statements.

CONTROL-C Depressing the control and c keys simultaneously will interrupt any program that is currently runnjng and return to coninand interpretive mode.If a program was being executed the line number about to be executed will be printed vai the message "INTERRUPTED AT LINE nnnn".The program may be continued by the CON']? or single—step commands or it may be restarted from the beginning by the RUN coirmand.

SINGLE—STEP (line—feed key) The single—step function is a feature not found in other versions of BASIC but is very useful in debugging programs and in teaching the principles of BASIC programming to newcomers.The single—step function causes the current line in the program to be listed on the user terminal and then executed.Any output generated by the execution of a PRINT statement will then follow on the next line.After the line has been executed the execution pointer is advanced to the next line and control returns to the user in the interactive command mode. Successive single—step coninands may be used to follow theprogram through its paces.Single—step is legal after program STOP statements, breakpoint interrupts, control—c interrupts, and other single—step functions.Note that the single—stepfunction is performedby hitting the line—feed key and not by actually entering the words "single—step".

BREAK

This is a feature not normally found in other versions ofBASIC which allows the user to set breakpoints on one or more line numbers in a program.During execution if a line that has a breakpoint seton it is encountered the program will suspend execution and the message "BREAK NP LINE nnnn" will be printed. The system will then be in interactive caintand mode to allow the inspectionor

29 changing of variable values.This suspension of execution occurs before the line that has the breakpoint seton it is executed.There is no limit to the number of breakpoints that may be set in oneprogram.There is no additional overhead paid in execution speed when breakpointsare set.Breakpoints may be cleared by placing a minus sign in front of the line numberor by compiling the program which always clears all breakpoints.If no line numbers follow the BREAK camnand all current breakpoints will be listedon the user terminal. For example:

BREAK Lists all currently set breakpoints BREAK 120 Sets a breakpoint at line 120 BREAK —120 Clears the breakpoint at line 120 BREAK 120,130,40,500 Sets breakpoints at lines 120,130,40, and 500 BREAK—50,60 Clearsthe breakpoint at 50 and sets one at 60 Once a breakpoint has been reached theuser may optionally continue the execution of the program by eithera CDRP command or a single—step command.The breakpoint ranains set after it has been reached untilexplicitly cleared by another BREAK or CDMPILE command.

DELETE The DElETE command is used to deletegroups of source lines from the program text.If the conutand is followed by a single line number, only that line will be deleted.If the command is followed by two line numbers separated bya coinna, space or other non—numeric character, all lines of text which fall between the two line numbers inclusive will bedeleted from the text.

BYE

This says goodbye to basic and returns theuser terminal to monitor ccmmand mode. Any program left in memory is lost foreverso you may want to save it first using the SAVE command.

30 PRX3RAN STATE14ENTS

Thesource program contains statements which are executed insequence, one at a tthe as they are encountered.Each of thesestatementsnormally starts with a verbfollowed by optional variables or statements modifiers. This section will list the program statements thatare supported by AlphaBasic and give some examples where necessaryfor clarity.

LET Assignsa calculated value to a specific variable during executionof the program.It is uniqueinthat the actual word "LET" may be omittedif desired. LET AS =12.4 LET SUM(4,5)=Al+SQR(B].) LETC$ ="JANUARY" AS =12.4 SUM(4,5)=Al+SQR(Bl) ="JANUARY"

(3010

The (3010 statement transfers executionof the program to a new statement location.This statement location must be eithera line numberora label defined somewhere in theprogram.The line number or label must follow theGOlD statementin the program. desired. The (3010 statement may be broken apartas GO 10 if

GOSUB —CALL—RETURN Calls asubroutine which starts with the linenumber or label following the GOSUBor CALL verb. The subroutine exits via the RETURNstatement which returns control to the statement following theGOSUB or CALL statement. Executing a RF7IUPN statement without first executinga GOSUB statement will result in an error message. Both GOSUBand RETURNare currently illegal in immediatemode. Notethat the CALL verb is merely anotherway of specifiying GOSUB for those programmers used to this verb from otherlanguages. cv.Gcyio

TheON (3010 statement allows multi—path(3010 branching to one of several points within the program based on the result of evaluating an expression. The actual format is:

ON expression (3db pointl, point2, point3,...pointw The expression can be any validexpression which will be evaluated downto a positive integer result. The result will then be tested to branchto pointl if 1, point2 if 2, point3 if 3, etc. If the result is zero, negativeor greater

31 than pDintN the program will fallthrough to the next statement,The points (pointl through pointN)may be line numbers, labels orany misture of the two.

ON...GOSUB The ON GOSUB statement parallelsthe ON 0320 statement in formatand operatjon except that pointl through pointNrepresent entries to subroutines that willbe executed based on the result of theexpression evaluation.As with the ODSUB statement, the verb CALLmay be used in place of the verb GOSUB giving CALLstatement. an ON

READ -DATA-RES1ORE

These calls allow data to bean integral part of the sourceprogram with a method for getting this data intospecific variables in DATA statements an orderly fashion. are follod by one or more literal valuesseparated by commas. String literals need not beenclosed in quotes unless the literal a comma. data contains All data statementsare placed into a dedicated area inmemory no matter where they appear in thesource program.READ statements are followed by one or more variables separated byccnrias.Each time a read statement is executed the next item of datais retrived fran the DATAstatement pool arid loaded into the variablenamed in the read statement.If there is no more data left in the data poolan error message results and the RESIORE statement is used program is aborted. The beginning again. to initialize the reading of thedata pool fran the DATA 1,2,3,4,5 DATA 2.3,O.555,cqFJSTRfl,E,"4,4" READA,B,C READ A$ READ C(2,3),B$(4) RESIDRE The READ statement is also used for reading data fromrandom access files.For details on this refer tothe section describing the fileI/O system.

Allows data to be enteredfran the user terminal andloaded into specific variables at execution time.The rwpryrstatementcontains one or more variables separated by camnas.When the INPUT statement isexecuted a single question mark is printed on theuser terminal to signal the request for Numeric variables require data entry. formats. the data to be in one of theacceptable floating point String variables requirethe data to be an ASCII stringof characters. If multiple variablesare used in one INPUT statement theuser is expected to enter multiple valuesseparated by carras sufficient variables called out.If insufficient data is enteredto satisfy the number of will be printed to signalthe need for additional data.a double question mark INPUT Al INPUT B$,C$,Q(8)

32 If the user entersa blank line (carriage—return only) inresponse to a request for input, the previous valuesof all variables will remainunchanged and the program will proceed to the nextstatement.This effectively bypassesthe entire input statement (orthe remainder of a partial datarequest).If a control—c is entered inresponse to a request for data the inputstatement is bypassed (as witha carriage—return) and the program is interruptedat the next statement following the inputstatement. or single—step commands. The program may be resumed bythe CONT The user may cause hisown prompt character or character stringto be printed in place of the standard questionmark by enclosing the string inquotes immediately following theINPUT verb.

INPUT "ENTER YOUR NAME: ",A$ INPUT "ENTER 3 VALUES FORX, Y AMO2: ",X,Y,Z The INPUT statement is also used forreading data fran sequential files.For details on this refer to thesection describing the file I/Osystem.

INPUT LINE

The INPUT LINE statementoperation is identical to thatof the INPUT statement with the exception that inputinto a string variable willaccept the entire line up to but not including the carriage—returnand line—feed.This allows commas, quotes, blank lines and otherspecial characters to be inputwithout the need for quotes around them.The INPUT LINE statementmay be used in sequential file processing as well as thestandard terminal inputstatement.The question mark prompt character is never printedfor an INPUT LINE statementbut the user may include his own promptstring as in the INPUT the statementare: statement above.Sane examples of

INPUT LINE A$ INPUT LINE "ENTER YOUR FULLNAME, PLEASE: ",NAME INPUT LINE #2, LINE'OF'INPUT

PRINT Theprint statement performsthe same as other versions detailed extensively inthis first printing. of BASIC and will not be printed on the Multiple variables or literalsare same line separated by commasor semicolons.Commas cause the next variable to beprintedin the next zone while variablesto be printed with semicolons cause the no separating spaces. If the line ends with semicolon the carriage a return will be suppressedso that the next PRINT statementexecuted at somelater time will For resume printing on the same line. compatibility with otherpopular BASIC implementations,Aiphasasic also recognizes the singlequestion mark as an alternateform of the PRINT verb.

PRINT USING is supported for formatted output andisdescribed in another section reserved for thatpurpose alone. The PRINT statement is also used for writing datato sequential files.For

33 details on this refer to the sectiondescribing thefileI/Osystem. ( FOR-NEXT-STEP These statements allow the execution of loopswithin the program and follow the same format and restrictions as other forms ofBASIC. The variable used may be subscripted if desired.If no S'FEP modifier is used the step value isassumed to be a positive 1.The variable name may be anitted in the NEXTstatement if desired in which case the previousFOR statement will be the one that is incremented.All normal rules for nested loops and enteringor exiting fran within the loops apply hereas in other BASIC versions.FOR and NEXT statements are illegal in inutediate mode.

FOR A =110 10 FOR B =Al/Bl10 Cl STEP 2 FOR A =1010 1 STEP —l

IF —THEN — ELSE The conditional processing featuresin AlphaBasic give a wide variety of formats which duplicate just about allfunctions performed by other versions of BASIC. The formats that are acceptableare:

IF THEN IF THEN ELSE IF IF ELSE IF THEN IF THEN ELSE The above formats may be nested toany depth and rather than go into detailwe suggest that you play around with themto determine the actual restrictions that exist. Sane examples: IFA=STHflJUO IF A>l4 THEN 110 ELSE220 IF B$="END" PRINT "END OF TEST" IF IOTPIL > 14.5 GCY1D 335 IF AA=5ANDBB=6 IF CC=7PRINT 567ELSEPRINT 56ELSEPRINT "ICNE" IFA=1 PRINT 1 ELSE IF B=2 THEN 335ELSE345

DIM

The dimension statement definesanarray which will be allocateddynamicallyat executiontime.There is no limit to the number ofsubscripts that may be used to define the individual levels withinthe array.The statement DIM A(20) defines an array with 20 elementsreferenced as A(l) through A(20).Multiple arrays may be dimensioned bya single DIM statement by separating them with conTuas. Subscripts are evaluated atexecution time and not at canpile time thereby

34 allowing variables to be usedas subscripts instead of fixed values. The statement DIM A(B,C) will allocate anarray whose size will depend on the actual vaules of B andCat the time the DIM statement is executed.

Stringarrays may also be allocated such as DIM A$ (5). Thesize of the array willdepend on the current default string size ineffect as specified by the lastSTRSIZ since each element inthearray must bethis number of bytes. Arrays may be redimensioned during the execution of theprogram if desired.The number of subscripts must remainthesame but the number of elements in each level of the array may bechanged. Each redimensioning of an existingarray effectivelyerases the old array first and then allocatesa new array with all elements zeroed out.

DIMA(l0) DIMC(8,8), C$(lO,4) DIM TES'r(A,B*4) DIM A(B(4))

SIGNIFICANCE

The significance statement allows theuser to dynamically change the default value of the numerical significance ofthe system for unformatted printing.The significance valuecan be any value from 1 through 11 and will represent the maximum number of digits to be printedin unformatted numbers.Rounding off to the specific number of digits willbe performed only prior to the actual printing of the result.The statement SIGNIFICANCE 8 willset the number of printabledigits to 8. The value is interpreted atruntimeand any therefore may be validnumeric expression including variablesif desired. The current significance of the system. is ignoredwhen PRINTUSINGis in effect.

Note that the signifcance statementonlyaffectsthe final printed result of all numericcalculations.The calculations themselves and thestorage of intermediateresults is always performedin full11—digit precision to minimize propagation of errors. Thesignificance of the system is initiallyset at 6 digits when the system is first started.This is equivalent to standard most of the popular versions of single—precision formats used in BASIC. The significance is not reset by theRUN coirruand and therefore may be set inilimediate mode just prior to the actual running of a test program.Of course, any SIGNIFICANCEstatements encountered during the execution of theprogram will reset the value.

STRSI Z

Thestring size statement sets the default value for all strings whichare encountered for the first time duringthe compilation phase. Initially, the default value of all strings in the absence of a STRSIZstatement is 10 bytes. The statement STRSIZ 25 would cause all newly allocated strings which followto have a maximum size of 25 bytesinstead of 10 bytes. This includes the allocation of string arrays. The size value is evaluatedat compilation time and thereforemust be a single positive integer.

35 RANI)DMIZE

Resets the random numbergenerator seed to begina new random number sequence starting with the nextPND(x) function call.

Slop

Causesthe program to suspendexecution and print the message LINE nnnn" and thenreturn control to the "PR(XRAM STOP AT The user may then continue user in the interactive coirmandmode. with the next statement insequence by executing a CONT corrnrtand or withsingle-step coninands.

Causes the program toterminate execution andreturn to the READY mode statement does not terminatecompilation of the • TheEND the end of theprogram. program nor is it required at

OTHER VERBS AlphaBasic supports otherverbs which are described fully go into the detailsof their operation. in separate sectionsto more elsewhere: The following verbsare described

SCALE —scaledarithmetic modifier CHAIN —executesa new program or ccnnand file CN ERROR — controlserror trapping and processing OPEN — opensan I/O file for processing CLOSE —closesan I/O file to further processing WRITE —writea record to a randomaccess file KILL —deletesa file from disk ALLOCATE — allocatesa random access file LOOKUP on disk — searchesfor a file and returns XCALL• its size — executesan external, assembly language ISAM subroutine• — facilitatesprocessing of indexed sequentialfiles

36 BASIC FUNCTIONS

Thefollowing is a ljst of thecurrently impleplented functions Whichare available for use in expressions.Note that the mode independence featureof the expression processor willperform autanatic conversions ifa numeric argument is used where a stringargument is expected and viceversa.

EXP(X)

Returnsthe constant e (2.71828) raisedto the power X.

LOS(X)

Returnsthe natural (base e) logarithmof the argument X.

rn3lo

Returnsthe decimal (base 10) logarithmof the argument X.

SQR(X)

Returns the square root of theargument X.

INr(x)

Returns the largest integer lessthan or equal to theargument X.

FIX(X) Returns the integer part ofX (fractional part truncated).

FACr(X)

Returns the factorial ofX.

ABS(X)

Returnsthe absolute value of theargument X.

SGN (X) Returns a value of —1, 0or 1 depending on the sign of the if Xis negative, 0 ifXis 0 and 1 if x is positive. argument X.Gives —1

37 RND(X)

Returns a random number: generated -bya pseudo—random number generator based ona previous value knot as the "seed".The argument X dontrols the number to be returned.If X is negative it will be usedas the seed to start a new sequence of numbers,if X is zero or positive the nextnumber in the sequence will be returned depending on the current valueof the seed (this is the normal mode). The RPN]XtlIZEstatement may be used to createa seed which is truly random and not based on a fixed beginning valueset by the system.

MR4(X) - Returnsa positive integer value which specifies the numberof bytes currently in use for variousmemory areas used by the compiler system.The most coninon use of this is with an argument of 0 whichreturns the number of free bytes left in the user memory partition.This MEM(0) call duplicates the actionperformed by the FRE (X) function in otherversions of BASIC.Other values of the argument X return memory allocations whichpertain to various areas inuse by the compiler and may ormay not be of use to you.The byte counts returned for the various values of Xare: 0 —Freememory space remaining in currentuser partition 1—Totalsize of current user partition 2 —Size of source code text area - 3 — Sizeof user label tree - 4 —Sizeof user symbol tree (variablenames and user function names) 5 —Sizeof compiled object codearea 6 —Sizeof data pool resulting from allcompiled DATA statements 7 —Sizeof array index area (dynamic linksto variable arrays) 8 —Sizeof variable storagearea (excluding arrays) 9—Sizeof file I/O linkage and bufferarea

Note that the parameters for valuesabove 1 may change as new versions of the compilerare developed.Also, some of these values will bemeaningless when running the runtime object modulein compiled mode.

EOF(X) The WF function returns is X. a value giving the status of a file whose file number The file is assumed to beopen for sequential input processing. The values returned by the BDF functionare: —l if the file is not openor the file number X is zero U if the file is not yet atend—of—file during input calls 1 if the file has reached theend—of—file condition Due to the method used by theAMOS operating system for processing files,the EOF status will not be validuntil after an INPUT statement whichreaches the end—of—file condition.Any INpuT statements which reachEDF will return numeric zero or null string values forevermore.This means that the normalsequence

38 for processing sequentialinput files would be to INPUTthedata into the variables ar then test theEOF(X) status before actually using thosevariables. the data in

FXJF should only be tested for sequential input files. Files open for outputor for randctn processing willalways return a zero value.

LEFr(A$,X) or LEFT$(A$,x)

Returns the leftmost X charactersof the string expression A$.

RIGHT(A$,x) or RIGHTs (A$,x)

Returns the rightmost X charactersof the string expression A$.

MID(A$,x,y) or MID$(A$,X,y)

Returns the substring composed ofthe characters of the stringexpression A$ starting at the Xth character and extending for Y characters. A null string will be returned if X> LEN(A$).

LEN(A$)

/ Returnsthe length of the stringexpression A$ in characters.

INSTR(X,A$ ,B$)

Performs a search for thesubstring B$ within the string character position. A$ beginning at the Xth it returns a value ofzero if B$ is not in A$ or the character position if B$ isfound within A$. Character position is measured from the start of the stringwith the first character one. position represented as

ASC(A$)

Returns the ASCII decimal value of the first character in stringA$.

CHR(X) or CHR$ (X)

Returns a single character string having the ASCII decimalvalue of X. Only one character is generated foreach CHR or CHR$ functioncall.

39 STR(X) or STR$(X)

Returns a string which is the character representation of the numericexpression X. No leading space is returned forpositive numbers.

VP1L(A$)

Returns the numeric value of thestring expression A$ BASIC format rules. converted under normal

SPACE(x) or SPACE$(x) Returns a string of Xspaces in length.

TRIG FUNCTIONS

The following trig functionsare Eliplemented in full 11—digitaccuracy: SIN(X) Sine of X CDS(x) Cosine of X ThN(X) Tangent of X ATh(X), Arctangent of X ASN(X) Arcsine of X ACS(x) Arccosine of X DNIN(x,y) Double arctangentof X,Y

40 FOR4AnED OUTPUT VIA PRINTusirs STATEMENTS

The PRINT USING statement isan extension of the standard PRINT allows statementwhich the output to be formatted intospecificcharacterpositions suitable for businessreports, formal, text applications,and the like. statement appears as follows: The format of the PRINT USING , (output to terminal) PRINT #, USING , (output to file) The string expression isused to control the formattingof the variables as they are enrountered in the print list andmust match the format of the variablesto be printed. The string may beeither a string constant,a string variable, or a stringexpression which is interpretedas an exact image of the printed. lineto be The list is the sequence ofvariables or expressions to be printed using all the rules of the standard PRINT statement. Allcharactersin the formatting string will be printedas they appear except for the special formatting characters which willbe described below. The string is continually scanned over and overuntil the' list of print items isexausted. The formatting characters andtheirusage in the string are described in the following paragraphs:

EXCLAMPATIaI MARK

An exclamation mark (I)in the format stringcauses the first character of the corresponding string variable to beprinted in the correspondingspace. The rest of the string variable if itexceeds one character will be ignored.

BACKSLASHES

Two backslashes(\) inthe format string definea string field whose size equals the number of characters enclosed by the brackets plus the bracketsthemselves. Normal BASIC syntax dictatesthat the characters between thebackslashes be spaces but Alphaeasic will acceptany characters. If the string variable to be printed exceeds the size of thespecified string field theexcess characters will be ignored. If the string variable is shorterthanthespecified string field, trailing blanks will beaddedtofill out the correct field size.

NUMERIC FIEL

Digit positions within formattednumeric fields are specified in the format string by the pound—sign (#) usingone for each position desired, both in front of and behindthe decimalpoint.One decimalpoint is allowed to define the explicit alignment of the digits withinthenumeric field format.Normally, numericfields are right justified withleading blanks being used to fill in for digitpositions that are not required infront of the decimal point. Unused digit positions behind the decimal point are filled with trailingzeros. If the numeric field specified in the formatstring is toosmallto contain the numeric variable to be printed, the fieldwill be printed witha leading percent—sign (%) indicating the overflow. This will be followed by the number standard BASIC format. in

41 If the formatfield specifies any digitpositionsin front of the decimalpoint, at least one digitis always output beforethe decimal point itself. necessary,this digit is azero. If

Notethat other special characters (described inthe following paragraphs)also definenumeric digit positionsin addition to performing functions. special formatting

ASTERISK FILL If a numeric field in the formatstring begins witha double asterisk (**) any leading spaces thatwould normally beoutput in front of a number will replaced by asterisks. be This is quite useful inprinting checks, for instance. The double asterisk alsodefines two digit positions.

FLOATING DDLLAR SIGN If a numeric field in the format string begins witha double dollar sign ($$)a dollar sign will be printedilnuediately preceding the firstdigit of the number. The double asterisk alsodefines two digit positions, bythe dollar sign itself. one of which is taken up

The above two special functionsmay be combined by starting the numericformat field with the symbols "**$"combinesthe asterisk fill ard floatingdollar sign functions described above.This combination also definesthree digit positions, one of which is takenup by the dollar sign itself.

TRAILING MINUS SIGN If a numeric field isterminated by a minus sign inthe format string, the sign of the output number isprinted following the numberinstead of before it.If the number is negative,a minus sign will be printed.If the number is zero positive, a blank will beprinted. or used, space must be provided Note that if the trailing minus signis not number if it is negative. in the numeric field for thesign to precede the

If the numeric format fieldcontains one or morecommas in front of the decimal point, a conna will beinserted every three digitsto the left of the decimal point when the number isprinted.Each ccituna also definesone digit position in the format field.Coinnas appearing after the printing characters. decimal point will be treatedas

EXPONENT IAL FOPMAT Exponential format may bespecified by following the numeric with four up—arrows(") which defines the field designation value.As with other numerical space taken up by the E NN exponent allowed and the significant formats, any decimal pointarrangement is adj us ted as necessary. digits are left justified withthe exponent being 42 SCALED ARITHMETIC

AlPhaHaSic usesa floating point format which givesan accuracy of 11 significant digits.Unfortunately, thisaccuracy is absolute only when dealing with those numbers whichare total integers in the first 11positions to the left of the decimal point.This fact stems from theconversions that are required from decimal inputto the binary floating point hardware. For most business format used in the users, the actual range of numberscontains two digits to the right ofthe decimal point and nine digits decimal to the left of the point.When the fractional part ofthe number isconverted between decimaland binary formats,a small but significant error is sometimes introduced whichmay propogate into large inaccuracieswhen dealing with absolute dollars—and—centsvalues. AlphaBasic incorporatesa scaling feature which helps to alleviatethese problems by storing all floatingpoint numbers witha scale offset.This offset may be used to effectively designatewhere the 11 absoluteaccuracy digits are located in relation to thedecimal point.This is done by multiplyingevery input number by the scalingfactor and then dividing it out againbefore printing.This is a simplified explanationand many other checks and conversions are done internallyto scaled numbers but that is the generalidea. The scaling factorrepresents the number of decimal places thatthe 11—digit "window" will be effectivelyshifted to the right inany floating point number. For example, the mostcommon application is in a business environmentwhere the scaling factor of 2 would beused to give absolute 11 placeaccuracy which extends 2 places to the right ofthe decimal point.This means that the value of 50.12 will be multipliedby the scaling factor of 2 digits(100) and stored as the floating point value of 5012.Since this value is an integer, it has accuracy. absolute Just before printing this number it willbe divided by the scaling factor to reduce itto its intended value of 50.12 and happy. everybodyis

Other little conversions hadto be included into the system to takecare of all the little subtle effects ofstoring scaled numbers.For example, when converting scaled numbers to integeror binary format, the number must be unscaled first before conversion.When two scaled numbersare multiplied together the result isa number which must be unscaled once.Division of two scaled numbers creates exactly theopposite problem.Dealing with scaled numbers for exponential, logarithmicand trigonometric functions createseven more exotic problems.All these conversionsare done automatically by AlphaBasicandso the programmer is relieved of the task of them. keeping track of

Scaled arithmetic will normallybe entered at the start ofa program andwill continuein effect throughout theprogram.The statement for setting the program into scaled mode is:

SCALE n

The scaling factor "n"must be a decimal digit in therange of —30 to +30 and may not be a variable since scaling is doneat compile time for constant values as well as at runtime for input andoutput conversions.Negative scaling moves

43 the 11—digit windowto the left and for most average prograniner. cases will not be of use tothe A few words of cautionare in order here. detectecj during ccinpilation, Once the SCALE statementhas been all constant values thatfollow are scaled by the scaling factor so thatthey are stored properly.In addition, a runtime is generated in theexecutable program which camnand performed on input and print cauSes the actual scalingto be values when theprogram is running.If two or more different SCALEstatements are executed inthe same program, results may cane outunless the user is totally saite very strange in regards to compile familiar with what ishappening time and run timeconversions.We suggest that you play with this onea bit before delving into it fullsteam. One other word of caution.Floating point numbers thatare stored in files by the sequential outputPRINT statement will beunscaled and output in ASCII no problems.Floating point numbers that with using the WRITE are written to random access files by statement will not be unscaledfirst and any program thatreads this file as input hadbetter be operating in thesame scaling mode or else apply the scale factorexplicitly to all values fromthe file. string values, ofcourse, are never modified regardless Binary and currently in use. of the scaling factor

44 ALPHABASIC FILE I/OSYSTEM

AlphaBasjc supports both sequential andrandomaccessdisk files.Data may optionally be written inASCII or packed binaryformats. AlphaBasic programsare Files created by compatible with all othersystem utility formats andmay be interchangeablyintroduced into andmanipulated languages.Conversely, files by programs written inother may be read and created by other languagesandsystemutilities manipulatedby programs written inAlphaBasic. Files are createdand referencedby the generalstatements OPEN, CLOSE, INPUT, PRINT, READ, and WRITE.Allfilereferences are done by be anylegal integervalue from 1 to 65535. a file number which may number of files that There is no absolute limitto the may be open at any given timeina filerequires a certain program but since each amount of memory there isa practical limit to this number based on availablememory. The file number alwaysfollows the verb in any file I/O statement andmay be any legal numeric expression by a pound sign which is preceded (#). Filenumber zero is definedas the user terminal and is legalin file statementstoallow generalized selectively output to either programs to be writtenwhich may a file or to the terminalat runtime.

All open filesare automatically closed (if statement) when the not closed explicitly bya CLOSE program exits or whena CHAIN statement is executed.No two files may be openedwiththe same file numberat the same time but aftera file has been closed anotherfile may be reopened usingthe same file number if desired.All file statementsare valid in ilunediate mode but automatically closed before any open files are files which each new PUN ccnnnand isexecuted thereby preventing were opened by an inujediatestatement to be writtenor read by statements withinan executable program.Under the current version of .AlphaBasic, eachopen file requires about580 bytes of free memory for and control blocks. buffers Future releases will allowmore than one file to share the same buffer area therby reducingthe execution memory requirements.

SEQUENTIAL ASCII FILES

Sequential disk filesare the easiest to understand AlphaBasic. and to implement in Data is written in ASCIIformat and ASCII string values. allnumerics are stored as Carriage—returns andline—feedsare included file as a result of inthe output the print statement formattingbut are bypassed when the file is read by anotherprogram. The data files created by sequential I/O functions AiphaBasic normally have the extension"DAT" unless explicitlystated in the OPEN statement. otherwise These files are normalASCII sequential files in allrespects andmay be manipulated by the text editor,the print spooler,or any of the other system utilities.

Data is written tosequential ASCII files by using file number (non—zero) the PRINT statement witha following the verb instandard I/O statement format. Data is read back fromsequential ASCII files by similar manner. using the INPUTstatementin a

45 RPNEXJM ACCESS FILES Random access files are more complex than sequentialfiles but offer a muchmore flexible method for storingand retrieving data indifferent formats. files are written inwhat is considered unformatted Random program accesses to random files or packed data mode.All are made via the "logical record"approach. A logical record is definedas a fixed number of bytes whose formatis explicitly under control of theprogram performing theaccess.Physical records on the disk are each 512 byteslong and each random file given number of these must be preallocated assome 512—byte physical records.Logical records may beany length from 1 byte to512 bytes in length.The AlphaBasic I/O system will automatically compute the number physical record and of logical records that willfit into one perform the blocking and unblockingfunctions for you.For example, if your logicalrecord size is definedas 100 bytes, then each physical record on the disk willcontain 5 logical records withthe last 12 bytes of each physicalrecord being lost. Therefore, the most efficient comeswhen the logical record use of random files 128, etc). size will evenly divide into512 bytes (32, 64,

Random accessfiles are preal1ocatdonce using the ALLOCATEstatement and givingthe numberof physical 512—byte recordsto be allocated.It is up to the programmer to calculate the maximumnumber of logical records requiredin the file and then, using theabove description, calculate howmany physical records will be required tocompletely contain the number oflogical records desired. For instance, assume thelogical record size is 100 andyou need a maximum of 252 logical records inyour file.Each physical disk record is 512bytes and therefore will containS logical records.You need 252 logical recordsso dividing 252 by S gives50 full physical records plus 2logical records remaining.Since the file must beallocated in whole physical recordsyou will need 53 physical records whichwill give you a maximum of 255logical records. These logical records willbe referenced in yourprogram as records 0 through 254 since the first recordof any random file is numberedrecord 0. The logical record size isspecified dynamically in the OPENstatement when the file type is RANEXYVIso it is possible to get things fouledup if you do not have the record size correct.No logical record size is maintainedwithin the file structure itself.This fact does make it nice inone respect and that is that a file which is accessed bymany programs can have its record sizeexpanded without recompiling allprograms.Heres how:Assume you have a file which is considered the parameterdescriptor file for all other filesin the entire system.This file gives the record sizeas 100 bytes for the vendor name arid address file (asan example). Allprograms which reference the vendor file first read this parameterfile to get the size of the vendorfile logical record.The programs then set the sizeinto a variable anduse this variable in the OPEN statement forthe record size.Each READ. or WRITE call will then manipulate the 100 bytes ofdata by reading or writingto or from variables whose size totals 100 bytes.Lets say you now want to expand the fileto 120 bytes and that most of theprograms will not have to makeuse of the extra 20 bytes until sane time inthe future.You write a program which copies the 100—byte file intoa new 120—byte file and update the mainparameter file to indicate that thenew record size for the vendor file is 120 bytesinstead of 100.Eachprogramwill now open the file usingthe new 120—byte record size (since it is read in fromthe parameter file at runtime) butwill only READ or WRITE the first 100 bytes ofeach record due to the variables used and WRITE calls.Got the message? by the READ

46 FILE I/O STATEMENTS

OPEN In order to manipulatedata to or frcma file it must be opened first. statement assignsa unique file number toa file and also specifies theThe open that is to be givento an output fileor to be used in the locating of name file.The general format is: an input

OPEN#, , , {record—size,record—number—variable} file —any numericexpression which evaluatesto an integer from 0—65535 (0 is defined as theuser terminal and treatedas such) filename—anystring expression whichevaluates to a legal file description mode — specifiesthe mode for opening the file: INPUT —opensan existing file for input operations OUTPUT —createsa file for output operations RMWM —opensan existing file for randan read/write

The remaining two optionsmust be used for RANDJM mode only: record—size —anexpression which specifiesdynamically at runtime the logical record size forread/write operationson the file record—number_varithle —anon—subscripted numeric variable whichmust contain the record number ofthe desired randomaccess for READ or WRITE statements whenthey are executed Any attempts to reador write to a file which has not been an error message and the opened will result in program will be aborted.The filename string may beas brief as thename of the file in whichcase it is assumed to have an extension of "DAT" and reside inthe current user's disk filearea.The filename string may expand to become a complete filespecification if desired givingthe explicit location of the filein another userarea and even on another disk drive. Some examples are:

OPEN #1, "DATFIL", INPUT OPEN #15, "PAYROL.Thlp",(XJTPUT OPEN#A, C$,OUTPUT OPEN#3, "DSK1:OFILE.ASC[200,201",CUTPIJT OPEN #1, "VENExJR.DAT", RANEOM,100, RECNUM The OPEN statement is the only statement which referencesthe file by its actual ASCII filename in thestandard operating system format. in the program All further references aremadebythe file number which isassigned in the OPEN statement # expression.

CLOSE

The CLOSE statement terminates the processing of data toor from a file. Once a

47 file has been closed, no further referencesare allowed to that file number until another OPENstatement is executed.Any files that the program exitswill be closed are still open when statement is: autatically.The format of the CLOSE CLOSE #

KILL

The KILL statementerases one file fraB the disk.It does not need a file number and no openor close need be performed to the KILL statement is: KILL a file.The format for KILL As in the OPEI statement,the filename is any string to alegal file description. expression which evaluates

ICOKUP The LLXDKUp statement looksfor a file on the disk you if the file was found and and returns a flag whichtells for the statement is: if so, how many recordsit contains.The format LOOKUP , As in the OPEN statement, the filename is any stringexpression which toa legal file description.The result—variable is evaluates which will receive the any legal. numeric variable result of the search.If the file was not found,a zero willbe returned. If the file wasfound and is a sequentialfile, a positive number will be returnedwhich is the number ofrecords in the file.If the file was found and is a randan(contiguous) file,a negative number will be returned which is the number ofrecords in the file.In either case, the number of records represents physical512—byte disk records andmust be divided by the blocking factor forrandm files if the numberof logical records is desired.

ALLOCATE

The ALLOCATE statementis used to preallocatea contiguous file on disk which may then be opened for randcnprocessing.An attempt to allocatea file which already exists willresult in an errormessage.A randaii file need only be allocated once andmay then be opened for randcinreth/write operations times as desired.The statement format is: as many

ALLOCATE , As in the OPEN statement, to a legal file description.the filename isany string expression which evaluates which represents the The number—of—records isa numeric expression the file. number of physical 512—bytedisk records to be allocatedto

48 INPUT Once a file has beenopened for input, the special form of the data is read from thefile by a INPUT statement usinga file number which correspo,nsto the number assigned in theOPEN statement.The variables in the list numeric or string variablesbut must follow the format may be either beingread. of the data in thefile Weird results willoccur if you attempt to read string numeric data into a variable or vice—versa.The general format of theINPUT statement is: INPUT #, , ,... During the reading of the input data into thevariable list all leadingspaces will be bypassed unlessenclosed within quotes justas in the normal form of the INPUT statement.Also, all carriage—returnsand line—feeds will be bypassed allowing the file createdby the PRINT statementsto contain formatted line data if desired.Coninas, spaces, and end—of—linecharacters will all terminate numeric data strings and willthen be bypassed.

PRINT Once a file has beenopened for output, the data form of the PRINT is written to it bya special statement using a file numberwhich corresponds to thenumber assigned in the OPENstatement.All techniques usable inthe normal form of the PRINT stab-i-tent whichoutputs to the terminalmay be used in the file form including PRINT USINGfor formatted data.The data which is outputto the file is in the exact formatthat would appearon the user terminal if the file number had been omitted.The general format of the valid examples follow: PRINT statement along withsome

PRINT #, PRINT#1, A, B, C PRINT#4, USINGA$,A, SQR(A) PRINT#Ql, USING "###.##",Al(lO); PRINT #1, "THIS IS A SINGLELINE"

READ

The READ statement isused to read a selectedlogical record froma file which has been openedfor random accessprocessing.The logical record which is transferredby the system I/O isthat whose record number is currently in the variablementioned in the OPEN READ statement is: statement.The format of the READ #, , ,... The variables in thelist may be any formatbut they obviously should of the designatedrecord format. match that unformatted bytes without The data will be read intothe variables as into each variable regard to variable type. Thedatawillbe transferred until the variable has beencompletely filled and then the next variable in the listwill be filled, andso on.If the record is longer than the variable listspecifies, allexcess data in the record will not be

49 transferre.3. Anattempttotransfermore data than is in the logical record sizewill result Th an error message. The most efficientuse of the random files comes when the variable or variables usedare mapped by the MAP statement to the exact picture ofthe record format inuse.

WRITE

TheWRITE statement is used to writea selected logical record intoa file which has been opened for randomaccess processing.The logical record which is trnasferred by the system I/Oisthat whose record number iscurrently in the variable mentioned in theOPEN statement.The format of the WRITE statement is: WRITE #, ,,... The variables in the listmay be any format but they obviously shouldmatch that of the designated recordformat.The data will be written into thelogical record from the user variablesas unformatted bytes without regard to variable type.The data will be transferr4from each variable until thevariable has been completely emptiedand then the next variable inthe list will be used, and so on.If the record is longerthan the variable list specifies,all excess data in the record willnot be modified.An attempt to transfermore data than is in the logical recordsize will result inan error message.The most efficient use of the randomfiles comes when the variableor variables used are mapped by the MAP statementto the exact picture of the recordformat in use.

50 CALLI EXTERNAL ASSE2IBLY LANGUAGESUBIflYPINES

External subroutines written inassembly language code may be called fromany AlphaBasic program using the XCALLstatement. as follows: The syntax for this statementis

XCALiJ routine,argi.unent—l,argnt_ argument—n The routine to be called isan assembly language program which has been assembled using the MAC assembler.The resulting PRG program filemust then be renamed to give it theassumed extension SBR indicatingthis is a subroutine and not a runnableprogram.When the XCA statement isexecuted by the AlphaBasic runtime system,the named subroutine will then called asa subroutine. be located in memory and certain parameters into AlphaBasic first saves all registersand then sets these registers foruse by the external subroutine.The addresses of thearguments are calculated andentered into an argument list in memory along with their sizesand type codes.The base address of this list is then passed to theuser routine in register R3. The argumentsmay be one of two basic forms.A variable name may be used in which case theargument entry in the list willreference the selected variable within the user impurearea.This variable is availableto the called subroutine for both inspectionand modification. expression The argument may also bean (numeric or string) in whichcase the expression is evaluated and the result is placed on the arithmetic stack (referencedby ItS). This result is then referenced in the argument list entry instead ofa single variable. it is available for inspectiononly since the stack is cleared exits. when the subroutine

The user routine is freeto use and modify all sixgeneral work registers (RU—PS) and may use the stack for work spaceas required. When the subroutine has completed its execution a return must be made to the runtimesystem by executing the R'IN subroutinereturn instruction.

RISTER PARAMETERS

The following registers are set up by the runtime system to beused as required by the external subroutine. They may be modified if desiredas they have been saved before the subroutinewas called.

RU — indexesthe user impure variablearea. RU is used throughout the runtime system to referenceall user variables. Details onthe format of thisarea are not available at this time and the user need not be a work register. concerned with them.RU may be used as

R3 —pointsto the base ofthe argumentlist. R3 may be used to scan the argument list for retrievalof the argument parameters. R4 —pointsto the base of the freememory area that may be used by the external subroutineas work space. This is actually the address of the first word followingthe argument list inmemory

51 and may be used to storea terminator word to stop scanning of the argument list if desired.

ES — thisis the arithmetic stack indexused by the runtijue system. The arithmeticstack is built at the topof the user partition and grows downward asitemsare addedtoit.when the external subroutine is called, R5 pointsto the current stack base.Since thearithmetic stackmay contain valid data, the external subroutine must notusetheword indexed by ESor anywords above thataddress.

AWUMENTLISTFORMAT

Thelist of arguments specifiedin the XCALL statement arguments at all to a number limited may range fran no only by the spaceon the coitnnand line. To pass these arguments to theexternal subroutine,an argument list is built in memory which describes eachvariable named in the list located in theuser impure area. and tells where itcan be passed to the subroutine, •The variables themselvesare not actually but rather their absolutelocations in memoryare.In this way, the subroutinemay inspect them and nodify themdirectly in their respective locations.This does not applyto expressions which stackas described previously. are built on the R3points to the firstword of the argument list many arguments were contained which is a binary countof how in the XCALL statement.Following this count word canes one 3—word descriptorblock for each argumentspecified.If there are no arguments in the XCAastatement, the argument listwill consist only of the single count wordcontaining the value ofzero. The format of each3—word block describingone argument is as follows: Word 1 —variabletype code.Bits 0—3 contain thehex type code for the specific variable:O=unformated, 2=string,4floating point, 6=binary, 8 through Eare currently unassigned.Bit 4 is set to indicate thevariable is subscriptedor clear to indicate the variableis not subscripted. type code wordare meaningless. Other bits in the

Word 2 — absolute address of variable inuser impure area.This address is the first byteof variable no matter orsize might be. what is type

Word 3 —sizeof the variable in bytes.

Note that the above descriptions also applyto the expression exceptionthat the results will arguments with the instead of below it. be located above theaddress specified by PS The argument list is built in freememory directly above thecurrently allocated user impure area.P4 points to the wordilTinediately following the argument list.The user may scan the the last word in either by decrenenting argument list and determine itsend the count word at thebase of the listor by scanning until the scan indexreaches the address inP4.

52 FREE MEMORY USAGE

When the subroutine is called,indexes R4 and R5 mark thebeginning and end of the free memory that iscurrently available foruse as workspace.This area is not preserved by the runtinesystem and the subroutine must notcount on its security between XCALLstatements.Note that the word at @R4may be used as the first word but the wordat @R5 is the base of the arithmetic be destroyed.The last word of free stack and must not practical purposes. memory is actually at —2(R5) for all

The runtime system has itsown internal memory managementsystem and does not conform to the AMOS operatingsystem memory management.Therefore, the external subroutine must notuse the GEThEM monitor calls to spacein memory. generate a block of work Also, if anyfile calls are to be donethey must be done with internalbuffers since the INIT callsets up a buffer by using the monitor call. GENEM

SUBROtyrILOADING

The version 3.1 releaserequires that the subroutines beingcalled by the BASIC program already exist either insystemmemory or user memory before beginning execution of the program.These subroutines must be loadedinto system memory by the SYSTEM call inthe SYSTEM. INI fileor they must be loaded individually into the usermemory partition with the WAD mode. command while in monitor command Note that this is the monitorLOAD conuTiand to load the SBRmodule which is vastly different fromthe WAD command used to you are running AlphaBasic. load a basic source fileonce Future releases will provide capabilitiesfor loading subroutines andoverlays from within the BASICprogram itself.

53 ERROR TRAPPING (T AiphaBasicallows the user program to traperrors that would normally cause the system to print an errormessage andabortthe program run.During interactive processing this would returnyou to Alphaasic command modeand during runprocessing compiled itwould return you to to monitorcommand mode. Useof the ON ERROR(3010 and RESUMEstatements allows these errors to be detectedwithin the user programand immediate action to be takenwhen appropriate.

ONERROR (3010 STATEMEtT

Error trapping is enabled anddisabledby using the ON ERROR (3CYO of two forms. statement in one The first form specifiesa line number (or label) within the program. When the program encountersthis ON ERROR statement it stores number the line and sets a flag enablingerror trapping.If an error occurs atany time after this control will betransferred to the routine specifiedby the line number. No error message will be printed. Examples of this form of statementare: the

ON ERROR CXYIO 500 ON ERROR (3010 TRAP 'ROCJPINE

The error routine must then take appropriate action basedon the type of error which caused the trap. The ERR function will returnthe following data basedon conditions at the time of theerror:

ERR(0) =numericcode specifying the type oferror detected ERR(l) =lastline number encountered priorto the error ERR(2) =lastfile number accessed (pertinentonly for file errors)

The second form of thestatement disables further line error trapping by specifying a numberof zero or leaving the linenumber of f completely.

ONERROR(30100 ON ERROR 0310

After executing the above formthe program will print the standarderror message and abort the programrun.A special case exists when theabove statement is encountered within an errorrecovery routine (prior to executing theRESUME statement).In this instance theerror trapping is disabled and the existing error is forced to be processedas if no error trapping wereever enabled.It is recommended thatall error trapping routinesexecute the ON ERROR (3010 0 statement for allerrors which have no specialrecovery processing. Note that if an erroroccurs within the error trapping routineitself that error will be forced and thestandard error message willoccur.There is no method to detect errors within theerror recovery routine.

54 RESUME STATR4ENT The RESUME statementis used to resume recovery procedure has been execution of theprogram after the error to the Cfl ERR auto performed.The statement takeson two forms similar statement.The first form specifiesa line number (or label) wihtin theprogram at which point the executionis to be resumed: RESUME 410 RESUME TRY' AGAIN The second form specifiesa line number of zero or causes the execution to be no line number at all and occur. resumed with the statementthat caused theerror to

RESUME 0 RESUME

Bothforms cause the error condition to be clearedand enabled again. errortrapping to be

CONTROL-CTRAPPING Whenthe operator typesa control—c on his keyboard during AlphaBasic the executionof an program the program issuspended at the next statement.Action taken then dependsupon the status of theerror trapping flag. is enabled theprogram is aborted with the If no error trapping the terminal. appropriate message being printedon If error trapping isenabled the error trappingroutine is entered with the code inERR(0) being set to 1.This feature allows the preventinadvertant aborting of user to updates. programs duringcritical times suchas file

Control—c action is suspended during errorrecovery processing to prevent accidental aborting of the program due toan error condition occurring within the error routine. The control—c will be the RESUMEstatement. detected immediatelyuponexecutionof

55 ER1R CODES RETURNEDBY ERR (0)

Code Meaning 1 Control—c interrupt 2 System error 3 Out of memory 4 Out of data 5 NEXT without POR 6 RETURN without GOSTJB 7 RESUME without ER1JR 8 Subscript out ofrange 9 Floating point overflow 10 Divide by zero 11 Illegal function value 12 XCPJLL subroutinenot found 13 File alreadyopen 14 10 to unopened file 15 Record size overflow 16 File specificationerror 17 File not found 18 Device not ready 19 Device full 20 Device error 21 Device in use 22 Illegal user code 23 Protection violation 24 Write protected 25 File type mismatch 26 Device does not exist 27 Bitmap kaput 28 Disk not mounted 29 File already exists 30 Redimensioned array 31 Illegal record number

56 SYSTEM FUNCTIONS

Alphaeasjcsupports a unique provide the group of operators calledsystem functions which programner with the abilityto get to the I/Oports, physical (sometimes referredto as PEEK and R)KE)and various system memory syntax of a systemfunction parallelsthat of a standard parameters.The reserved word representingthe desired function function with the enclosed withinparenthesis. followed by optionalarguments appear on the left side The major differenceis that a systemfunction may of an assignmentstatement whereby it output or writecondition to thesystem function. represents an expressions on the rightside of an assignment System functions usedwithin orread operation and statement will performan input evaluation. deliver backa result to be used in theexpression

10(X)

The 10 system functionallows .the 256 I/O written to. ports to be selectivelyread from or In both cases onlyone byte will be considered expression greater than and an output 255 will merely ignorethe unused bits. 10(X) = !writes the low byteof expr to port X A = 10(x) !reads port X and placesthe result into A

BYTE(X)and WORD(X) The BYTE and WORDsystem functions allow memory locations within the programmer to inspectand alter any the 65K memoryaddressing range of themachine. operationshave often beencalled PEEK and POKE These implementationsof BASIC. statements in other The BYTE functionswill deal with 8 bits the range of 0—255andthe WORD functions of data in rangeof 0—65535 inclusive. will deal with 16 bitsof data in the Anyunusedbits will be ignored message. Note that these with no error the operating commands arenot protected and itis possible to poke system, other usersor yourself to death withimproper use. BYTE (X) = !writes the low byte WOPD(X)= of expr intomemory bc X !writes the low wordof expr intomemory bc X A =BYTE(x) !reads memory bcX and places the byte into A - = WORD(x) A !reads memory bc Xand places the word intoA

TIME

The TIME system function requiresno argument and is usedto set and retrieve the time of dayas stored in the systemmonitor cournwiications isstored as a two—wordinteger representing area.The time midnight. the number of clockticks since The prograimijer isresponsible for conversions those cases where it5required. to printable format in the CPU line clock Gne clocktick representsone interrupt from which is usually60 hz for domestic overseas systems. systems and 50 hz for Dividing the timeby the clock rate will secondssince midnight.Converting this to give the number of successive division by current time is then accomplishedby 60 to get minutesandagain by 60 to get hours.

57 TIME = I sets time—of—day in system toexpr A =TIME Ireturnstime—of—day in clock ticks into A

DATE The DATE system function is identicalto the TIME function except that it sets and returns the two—word systemdate. Thereis no current format defined by Alpha Microsystems for this date and itmay be stored in any format you choose. Sane coirmon methodsare to pick a base date (say 1/1/60) and store the dateas the number of days since thatdate.Mother method is to store the Julian date with the year being offset bythe appropiate integer amount.The date will store a positive value of 232or greater than 4billion.

DATE= !sets system date to expr A =DATE Ireturns system date into A

2 DeMo ofuse of AlphaBasic DATEroutinewith "DATE"forMatted date.

10 IIAP1 DATE'HOLDER,B,3 11 MAP1 MMBDYY,,,,I!DATE'HOLDER 12 MAP2 MM,B,1 13 MAP2 DD,B,1 14 MAP2 YY,B,1 15PRINT 16 20DATE'HOLDER = DATE 21 PRINT USING "Current date is #*J##/##", IIM,IiD,YY 22 PRINT 30 32 INPUT "Enter new date MM,DD,YY ",fIN,DI',Vy 34 DATE DATE'HOLDER 36 PRINT 38 GOTU 20

58 EXPANDED TAB FUNCTIONS

The TAB function in AlphaBasjc has beenexpanded past the normalusage to include terminalscreen handling such ascursor control and other special functions.Th be used only ina PRINT statement, the TAB function thetraditional manner when operates in supplied with onlya single numeric argument such TAB(X). In this case the function as the "x" causes the carriage to be positionedover to columnonthe current line. When supplied with two TAB(X,Y), however, the arguments such as TABfunctionperforms special CRT functions. If the value of X is positive the x,yarguments will be treated coordinates for positioning as (row,colurm) the cursor on the terminalscreen. characters will then The following be printed beginning inthat position. As in other functions, the X andY arguments may be expressions. begin with row 0 (top Terminals are assumed to of screen) and column0(left end of each row). If the value of X is negative the function isinterpreted as a special terminal commandand thecommand codemust be specified as theY argument. The codes will be transmittedto the terminal driver (TDV actual interpretation module in 1,6) which will do the and perform the specialfunction. The following list will give the standardcodes in use for the ADM3, drivers: SORT and Hazeltime CRF terminal

Code Function

0 Clear screen 1 Cursor home (upper leftcorner) 2 Cursor return (column 0 withoutline—feed) 3 Cursor up one row 4 Cursor down one row S Cursor left one column 6 Cursor right one column 7 Lock keyboard 8 Unlock keyboard 9 . Eraseto end of line 10 Erase to end of screen 11 Protect field (reduced intensity) 12 Unprotect field (normal intensity) 13 Enable protected fields 14 Disable protected fields 15 Delete line 16 Insert line

The actual routines that perform the screen controlsare in the specific terminal drivers and not in AlphaBasic itself. Therefore, if you havea different terminaland you write a driver to perform the above functions forthe terminal in use it willoperate properly with AlphaBasic with to either the compiler no modifications or to your programs. Note that mDst terminals do support all of the above not commands. Coirniands that are not supportedon the terminal in use willmerely be ignored by thedriver.

59 FORMATTING NUMERICDATAVIAThE"USING"MODIFIER C Oftenit is desirableto format a numeric print it on the terminalor output it to avalue file. without havingto iimiediately formatting but theoutput must be to the The PRINT USING performsthe extra code to begenerated. terminal or a file whichcan cause image lines and Formatted numeric datais handy for creatingprint headers.Sane more exotic operationswould allow pre—inspection of numeric data andstring manipulationof that data for application•AlphaBasic allows formatting specialized equivalent with the numeric data into its string this is: USING expression modifier.Basically the format fordoing

=BUSINGC$ The formatting of the numeric value in B isperformed using the formatmask in C$ and the result isleft in A.$ as a string.The mask must be formatting rulesare the same as those used for a string and the actual syntax rule delivers the PRINT USING statement.The followed a strin result anytimea numeric expression is by the word USING and thecorresponding mask string. ccanplex statementis legal: The following

="ABCD"+(ffl*HOURS)USING (B$[2,4}+"####")) + "END" Although it is academicin nature, a restriction modifieris not recursive; i.e. exists in that the USING the mask string itselfcannot USING modified expression. be theresult of a

60 PICCESSING INDEXEDSEQUENTIALFILES

Alphasasic has the abilityto process inde,tedsequential files by linking ISAM assembly languagepackage which must reside to the individualuser memory. wither in systemmemory or Multiple directory filesare supported via sane elementary 1SAM statementswhich allow the direct fileitems. control of index file anddata The ISAM packageas implemented requiresmore direct user control over the files than otherimplementations fOr reasonis memory limitations two main reasons.The major which restrict theamountof "smarts"that could be put into the Aiphaeasicruntime packagefor handling ISAJI files. The second reason is the current structureof the existing iSl½r,4 package which precludeda more extensive implementationwithin the timespan feel that the version allocated to the project. We we are releasing will.provjdesufficient control for all users even though the initialtraining andprogramming complexthan other versions of may at first appear more ISAM handlers.For more detailed informationon ISAM files and the ISAMassembly language package theuser is referred to the separate manual titled "ISAMSystem User's Guide".

FILE STRUCTURE

An indexed sequential fileconsists of one data file andone or more index files whichlink to the data file. The data file is structured identical random access file with the to a normal not currently active additional restriction thatall records whichare record list". are linked to each other ina chain called the "free data All data records reside inthe data file and the datarecords may be any size up to themaximum of 512 bytes.As in the normal randan file, data records willnot be split across physical access inthe file. 512—byte block boundaries Index files are arranged inacomplex balanced tree structure and contain one symbolic keyfor each active data recordplus a link to that data record in the data file.This link is the relativerecord number and is used in the same manneras its counterpart in a normalrandom access file. file also containsan array of internal linkâ which The index accesstree structure. comprise the sequential

No references used in this manual may be confusing if theyare not understood. References to an "indexed file"are made when speaking of the entire file structure in general including the data file and oneor index files. to an "index file" References are used when specifically speakingof the portion of the structure which contains only the symbolic keys andthe tree links. Index files may be primary or secondary andhave the extension ilJX. All indexedsequential files must becreated by the ISMBLD access by any AlphaBasic programprior to program. There is no method for the indexed file within the creation of a new Alphabasic language since thiswould require a prohibitiveamount of seldom—used code forexecution.The user may, however, create indexed files ina system structure by using the featurethat allows a BASIC program to createand then execute a coirrand file.This coinriand file could set up parametersand then call the ISbSLD creation of the files. program to perform the actual For compatibility with existingstructures the data file must have of I1 and all index files an extension must have an extension of IDX. There must be at

61 least one index file which iscalled the primary index file. There may also be additional index filescalled secondary index primarydata file.The primary index files which also linkto the file must alwaysbeopened in any in order to gainaccess to the data file. program to access the data This is trueeven if you only intend file throughone of the secondary index program. For information files in thecurrent on file structures andoperating the ISMELD refer to the ISAMSystemUser's Guide. program

SYMBOLICPNDRELATIVE KEYS Indexedfiles areaccessed by one of two key is alreadyfamiliar to us since specific types of keys.The relative it is the sametype of key used toaccess normal random files.A relative key whenused with an indexed file to access a specificrecord in a data file. is used only floating intvariable which is The relative key must bea specific key is new to specified in the OPENstatement. The symbolic us and is used only withindexed files.Symbolic keys are ASCII strings of variablelengths and are usedto access the index file secondary).Symbolic keysare specified in the ISAM (primary or the index file andare used to retrieve the statements when accessing record in the data relative key of the associateddata file.The concept of symbolicverses relative keys and their differentuses is an impertantone and misuse of them will tomalfunction in cause the ISAM system a number of ways. Symbolic keys are used with statementand the ISAM relative keysare used with the READ andWRITE statements. mostinstances theuse of the relative key will In willmerely be a device be transparent to theuser and automatically set up andreferencedby the above calls.

THE ISAM STATEMENT

Indexed filesare accessed by a special statement in Alphasasiccalled the ISAM statement. This statement has thegeneral form: ISAM#, , All ISAM statements followthe above formatusing a different numeric to specify thespecific function to be value in AllISAM performed by the ISAM package. statementsdirectly translate intoa specific type assemblylanguage iSAM of call to the program which must be inmemory asexplained previously. A symbolickey must always bespecified even require the use of for those functions whichdo not one (this simplifiessyntax A dunny string variable checking and executioncoding). may be usedifdesired. are used by the ISAMstatement: Briefly, the followingcodes

1—Finda record by symbolickey 2 —Findthe next sequentialrecord in file 3 —Addasymbolickeyto an index file 4 — Deletea symbolickey from anindex file 5 —Locatenextfreedata record in data file 6—Delete a record from data fileand return to free list

An error will resultif an ISAN statement not equalto is executed with thevalue of one of the abovevalidnuthbers. The codemaybe any legal numeric

62 expression which isresolved at runtime.

OPENING ANINDEXEDFILE

As withother types of files, an indexed file must beopened with a specific file number priorto any references to the file by otherstatements. The OPEN statement follows thesameformat as that used by the normalrandom files. OPEN #, , INDEXED, , The filename mustrefer to the name given creation. to the index file during theISMEUD If this is a callto open a secondary indexfile the user must have already previouslyopenedthecorresponding primary index file number so that the datafile may be accessed. on another file As an example,assume that an indexed file index arid data files structure consists of the primary named MASTER. lOX and MASTER.IDA respectively.The structure also has secondaryipdex files namedADRESS.IDX and PAYROL.IDX which access the MASTER.IDAfilein differentsequences. thefile structure via If it is desired toprocess the sequence used by theADRESS.IDX index file the followingtwo statements would berequired:

OPEN#1, "MASTER", INDEXED,RECSIZ, RELKEY OPEN#2,"ADRESS",INDEXED, RECSIZ, RELKEY

Note that the record sizeexpression (RECSIZ) and therelative key variable (RELKEY)areidentical in bothstatements. refer to the same data This is important since theyboth referring to either indexfile (MASTER. IDA). ISAMstatements may then be made file (#1 or #2) but allREAD and WRITE statementsmust be made to the data filewhich is associated withthe primary index file (#1). Inother words, READ andWRITE statements must not bemade to file #2.

ISAM STATEMENTS There are six functions which are performed by the ISAM statement withthe codes 1—6 as listed previously.They will be explained inmore detail in thiâ section. In the following descriptionsthere are codes which either relative key as input require a or return a relative key to beused when accessing the data record. In all cases this relativekey will be specifiedin the OPEN statement retuned in the variable statement. for the index file beingaccessed by the ISAM This then leaves thesystem properly setup for an ingnediate access to the corresponding datarecord via a READ or WRITEstatement. Code 1—thespecified index file issearched for the key which symbolic key in thestatement. matches the will be delivered back If a match is found theassociated relative key for access to the data file.If the key is not foundan error code 33 will be returned(see section onerror processing).

Code 2— thespecified index file isaccessed and the next sequentialkey is located. The corresponding relativekey is returned in preparation or WRITE to the data file. for a READ If this is the firstaccess to the file following the OPEN statement, the first sequential key willbe located. If this statement

63 follows a 1 key willprevious code 1statement, thenext sequentia' be located.If thereare no more keys key followingthe Code end—of_index_fileerror (38) will be in the indexfile and madeto the data file returned andno further acceses until anotheris'i should be relative key. callis made whichreturns a valid Code3 —thespecifiedsymbolic relative key is addedtothe index file key whichmust be in thecorrespondi variable along with the statement.This relative specified in theOPEN ISAM key willnormally be already statement whichdelivered the set up bya prior code 5 relative key then next free datarecord to be used. becomestheresult of anyindex This specificassociated symbolickey. search which locatesthis Code 4 thespecifi symbolickey is located fromit. The corresIndi in the indexfile and deleted data record data recordrelative key is may then be deletedand returned so thatthe ISNI statements returnedto the free listby using a code If the symbolickey is not 6 not founderror will be returned. located in the indexfile a record

Code 5 the next availabledata record is relative key is extracted from thefree list and returned in preparationfor a code 2 the statement If no more data index key addition error records are free inthe data file will be returned.All free recordsin the data file a data file full list calledthe free list.This list is built are kept in a linked all the recordsin the data file. initially by ISMBLDand contains free list delivers As code 5 ISAMstatements are these recordsand as code 6 executed the records are againreturned to the free IS statementsare executed the modified andthe symbolic key list forreuse.The index file isnot made only to the in the statementis ignored. primary index filenumber. This call mustbe Code 6 thedata recordspecified by the list for relative key isreturned to the free reuse by a code 5call. The index file symbolickey in thestatement is ignored. is not modifiedand the primaryindex file number. This call mustbe made onlyto the

READ AND WRITESTATEJ4n5

TheISAN calls do not access thedata records the relative key themselves butmerely deliver of the associateddata record to back WRITEstatements are then be used. Normal READ and record itself. used to actuallyretrieve or writeinto the data These READ andWRITE statementsfollow the accessing a normalrandom access datafile in Alphasasic.same format used when associated withthe primary file(as specified in The relative key contain a va.Iidrelativekey for the the OPEN statement)must and WRITE operation oran statements asmentioned before error will result. READ index filenumber. must only be madeusing the primary

CtOSI AN INDExFILE In order to insurethat alldata andthat all links records have beenrewritten to the in the indexfilehave been data file the disk it isimperativethat all index properly updatedand rewrittento files (primaryand secondary)be closed

64 using the normal CWSE statement and referencing thecbrrect file number. Failure to doso may result in the link structure being sacrificedto the god TItJ (godof electrons andintegrated circuits).

CREATING ANINEEXEL) FILE The steps used in theinitial creation ofan indexed file will be traced here. Initially, the structuremust be created using theISMBLD ISAM program. Refer to the System User's Guide for detailson this procedure. Any secondary filesmust also be created by the index ISMBLD program. The program to add thedata items will thenopen all index files associated withthe structure. For each new data record to be added, the followingsteps are performed. The next free data record isretrieved (ISAN code 5) and thedata record is written into it with a WRITEstatement.One symbolic key is then addedto each of the index files using ISAMcode 3 statements.Allkeys samedata record. will therefore link to the

After all data records have been written to the file,all files are closed.

READING /'iNINDEXED FILE SEQUENTIALLY To read an indexed file in thesequence of the symbolic keys the file is first openedbythe program.If it is desired to read inthe sequence of a secondary file both the primaryand secondary files must beopened. Each record is retrievedby executing first a REAl) statement. an ISAI'4code2 statement followed by Remembertha.tthe READ statement must beto the primary file even though a secondary index fileis being used for the sequentialaccesses. After each ISAM code 2statement the user should checkfor an end—of—file condition using the ERF(X)function to determine whenno more data is left. Referto the section onerror processing.

Close all files.

READING AN INDEXED FILE RANDi'4LYBY KEY

To read a file randomly by symbolic keys the filesare opened as above for sequentialaccess.As many secondary index filesmay be opened simultaneously as will be required for the randommode processing. Each data record is locatedwith an ISAM code 1 key and the file number statement giving the symbolic ofthe index file to which thesymbolickeypertains. Acheckshould be made fora record not found error at this point indicating the symbolic key that was not located in the specified indexfile. Assuming the key isvalid a READ statement should data record. be made to the primary fileto get the correct This operation may beperformedforeach data record to be read. Close all files.

65 UPTING D1TA RECORDS Data recordsmay be updated bylocating the data record and then updating thedata buffer with the via either niethodabove by a WRITEstatement new data desired.This is followed to rewrite the datarecord.The WRITE statement must be made to the primaryfile.The index filesare not altered in this operation. Note that the abovemethod should only be used direct part ofany symbolic key. to alter data that is nota key in the 'lb change a symbolic keyyou must delete the correct index file and thenadd the new key with anotherISAM statement.The data record neednot be deleted and recreated duringthis operationunless necessary forComplete new data.

DELgrnqG A DATA RECORD

Thedeletion of a data record in an indexed file structureinvolves not only the deleting of the datarecord itself but also the associated deleting of all symbolic keys with that data record.A11 indexfiles must be open for this operation. The data record is firstlocated by one of the symbolic ISAt4 code 1) and thenthe data record is read into keys (via statement to the primary file. the buffer with a READ the data record and Each symbolic key must thenbe extracted from usedto delete each key from itsassociated index file with successive15fl4 code 4 statements.The data record itself isthen deleted and returned to the free listwith an ISAM code 6statement. NOTE: Agood check onthe structure would beto store the relative key in another variable and thencompare the relative keys returned by statement to insure that each I5A14 code 4 the symbolic keys all didindeed link to the correct data record. You should also check each ISAII statement for any possibleerror that might otherwisego unnoticed.

ERICRPWCESSING

Every ISAN statement executed may potentially result insome form of error. Errors will fall into one of two categories: hardor soft. Hard errors are defined as errors whicharereturnedto the ISA!.! processor fran the service system indicating monitor file sane invalid disk operation. Soft which occur within the errorsare those ISA!.! processor indicatingan error or condition peculiar to ISAM files only.

AlphaBasic handles these twotypesof errors in differentways. will cause the standard Hard errors BASIC error processor to beinvoked resulting in either a message and program abort or an error trap if (14 ERR(DiVis in effect. These errors may be detected with the normalerrorprocessing defined in the section dealing with the(14 ER1R(DiVstatement. Soft errorswill never result inan error message or error trap and it is therefore up to the prograniner to test for theseerror conditions after every ISA!.! statement. This is done by using the the file number used in ERF(X) file error function where X is the ISA!.!statement. The ERF function operates in similar a fashion to the EOF(X) function. If the ERFfunctionreturns a zero the precedingISAM operation was successful.If the value returned is notzero then

66 an error or abnormalcondition was detected betaken andpropercorrective action should in the programprior to the nextaccess to the file.

Current softerrorcodes in effectare:

32 —illegalISAMstatementcode 33 — recordnot found in index filesearch 34 —duplicate key found inindexfile during attempted keyaddition 35 —linkstructure is smashed andmust be recreated 36 —indexfile is full 37—datafile is full (free listis empty) 38 —endof file duringsequential key read

67 CHAINING ¶10 OTHERPRCX3RAMS AND SYSTEMS

Alphasasicsupports the CHAIN statementwhich terminates n current program and initiatesthe execution of execution of the The new programto be executed must be a new program or system function. may be a full file specification named in the CHAINstatement itself and if desired.The program named inthe statement may be another AlphaBasicprogram (compiled only) or command file name.This allows a or it may be a system command invoke systemccninands if required.program to execute a commandfile and

CHAINING ¶10 ANOTHERALIPHABASIC PROGRAM The default extension of the file specificationin the CHAIN statementis RUN which names anew Alphaeasic program to beexecuted. evaluatedfile specification is If the extension of the indeed RUN (either explicitlyor by default) the new program is loaded intomemory and executed. program All variables in thenew are first cleared to zeropriorto execution.The program must be compiled and must be inthe current userarea on disk unless an explicit named in the filespec.The program may also area is system memory if desired. optionally be resident inuser or Sane examples of legalstatementsare: CHAIN "PPSYROL" CHAIN "PAYROL.RUN" CHAIN"DSK1:PAYROL[lQl,l3]" Due to the fact that for executing programs are compiled and not interpretedthere is no means a program at any entry pointother than its physicalbeginning. There is also no internalmethod for passingparameters between programs (sometimes referred toas "common" area) but thiscan be easily accanplished in a numberofways by making use of the within an external XCALLstatementandcreating a commonarea subroutine.A parameter could alsobe passed to the next program using this methodwhich is then used ina computed (3010 statement to effectively begin executionat one of several points in the value passed inthe parameter. the new program basedon

CHAINING¶10 SYSTEMFUNCTIGS Itis sometimes desirable to transfer execution to function corrinandfile a system or a fran a BASICprogram.If the name of the filein the CHAIN statement does nothave the RUN extension it isassumed to be a systemcommand function. In this case theAlphaBasicruntime package will commandfile at the top of create a dummy to the monitor camtar the current user partitionand then transfercontrol processor.The monitor will theninterpret this dummy coirruand file as a directcommand and will continue Note that the duniny execution at that point. command file created by theruntirne package is merelythe one—line name specifiedin the CHAIN statementand not the camnand fileitself which may be thetarget function desired.Sane valid examplesare: CHAIN "SYSTAT P[l,4J" CHAIN "TESTl (lID" CHAIN "DSKO:Mt24BLE.Qlw[2,2I'.

68 Note that if theaccount nunter is not specifiedthe action taken same as if the coimiarwas entered directly fran the will be the programs and command files will keyboard,In other words, due to the fact that normally be searched for inthe user area only the extension had toentered explicitly.Note also that the system function willbe executed as a mainlinefunction and not subroutine to the runtimesystem. as a return to some AlphaBasic This means that ifyou wish to automatically program you will have to executea command file whose final conutand isa RUN catniand to begin theexecution of said AlphaBasic program.Confused??Me too!!Good luck.

69 July 1979 EMIM—OOlO0—44

ADDENDUMTO ThEALPHABASICUSER'SMANUAL

1.0 INTRODUCTION

Thepurpose of this document is to provide additional information for the BASIC prograrriner until such time as we can issue a new AlphaBASICuser's manual (part number ThN—OOlOO—01). For more information on using the A1phaBASIC system, turn to the "AlphaBASIC User's Manual."

1.1 Contents

The next few sections discuss new A1phaBASIC features that are not discussed in the current A1phaBASIC manual.Section 10.0 lists all messages displayed by the A1phaBASIC system, and Section 11.0 lists all reserved keywords used by A1phaBASIC.

2.0 EDITING MASKS

The section in the current BASIC manual that discusses formatted output describes the use of the PRINT USING and USING statements which allow you to format output into specific character positions by use of editing masks.

In addition to the masks mentioned, there exists one type of mask that you can use to generate a number with leading zeros. This mask takes the form of one standard numeric mask character, I, followed by a series of Zs. The total size of the output string will be the number of Zs plus the one #. Forexample:

PRINT 123 USING "#ZZZZZ" yields:

000123

3.0 FILEBASE

During normal operation, the first record ina random file is referred to as record number zero (i.e., you set the recordnumber variable to zero to access the first record in the file). In some applications it is desirable to have this first record referred to by some number other thanzero. This is often done to allow you to use zero to flag some special condition, such

(July 1979) ADDENDUM '10 THE ALPHABASICUSER'S MANUAL Page 2 as a deleted record.The FILFIBASE command allows you to set the number used torefer to the first record to any value. For example:

FILEBASE 1 tells BASIC that the first record in the file is record number one, not record number zero. You may use any numeric argument with FILEBASE.

Note that FILEBASE does not associate its value with a file, but is only in effect in the program where it is executed. If one program uses aFILEBASE commandwhen referencing a file, all other programs which reference that file should also use a FILEBASE command.

4.0 EXTENDED TAB FUNCTIONS

Contrary to the statement in the A1phaBASIC manual, the home position of the cursor (the upper left—hand corner) is 1,1 NOT 0,0.

Inaddition to the standard TAB(—l,n) functions listed in the manual, the following are also available:

Code Function

17 Delete Character lA Insert Character 19 Read Cursor Address 20 Read Character at Current Cursor Address 21 Start Blinking Field 22 End Blinking Field 23 Start Line Drawing Mode (enable alternate character set) 24 End Line Drawing Mode (disable alternate character set) 25 Set Horizontal Position 26 Set Vertical Position 27 Set Terminal Attributes

Not all terminal drivers have all of the functions above simply because all terminals are not able to perform all of these functions. If your terminal has additional features, Alpha Micro reconnnends starting at 64 (decimal) when you assign function codes in your terminal driver.

5.0 MAP STATEMENTS

As of BASIC version 4.0, all MAP statements must appear at the front of a programbefore any executable code.

(July 1979) ADDENDUM TOTHEALPHABP.SICUSER'S MN4UAL Page3

6.0 LIBRARY SEARCHING Wheneveraprogram(calledvia RUNorCHAIN) or a subroutine (called via XCALL)is requested, BASIC follows a specific pattern in looking for the requestedmodule,If you specifya PPN, then BASIC uses thecurren% default device and the specified PPN. If you specify no PPN, the search sequence is as follows:

Default disk:[User P,PN] Default disk:[tJser P,O] DSRO: [7,6]

Note that earlierversions of BASIC (pre—4.2) used a different search algorithm that was in reverse of the one outlined above.

7.0 AUTOMATIC SUBROUTINE LOADING

When a BASIC program calls a subroutine via an XCALL statement, BASIC attempts to locate the subroutine in user or system memory. If it is unable to do so, it attempts to load the subroutine off the disk, following the search pattern outlined above. If a BASIC fetches a subroutine from disk, BASIC loads it into memory only for the duration of its execution. Once the subroutine has completed its execution, it is removed from memory. Therefore, if a subroutine is to be called a large number of times, it is wise to load it into memory to avoid the overhead of fetching the subroutine from disk.

8.0 ADDITIONAL ERROR MESSAGES

In addition to the error codes defined on page 56 of the AlphaBASIC manual, two more error codes exist. We give a complete list of all BASICmessages in Section 9.0.

32 Invalid filename 33 Stack overflow

9.0 DISK COMPILER PROSRAM(COMPIL)

To enable you to compile programs that are too large to fit into memory, we provide a disk—based compiler (COMPIL). COMPIL is a two—pass compiler that gains memory space by omitting the interactive features of BASIC. COMPIL produces .RUN modules that are completely compatible with those producedby the interactive system.

(July 1979) ADDENDUM TO THE ALPHABASIC USER'S MANUAL Page 4

9.1 COMPIL Operation I Touse COMPIL, enter:

.COMPIL filespec{/switches} ,

where filespec selects the .BAS file you want to compile, and {/swltches} select one or both of the optional COMPIL options. COMPIL allows the compilation of source files located on any device or Inany account. COMPIL always places the resultant .RIJN module in the account and device you are currently logged into (for BASIC versions 4.2 and later). BASIC does not support wildcarded filespecs.

9.1.1 OperationSwitches — COMPIL allows the use of two switches, /0 and IT. The /0 switch is the same as the /0 switch in the interactive compiler. That is, it tells COMPIL to omit line number references from the compiled code. This reduces the total object code size, but It prevents COMPILerror messages from reporting the line numbers where errors occurred.

TheArswitchis primarily designed for debugging purposes. If you specify the trswitch,as C&4PIL scans each source line of your program itdisplays that line on your terminal. If a problem occurs during the compilation, you can use the ftp switch to determine the line in which the problem is occurring. You may also use this switch to gauge the compilationspeed of various statements.

9.2Compiler Messages

COMPIL reports a number of statistics on your terminal as it compiles. A typical compilation might look something like this:

.COMPIL AGSISLS? phase 1—Initialwork memory is 2310 bytes Phase 2 —Adjustobject file and process errors Illegal MAP level — 350MAPFILL'7,S,2 Syntax error —980SLSMTD=SLSMW;SSLAMT Memoryusage: Total work space —4712bytes Label symbol tree—322bytes Variablesyntol tree —1186bytes Data statement pool —0bytes Variable indexirn area— 274bytes Conpiler work stack —140bytes Excess available memory —11918bytes Note that any error messages are reported duringpasstwo,andthatthe sourcelinecontainingtheerror is typed on your terminal.The "Excess available memory" line is useful for letting you know how close youareto runningoutofmemory. Ifyoudo run out of memoryduringa compilation,

(July 1979) ADDENDUM TO THE ALPHABASIC USER'S MANUAL Page5

you see the message "[Outof memory — compilationabortedi",and COMPIL returns your terminal to AMOS conunand level.

9.3Line Numbers Because A1phaBASIC allows the use of labels, and because COMPIL assumes that youare using one of the text editors (WE or EDIT) to maintain your source code, line numbers are optional in source code given to COMPIL. By omitting line numbers, and with judicious use of indentation, you cangive source code a much more structured look than is normally possible in BASIC.

9.4 Continuation Lines

COMPIL allows the use of continuation lines within the source program. This is especiallyuseful for giving source code a structured appearance. Specify a continuation line by making an ampersand (&) the last character on that line. For example:

10 IF (X < 12.2) OR (B > 0) THEN & 3 =X/167.2& ELSE & 3 =B 20 Q=1252

The maximum size of any line, including any continuation lines, is 500 characters.

If a programwith continuation lines is loaded into the interactive compiler, the lines are concatenated into one line. Therefore, loading and saving a programwith continuation lines under the interactive compiler (BASIC) results in the elimination of the continuation lines.

10.0 MESSAGES OUTPUT BY THE ALPHABASIC SYSTEM

Below is a complete list of all messages output by theAlphaBASIC system (i.e., BASIC, RUN, and COMPIL), along with a brief explanantion of each message.

Bitmap kaput Your program attempted a file operation (OPEN, ALLOCATE, etc.) on a device with a bad bitmap.

Break at line n The program reached the breakpoint that was set at line n.

COMPILE BASIC is telling you that it is compiling your program.

(July 1979) ADDENDUM TO THE ALPHARASICUSER'S MANUAL page6

Can't continue Youhave attempted to continue a program which is not stopped at a breakpoint, or which has reached a point where it can go no further (e.g., it has reached an END statement).

Cannot find xxxxxx Theprogram xxxxxx was not found.

Compiletime was x.x seconds BASIC is telling you how long (in elapsed time, not compute time) it took to compile your program.

DELETE what? Youhave specified a DELETE command without specifying what line(s) are to be deleted.

Device does not exist The device you specified in a file operation (OPEN, LOOKUP, etc.) does not exist.

?Device driver must be loaded into user or system memory If you are accessing a non—DSK device, the appropriate device driver must be loaded into user or system memory.

Device error An error has occurred on the referenced device.

Device full The specified device has run out of room during a WRITE, CLOSE, or ALLOCATE operation. Remember that an ALLOCATE requires contiguous disk space, so that a Device full error may occur when there are still a number of non—contiguous blocks available.

Device in use The specified device is currently assigned to another user.

Device not ready The specified deviceis not ready for use.

Disk not mounted The specified disk has not been mounted. Mount it via the MOUNT monitor connand or via the XMOUNT subroutine.

Divide by zero Yourprogram attemptedto perform a division by zero.

Duplicate label Your program has defined the same label name more thanonce. ''Endof Program '*' Youhavereachedthe end of the program during single—stepping.

(July1979) ADDENDUM TO THE ALPHABASIC USER'S MN1UAL Page 7

Enter to continue: You have reached a STOP statement in your program. You may continue from the STOP statement via a carriage—return, or may abort the run via a Control—C.

File already exists Your program tried to create a file which already exists.

File already open You have attempted to open a file that is already open onthe same file number.

File not found BASIC was unable to locate the specified file.

File spec error The file specification you gave in a file operation (OPEN, LOOKtJP, etc.) is In error. Alt file specifications must conform to the system standard (i.e. devn:file.ext(p,pn]).

File type mismatch Your programtried to perform a sequential operation on a random file or vice—versa.

Floating point overflow A floating point overflow occurred during a calculation.

10 to unopened file Your program tried to perform input or output to a file that is not open.

Illegal GUrO or GOSUB The format of the C,OTO or GOSUB statement is Invalid.

Illegal NEXT variable Thevariable used in the NEXT statement is not valid (e.g.,not floating point).

Illegal PRINT USING format The edit format used in a PRINT USING statement is invalid.

Illegal SCALE argument The argument given In a SCALE statement is invalid (the argument must range between —30 and +30).

Illegal STRSIZ argument The argument given in a STRSIZ statement is invalid.

Illegal TAB format Your program has incorrectly specifieda TAB function.

Illegal expression The specified expression is not valid.

(July 1979) ADDENDUM TO THEALPHABASIC USER'S MANUAL. Page 8

Illegalfunction value Thespecified function value is not valid for the particular function.

Illegal line number The specified line number is invalid (e.g., not between 1 and 65534).

Illegal or undefined variable in overlay The variable specified in a MAP statement overlay (via @) has not been previously defined, or is not a mapped variable.

Illegal record number The relative record number specified in a random file processing statement (i.e., READ or WRITE) is either less than the current FILEBASE or outside of the file.

Illegal size for variable type The specified variable size is not valid for the particular variable type. Floating point variables must be size 6, and binary variables must have size 1—5.

Illegal subroutine name The name specified as a subroutine is not valid.

Illegal subscript The subscript expression is not valid.

Illegal type code The variable type code specified in a MAP statement is not one of the valid types.

Illegal user code Thespecified PPN was not found on the specified device, or is not in a valid format.

Insufficient memory to load program xxxxxx TheRUN program did not find enough free memory to be able to load the specified program.

Invalid filename The specified filename was not a legal filename.

(Invalid syntax code] An internal error has occurred in BASIC. Please notify Alpha Micro of this error. Provide an example of what caused it.

Line number must be from l—f5534 The line number entered was not in the range of legal line numbers.

Line x not found The specified linewas not found for a DELETE, LIST, etc., operation.

(July 1979) ADDENDUM TO THE ALPHABASIC USER'S MANUAL Page 9

NEXT without FOR A NEXT statment was encountered without a matching FOR statement.

No breakpoints set BASIC is telling you that there are currently no breakpoints setin your program.

No source program in text buffer You tried to compile when there was no program inmemory. Operator interrupt You typed a Control—c to interrupt program execution.

Out of data A READ statement was encountered after the data in all DATA statements had been used.

Out of memory BASIC is tellingyou that it has run out of memory in which to execute your program.

Out of memory—compilationaborted COMPIL is telling you that it does not have enough free memory to finish compiling your program.

Program name: You tried to SAVE or LOAD a program without providinga filename. Enter the filename at this point.

Protection violation Your program tried to write into anotheraccount where youdo not have write priviliges.

RESUME without error A RESUME statement was encountered, butno error has occurred. RETURN without GOSUB A RETURN statement was encountered, butno corresponding GOSUB has been executed.

Record size overflow Your program tried to read a file record intoa variable larger than the file record size.

Redimensioned array You tried to redimension an array.

Runtime was x,x seconds BASIC is telling you how long It tookto run your program.

?Runtime package (RtJN.PRG) not found BASIC or COMPIL was unable to locate theruntime package, or did not have sufficient memory in whichto load it.

(July 1979). ADDENDUM TO THE ALPHABASIC USER'SMANUAL Page 10

Stack overflow BASIC's internal stack has overflowed. This is niost often caused by such operations as nesting GOSUBs too deep, or branching out of FOR—NEXTloops. Subroutinenot found The specified subroutine could not be found.

Subscriptout of range The specified subscript is outside therange specified in the DIM or MAP statement for the subscripted variable.

Syntax error The syntax of the specified line is invalid.

System commands are illegal within thesource program BASICsystem commands (LOAD, DELETE, LIST, etc.) are not valid within a BASIC source program.

System error A system error has occurred during the execution of the specified line. Systemerror is used as a catch—all error message for a variety of unlikely occurrences.

Temporarily all arrays must be less than 32K The array size you specified is larger than32K bytes. Undefined line number or label The line number or label specified Ina GCYrO or GOSUB statement is not defihed within the program.

Write protected Your program tried to write on a write—protecteddevice. Wrongnumberofsubscripts Thenumber of subscripts specified is not the same as the number defined in the DIM or MAP statement for thesubscripted variable.

(July 1979) P.JDDENIDUM ¶ID THE ALPHABASIC USER'S MANUAL Page 11

11.0 RESERVED WORDS

Below is a list of the reserved words used bythe BASIC (BASIC and COMPIL). You MUST not use any of these reserved wordsas variable names or labe is.

Reserved Word Meaning

ABS absolute value ACS arccosine ALLOCATE allocate file AND logical AND ASC ASCII value ASN arcsine ATM arctangent BREAK set breakpoint BYE exit to monitor BYTE memorybyte CALL call subroutine CHAIN chain next program CHR character value CHR$ character value CLOSE close file COMPILE compile program CONT continue execution COS cosine DATA data statement DATE system date DATM double arctangent DEE' define function DELETE delete lines DIM dimension ELSE else END end of program EOF end of file EQV logical equivalence ERF file error ERR error status ERROR error EXP exponentiation EXPAND expand mode on FACT factorial FILEBASE file base offset FIX fix FOR loop initiation GO program jump GOSUB call subroutine GEYTO program jump IF' conditional test INDEXED indexed INPUT input data INSTR search string INT integer

(July 1979) ADDENDUM TO THE ALPHABASIC USER'SMANIJM. Page 12

IC input/output ISAM ISAM control KILL kill file LCS lower case string LEfl left string LEFr$ left string LEN length string LT variable assignment LINE line LIST list text LOAD load program LCC natural logarithm LOGlO base 10 logarithm LOOKiJP lookup file MAP mapvariable MAX maximumvalue MEM memory size MID mid,string MID$ mid string MIN minimum value NEW new program NEXT loop termination NOEXPAND expand mode of £ Nm' logical complement ON on (goto,gosub,error) OPEN open file OR logical OR OUTPUT output PRINT print on terminal/file RANDOM random RANDOMIZE randomize RND function READ read data REM remark line RESTORE restore data RESUME resume after error RETURN subroutine exit RIGHT right string RIGHT$ right string RND random number RUN runprogram SAVE save program SCPJJE set scale factor SGN sign SIGNIFICANCE set significance SIN sine SPACE spaces SPACE$ spaces SQR square root STEP step STOP stop program 5TH ntneric to string conversion STR$ numeric to string conversion STPSIZ set string size

(July 1979) ADDENDUM W THE ALPHABASIC USER'SM.NUAL Page13

SUB sub(gosub) TAB tab TAN tangent THEN optional statement verb TIME system time TO to UCS uppercase string USING using VPL string to numeric conversion WOPD memory word WRITE write file XCALL external subroutine call XOR logical XOR

(July 1979)