Block Transfers: Variables Transfer (Part 2)

See all articles from SYNC v2 n6
Author(s): John Hoagland-Scher
Publication: SYNC
Pub Details: SYNC v2 n6 (Volume 2, Issue 6)
Date: November/December 1982
Pages: 102-107

The Problem of Saving Variables

One drawback of Timex/Sinclair computers is that LOADing a program erases any data that you have in the variables area to make room for in-coming variables. However, the program developed here allows you to keep variables in the machine safe from NEW, CLEAR, and LOAD. Furthermore, it allows you to transfer variables from one Basic program to another. This spares you the effort of re-entering a data base in each new program that you wish to use it in. You can even combine data stored in several different programs into a single data base, a facility you may desire should you upgrade your computer with additional memory. The heart of the Variables Transfer routine consists of block transfers to and from the space above RAMTOP of the sort we began exploring in Block Transfers, Part 1, in the last issue.

Those of you who completed Part I will have an easier time understanding the workings of the machine code presented here. However, even if this is your first attempt at a machine language program, you can cook-book your way through without much trouble. Chapters 24 through Appendix A of the Sinclair manual or Chapters 23 through Appendix A of the Timex/Sinclair manual and Dr. Ian Logan’s article “An Introduction to Machine Language” are useful, but not essential references. (See SYNC 1:6 or the SYNC special issue.)

The Variables Transfer Routine

Because Timex/Sinclair users now have anywhere from 1K to 56K of RAM, the Variables Transfer routine was written so that it will operate at any location in memory. In fact, the program modifies itself according to where it is located in memory, and according to how large the variables are that you wish to transfer. You do not have to change a single byte.

As in Part 1, the block transfers used here employ the LDIR instruction of the Z80(A). Recall that LDIR uses three register pairs, BC, DE, and HL, in the following way. Initially the BC pair holds the number of bytes (#bytes) to be transferred, the DE pair holds the first address of the destination block of memory (dest’n) to which information will be transferred, and the HL pair holds the first address of the block of information that you wish to transfer (source). The LDIR instruction transfers the contents of the address held in the HL pair to the address held in the DE pair, then it increments (adds 1 to) HL and DE, and decrements (subtracts 1 from) the BC pair. It then compares BC to zero,, and if BC is not equal to zero, the instruction is repeated. Otherwise the next instruction is executed. Thus the BC pair is a count-down register which reaches zero when the entire block has been transferred. Examine the blocks labeled A, C, F, and G in Figure 2. For now just look at column 5. Each of these blocks is a block transfer routine illustrating the use of the three register pairs and the LDIR instruction as just described. I will explain more about these blocks, and about how the program modifies itself later. Right now we should get down to business.

An Overview of the Process

In summary, what we will do is load a machine language routine into the space above RAMTOP, then transfer it to a SAVEable REM statement for future use. Then we will put it back up above RAMTOP and illustrate its uses with a pair of simple Basic programs. Before beginning you must reserve enough space above RAMTOP to accomodate the Variables Transfer routine (block D, figure 2), along with blocks A and C which will eventually be dispensed with. To do this, change RAMTOP to 17302 by typing POKE 16388,150 and ENTER, then POKE 16389,67 and ENTER, then hit NEW. Even if you have additional memory, you must load the machine language into the addresses in column 1 in Figure 2 initially, although this will not restrict future use of the program, so set RAMTOP to 17302 as above.

Beginning with Hex Loading

Now enter the hex loading program shown in Figure 1. This program is identical to the loading program that we used in the last issue, with the exception of the address in line 280, 17302. When you RUN this program, the screen will prompt you for a byte in hexadecimal. Begin entering the bytes listed in column 4 in Figure 2 (i.e., enter two digits from the column at a time as follows: type 01 and ENTER, then 5C and ENTER, 00 and ENTER, 11 and ENTER, and so on until you have finished entering the entire column, then type END and ENTER). Note that the program gives you a back-space key, ‘/’, in case you ENTER the wrong byte. Remember also that in a hexadecimal listing like that shown in column 4, Figure 2, 0 is always a zero and never the letter O.

Once you type END and ENTER, you can check to see that you did not leave any bytes out by typing PRINT PEEK 17405. The number 201 should appear on your screen (201d = C9h). Now SAVE the hex loading program for future use, then type NEW and ENTER to clear but the memory. Put the machine into FAST mode and enter a REM statement with 92 X’s (i.e., type 1 REM XXXXX . . .etc., then ENTER). You can change back to SLOW now. Note that the first X in the REM statement is at the address 16514. Now look more closely at block A, column 5 and 6 of Figure 2. Convince yourself that block A transfers block B from the addresses in column 1 to the addresses in column 2, the REM statement addresses. Call the routine in block A by typing RAND USR 17302 and ENTER, then ENTER again. Your REM statement should now contain the character representation of the bytes in block B (see Appendix A of your manual). The last character in the REM statement should be TAN if all has gone properly. If your REM statement remains full of X’s, you had better PRINT PEEK a few addresses between 17302 and 17313 to be sure that you entered block A properly.

Now that the Variables Transfer routine is in a SAVEable REM statement, SAVE it under a name such as “VARIABLES TRANSFER” or some suitable shorter mnemonic. Be sure your SAVE was successful.

Using over 1K RAM

At this point those of you with more than 1K RAM can begin to take advantage of it. The demonstration programs in Figures 3 and 4 require about 115 bytes above RAMTOP, but so that you can try out larger applications, reserve 156 bytes above RAMTOP by typing POKE 16388,100 and ENTER, then POKE 16389,67 and ENTER, then NEW. If you have additional memory, you may want to reserve several hundred bytes at the top of your RAM. LOAD “VARIABLES TRANSFER” and type RAND USR 16514. The USR 16514 entry calls the block C routine. Look again at Figure 2 and convince yourself that block C transfers block D from the addresses shown in column 2 to the addresses shown in column 3, the Operating Addresses (note that the DE register pair is loaded indirectly from the systems variable; 4004h = 16388d). The Variables Transfer routine is now safely above RAMTOP, and you should type NEW to clear out the memory.

Trying the Application Program

Enter the sample application program in Figure 3 (named in reference to the fact that I am still working with a 1K machine). When you RUN this program, line 40 checks to see how big the variables are that you set aside in earlier lines and asks you to confirm that there is sufficient space above RAMTOP for this amount of variable space, and in addition, for the Variables Transfer routine, block D. Because the routine in line 40 uses a set of registers that are also used for generating the display, some users have found that they must run the machine in FAST mode to avoid crashing the system. Conservative advice would be to add the following lines:

35 FAST
45 SLOW

The variable space above RAMTOP will be referred to as block Z from now on. Line 40 also lets you determine which variables will be transferred, although nothing is transferred as of yet. Arrays DIMensioned in earlier lines, such as A(3) and A$(3), and simple variables such as P will be transferred while variables introduced in later lines, such as N in line 70, will not be transferred.

RUN the program, confirm that you have reserved adequate space, then type CONTinue and ENTER. The screen will prompt you for a number and then a letter. This will happen three times for a total of six items. Enter anything you like, or just type 7 and ENTER, X and ENTER, 8 and ENTER, Y and ENTER, 9 and ENTER, Z and ENTER. You have now loaded the arrays that were DIMensioned in lines 10 and 20, and the computer has now transferred those two arrays and the variable P to block Z. The transfer was executed by line 130, RAND USR (P3+4) which calls the block transfer routine in block F. Look again at blocks F and G in Figure 2. Block F transfers variables and arrays into block Z, and block G transfers block Z back down into the variables area of the same, or a different, Basic program.

The screen should now be telling you to type NEW and ENTER, then LOAD and “RESTORE”, the program in Figure 4, so go ahead. You may actually want to SAVE “CRAMTOP” first for future reference. Note that the first three lines of RESTORE are identical to the first three lines of CRAMTOP. This is a necessity because space must be created in a Basic program before information can be transferred from block Z into the program. Line 40, RAND USR (P3+6) then calls the block G routine which performs the transfer. The rest of the program simply prints your arrays. RUN the program. If you entered 7, X, 8, Y, 9, Z, in CRAMTOP, these numbers should now appear. If they do not appear, recheck RESTORE, then SAVE it, then recheck CRAMTOP, and, if neither of these programs contains an error, go back to square one. If you made it this far successfully, you deserve a round of applause.

The Steps of the Variable Transfer Routine

Let me now summarize the steps you must go through to use the Variables Transfer routine in your own applications.

1) You must decide how much space you need to reserve above RAMTOP. Figure 5 contains formulas that are likely to be useful for this. In the case of CRAMTOP, A(3), A$(3), and P take up 21 +9 +6=36 bytes. Add this to the 79 bytes required to hold block B, and you will understand why CRAMTOP asked you if you had reserved at least 36+79=115 bytes. Reserve adequate space above RAMTOP (see chapter on the organization of memory or storage in your manual).

2) LOAD the Variables Transfer routine, then type RAND USR 16514 and ENTER to transfer it above RAMTOP.

3) DIMension arrays and assign variables that you will later want to transfer at the beginning of your Basic program as we did in CRAMTOP.

4) Call the block E routine, USR P, as we did in line 40 of CRAMTOP. There are several ways you can do this to obtain slightly different information.

PRINT USR P gives the last address in block Z. This must be smaller than the last address in your RAM, of course, or else you will lose your data.

PRINT USR P-P gives you the number of bytes that you must reserve above RAMTOP, as in line 40 of CRAMTOP.

PRINT USR P-P-79 gives you the number of bytes required in block Z, and thus allows you to check your calculations from Figure 5.

One of these three choices must go in a line like line 40 of CRAMTOP, even if you already know the answer it will return, because USR P sets up blocks F and G for the transfer.

5) Use any other variables that you need to in your Basic program after you call USR P. These will not be transferred. Then call USR (P3+4) once the arrays that you want to transfer are filled.

6) LOAD the program that you want to transfer your variables to, and DIMension arrays and assign variables at the beginning of the program that you wish to restore to the program. Do not forget P. Then, before any other variables are introduced in the program listing, insert a line containing RAND USR (P3+6). See the RESTORE program again if you are confused about this step. When you RUN the program, your arrays and variables will be written in from block Z.

Protecting Your Variables

RUN, CLEAR, LOAD, and NEW all possess the ability to erase variables that it may have taken you hours to type into the machine. You can employ one safety measure in the portion of any Basic program that serves to load a large array. You add a line which calls USR (P3+4) after each data point is entered. Each time that you call USR (P3+4) the data previously transferred will be written over identically, and the current entry will be added to block Z. Then if you hit one of the four functions above, just type RAND USR (P3+6) and the data will be restored. In the case of NEW, you will, of course, have to load your Basic program over again before restoring the data.

For example, add this feature to CRAMTOP by moving line 130 into the FOR-NEXT loop. Type 115 RAND USR (P3+4) and ENTER. An occasional SAVE is also a good idea to protect your data from power failures.

If you think you have the hang of Variables Transfers, you are now ready for your next crack at machine language.

The Problem of Fixed Addresses

Many machine language routines for the Sinclair computer are written so that they will work properly only if they are located at a fixed starting address. This might at first seem to be a requirement in programs which draw upon specific addresses within the routine for the information stored at those addresses. A fixed starting address might also seem necessary in a program in which one subroutine in the program (block E) is used to rewrite other subroutines within the program (blocks F and G). Let’s see how the Variables Transfer routine can modify itself so that it can be used at any location in memory.

First, look at the first instruction in block F, LD BC, #bytes. While claiming to load BC with the number of bytes in the variables space of a Basic program, the four zeros in column 4 show that in actuality BC is only loaded with zero, that is, if block E, i.e., USR P, is not called prior to calling block F, i.e., USR (P+54). How does block E change those four zeros to the number of bytes to be transferred?

The four zeros make up the two bytes at RAMTOP + 37h and RAMTOP + 38. Confirm this with column 3 (37h = 55d and 38h = 56d). Now look at block I. Block I subtracts VARS from E LINE then decrements the result to obtain the amount of variable space that you want to transfer when you call block E (i.e., USR P) (see the chapter on system variables in your manual). The amount of variable space is now sitting in the HL register pair. Because the IX register was loaded earlier with RAMTOP, the next two instructions, LD (IX+37),L and LD (IX+38),H rewrite the two bytes that we just discussed in block F. Now block F truly contains the number of bytes to be transferred. Four instructions in blocks F and G appear to load a register pair with zero. Actually, block H writes the destination into block F and the source into block G, then block I writes the number of bytes into blocks F and G. Block J puts the last address in block Z into the BC register pair so that this information is returned to you when you PRINT USR P.

Although I said that the Variables Transfer routine can be used at any starting address, the use of the IX register just described above forces one qualification on that statement. The Variables Transfer routine can be used at any starting address provided that its starting address is RAMTOP. Rather than loading RAMTOP into the IX register, we could have the program discover its own starting address by reading the program counter, and then load that address into the IX register. This would free us from the above qualification. I will leave the method by which one transfers the contents of the program counter to the IX register as a puzzle for those of you who write machine language. (The answer will appear at the end of this article.)

Suggestions to Machine Code Programmers

The Sinclair and Timex/Sinclair computers are serious computers, and their usefulness will be limited only by the quality of the software available for them. Therefore, I suggest that those of you who write machine language routines write them so that they can be used at any location in memory.

To return now to practical matters, Sinclair cautions us that a USR routine should not disturb the IX register if compute and display is operating. In spite of this caution, I have failed to crash my system yet. Conservative advice would be to run the machine in the FAST mode when you are dealing with a questionable situation like this one.

A Mystery Application

The Variables Transfer routine can be used to compile machine language routines for use in a single Basic program. All you need is a loading program that places your machine language in an array. This is easily obtained by adding and substituting a few lines in Figure 1.

Make the changes in Figure 1 that are shown in Figure 6. The number, m, should be large enough that 5 * m is greater than or equal to the number of bytes in your routine. If Z(m) is the first array held in block Z, then the starting address of your machine language routine is RAMTOP + 85 in block Z and

PEEK 16400+256*PEEK 16401+6

in the variables area of your Basic program. PEEKing the contents of the machine language that you enter will be easier from its block Z addresses because the variables space below RAMTOP moves around quite a bit.

When modifying Figure 1, set m in line 100 equal to 4. This provides you with 4 * 5 = 20 bytes of space. RUN the modified program, then type CONTinue. Figure 7 contains a routine which returns the number of unused bytes below RAMTOP. (This was written by Dr. Ian Logan and is reprinted here with the kind permission of SYNTAX ZX80, RD2 Box 457, Harvard, MA 01451.) Enter the bytes in Figure 7 (i.e., 2A and ENTER, 1C and ENTER, and so on). Then type END and ENTER. To find out how much unused memory you still have below RAMTOP, type PRINT USR (P+85) and ENTER. The number 204 should appear at the top of your screen if you are working with a 1K machine. As you can see, there is not much space left. On the other hand,, you do not need much memory to have fun with machine language!

Congratulations if you have made it through this article. If you have a useful program or two, and in addition, a few points to puzzle over, then we have both succeeded.

The Answer to the Puzzle

When you CALL a subroutine from within a machine language routine, the program counter is pushed onto the stack. The first instructions in the subroutine should then be POP IX, PUSH IX . . . etc. RET. When the main program is returned to, the IX register will contain the address of the instruction following the CALL instruction in the main routine. For the sake of simplicity, we can have the subroutine decrement the IX register so that it contains the starting address of the main routine upon return to the main routine. To preserve the contents of the IX register through all of this, the first instruction in the main routine should be PUSH IX. Then, CALL the routine immediately. At the end of your main routine, do not forget to POP IX.

Figure 8 shows a subroutine that will put the starting address of a main routine from which it is called into the IX register on return. The main routine must begin with PUSH IX, CALL 16514, as above.

To implement this routine with a version of the Variables Transfer routine, VAR PLUS, load the bytes in Figure 8 into the test program in Figure 9 and SAVE the result.

Now LOAD the Variables Transfer routine, but do not type RAND USR 16514. Just leave it in the REM statement. POKE in the changes that are shown in Figure 10, (i.e., POKE 16520,0 and ENTER, POKE 16521,17 and ENTER, and so on). Add the lines in Figure 11, and you have a program that prompts you for a starting address, and then locates itself there. Be sure that you have plenty of space above RAMTOP, then RUN the program. For the test program in Figure 9, you should enter 17252 when the screen prompts you. RAMTOP must be smaller than this.

LOAD the test program and RUN it. The screen should show the following:

INITIAL A10
ALTERED A1
RESTORED A10

Note that any program that uses the IX register in the manner that the modified Variables TRansfer routine (VAR PLUS) does, can use the Figure 8 routine to locate itself. Thus one routine must remain tied to an address while the others go free.

Figure 1.

   1 REM FROM BOOTH, SYNC VOL.2, NUMBER 1
200 LET V=-1
210 LET V=V+1
220 IF INT (V/50)*50=V THEN CLS
230 INPUT H$
240 IF H$="" THEN GOTO 230
250 PRINT H$;"#";
260 IF H$="END" THEN STOP
270 IF H$="/" THEN GOTO 300
280 POKE 17302+V,16*CODE (H$)+CODE (H$(2))-476
290 GOTO 210
300 LET V=V-1
310 GOTO 230

Figure 2.

          REM
Loading   Statement Operating Object
Addresses Addresses Addresses Code      Instruction       Comment               Blocks
17302                         015C00    LD BC,#bytes      005Ch=92d                    :
17305                         118240    LD DE,dest'n      4082h=16514d                 :
17308                         21A243    LD HL,source      43A2h=17314d                 A
17311                         EDB0      LDIR              blk B transfer               :
17313                         C9        RET               return                       :
17314     16514               014F00    LD BC,#bytes      004Fh=79d                  : :
17317     16517               218F40    LD HL,source      408Fh=16527d               : :
17320     16520               ED5B0440  LD DE,(dest'n)    4004h=RAMTOP               C :
17324     16524               EDB0      LDIR              blk D transfer             : :
17326     16526               C9        RET               return                     : :
17327     16527     RAMTOP    DDE5      PUSH IX           save initial IX          : : :
17329     16529     +2        2A0440    LD HL,(4004)      RAMTOP in HL           : : : :
17332     16532     +5        E5        PUSH HL           HL to IX               : : : :
17333     16533     +6        DDE1      POP IX            RAMTOP in IX           : : : :
17335     16535     +8        014F00    LD BC,004F        004Fh=79d              : : : :
17338     16538     +11       09        ADD HL,BC         addr.of blk Z          H : : :
17339     16539     +12       DD753A    LD (IX+3A),L      dest'n to blk F        : : : :
17342     16542     +15       DD743B    LD (IX+3B),H      dest'n to blk F        : : : :
17345     16545     +18       DD754A    LD (IX+4A),L      source to blk G        : : : :
17348     16548     +21       DD744B    LD (IX+4B),H      source to blk B        : : : :
17351     16551     +24       E5        PUSH HL           save addr.blk Z          : : :
17352     16552     +25       2A1440    LD HL,(4014)      4014h=E_LINE           : : : :
17355     16555     +28       ED4B1040  LD BC,(4010)      4010h=VARS             : : : :
17359     16559     +32       ED42      SBC HL,BC         E_LINE-VARS            : : : :
17361     16561     +34       2B        DEC HL            variable space         I E D B
17362     16562     +35       DD7537    LD (IX+37),L      #bytes to blk F        : : : :
17365     16565     +38       DD7438    LD (IX+38),H      #bytes to blk F        : : : :
17368     16568     +41       DD7543    LD (IX+43),L      #bytes to blk G        : : : :
17371     16571     +44       DD7444    LD (IX+44),H      #bytes to blk G        : : : :
17374     16574     +47       C1        POP BC            addr.of blk Z          : : : :
17375     16575     +48       09        ADD HL,BC         last addr.blk Z        J : : :
17376     16576     +49       E5        PUSH HL           HL to BC               : : : :
17377     16577     +50       C1        POP BC            last addr.blk Z        : : : :
17378     16578     +51       DDE1      POP IX            restore intl.IX          : : :
17380     16580     +53       C9        RET               gives end blk Z          : : :
17381     16581     +54       010000    LD BC,#bytes      variable space           : : :
17384     16584     +57       110000    LD DE,dest'n      addr.of blk Z            : : :
17387     16587     +60       2A1040    LD HL,(source)    4010h=VARS               F : :
17390     16590     +63       EDB0      LDIR              blk transfer             : : :
17392     16592     +65       C9        RET               return                   : : :
17393     16593     +66       010000    LD BC,#bytes      variable space           : : :
17396     16596     +69       ED5B1040  LD DE,(dest'n)    4010h=VARS               : : :
17400     16600     +73       210000    LD HL,source      addr.of blk Z            G : :
17403     16603     +76       EDB0      LDIR              blk transfer             : : :
17405     16605     +78       C9        RET               return                   : : :
                    +79       The size of this block is                            :
                              user defined. It is the area used                    Z
                              for variable storage above RAMTOP,
                              safe during NEW, LOAD, and CLEAR.                    :

Figure 3.

   1 REM CRAMTOP
10 DIM A(3)
20 DIM A$(3)
30 LET P=PEEK 16388+256*PEEK 16389
40 PRINT "HAVE YOU RESERVED AT LEAST#";USR P-P;"##BYTES ABOVE RAMTOP?"
50 STOP
60 PRINT "A(3)","A$(3)"
70 FOR N=1 TO 3
80 INPUT A(N)
90 PRINT A(N),
100 INPUT A$(N)
110 PRINT A$(N)
120 NEXT N
130 RAND USR (P+54)
140 PRINT "NOW TYPE NEW, THEN LOAD RESTORE."

Figure 4.

   1 REM RESTORE
10 DIM A(3)
20 DIM A$(3)
30 LET P=PEEK 16388+256*PEEK 16389
40 RAND USR (P+66)
50 PRINT "A(3)","A$(3)"
60 FOR N=1 TO 3
70 PRINT A(N),A$(N)
80 NEXT N
Figure 5. Sample Calculations of the Bytes Used to Store Three types of Variables.

Variable Type        Bytes Used

Simple Variables
  LET P=             1+5
  LET PI=            2+5
  LET POP=           3+5
Numerical Arrays
  DIM A(m)           1*2+4+5*m
  DIM A(m,n)         2*2+4+5*m*n
  DIM A(m,n,p)       3*2+4+5*m*n*p
Character Arrays
  DIM A$(m)          1*2+4+m
  DIM A$(m,n)        2*2+4+m*n
  DIM A$(m,n,p)      3*2+4+m*n*p

Figure 6.

Add these lines
1 REM MC ARRAYS
100 DIM Z(m)
110 LET P=PEEK 16388+256*PEEK 16389
120 PRINT "AT LEAST#";USR P-P;"#BYTES ABOVE RAMTOP?"
130 STOP
285 RAND USR (P+54).

Change line 280 to,
280 POKE PEEK 16400+256*PEEK 16401+6+V,16*CODE (H$)+CODE (H$(2))-476

Figure 7.

Dr. Logan's Bytes Remaining Sequence
2A,1C,40,CD,CB,0E,E5,C1,21,14,
00,00,ED,42,E5,C1,C9
Figure 8.

Address    Hex      Decimal
in REM     object   object
statement  code     code      Instruction
16514      DD,E1    221,225   POP IX
16516      DD,E5    221,229   PUSH IX
16518      06,05    006,005   LD B,5
16520      DD,2B    221,043   DEC IX
16522      10,FC    016,252   DJNZ e
16524      C9       201       RET

Figure 9.

   1 REM XXXXXXXXXXX
10 LET P=17252
20 LET A=10
30 PRINT "INITIAL A=";A
40 RAND USR P
50 RAND USR (P+54)
60 LET A=1
70 PRINT "ALTERED A=";A
80 RAND USR (P+66)
90 PRINT "RESTORED A=";A
Figure 10.

REM Statement
addresses      Hex changes    Decimal changes   Instruction
16520          00,11,00,00    0,17,0,0          LD DE,nn
16529          CD,82,40       205,130,64        CALL 16514
16532          DD,E5          221,229           PUSH IX
16534          E1             225               POP HL

Figure 11.

   2 REM VAR PLUS
10 PRINT "ENTER THE ADDRESS THAT YOU WANT VAR PLUS TO BEGIN AT "
20 INPUT P
30 POKE 16522,256*(P/256-INT (P/256))
40 POKE 16523,INT (P/256)
50 RAND USR 16514
60 PRINT "P IN YOUR APPLICATIONS MUST NOW =#";P

Note: Type-in program listings on this website use ZMAKEBAS notation for graphics characters.