Original Title: Commodore 128 Personal Computer System Guide
Published by: Commodore Business Machines, Ltd. 1985
Typed by: Rene van Belzen
Version: April 9, 2000


Notes from the typist
=====================

Entering (data typing) the Commodore 128 System Guide... This entailed far
more than I bargained for. This is because not only because the original
text contained errors, which had to be corrected, but also because some
useful information and hints were missing.

I could have written a separate e-book containing what I feel should have
been included in the C128 System Guide as well (and I still may do that
one day). In stead I added some words here and there to clarify matters,
to avoid wandering off too much from the original text. This means this
e-text is not an exact 1:1 replica of the original, but I'm sure the
authors of the original System Guide wouldn't object (too much). They pro-
bably had to write the System Guide in a jiffie, while I could take as long
as I wanted to get the text just right.


Credits:
-------

Most of the e-text I have typed (and corrected) myself. However,
some of the ASCII art and some of the appendixes I have copied and adapted
from the C64 Programmer's Reference Guide, the e-text version by Ville
Muikkula. Also, where the original text by Commodore had shortcomings I
added/corrected text.

Many thanks to all those people who pointed me to the existing errors in
one of my earlier publications of the C128 System Guide.


April 9, 2000

Rene van Belzen
mailto:hurray@xs4all.nl
http://www.xs4all.nl/~hurray/cbm/
(Note that both the e-mail and web address may change at any point in the
future.)



                                System Guide
                                  Commodore
                                     128
                              Personal Computer



(c) Commodore Electronics, Ltd. 1985. All rights reserved.

Copyright (c) 1985 by Commodore Electronics Limited
All rights reserved

This manual contains copyrighted and proprietary information. No part of
this publication may be reproduced, stored in a retrieval system, or trans-
mitted in any form or by any means, electronic, mechanical, photocopying,
recording or otherwise, without the prior written permission of Commodore
Electronics Limited.

Commodore BASIC 7.0

Copyright (c) 1985 by Commodore Electronics Limited; All rights reserved

Copyright (c) 1977 by Microsoft Corp.
All rights reserved

CP/M (R) Plus Version 3.0

Copyright (c) 1982 Digital Research Inc.
All rights reserved

CP/M is a registered trademark of Digital Research Inc.



CONTENTS

C128 SYSTEM GUIDE

CHAPTER I - INTRODUCTION

  SECTION 1 - HOW TO USE THIS GUIDE                                   
  SECTION 2 - OVERVIEW OF THE COMMODORE 128 PERSONAL COMPUTER          

CHAPTER II - USING C128 MODE

  SECTION 3 - GETTING STARTED IN BASIC                                 
  SECTION 4 - ADVANCED BASIC PROGRAMMING                               
  SECTION 5 - SOME BASIC COMMANDS AND KEYBOARD OPERATIONS
              UNIQUE TO C128
  SECTION 6 - COLOR, ANIMATION AND SPRITE GRAPHICS
  SECTION 7 - SOUND AND MUSIC IN C128 MODE
  SECTION 8 - USING 80 COLUMNS

CHAPTER III - USING C64 MODE

  SECTION 9 - USING BASIC IN C64 MODE
  SECTION 10 - STORING AND REUSING YOUR PROGRAMS IN C64 MODE

CHAPTER IV - CP/M MODE

  SECTION 11 - INTRODUCTION TO CP/M 3.0
  SECTION 12 - FILES, DISKS AND DRIVES IN CP/M 3.0
  SECTION 13 - USING THE CONSOLE AND PRINTER IN CP/M 3.0
  SECTION 14 - SUMMARY OF MAJOR CP/M 3.0 COMMANDS
  SECTION 15 - COMMODORE ENHANCEMENTS TO CP/M 3.0

CHAPTER V - BASIC 7.0 ENCYCLOPAEDIA

  SECTION 16 - INTRODUCTION
  SECTION 17 - BASIC COMMANDS AND STATEMENTS
  SECTION 18 - BASIC FUNCTIONS
  SECTION 19 - VARIABLES AND OPERATIONS
  SECTION 20 - RESERVED WORDS AND SYMBOLS


  APPENDICES

  APPENDIX A - BASIC LANGUAGE ERROR MESSAGES
  APPENDIX B - DOS ERROR MESSAGES
  APPENDIX C - CONNECTORS/PORTS FOR PERIPHERAL EQUIPMENT
  APPENDIX D - SCREEN DISPLAY CODES
  APPENDIX E - ASCII AND CHR$ CODES
  APPENDIX F - SCREEN AND COLOR MEMORY MAPS
  APPENDIX G - DERIVED MATHEMATICAL FUNCTIONS
  APPENDIX H - MEMORY MAP
  APPENDIX I - CONTROL AND ESCAPE CODES
  APPENDIX J - MACHINE LANGUAGE MONITOR
  APPENDIX K - BASIC 7.0 ABBREVIATIONS
  APPENDIX L - DISK COMMAND SUMMARY

GLOSSARY

INDEX



                                   CHAPTER

                                      1

                                INTRODUCTION



SECTION 1

1. How to Use This Guide



This Commodore 128 System Guide is designed to help you make full use of
the advanced capabilities of the Commodore 128 computer.

    Before you read any further in this System Guide, make sure you have
    read the other book that comes with your computer, the Commodore 128
    Personal Computer Introductory Guide. This introductory guide contains
    important information on getting started with the Commodore 128.

    If you are primarily interested in using the BASIC language to create
    and run your own programs, you should read Chapter II, USING C128 MODE.
    This chapter introduces you to the BASIC programming language as used
    in both C128 and C64 modes, describes the Commodore 128 keyboard,
    defines some advanced commands you can use in both C128 and C64 modes,
    shows how to use a number of powerful new BASIC commands (including
    colour, graphic and sound commands) that are unique to C128 Mode, and
    describes how to use the 80-column capabilities available in C128 Mode.

    If you want to use BASIC in C64 Mode, read Chapter III, USING C64 MODE.

    If you want to use CP/M on the Commodore 128, read Chapter IV, USING
    CP/M MODE. This chapter tells you how to start up and use CP/M on the
    Commodore 128. In CP/M you can choose from thousands of commercial
    software packages, including the PERFECT series (PERFECT WRITER,
    PERFECT CALC, PERFECT FILER). You can also create your own CP/M
    programs.

    If you want details on the BASIC 7.0 commands, read Chapter IV, BASIC
    7.0 ENCYCLOPAEDIA. This chapter gives format and usage details on all
    BASIC 7.0 commands, statements and functions.

    If, after reading Chapters I through V, you are looking for additional
    technical information about a particular Commodore 128 topic, first
    check the Appendices to this System Guide. These appendices contain a
    wide range of information, such as a complete list of BASIC and DOS
    error messages and a summary of disk commands. A Glossary following the
    Appendices provides definitions of computing terms.

For complete technical details about any feature of the Commodore 128, con-
sult the Commodore 128 Programmer's Reference Guide.



SECTION 2

2. Overview of the Commodore C128 Personal Computer



2.1 OVERVIEW OF THE COMMODORE C128 PERSONAL COMPUTER

  2.1.1 C128 MODE
  2.1.2 C64 MODE
  2.1.3 CP/M MODE

2.2 SWITCHING BETWEEN MODES

  2.2.1 MODE SWITCHING CHART



2.1 OVERVIEW OF THE COMMODORE C128 PERSONAL COMPUTER

The Commodore 128 Personal Computer offers three primary operating modes:

    * C128 Mode
    * C64 Mode
    * CP/M Mode


2.1.1 C128 Mode

In C128 Mode, the Commodore 128 Personal Computer provides access to 128K
of RAM and a powerful extended BASIC language known as BASIC 7.0. BASIC 7.0
offers over 140 commands, statements and functions. C128 Mode also provides
both 40 and 80 column output and full use of the 92-key keyboard. A built-
in machine language monitor allows you to create and debug your own machine
language programs. In C128 Mode you can use a number of new peripheral
devices from Commodore, including a new fast serial disk drive (the 1571),
a mouse, and a 40/80 column composite video/RGBI monitor (the 1901). You
can also use all standard Commodore serial peripherals.


2.1.2 C64 Mode

In C64 Mode, the Commodore 128 operates exactly like a Commodore 64 com-
puter, allowing you to take full advantage of the wide range of available
C64 software. You also have full compatibility with all C64 peripherals.

C64 Mode provides BASIC 2.0 language, 40 column output and access to 64K of
RAM.


2.1.3 CP/M Mode

In CP/M Mode, an onboard Z80 microprocessor gives you all the capabilities
of Digital Research's CP/M Plus version 3.0, plus several new capabilities
by Commodore. The Commodore 128's CP/M package, called CP/M Plus, provides
128K of RAM, 40 and 80 column output, access to the full keyboard, inclu-
ding the numeric keypad and special keys, and access to the new Commodore
1571 fast serial disk drive as well as standard serial peripherals.

Chapters II, III and IV, which include Sections 3 through 15, tell you how
to access and use the capabilities of the three powerful and versatile
operating modes of the Commodore 128 Personal Computer.


2.2 Switching Between Modes

The following chart tells you how to switch to one mode from another.

NOTE: If you are using a Commodore 1901 dual monitor remember to move the
video switch on the monitor from the COMPOSITE or SEPARATED to RGBI when
switching from 40 column to 80 column display. Reverse this step when
switching from 80 to 40 columns.


2.2.1 MODE SWITCHING CHART

                                     FROM
T| OFF          C128        C128        C64         CP/M        CP/M
O|              40 COL(1)   80 COL(2)   (3)         40 COL(4)   80 COL(5)
-+------------+-----------+-----------+-----------+-----------+-----------+
1|1.Check that|           |1.Press    |1.Check    |1.Check    |1.Check    |
 |  {40/80}   |           |  {esc}    |  that     |  that     |  that     |
 |  key is UP.|           |  key;     |  {40/80}  |  {40/80}  |  {40/80}  |
 |2.Turn      |           |  release. |  key is   |  key is   |  key is   |
 |  computer  |           |2.Press X  |  UP.      |  UP.      |  UP.      |
 |  ON.       |           |  key.     |2.Turn     |2.Remove   |2.Remove  
 |            |           |      OR   |  computer |  CP/M     |  CP/M     |
 |            |           |1.Check    |  OFF, then|  system   |  system   |
 |            |           |  that     |  ON.      |  disk, if |  disk, if |
 |            |           |  {40/80}  |           |  neces-   |  neces-   |
 |            |           |  key is   |           |  sary.    |  sary.    |
 |            |           |  UP.      |           |3.Turn     |3.Turn     |
 |            |           |2.Press    |           |  computer |  computer |
 |            |           |  {reset}  |           |  OFF, then|  OFF, then|
 |            |           |  button.  |           |  ON.      |  ON.      |
-+------------+-----------+-----------+-----------+-----------+-----------+
2|1.Press     |1.Press    |           |1.Press    |1.Press    |1.Check    |
 |  {40/80}   |  {esc}    |           |  {40/80}  |  {40/80}  |  that     |
 |  key DOWN. |  key;     |           |  key DOWN.|  key DOWN.|  {40/80}  |
 |2.Turn      |  release. |           |2.Turn     |2.Remove   |  key is   |
 |  computer  |2.Press X  |           |  computer |  CP/M     |  DOWN.    |
 |  ON.       |  key.     |           |  OFF, then|  system   |2.Remove   |
 |            |      OR   |           |  ON.      |  disk from|  CP/M     |
 |            |1.Press    |           |           |  drive, if|  system   |
 |            |  {40/80}  |           |           |  neces-   |  disk from|
 |            |  key DOWN.|           |           |  sary.    |  drive, if|
 |            |2.Press    |           |           |3.Turn     |  neces-   |
 |            |  {reset}  |           |           |  computer |  sary.    |
 |            |  button.  |           |           |  OFF, then|3.Turn     |
 |            |           |           |           |  ON.      |  computer |
 |            |           |           |           |           |  OFF, then|
 |            |           |           |           |           |  ON.      |
-+------------+-----------+-----------+-----------+-----------+-----------+
3|1.Hold {C=} |1.Type     |1.Type     |           |1.Turn     |1.Turn     |
 |  key DOWN. |  GO 64;   |  GO 64;   |           |  computer |  computer |
 |2.Turn      |  press    |  press    |           |  OFF.     |  OFF.     |
 |  computer  |  {return}.|  {return}.|           |2.Check    |2.Check    |
 |  ON.       |2.The      |2.The      |           |  that     |  that     |
 |      OR    |  computer |  computer |           |  {40/80}  |  {40/80}  |
 |1.Insert C64|  responds:|  responds:|           |  key is   |  key is   |
 |  cartridge.|  ARE YOU  |  ARE YOU  |           |  UP.      |  UP.      |
 |2.Turn      |  SURE?    |  SURE?    |           |3.Hold DOWN|3.Hold DOWN|
 |  computer  |  Type Y;  |  Type Y;  |           |  {C=} key |  {C=} key |
 |  ON.       |  press    |  press    |           |  while    |  while    |
 |            |  {return}.|  {return}.|           |  turning  |  turning  |
 |            |           |           |           |  computer |  computer |
 |            |           |           |           |  ON.      |  ON.      |
 |            |           |           |           |      OR   |      OR   |
 |            |           |           |           |1.Turn     |1.Turn     |
 |            |           |           |           |  computer |  computer |
 |            |           |           |           |  OFF.     |  OFF.     |
 |            |           |           |           |2.Insert   |2.Insert   |
 |            |           |           |           |  C64 car- |  C64 car- |
 |            |           |           |           |  tridge.  |  tridge.  |
 |            |           |           |           |3.Turn     |3.Turn     |
 |            |           |           |           |  power ON.|  power ON.|
-+------------+-----------+-----------+-----------+-----------+-----------+
4|1.Turn disk |1.Turn disk|1.Turn disk|1.Check    |           |1.Insert   |
 |  drive ON. |  drive ON.|  drive ON.|  that     |           |  CP/M     |
 |2.Insert    |2.Insert   |2.Insert   |  {40/80}  |           |  utilities|
 |  CP/M sys- |  CP/M sys-|  CP/M sys-|  key is   |           |  disk in  |
 |  tem disk  |  tem disk |  tem disk |  UP.      |           |  drive.   |
 |  in disk   |  in disk  |  in disk  |2.Turn disk|           |2.At screen|
 |  drive.    |  drive.   |  drive.   |  drive ON.|           |  prompt,  |
 |3.Check that|3.Check    |3.Check    |3.Insert   |           |  A> type: |
 |  {40/80}   |  that     |  that     |  CP/M     |           |  DEVICE   |
 |  key is UP.|  {40/80}  |  {40/80}  |  system   |           |  CONOUT   |
 |4.Turn      |  key is   |  key is   |  disk in  |           |  = 40COL. |
 |  computer  |  UP.      |  UP.      |  drive.   |           |3.Press    |
 |  ON.       |4.Type:    |4.Type:    |4.Turn     |           |  {return}.|
 |            |  BOOT.    |  BOOT.    |  computer |           |           |
 |            |5.Press    |5.Press    |  OFF, then|           |           |
 |            |  {return}.|  {return} |  ON.      |           |           |
-+------------+-----------+-----------+-----------+-----------+-----------+
5|1.Turn disk |1.Turn disk|1.Turn disk|1.Press    |1.Insert   |           |
 |  drive ON. |  drive ON.|  drive ON.|  {40/80}  |  CP/M     |           |
 |2.Insert    |2.Insert   |2.Insert   |  key DOWN.|  utilities|           |
 |  CP/M sys- |  CP/M sys-|  CP/M sys-|2.Turn disk|  disk in  |           |
 |  tem disk  |  tem disk |  tem disk |  drive ON.|  drive.   |           |
 |  in disk   |  in disk  |  in disk  |3.Insert   |2.At screen|           |
 |  drive.    |  drive.   |  drive.   |  CP/M     |  prompt   |           |
 |3.Press     |3.Press    |3.Check    |  system   |  A> type: |           |
 |  {40/80}   |  {40/80}  |  that     |  disk in  |  DEVICE   |           |
 |  key DOWN. |  key DOWN.|  {40/80}  |  drive.   |  CONOUT   |           |
 |4.Turn      |4.Type:    |  key is   |4.Turn     |  = 80COL. |           |
 |  computer  |  computer |  DOWN.    |  computer |3.Press    |           |
 |  ON.       |  BOOT.    |4.Type:    |  OFF, then|  {return}.|           |
 |            |5.Press    |  BOOT.    |  ON.      |           |           |
 |            |  {return}.|5.Press    |           |           |           |
 |            |           |  {return}.|           |           |           |
-+------------+-----------+-----------+-----------+-----------+-----------+

NOTE: If you are using a Commodore 1902 dual monitor, remember to move the
video switch on the monitor from COMPOSITE or SEPARATED to RGBI when
switching from 40-column to 80-column display; reverse this step when
switching from 80 to 40 columns. Also, when switching between modes remove
any cartridges from the expansion port and any disks from the disk drive.



                                   CHAPTER

                                      2

                               USING C128 MODE



SECTION 3

3. Getting Started in Basic



3.1 BASIC PROGRAMMING LANGUAGE

  3.1.1 Direct Mode
  3.1.2 Program Mode


3.2 USING THE KEYBOARD

  3.2.0.1 C128 Keyboard Lay-Out
  3.2.1 Keyboard Character Sets
  3.2.2 Using the Command Keys
    3.2.2.1 Return
    3.2.2.2 Shift
    3.2.2.3 Shift Lock
    3.2.2.4 Moving the cursor
      3.2.2.4.1 Using the four Arrow Cursor keys
      3.2.2.4.2 Using the CRSR keys
    3.2.2.5 INST/DEL
      3.2.2.5.1 Insterting characters
      3.2.2.5.2 Deleting characters
      3.2.2.5.3 Using INSerT and DELete together
    3.2.2.6 Control
    3.2.2.7 Run/Stop
    3.2.2.8 Restore
    3.2.2.9 CLR/Home
    3.2.2.10 Commodore key
  3.2.3 Function Keys
  3.2.4 Displaying Graphic Characters
  3.2.5 Rules for Typing BASIC Language Programs

3.3 GETTING STARTED - THE PRINT COMMAND

  3.3.1 Printing Numbers
  3.3.2 Using the Question Mark to Abbreviate the PRINT Command
  3.3.3 Printing Text
  3.3.4 Printing in Different Colors
        Table 3-1. Available Colors in 40- and 80-Column Screen Formats.
  3.3.5 Using the Cursor Keys Inside Quotes with the PRINT Command

3.4 BEGINNING TO PROGRAM

  3.4.1 What a Program Is
  3.4.2 Line Numbers
  3.4.3 Viewing your Program - The LIST Command
  3.4.4 A Simple Loop - The GOTO Command
  3.4.5 Clearing the Computer's Memory - The NEW Command
  3.4.6 Using Color in a Program

3.5 EDITING YOUR PROGRAM

  3.5.1 Erasing a Line from a Program
  3.5.2 Duplicating a Line
  3.5.3 Replacing a Line
  3.5.4 Changing a Line

3.6 MATHEMATICAL OPERATIONS

  3.6.1 Addition and Subtraction
  3.6.2 Multiplication and Division
  3.6.3 Exponentiation
  3.6.4 Order of Operations
  3.6.5 Using Parentheses to Define the Order of Operations

3.7 CONSTANTS, VARIABLES AND STRINGS

  3.7.1 Constants
  3.7.2 Variables
  3.7.3 Strings

3.8 SAMPLE PROGRAM

3.9 STORING AND REUSING YOUR PROGRAMS

  3.9.1 Formatting a Disk - The HEADER Command
  3.9.2 SAVEing on Disk
  3.9.3 SAVEing on Cassette
  3.9.4 LOADing from Disk
  3.9.5 LOADing from Cassette Tape
  3.9.6 Other Disk-Related Commands
    3.9.6.1 Verifying a Program
    3.9.6.2 Displaying Your Disk Directory



3.1 BASIC PROGRAMMING LANGUAGE

The BASIC programming language is a special language that lets you communi-
cate with your Commodore 128. Using BASIC is one means by which you
instruct your computer what to do.

BASIC has its own vocabulary (made up of commands, statements and func-
tions) and its own rules of structure (called syntax). You can use the
BASIC vocabulary and syntax to create a set of instructions called a
program, which your computer can then perform or "run".

Using BASIC, you can communicate with your Commodore 128 in two ways:
within a program, or directly (outside a program).


3.1.1 Direct Mode

Your Commodore 128 is ready to accept BASIC commands in direct mode as soon
as you turn on the computer. In the direct mode, you type commands on the
keyboard and enter them into the computer by pressing the {return} key.
Most BASIC commands in your Commodore 128 can be used in direct mode as
well as in a program.


3.1.2 Program Mode

In program mode you enter a set of instructions that perform a specific
task. Each instruction is contained in a sequential program line. A state-
ment in a program may be as long as 160 characters; this is equivalent to
four full screen lines in 40-column format, and two full screen lines in
80-column format.

Once you have typed a program, you can use it immediately by typing the RUN
command and pressing the {return} key. You can also store the program on
disk or tape by using the DSAVE (or SAVE) command. Then you recall it from
the disk or tape by using the DLOAD (or LOAD) command. This command copies
the program from the disk or tape and places that program in the Commodore
128's memory. You can then use or "execute" the program again by entering
the RUN command. All these commands are explained later in this section.
Most of the time you will be using you computer with programs, including
programs you yourself write, and commercially available software packages.
The only time you operate in direct mode is when you are manipulating or
editing your programs with commands such as LIST, LOAD, SAVE and RUN. As a
rule, the difference between direct mode and operation within a program is
that direct mode commands have no line numbers.


3.2 USING THE KEYBOARD

Shown below is the keyboard of the Commodore 128 Personal Computer.


3.2.0.1 C128 Keyboard Lay-Out
                                                   +--------------+
  /E\/T\/A\/C\      /H\/L\/4\/N\      /u\/d\/l\/r\ | /F\/F\/F\/F\ |
  |s  a  l   |      |l         |      |p  w  f  g| | |1  3  5  7| |
  \c/\b/\t/\L/      \p/\F/\8/\S/      \ /\n/\t/\t/ | \ /\ /\ /\ / |
+--------------------------------------------------+--------------+
| /L\/!\/"\/#\/$\/%\/&\/'\/(\/)\/ \/ \/ \/l\/C\/I\ | / \/ \/ \/ \
| |                              0  +  -  b      | | |7  8  9  +|
| \A/\1/\2/\3/\4/\5/\6/\7/\8/\9/\ /\ /\ /\s/\H/\D/ | \ /\ /\ /\ /
|                                                  |
| /co\/ \/ \/ \/ \/ \/ \/ \/ \/ \/ \/ \/ \/U\/RES\ | / \/ \/ \/ \
| |nt  Q  W  E  R  T  Y  U  I  O  P  @  *     STO| | |4  5  6  -|
| \rl/\ /\ /\ /\ /\ /\ /\ /\ /\ /\ /\ /\ /\A/\RE / | \ /\ /\ /\ /
|                                                  |
| /R\/S\/ \/ \/ \/ \/ \/ \/ \/ \/ \/ \/[\/]\/RE  \ | / \/ \/ \/ \
| |   h  A  S  D  E  F  G  H  J  K  L        TURN| | |1  2  3||E|
| \S/\L/\ /\ /\ /\ /\ /\ /\ /\ /\ /\ /\:/\;/\    / | \ /\ /\ /|N|
|                                                  |          |T|
| /C\/SH\/ \/ \/ \/ \/ \/ \/ \/<\/>\/?\/SHI\/C\/C\ | /    \/ \|E|
| |=  IF  Z  X  C  V  B  N  M           FT ||u||l| | | 0    .||R|
| \ /\T /\ /\ /\ /\ /\ /\ /\ /\,/\./\//\   /\d/\r/ | \    /\ /\ /
|                                                  |
|           [       spacebar          ]            |
+--------------------------------------------------+

C L = {caps lock}    Hlp = {help}       L F = {line feed} 4 8 = {40/80 dsp}
N S = {no scroll}    up  = {crsr up}    dwn = {crsr down} lft = {crsr left}
rgt = {crsr right}   L A = {left arrow} lbs = {pound}     C H = {clr/home}
I D = {inst/del}  contrl = {ctrl}       U A = {up arrow}  R S = {run/stop}
ShL = {shift lock}    C= = {commodore}  Cud = {crsr up/down}
Clr = {crsr left/right}

Note: Outlined key areas can be used in C64 Mode.


Using BASIC is essentially the same in both C64 and C128 modes. Most of the
keys, and many of the commands you will learn, can be used to program BASIC
in either mode. The keys that are shaded in the diagram above can be used
in C64 mode. In C128 mode you can use all of the keys on the keyboard.


3.2.1 Keyboard Character Sets

The Commodore 128 keyboard offers two different sets of characters:

    - Uppercase letters and graphic characters
    - Upper- and lowercase letters

In 80-column format, both character sets are available simultaneously. This
gives you a total of 512 different characters that you can display on the
screen. In 40-column format you can use only one character set at a time.

When you turn on the Commodore 128 in 40-column format, the keyboard nor-
mally is using the uppercase/graphic character set. This means that every-
thing you type is in capital letters. To switch back and forth between the
two character sets, press the {shift} key and the {C=} key (the COMMODORE
key) at the same time. To practice using the two character sets turn on
your computer and press several letters or graphic characters. Then press
the {shift} key and the {C=}(Commodore) key. Notice how the screen changes
to upper- and lowercase characters. Press {shift} and {C=} again to return
to the uppercase and graphic character set.


3.2.2 Using the Command Keys

COMMAND keys are keys that send messages to the computer. Some command keys
(such as {return}) are used by themselves. Other keys such as {shift},
{ctrl}, {C=} and {restore}) are used with other keys. The use of each of
the command keys is explained below. The keys used in C128 mode are des-
cribed in Section 5.


3.2.2.1 Return

When you press the {return} key, what you have typed is sent to the Commo-
dore 128 computer's memory. Pressing the {return} key also moves the cursor
(the small flashing rectangle that marks where the next character you type
will appear) to the next line.

At times you may misspell a command or type in something the computer does
not understand. Then, when you press the {return} key, you probably will
get a message like SYNTAX ERROR on the screen. This is called an "Error
Message". Appendix A lists the error messages and tells how to correct the
errors.


3.2.2.2 Shift

There are two {shift} keys on the bottom row of the keyboard. One key is
the one on the left and the other on the right, just as on a standard type-
writer keyboard.

The {shift} key can be used in three ways:

1. With the upper/lowercase character set, the {shift} key is used like the
   shift key on a regular typewriter. When the {shift} key is hold down, it
   lets you print capital letters or the top characters on double-character
   keys.
2. The {shift} key can be used with some of the other command keys to per-
   form special functions.
3. When the keyboard is set for the uppercase/graphic character set, you
   can use the {shift} key to print the graphic symbols or characters that
   appear on the right of the front face of certain keys. See paragraph
   3.2.4 at the end of this section for more details.


3.2.2.3 Shift Lock

When you press this key down, it locks into place. Then, whatever you type
will either be a capital letter, or the top character of a double-character
key. To release the lock, press down on the {shift lock} key again.


3.2.2.4 Moving the cursor

In C128 mode, you can move the cursor by using either the four arrow keys
located just above the top right of the main keyboard, or the two keys
labeled {crsr}, at the right of the bottom row of the main keyboard.


3.2.2.4.1 Using the four Arrow Cursor keys

In C128 mode, the cursor can be moved in any direction simply by using the
arrow key in the top row that points in the direction you want to move the
cursor. (These keys cannot be used in C64 mode).


3.2.2.4.2 Using the CRSR keys

In both C128 and C64 mode, you can use the two keys on the right side of
the bottom row of the main keyboard to move the cursor:

- Pressing the {crsr up/down} key alone moves the cursor down.
- Pressing the {crsr up/down} and {shift} keys together moves the cursor
  up.
- Pressing the {crsr left/right} key alone moves the cursor right.
- Pressing the {crsr left/right} and {shift} keys together moves the cursor
  left.

You don't have to keep tapping a cursor key to move more than one space.
Just hold the key down and the cursor continues to move, release it when it
reaches the position you want.

Notice that when the cursor reaches the right side of the screen, it
"wraps", or starts again at the beginning of the next row. When moving
left, the cursor will move along until it reaches the edge of the screen,
then it will jump up to the end of the preceding line.

You should try to become very familiar with the cursor keys, because moving
the cursor makes your programming much easier. With a little practice you
will find that you can move the cursor almost without thinking about it.


3.2.2.5 Inst/Del

This is a dual purpose key. INST stands for INSerT, and DEL for DELete.


3.2.2.5.1 Inserting Characters

You must use the {shift} key with the {inst/del} key when you want to
insert characters in a line. Suppose you left some characters out of a line
like this:

    WHILE WERE OUT_

To insert the missing characters, first use the cursor keys to move the
cursor back to the error. like this:

    WHILE_WERE OUT

Then, while you hold down the {shift} key, press the {inst/del} key until
you have enough space to add the missing characters:

    WHILE_    WERE OUT

Notice that {inst} doesn't move the cursor; it just adds space between the
cursor and the character to its right. To make the correction type the mis-
sing {space}, {y}, {o} and {u} like this:

    WHILE YOU_WERE OUT


3.2.2.5.2 Deleting characters

When you press the {del} key, the cursor move one space to the left and
erases the character that is there and moves any characters to the right of
the cursor one position to the left. This means that when you want to
delete something, you move the cursor just to the right of the character
you want to DELete. Suppose you have made a mistake in typing, like this:

    PRINT "ERROER"_

You wanted to type the word ERROR, not ERROER. To delete the incorrect E
that precedes the final R, position the cursor on the final R. When you
press the {del} key, the R automatically moves over one space to the left.
You now have the correct wording like this:

    PRINT "ERROR"


3.2.2.5.3 Using INSerT and DELete together

You can use the INSerT and DELete functions together to fix incorrect
characters. First, move the cursor one space after the incorrect characters
and press the {inst/del} key by itself to delete the incorrect characters.

Next, press the {shift} key and the {inst/del} key together to add any
necessary space.


3.2.2.6 Control

The {ctrl} key is used with other keys to do special task called control
functions. To perform a control function, hold down the {ctrl} key while
you press some other key. A full list of control sequences is given in
ASCII, CHR$ and ESC codes. Control functions are often used in prepackaged
software such as a word processing system.

One control function that is used often is setting the character and cursor
color. To select a color, hold down the {ctrl} key while you press a number
key ({1} throught {8}), on the top row of the main keyboard. There are
eight more colors available to you; these can be selected with the {C=}
key, as explained later.


3.2.2.7 Run/Stop

This is a dual function key. Under certain conditions you can use the RUN
function of this key by pressing the {shift} and {run/stop} key together.
It is also possible to use the STOP function of the key to halt a program
or a printout by pressing this key while the program is running. However,
in most prepackaged programs, the STOP function of the {run/stop} key is
intentionally disabled (made unusable). This is done to prevent the user
from trying to stop a program that is running before it reaches its normal
end point. If the user were able to stop the program, valuable data could
be lost.


3.2.2.8 Restore

The {restore} key is used with the {run/stop} key to return the computer to
its standard condition. Most prepackaged programs disable the {restore} key
for the same reason the disable the STOP function of the {run/stop} key: to
prevent losing valuable data.


3.2.2.9 CLR/Home

CLR stands for CLeaR. HOME refers to the upper left corner of the screen,
which is called the HOME position. If you press this by itself the cursor
returns to the HOME position. When you use the {shift} key with the
{clr/home} key, the screen CLeaRs and the cursor returns to the HOME
position.


3.2.2.10 Commodore key

The {C=} key (known as the {commodore} key) has a number of functions,
including the following ones:

1. When used with the {shift} key, the {C=} key lets you switch between
   uppercase/graphics mode and upper-/lowercase text modes.
2. When you're in either mode, the {C=} key acts as a shift to let you type
   graphics symbols pictured on the LEFT front of each key. Just hold down
   the {C=} and press teh graphic key you want.
3. When you want to change the color you are typing in to one of the 8
   colors listed on the BOTTOM row of the face of the color keys (number
   keys {1} through {8} on the main keyboard): press {C=} and the color you
   want.
4. When you want to slow down a scrolling program display, hold down the
   {C=} key. The display scrolling speed slows down considerably. When you
   release this key, the screen scrolling resumes at normal speed.
5. If you hold down the {C=} key while turning on the computer, you
   immediately access C64 mode.


3.2.3 Function Keys

The four keys above the numeric keypad (marked F1, F3, F5 and F7 on the top
and F2, F4, F6 and F8 on the front) are called function keys. In both C128
and C64 modes, you can program the function keys. (See the KEY command des-
criptions in Section 5, paragraph 5.9.2  of Chapter II and in Section 17,
paragraph 17.53  of Chapter V, BASIC 7.0 Encyclopaedia). These keys are
often used by prepackaged software to allow you to perform a task with a
single keystroke.


3.2.4 Displaying Graphic Characters

To display the graphic symbol on the right front of a key, hold down the
{shift} key while you press the key that has the graphic character you want
to print. You can display the right side graphic character only when the
keyboard is in the uppercase/graphics character set (one normal character
set usually available at power-up).

To display the graphic character on the left front face of a key, hold down
the {C=} key while you press the key that has the graphic character you
want. You can display the left graphic character while the keyboard is in
either character set.


3.2.5 Rules for Typing BASIC Language Programs

You can type and use BASIC language programs even without knowing BASIC.
You must type carefully, however, because a typing error may cause the
computer to reject your information. The following guidelines will help
minimize errors when typing or copying a program listing.

1. Spacing between words is not critical; e.g. typing FORT=1TO10 is the
   same as typing FORT=1 TO 10. However, a BASIC keyword itself must not
   be broken up by spaces (see Section 20, paragraph 20.1, of the BASIC 7.0
   Encyclopaedia in Chapter V for a list of BASIC keywords).
2. Any characters can be typed inside quotation marks. Some characters have
   special functions when placed inside quotation marks, These functions
   are explained later in this guide.
3. Be careful with punctuation marks. Commas, colons and semicolons also
   have special properties, explained later in this guide.
4. Always press the {return} key after completing a numbered line.
5. Never type more than 160 characters in a program line. Remember, this is
   the same as four full screen lines in 40-column format, or two full
   screen lines in 80-column format. See Section 8 for more details on 40-
   and 80-columns formats.
6. Distinguish clearly between the letter {l} and the numeral {1} and
   between the capital letter {O} and the numeral {0} (zero).
7. The computer ignores anything following the letters REM on a program
   line. REM stands for REMark. You can use the REM statement to put com-
   ments in you program that tell anyone listing the program what is happe-
   ning at a specific point.

Follow these guidelines when you type the examples and programs shown in
this section.


3.3 GETTING STARTED - THE PRINT COMMAND

The PRINT command tells the computer to display information on the screen.
You can print both numbers and text (letters), but there are special rules
for each case, described in the following paragraphs.


3.3.1 Printing Numbers

To print numbers, use the PRINT command followed by the number(s) you want
to print. Try typing this on you Commodore 128:

     PRINT 5

Then press the {return} key. Notice the number 5 is now displayed on the
screen.

Now type this and press {return}:

     PRINT 5,6

In this PRINT command, the comma tells the Commodore 128 that you want to
print more than one number. When the computer finds commas in a string of
numbers in a PRINT statement, the output is displayed to the nearest tenth
column.

If you don't want all the extra spaces, use a semicolon (;) in your PRINT
statement instead of a comma. The semicolon tells the computer to print the
numbers next to each other. A number when printed has either a space or a
minus sign preceding it and a skip character after it. Type these examples
and see what happens:

     PRINT 5;6 {return}
     PRINT 100;-200;300;-400;500 {return}


3.3.2 Using the Question Mark to Abbreviate the PRINT Command

You can use a quotation mark (?) as an abbreviation for the PRINT command.
Many of the examples in this section use the ? symbol in place of the word
PRINT. In fact, most of the BASIC commands can be abbreviated. The
abbreviations for BASIC commands can be found in Appendix K of this Guide.


3.3.3 Printing Text

Now that you know how to print numbers, it's time to learn how to print
text. It's actually very simple. Any words or characters you want to dis-
play are typed on the screen, with a quote symbol at each end of the string
of characters. String is the BASIC name for any set of characters sur-
rounded by quotes. The quote character is obtained by pressing "SHIFT" and
the number {2} key on top of the main keyboard (not the {2} in the numeric
keypad). Try these examples:

     ? "COMMODORE 128" {return}
     ? "4*5" {return}

Notice that when you press {return}, the computer displays the character
within the quotes on the screen. Also note that the second example did not
calculate 4*5 since it was treated as a string and not a mathematical cal-
culation. If you want to calculate the result of 4*5, use the following com-
mand:

     ? 4*5 {return}

You can PRINT any string you want by using the PRINT command and surroun-
ding the printed characters with quotes. You can combine text and calcula-
tions in a single PRINT command like this:

     ? "4*5 = "4*5 {return}

See how the computer PRINTs the characters in quotes, makes the calculation
and PRINTs the result. It doesn't matter whether the text or calculation
comes first. In fact, you can use both several times in one PRINT command.
Type the following statement:

     ? 4*(2+3)" is the same as "4*5 {return}

Notice that even spaces inside the quotation marks are printed on the
screen. Type:

     ? "   OVER HERE" {return}


3.3.4 Printing in Different Colors

The Commodore 128 is capable of displaying 16 different colors on the
screen. You can change colors easily. All you do is hold down the {ctrl}
key and press a numbered key between one and eight on the top row of the
main keyboard. Notice that the cursor changes color according to the num-
bered key you pressed. All the succeeding characters are displayed in the
color you selected. Hold down the {C=} key and press a numbered key
between one and eight, and eight additional colors are displayed on the
screen.

Table 3-1 list the colors available in C128 mode, for both 40-column and
80-column screen formats. The tables also show the key sequence (CONTROL
key plus number key, or {C=} key plus number key) used to specify a given
color.


Table 3-1. Available Colors in 40- and 80-Column Screen Formats.

CONTROL + Color           {C=} +  Color

  1       Black           1      Orange
  2       White           2      Brown
  3       Red             3      Light Red
  4       Cyan            4      Dark Grey
  5       Purple          5      Middle Grey
  6       Green           6      Light Green
  7       Blue            7      Light Blue
  8       Yellow          8      Light Grey

Colors in 40-Column Format


CONTROL + Color           {C=} +  Color

  1       Black           1       Dark Purple
  2       White           2       Brown
  3       Dark Red        3       Light Red
  4       Light Cyan      4       Dark Cyan
  5       Light Purple    5       Middle Grey
  6       Dark Green      6       Light Green
  7       Dark Blue       7       Light Blue
  8       Light Yellow    8       Light Grey

Colors in 80-Column Format


3.3.5 Using the Cursor Keys Inside Quotes with the PRINT Command

When you type the cursor keys inside quotation marks, graphic characters
are shown on the screen to represent the keys. These characters will NOT be
printed on the screen when you press {return}. Try typing a question mark
({?}), open quotes ({shift}ed {2} key); then press either of the down
cursor keys 10 times, enter the words "DOWN HERE", and close the quotes.
The line should look like this:

     ?"QQQQQQQQQQDOWN HERE"

Now press {return}. The Commodore 128 prints 10 blank lines, and on the
eleventh line, it prints "DOWN HERE". As this example shows, you can tell
the computer to print anywhere on your screen by using the cursor control
keys inside quotation marks.


3.4 BEGINNING TO PROGRAM

So far most of the commands we have discussed have been performed in DIRECT
mode. That is, the command was executed as soon as the {return} key was
pressed. However, most BASIC commands and functions can also be used in
programs.


3.4.1 What a Program Is

A program is just a set of numbered BASIC instructions that tell your com-
puter what you want it to do. These numbered instructions are referred to
as statements or lines.


3.4.2 Line Numbers

The lines of a progam are numbered so that the computer knows in what order
yo want them executed or RUN. The computer executes the program lines in
numerical order, unless the program instructs otherwise. You can use any
whole number from 0 to 63999 for a line number. Never use a comma in a line
number.

Many of the commands you have learned to use in DIRECT mode can easily be
made into program statements. For example, type this:

     10 ?"COMMODORE 128" {return}

Notice the computer did not display COMMODORE 128 when you pressed
{return}, as it would do if you were using the PRINT command in DIRECT
mode. This is because the number, 10, that comes before the PRINT symbol
(?) tells the computer that you are entering a BASIC program. The computer
just stores the numbered statement and waits for the next input from you.

Now type RUN and press {return}. The computer prints the words COMMODORE
128. This not the same as using the PRINT command in DIRECT mode. What has
happened here is that YOU HAVE WRITTEN AND RUN YOUR FIRST BASIC PROGRAM as
small as it may seem. The program is still in the computer's memory, so you
can run it as many times as you want.


3.4.3 Viewing your Program - The LIST Command

Your one-line program is still in the C128 memory. Now clear the screen by
pressing the {shift} and {clr/home} keys together. The screen is empty. At
this point you may want to see the program listing to be sure it is still
in memory. The BASIC language is equipped with a command that lets you do
just this - the LIST command.

Type LIST and press {return}. The Commodore 128 responds with:

     10 PRINT "COMMODORE 128"
     READY.


Anytime you want to see all the lines in your program, type LIST. This is
especially helpful if you make changes, because you can check to be sure
the new lines have been registered in the computer's memory. In response
to the command, the computer displays the changed version of the line,
lines, or program. Here are the rules for using the LIST command:

     - To see line n only, type LIST n and press {return}.

     - To see from line n to the end of the program, type LIST n- and press
       {return}.

     - To see the lines from the beginning of the program to line n, type
       LIST -n and press {return}.

     - To see from line n1 to line n2 inclusive, type LIST n1-n2 and press
       {return}.


3.4.4 A Simple Loop - The GOTO Command

The line numbers in a program have another purpose besides putting your
commands in the proper order for the computer. The serve as a reference for
the computer in case you want to execute the command in that line repeti-
tively in your program. You use the GOTO command to tell the computer to go
to a line and execute the command(s) in it. Now type:

     20 GOTO 10

When you press {return} after typing line 20, you add it to your program in
the computer's memory.

Notice that we numbered the first line 10 and the second line 20. It is
very helpful to number program lines in increments of 10 (that is 10, 20,
30, 40, etc.) in case you want to go back and add lines in between. You can
number such added lines by fives (15, 25...), or ones (1, 2...) - in fact,
by any whole number - to keep the lines in proper order. (See the RENUMBER
and AUTO commands in the BASIC Encyclopaedia, paragraphs.)

Type RUN and press {return}, and watch the words COMMODORE 128 move down
your screen. To stop the message from printing on the screen, press the
{run/stop} key on the left side of the main keyboard.

The two lines that you have typed make up a simple program that repeats it-
self endlessly, because the second line keeps referring the computer back
to the first line. The program will continue indefinitely unless you stop
it or turn off the computer.

Now type LIST {return} The screen should say:

     10 PRINT "COMMODORE 128"
     20 GOTO 10
     READY.

Your program is still in memory. You can RUN it again if you want to. This
is an important difference between PROGRAM mode and DIRECT mode. Once a
command is executed in DIRECT mode, it is no longer in the computer's
memory. Notice that even though you used the ? symbol for the PRINT state-
ment, your computer has converted it into the full command. This happens
when you LIST any command you have abbreviated in a program.


3.4.5 Clearing the Computer's Memory - The NEW Command

Anytime you want to start all over again or erase a BASIC program in the
computer's memory, just type NEW and press {return}. This command clears
out the computer's BASIC memory, the area where programs are stored.


3.4.6 Using Color in a Program

To select color within a program, you must include the color selection
information within a PRINT statement. For example, clear your computer's
memory by typing NEW and pressing {return}, the type the following, being
sure to leave space between each letter:

     10 PRINT " R A I N B O W" {return}

Now type line 10 again, but this time hold down the {ctrl} key and press
the (numeral) {1} key directly after entering the first set of quote marks.
Release the {ctrl} key and type the {r}. Now hold down the {ctrl} again and
press the {2} key. Release the {ctrl} key and type the {a}. Next hold down
the {ctrl} again and press the {3} key. Continue this process until you
have typed all the letters in the word RAINBOW and selected a color between
each letter. Press the {shift} and the {2} keys to type a set of the clo-
sing quotation marks and press the {return} key. Now type RUN and press the
{return} key. The computer displays the word RAINBOW with each letter in a
different color. Now type LIST and press the {return} key. Notice the
graphic characters that appear in the PRINT statement in line 10. These
characters tells the computer what color you want for each printed letter.
Note that these graphic characters do not appear when the Commodore 128
PRINTs the word RAINBOW in different colors.

The color selection characters, known as control characters, in the PRINT
statement in line 10 tell the Commodore 128 to change colors. The computer
then prints the characters that follow in the new color until another color
selection character is encountered. While characters enclosed in quotation
marks are usually PRINTed exactly as they appear, control characters are
only displayed within a program LISTing.


3.5 EDITING YOUR PROGRAM

The following paragraphs will help you to type in your programs and make
corrections and additions to them.


3.5.1 Erasing a Line from a Program

Use the LIST command to display the program you typed previously. Now type
10 and press {return}. You just erased line 10 from the program. LIST your
program and see for yourself. If the old line 10 is still on the screen,
move the cursor up so that it is blinking anywhere on that line. Now, if
you press {return}, line 10 is back in the computer's memory.


3.5.2 Duplicating a Line

Hold down the {shift} key and press the {clr/home} key on the upper right
side of the main keyboard. This will clear your screen. Now LIST the pro-
gram. Move the cursor up again so that it is blinking in the (numeral) "0"
in the line numbered 10. Now type a {5} and press {return}. You have just
duplicated (i.e. copied) line 10. The duplicated line is numbered 15. Type
LIST and press RETURN to see the program with the duplicated line.


3.5.3 Replacing a Line

You can replace a whole line by typing in the old line number followed by
the text of the new line, the pressing {return}. The old version of the
line will be erased from memory and replaced by the new line as soon as you
press {return}.


3.5.4 Changing a Line

Suppose you want to add something in the middle of a line. Simply move the
cursor to the character or space that immediately follows the spot where
you want to insert the new material. Then hold down the {shift} key and the
{inst/del} key together until there is enough space to insert your new
characters.

Try this example. Clear the computer's memory by typing NEW and pressing
{return}. The type:

     10 ? "MY 128 IS GREAT" {return}

Let's say you want to add the word COMMODORE in front of the number 128.
Just move the cursor so that it is blinking on the "1" in 128. Hold down
the {shift} and {inst/del} keys until you have enough room to type in
COMMODORE (don't forget to leave enough room for a space after the last
letter "E"). Then type in the word COMMODORE.


3.6 MATHEMATICAL OPERATIONS

You can use the PRINT command to perform calculations like addition, sub-
traction, multiplication, division and exponentiation. You type the calcu-
lation after the PRINT command.


3.6.1 Addition and Subtraction

Try typing these examples:

     PRINT 6 + 4 {return}

     PRINT 50 - 20 {return}

     PRINT 10 + 15 - 5 {return}

     PRINT 75 - 100 {return}

     PRINT 30 + 40,55 - 25 {return}

     PRINT 30 + 40;55 - 25 {return}

Notice that the fourth calculation (75-100) resulted in a negative number.
Also notice that you can tell the computer to make more than one calcula-
tion with a single PRINT command. You can use either a comma or semicolon
in your command, depending on whether or not you want your results printed
tabulated or next to each other.


3.6.2 Multiplication and Division

Find the asterisk key (*) on the right side of the main keyboard. This is
the symbol that the Commodore 128 uses for multiplication. The slash (/)
key, located next to the right {shift} key, is used for division.

Try these examples:

     PRINT 5*3 {return}
     PRINT 100/2 {return}


3.6.3 Exponentiation

Exponentiation means to raise a number to a power. The up arrow key
({up arrow}, located next to the asterisk on the main keyboard, is used for
exponentiation. If you want to raise a number to a power, use the PRINT
command, followed by the number, the up arrow and the power, in that order.
For example, to find out what 3 squared is, type:

     PRINT 3{up arrow}2 {return}


NOTE: From now on, the {up arrow} keystroke is represented by the {^} key-
      stroke, or simply ^.

3.6.4 Order of Operations

You have seen how you can combine addition and subtraction in the same
PRINT command. If you combine multiplication or division with addition or
subtraction operations, you may not get the result you expect. For example,
type:

     PRINT 4 + 6/2 {return}

If you assumed you were dividing 10 by 2, you were probably surprised when
the computer responded with the answer 7. The reason you got this answer is
that multiplication and division operations are performed by the computer
before addition or subtraction. Multiplication and division are said to
take precedence over addition and subtraction. It doesn't matter in what
order you type the operation. In computing, the order in which mathematical
operations are performed is known as the order of operations.

Exponentiation, or raising a number to a power, takes precedence over the
other four mathematical operations. For example, if you type:

     PRINT 16/4^2 {return}

the Commodore 128 responds with 1, because it squares the 4 before it
divides 16.


3.6.5 Using Parentheses to Define the Order of Operations

You can tell the Commodore 128 which mathematical operation you want per-
formed first by enclosing that operation in parentheses in the PRINT
command. For instance, in the first example above, if you want to tell the
computer to add before dividing, type:

     PRINT (4 + 6)/2 {return}

This gives you the desired answer, 5.

If you want the computer to divide before squaring in the second example,
type:

     PRINT (16/4)^2 {return}

Now you have the expected answer, 16.

If you don't use parentheses, the computer performs the calculations accor-
ding to the above rules. When all operations in a calculation have equal
precedence, they are performed from left to right. For example, type:

PRINT 4*5/10*6 {return}

Since the operations in this example are performed in order from left to
right, the result is 12 (4*5 = 20... 20/10 = 2... 2*6 = 12). If you want to
divide 4*5 by 10*6 you type:

     PRINT (4*5)/(10*6) {return}

The answer is now .333333333.


3.7 CONSTANTS, VARIABLES AND STRINGS

3.7.1 Constants

Constants are numeric values that are permanent: that is, they do not
change in value over the course of an equation or program. For example, the
number 3 is a constant, as is any number. This statement illustrates how
your program uses constants:

     10 PRINT 3

No matter how many times you execute this line, the answer will always
be 3.


3.7.2 Variables

Variables are values that can change over the course of an equation or
program statement. There is a part of the computer's BASIC memory that is
reserved for the characters (number, letters and symbols) you use in your
program. Think of this memory as a number of storage compartments in the
computer that store information about your program; this part of the com-
puter's memory is referred to as variable storage. Type in this program:

     10 X=5
     20 ?X

Now RUN the program and see how the computer prints a 5 on your screen. You
told the computer in line 10 that the letter X will represent the number 5
for the remaninder of the program. The letter X is called a variable, be-
cause the value of X varies depending on the value to the right of the
equals sign. We call this an assignment statement because now there is a
storage compartment labeled X in the computer's memory, and the number 5
has been assigned to it. The = sign tells the computer that whatever comes
to the right of it will be assigned to a storage compartment (a memory
location) labeled with the letter X to the left of the equals sign.

The variable name on the left side of the = sign can be either one or two
letters, or one letter and one number (the letter MUST come first). The
names can be longer, but the computer only looks at the first two charac-
ters. This means the names PA and PART would refer to the same storage
compartment. Also, the words used for BASIC commands (LOAD, RUN, LIST,
etc.) or functions (INT, ABS, SQR, etc.) cannot be used as names in your
programs. Refer to the BASIC Encyclopaedia in Chapter V if you have any
questions about whether a variable name is a BASIC keyword. Notice that the
= in assigment statements is not the same as the mathematical symbol
meaning "equals", but rather means allocate a variable (storage compart-
ment) and assign a value to it.

In the sample program you just typed, the value of the variable X remains
at 5 throughout. You can put calculations to the right of the = sign to
assign the result to a variable. You can mix text with constants in a PRINT
statement to identify them. Type NEW and press {return} to clear the Commo-
dore 128's memory; then try this program:

     10 A = 3*100
     20 B = 3*200
     30 ?"A IS EQUAL TO"A
     40 ?"B IS EQUAL TO"B

Now there are two variables, labeled A and B, in the computer's memory,
containing the numbers 300 and 600 respectively. If, later in the program,
you want to change the value of a variable, just put another assignment
statement in the program. Add these lines to the program above and RUN it
again.

     50 A = 900*30/10
     60 B = 95 + 32 + 128
     70 GOTO 30

You'll have to press the {stop} key to halt the program.

Now LIST the program and trace the steps taken by the computer. First, it
assigns the value to the right of the = sign in line 10 to the letter A. It
does the same thing in line 20 for the letter B. Next, it prints the messa-
ges in lines 30 and 40 that give you the values of A and B. Finally, it
assigns new values to A and B in lines 50 and 60. The old values are repla-
ced and cannot be recovered unless the computer executes lines 10 and 20
again. When the computer is sent to line 30 to begin printing the values of
A and B again, it prints the new values calculated in lines 50 and 60.
Lines 50 and 60 reassign the same values to A and B and line 70 sends the
computer back to line 30. This is called an endless loop, because lines 30
through 70 are executed over and over again until you press the {run/stop}
key to halt the program. Other methods of looping are discussed later in
this and following two sections.


3.7.3 Strings

A string is a character or group of characters enclosed in quotes. These
characters are stored in the computer's memory as a variable in much the
same way numeric variables are stored. You can also use variable names to
represent strings, just as you use them to represent numbers. When you put
the dollar sign ($) after the variable name, it tells the computer that the
name is for a string variable, and not a numeric variable.

Type NEW and press {return} to clear your computer's memory, then type in
the program below:

     10 A$ = "COMMODORE"
     20 X = 128
     30 B$ = "COMPUTER"
     40 Y = 1
     50 ? "THE "A$;X;B$" IS NUMBER"Y

See how you can print numeric and string variables in the same statement?
Try experimenting with variables in your own short programs.

You can print the value of a variable in DIRECT mode, after the program has
been RUN. Type ?A$;B$;X;Y {return} after running the program above and see
that those four variable values are still in the computer's memory.

If you want to clear this area of BASIC memory but still leave your program
intact, use the CLR command. Just type CLR {return} and all constants,
variables and strings are erased. But when you type LIST, you can see the
program is still in memory. The NEW command discussed earlier erases both
the program and the variables.


3.8 SAMPLE PROGRAM

Here is a sample program incorporating many of the techniques and commands
discussed in the section.

This program calculates the avarage of three numbers (X, Y and Z) and
prints their values and their avarages on the screen. You can edit the pro-
gram and change the calculations in line 10 through 30 to change the values
of the variables. Line 40 adds the variables and divides them by 3 to get
the average. Note the use of parentheses to tell the computer to add the
numbers before it divides.

     TIP: Whenever you are using more than one set of parentheses in a
     statement, it's a good idea to count the number of left parentheses
     and right parentheses to make sure they are equal.

     10 X = 46
     20 Y = 73
     30 Z = 114
     40 A = (X + Y + Z)/3
     50 ?"THE AVERAGE OF"X;Y;"AND"Z;"IS"A;
     60 END


3.9 STORING AND REUSING YOUR PROGRAMS

Once you have created your program, you will probably want to store it
permanently so you will be able to recall and use it at some later time. To
do this, you'll need either a Commodore disk drive or the Commodore 1530
(or 1531) Datassette, or similar storing device.

You will learn several commands that let you communicate between your com-
puter and your disk drive or Datassette. These commands are structured with
the use of a command word followed by several parameters. Parameters are
letters, words or symbols in a command that supply specific information to
the computer, such as a filename, or a numeric variable that specifies a
device number. Each command may have several parameters. For example, the
parameter of the disk format command include a name for the disk and an
identifying number or code, plus several other parameters. Parameters are
used in almost every BASIC command; some are variables which change and
others are constant. These are the parameters that supply disk information
to the C128 and the disk drive:


3.9.0.1 Disk Handling Parameters

     disk name -      arbitrary 16 character identifying name you supply.
     filename -       arbitrary 16 character identifying name you supply.
     i.d. number -    arbitrary two-character identifying code you supply.
     drive number -   must use 0 for a single disk drive, 0 or 1 in a dual
                      disk drive.
     device number -  a preassigned number for a peripheral device. For
                      example, the device number for a Commodore disk drive
                      is 8.


3.9.1 Formatting a Disk - The HEADER Command

To store programs on a new (or blank) disk, you must first prepare the disk
to receive data. This is called "formatting" the disk.

NOTE: Make sure you turn on the disk drive before inserting any disk.

The formatting process divides the disk into sections called tracks and
sectors. A table of contents, called a directory, is created. Each time you
store a program on disk, the name you assign to that program will be added
to the directory.

The Commodore 128 has two kinds of formatting commands. One can be used in
C128 mode only, and one can be used in both C64 and C128 mode. The follo-
wing describes the C128 mode formatting command only. See your disk drive
manual for the disk handling in C64 mode.

The command that formats a diskette is called the HEADER command. It has a
long form and a short form. To format a blank (new) disk, you MUST use the
long form as follows:

     HEADER "diskname", Ii.d. [,Ddrive number] [,[ON]Udevice number]

After the word HEADER, you type a name of your choice for the disk, within
quotes. You can choose any name with up to 16 characters. You should choose
disk names that help you identify what will be stored on the disk.

Follow the diskname with a comma and the letter "I". Now a two character
i.d. Your disk i.d. does not have to be numbers; you can also choose let-
ters. You may want to develop a consecutive coding system for your disk,
such as A1, A2, B1, B2.

If you have one single disk drive, just press {return} at this point since
the Commodore 128 automatically assumes the drive number is 0 and the
device number is 8. You can specify these parameters if you have more than
one drive or a dual drive.

The next parameter in the command selects the drive number. Press the {d}
key and if you have a single disk drive, press the {zero} key followed by a
{comma}. Dual drives are labeled 0 and 1. The device number parameter
starts with the letter U so press the {u} key followed by the preassigned
device number for a Commodore disk drive which is {8}.

Here is an example of the long form of the HEADER command:

     HEADER"RECS",IA1,D0,U8 {return}

This command formats the diskette, calling it "RECS", the i.d. number "A1",
on drive 0, unit 8.

The default values for disk drive (0) and device number (8) will be used if
none are supplied. This is an acceptable long form of the HEADER command:

     HEADER "MYDISK",I51 {return}

The HEADER command can also be used to erase all data from a used disk, so
the disk can be reused as if it were a brand new disk. Be careful that you
don't erase a disk that contains data you may want someday.

The quick form of the HEADER command can be used if the disk was previously
formatted with the long form of the HEADER command.

The quick form clears the directory, erasing all data in the same way as
the long form, but keeps the same i.d. as was previously used. Here is what
the quick HEADER might look like:

     HEADER "NEWPROGS" {return}


3.9.2 SAVEing on Disk

In C128 mode, you can store you program on disk by using either of the
following commands:

     DSAVE "program name" {return}
     SAVE "program name",8 {return}

Either command can be used. Remember that the character sequence DSAVE" can
be displayed on the screen by pressing the function key labeled {f5}, or
you can type the sequence yourself. The progam name can be any name you
choose, up to 16 characters long. Be sure to enclose the program name in
quotes. You cannot put two programs with the same name on the same disk.
If you do, the second program will not be accepted; the disk will retain
the first one. In the second example, the 8 indicates that you are saving
your program on device number 8. You do not need the 8 with DSAVE, because
the computer automatically assumes you are using device number 8.


3.9.3 SAVEing on Cassette

If you are using a Datassette to store your program, insert a blank tape in
the recorder, rewind the tape if necessary, and type:

     SAVE "program name" {return}

You must type the word SAVE, followed by the program name. The program name
can be any name you choose up to 16 characters.

     NOTE: The 40-column screen will go blank while the program is being
     SAVEd, but returns to normal when the process is completed.

Unlike disk, you can save two programs to tape under the same name. However
when you load it back into the computer, the first progam sequentially on
the tape will be loaded, so avoid giving programs the same name.

Once a program has been SAVEd, you can LOAD it back into the computer's
memory and RUN it anytime you wish.


3.9.4 LOADing from Disk

Loading a program simply copies the contents of the program from the disk
into the computer's memory. If a BASIC program was already in memory before
you issued the LOAD command, it is erased.

To load your BASIC program from a disk, use either ot the following com-
mands in C128 mode:

     DLOAD "program name" {return}
     LOAD "program name",8 {return}

Remember, in C128 mode you can use the {f2} function key (which you acti-
vate by pressing {shift} and {f1} together) to display the sequence DLOAD",
or you can type the letters yourself. In the second example, the 8 indi-
cates to the computer that you are loading from device number 8. Again,
like DSAVE, DLOAD assumes the disk drive device number is 8. Be careful to
type the program name exactly as you typed it when SAVEing the program, or
the computer will respond FILE NOT FOUND.

Once the program is loaded, type RUN to execute. The Commodore 128 has a
special form of the RUN command used to LOAD and RUN the program in C128
mode with one command. Type RUN, followed by the name of the program (also
known as the filename) in quotes:

     RUN"MYPROG" {return}


3.9.5 LOADing from Cassette Tape

To LOAD your program from cassette tape, type:

     LOAD "program name" {return}

If you do not know the name of the program, you can type:

     LOAD {return}

and the next program on tape will be found. While the Datassette is sear-
ching for the program the 40 column screen is blank. When the program is
found, the screen displays:

     FOUND PROGRAM NAME

To actually load the program, you then press the Commodore key, or in 128
mode press the space bar to find the next program on tape.

You can use the counter on the Datassette to identify the starting position
of the programs. Then, when you want to retrieve a program, simple wind the
tape forward from 000 to the program's start location, and type:

     LOAD {return}

In this case you don't have to specify the program name; your program will
load automatically because it is the next program on the tape.


3.9.6 Other Disk-Related Commands


3.9.6.1 Verifying a Program

To verify that a program has been correctly saved, use the following com-
mand in C128 mode:

     DVERIFY "program name" {return}

If the program in the computer is identical to the one on the disk, the
screen display will respond with the letters "OK".

The VERIFY command also works for tape programs. You type:

     VERIFY "program name" {return}

You do not enter the comma and a device number.


3.9.6.2 Displaying Your Disk Directory

In C128 mode, you can see a list or directory of the programs on your disk
by using the following command:

     DIRECTORY {return}

This lists the contents of the directory. The easy way is to press the {f3}
function key. When you press {f3}, the C128 displays the word DIRECTORY and
performs the command.

For further information on SAVEing and LOADing your programs, or other disk
related information refer to your Datassette or disk drive manual. Also
consult the LOAD and SAVE command descriptions in the Chapter V, BASIC 7.0
Encyclopaedia.


                                 **********


You now know something about the BASIC language and some elementary pro-
gramming concepts. The next section builds on these concepts, introducing
additional commands, functions and techniques that you can use to program
in BASIC.



SECTION 4

4. Advanced Basic Programming



4.1 COMPUTER DECISIONS - The IF-THEN Statement

  4.1.1 Using the Colon

4.2 LOOPS - The FOR-NEXT Command

  4.2.1 Empty Loops - Inserting Delays in a Program
  4.2.2 The STEP Command

4.3 INPUTTING DATA

  4.3.1 The INPUT Command
    4.3.1.1 Assigning a value to a variable
    4.3.1.2 Prompt Messages
  4.3.2 The GET Command
  4.3.3 Sample Program
  4.3.4 The READ-DATA Commands
  4.3.5 The RESTORE Command
    4.3.5.1 Assigning values to string variables
  4.3.6 Using Arrays
    4.3.6.1 Subscripted Variables
    4.3.6.2 Dimensioning Arrays
    4.3.6.3 Sample Program

4.4 PROGRAMMING SUBROUTINES

  4.4.1 The GOSUB-RETURN Commands
  4.4.2 The ON GOTO/GOSUB Commands

4.5 USING MEMORY LOCATION

  4.5.1 Using PEEK and POKE for RAM Access
    4.5.1.1 Using PEEK
    4.5.1.2 Using POKE

4.6 BASIC FUNCTIONS

  4.6.1 What is a Function?
  4.6.2 The INTEGER Function (INT)
  4.6.3 Generating Random Numbers - The RND Function
  4.6.4 The ASC and CHR$ Functions
  4.6.5 Converting Strings and Numbers
    4.6.5.1 The VAL Function
    4.6.5.2 The STR$ Function
  4.6.6 The Square Root Function (SQR)
  4.6.7 The Absolute Value Function (ABS)

4.7 THE STOP AND CONT (CONTINUE) COMMANDS



This section describes how to use a number of powerful BASIC commands,
functions and programming techniques that can be used in both C128 and C64
modes.

These commands and functions allow you to program repeated actions through
looping and nesting techniques; handle tables of values; branch or jump to
another section of a program, and return from that section; assign varying
values to a quantity - and more. Examples and sample programs show just how
these BASIC concepts work and interact.


4.1 COMPUTER DECISIONS - The IF-THEN Statement

Now you know how to change the values of variables, the next step is to
have the computer make decisions based on these updated values. You do this
with the IF-THEN statement.

You tell the computer to execute a command only IF a condition is true
(e.g. IF X=5). The command you want the computer to execute when the condi-
tion is true comes after the word THEN in the statement.

Clear your computer's memory by typing NEW and pressing {return}, then
type in this program:

     10 J=0
     20 J=J+1
     30 ? J,"COMMODORE 128"
     40 IF J=5 THEN GOTO 60
     50 GOTO 20
     60 END

You no longer have to press the {stop} key to break out of a looping pro-
gram. The IF-THEN statement tells the computer to keep printing "COMMODORE
128" and incrementing (increasing) J until J=5 is true. When an IF condi-
tion is false, the computer jumps to the next line of the program, no
matter what comes after the word THEN.

Notice the END command in line 60. It is good practice to put an END state-
ment as the last line in your program. It tells the computer where to stop
executing statements.

Below is a list of comparison symbols that may be used in the IF statement
and their meanings:

     SYMBOL  MEANING

     =       EQUALS
     >       GREATER THAN
     <>      NOT EQUAL TO
     >=      GREATER THAN OR EQUAL TO
     <=      LESS THAN OR EQUAL TO

You should be aware that these comparisons work in expected mathematical
ways with numbers. There are different ways to determine if one string is
greater than, less than, or equal to another. You can learn about these
"string handling" functions by referring to Chapter V, Basic 7.0 Encyclo-
paedia.

Section 5 describes some powerful extensions of the IF-THEN concept, con-
sisting of the BASIC 7.0 commands BEGIN, BEND and ELSE.


4.1.1 Using the Colon

A very useful tool in programming is the colon (:). You can use the colon to
separate two (or more) BASIC commands on the same line.

Statements after a colon on a line will be executed in order, from left to
right. In one program line you can put as many statements you can fit into
160 characters, including the line number. This is equivalent to four full
screen lines in 40-column format, and two full lines in 80-column format.

This provides an excellent oppurtunity to take advantage of the THEN part
of the IF-THEN statement. You can tell the computer to execute several com-
mands when you IF statement is true.

Clear the computer's memory and type in the following progam:

     10 N=1
     20 IF N<5 THEN PRINT N;"LESS THAN 5":GOTO 40
     30 ? N;"GREATER THAN OR EQUAL TO 5"
     40 END

Now change line 10 to read N=20, and RUN the program again. Notice you can
tell the computer to execute more than one statement when N is less than 5.
You can put any statement(s) you want after the THEN command. Remember that
the GOTO 40 will not be reached if N is true. Any command that should be
followed whether or not the specified condition is met should appear on a
separate line.


4.2 LOOPS - The FOR-NEXT Command

In the program used for the IF-THEN example, we made the computer print
COMMODORE five times by telling it to increase or "increment" the variable
J by units of one, until the value of J equalled five; then we ended the
program. There is a simpler way to do this in BASIC. We can use a FOR-NEXT
loop, like this:

     10 FOR J=1 TO 5
     20 ?J,"COMMODORE 128"
     30 NEXT J
     40 END

Type and RUN this program and compare the result with the result of the
IF-THEN program - they are the same. In fact, the steps taken by the com-
puter are almost identical for the two programs. The FOR-NEXT loop is a
very powerful programming tool. You can specify the number of times the
computer should repeat an action. Let's trace the computer's steps for the
program above.

First, the computer assigns a value of 1 to the variable J. The 5 in the
FOR statement tells the computer to execute all statements between the FOR
statement and the NEXT statement, until J is equal to 5. In this case there
is just one statement - the PRINT statement.

The computer first assigns 1 to J, it then goes on to execute the PRINT
statement. When the computer reaches the NEXT J statement, J is incremented
and compared with 5. If J has not exceeded 5 the computer loops back to the
PRINT statement.

After five executions of this loop the value of J exceeds 5, the program
drops down to the statement that comes immediately after the NEXT statement
and continues from there. In this case the following statement is the END
statement, so the program stops.


4.2.1 Empty Loops - Inserting Delays in a Program

Before you proceed any further, it will be helpful to understand about
loops and some ways they are used to get the computer to do what you want.
You can use a loop to slow down the computer (by now you have witnessed the
speed with which the computer executes commands). See if you can predict
what this program will do before you run it.

     10 A$="COMMODORE 128"
     20 FOR J=1 TO 20
     30 PRINT
     40 FOR K=1 TO 1500
     50 NEXT K
     60 PRINT A$
     70 NEXT J
     80 END

Did you get what you expected?

The loop contained in line 40 and 50 tells the computer to count to 1500
before executing the remainder of the program. This is known as a delay
loop and is often used. Because it is inside the main loop of the program,
it is called a nested loop. Nested loops can be very useful when you want
the computer to perform a number of tasks in a given order, and repeat the
entire sequence of commands a certain number of times.

Section 5 describes an advanced way to insert delays through the use of the
new BASIC 7.0 command, SLEEP.


4.2.2 The STEP Command

You can tell the computer to increment your counter by units (e.g. 10, 0.5
or any other number). You do this by using a STEP command with the FOR
statement. For example, if you want the computer to count by tens to 1000,
type:

     10 FOR X=0 TO 1000 STEP 10
     20 ? X
     30 NEXT

Notice that you do not need the X in the NEXT statement if you are only
executing one loop at a time - this is discussed later in this section.
Also, note that you do not have to increase (or "increment") your counter
- you can decrease (or "decrement") it as well. For example, change line 10
in the program above to read:

     10 FOR X=100 TO 0 STEP - 10

The computer will count backward from 100 to 0, in units of 10.

If you don't use a STEP command with a FOR statement, the computer will
automatically increment the counter by units of 1.

The parts of the FOR-NEXT commands are:


FOR    - word used to indicate beginning of loop.
X      - counter variable; any number variable can be used.
1      - starting value; may be any number, positive, negative or zero.
TO     - connects starting value to ending value.
100    - ending value; may be any number, positive, negative or zero.
STEP   - indicates an increment other than 1 will be used.
2      - increment; can be any number, positive, negative or zero.

Section 5 describes DO/LOOP, a new, more powerful BASIC 7.0 command to per-
form a similar task to the STEP command.


4.3 INPUTTING DATA


4.3.1 The INPUT Command


4.3.1.1 Assigning a value to a variable

Clear the computer's memory by typing NEW and pressing {return}, and then
type and RUN this program:

     10 K=10
     20 FOR I=1 TO K
     30 ?"COMMODORE 128"
     40 NEXT

In this program you can change the value of K in line 10 to make the com-
puter execute the loop as many times as you want it to. You have to do this
when you are typing in the program, before it is RUN. What if you wanted to
be able to tell the computer how many times to execute the loop at the time
the program is RUN?

In other words, you want to be able to change the value of the variable K
each time you run the program, without having to change to program itself.
We call this the ability to interact with the computer. You can have the
computer ask how many times you want it to execute the loop. To do this,
use the INPUT command. For example, replace line 10 in the program with:

     10 INPUT K

Now when you RUN the program, the computer reponds with a ? to let you know
it is waiting for you to enter what you want the value of K to be. Type 15
and press {return}. The computer will execute the loop 15 times.


4.3.1.2 Prompt Messages

You can also make the computer print a message in an INPUT statement to
tell you what variable it's waiting for. Replace line 10 with:

     10 INPUT"PLEASE ENTER A VALUE FOR K";K

Remember to enclose the message to be printed in quotes. This message is
called a prompt. Also, notice that you must use a semicolon (;) between the
ending quote marks of the prompt and the K. You may put any message you
want in the prompt, but the INPUT statement must be 160 characters or less,
just as any BASIC command must.

The INPUT statement can also be used with string variables. The same rules
that apply for numeric variables apply for strings. Don't forget to use the
{$} to identify all you string variables.

Clear you computer's memory by typing NEW and pressing {return}. Then type
this program.

     10 INPUT"WHAT IS YOUR NAME";NM$
     20 ? "HELLO ";N$

Now RUN the program. When the computer prompts "WHAT IS YOUR NAME?", then
type your name. Don't forget to press {return} after you type your name.

Once the value of a variable (numeric or string) has been inserted into a
program through the use of INPUT, you can refer to it by its variable name
any time in the program. Type ?N$ {return} - your computer remembers your
name!


4.3.2 The GET Command

There are other BASIC commands you can use in your program to interact with
the computer. One is the GET command and is similar to INPUT. To see how
the GET command works, clear the computer's memory and type this program:

     10 GET A$
     20 IF A$="" THEN 10
     30 ? A$
     40 END

When you type RUN and press {return}, nothing seems to happen. The reason
is that the computer is waiting for you to press a key. The GET command, in
effect, tells the computer to check the keyboard and find out what
character or key is being pressed. The computer is satisfied with a null
character (that is, no character). This is the reason for line 20. This
line tells the computer that if it gets a null character, indicated by
double quotes with no space in between them, it should go back to line 10
and try to GET another character. This loop continues until you press a
key. The computer then assigns the character on that key to A$.

The GET command is very important because you can use it, in effect, to
program a key on your keyboard. The example below prints a message on the
screen when {q} is pressed. Type the program and RUN it. The press {q} and
see what happens.

     10 ?"PRESS Q TO VIEW MESSAGE"
     20 GET A$
     30 IF A$="" THEN 20
     40 IF A$="Q" THEN 60
     50 GOTO 20
     60 FOR I=1 TO 25
     70 ? "NOW I CAN USE THE GET STATEMENT"
     80 NEXT
     90 END

Notice that if you try to press any key other than the {q}, the computer
will not display the message, but will go back to line 20 to GET another
character.

Section 5 describes how to use the GETKEY statement, which is a new and more
powerful BASIC 7.0 command that can be used to perform a similar task.


4.3.3 Sample Program

Now that you know how to use the FOR-NEXT loop and the INPUT command, clear
the computer's memory by typing NEW {return}, then type the following
program:

     10 T=0
     20 INPUT"HOW MANY NUMBERS";N
     30 FOR J=1 TO N
     40 INPUT"PLEASE ENTER A NUMBER";X
     50 T=T+X
     60 NEXT
     70 A=T/N
     80 PRINT
     90 ? "YOU HAVE";N"NUMBERS TOTALING "T
     100 ? "AVERAGE = ";A
     110 END

This program lets you tell the computer how many numbers you want to ave-
rage. You can change the numbers every time you run the program without
having to change the program itself.

Let's see what the program does, line by line:

     Line 10 assigns a value of 0 to T (which will be the running total of
          the numbers).
     Line 20 lets you determine how many numbers to average, stored in
          variable N.
     Line 30 tells the computer to execute a loop N times.
     Line 40 lets you type in the actual numbers to be averaged.
     Line 50 adds each number to the running total.
     Line 60 tells the computer to increment the counter (J) and loop back
          to line 30 while the counter (J) <= N.
     Line 70 divides the total by the amount of numbers you typed in (N)
          after the loop has been executed N times.
     Line 80 prints a blank line on the screen.
     Line 90 prints the message that gives you the amount of numbers and
          their total.
     Line 100 prints the average of the numbers.
     Line 110 tells the computer that your progam is finished.

4.3.4 The READ-DATA Commands

There is another powerful way to tell the computer what numbers or charac-
ters to use in your program. You can use the READ statement in your program
to tell the computer to get a number or character(s) from the DATA state-
ment. For example, if you want the computer to find the average of five
numbers, you can use the READ and DATA statements this way:

     10 T=0
     20 FOR J=1 TO 5
     30 READ X
     40 T=T+X
     50 NEXT
     60 A=T/5
     70 ? "AVERAGE =";A
     80 END
     90 DATA 5,12,1,34,18

When you RUN the program, the computer will print AVERAGE = 14. The program
uses the variable T to keep a running total, and calculates the average in
the same way as the INPUT average program. The READ-DATA average program,
however, finds the numbers to average on a DATA line. Notice line 30, READ
X. The READ command tells the computer there must be a DATA statement in
the program. It finds the DATA line, and uses the first number as the cur-
rent value for the variable X. The next time through the loop the second
number in the DATA statement will be used as the value for X, and so on.

You can put any number you want in a DATA statement, but you cannot put
calculations in a DATA statement. The DATA statement can be anywhere you
want in the program - even after the END statement, or as the first program
line. This is because the computer never really executes the DATA state-
ment; it will just refer to it. Be sure to separate your data items with
commas, but be sure not to put a comma between the word DATA and the first
number in the list.

If you have more than one DATA statement in your program, the computer will
start READing from the first DATA statement in the program listing when the
program is RUN. The computer uses a pointer to remind itself which piece of
data it read last. After the computer reads the first number in the DATA
statement, the pointer moves to the next number. When the computer comes
to the READ statement again, it assigns the value the pointer indicates to
the variable in the READ statement.

You can use as many READ and DATA statement as you need in a program, but
make sure there is enough data in the DATA statements for the computer to
READ. Remove one of the numbers from the DATA statement in the last program
and RUN it again. The computer responds with ?OUT OF DATA ERROR IN 30. What
happened is that when the computer executed the loop for the fifth time,
there was no data for it to read. That is what the error message is telling
you. Putting too much into the DATA statement doesn't create a problem in
this program, because the computer never realizes the extra data exists.


4.3.5 The RESTORE Command

You can use the RESTORE command in a program to reset the data pointer to
the first piece of data if you need to. Replace the END statement (line 80)
in the program above with:

     80 RESTORE

and add:

     85 GOTO 10

Now RUN the program. The program will run continuously using the same DATA
statement.

NOTE: If the computer gives you an OUT OF DATA error message, it is because
you forgot to replace the number that you removed previously from the DATA
statement, so the data is all used before the READ statement has been exe-
cuted the specific number of times.


4.3.5.1 Assigning values to string variables

You can use DATA statements to assign values to string variables. The same
rules apply as for numeric data. Clear the computer's memory and type the
following program:

     10 FOR J=1 TO 3
     20 READ A$
     30 ? A$
     40 NEXT
     50 END
     60 DATA COMMODORE,128,COMPUTER

If the READ statement calls for a string variable, you can place letters or
numbers in the DATA statement. Notice however, that since the computer is
READing a string, numbers will be stored as a string of characters, not as
a value which can be manipulated. Numbers stored as strings can be printed,
but not used in calculations. Also you cannot place letters in a DATA
statement if the READ statement calls for a number variable.


4.3.6 Using Arrays

You have seen how to use READ-DATA to provide many values for a variable.
But what if you want the computer to remember all the data in the DATA
statement instead of replacing the value of a variable with the new data?
What if you want to be able to recall the third number, or the second
string of characters?

Each time you assign a new value to a variable, the computer erases the old
value in the variable's box in memory and stores the new value in its
place. You can tell the computer to reserve a row of boxes in memory and
store every value that you assign to that variable in your program. This
row of boxes is called an array.


4.3.6.1 Subscripted Variables

If the array contains all of these values assigned to the variable X in the
READ-DATA example, it is called the X array. The first value assigned to X
in the program is called X(1), the second value is X(2), and so on. These
are called subscripted variables. The numbers in the parentheses are called
subscripts. You can use the value of a variable or the result of a calcu-
lation as a subscript. The following is another version of the averaging
program, this time using subscripted variables.

      5 DIM X(5)
     10 T=0
     20 FOR J=1 TO 5
     30 READ X(J)
     40 T=T+X(J)
     50 NEXT
     60 A=T/5
     70 ? "AVERAGE =";A
     80 END
     90 DATA 5,12,1,34,18

Notice there are not many changes. Line 5 is the only new statement. It
tells the computer to set aside five boxes in memory for the X array. Line
30 has been changed so that each time the computer executes the loop, it
assigns a value from the DATA statement to the position in the X array that
corresponds to the loop counter (J). Line 40 calculates the total, just as
it did before, but you must use a subscipted variable to do it.

After you RUN the program, if you want to recall the third number, type:

     ?X(3) {return}

The computer remembers every number in the array X.

You can create string arrays to store the charachters in string variables
the same way. Try updating the COMMODORE 128 COMPUTER READ-DATA program so
the computer will remember the elements in the A$ array.

      5 DIM A$(3)
     10 FOR J=1 TO 3
     20 READ A$(J)
     30 ? A$(J)
     40 NEXT
     50 END
     60 DATA COMMODORE,128,COMPUTER

TIP: You do not need the DIM statement in your program unless the array you
use has more than 10 elements, see the next paragraaf, Dimensioning Arrays.


4.3.6.2 Dimensioning Arrays

Arrays can be used with nested loops, so the computer can handle data in a
more advanced way. What if you had a large chart with 10 rows and 5 numbers
in each row. Suppose you wanted to find the average of the five numbers in
each row. You could create 10 arrays and have the computer calculate the
average of the five numbers in each one. This is not necessary, because you
can put all the numbers in a two-dimensional array. This array would have
the same dimensions as the chart of numbers you want to work with - 10 rows
by 5 columns. The DIM statement for this array (we will call it array X)
should be:

     10 DIM X(10,5)

This tells the computer to reserve space in its memory for a two dimen-
sional array named X. The computer reserves enough space for 50 numbers.
You do not have to fill an array with as many numbers as you DIMensioned it
for, but the computer will still reserve enough space for all the positions
in the array.


4.3.6.3 Sample Program

Now it becomes very easy to refer to any number in the chart by its column
and row position. Refer to the chart below. Find the third element in the
tenth row (1500). You would refer to this number as X(10,3) in your program.
The following program reads the numbers from the chart into a two-dimen-
sional array (X) and calculates the average of the numbers in each row.


                             Column
----------+--------------------------------------------------
     Row  |        1        2        3        4        5    
----------+--------------------------------------------------
       1  |        1        3        5        7        9
       2  |        2        4        6        8       10
       3  |        5       10       15       20       25
       4  |       10       20       30       40       50
       5  |       20       40       60       80      100
       6  |       30       60       90      120      150
       7  |       40       80      120      160      180
       8  |       50      100      150      200      250
       9  |      100      200      300      400      500
      10  |      500     1000     1500     2000     2500


     10 DIM X(10,5), A(10)
     20 FOR R=1 TO 10
     30 T=0
     40 FOR C=1 TO 5
     50 READ X(R,C)
     60 T=T+X(R,C)
     70 NEXT C
     80 A(R)=T/5
     90 NEXT R
     100 FOR R=1 TO 10
     110 PRINT "ROW #";R
     120 FOR C=1 TO 5
     130 PRINT X(R,C)
     140 NEXT C
     150 PRINT "AVERAGE =";A(R)
     160 FOR D=1 TO 1000:NEXT
     170 NEXT R
     180 DATA 1,3,5,7,9
     190 DATA 2,4,6,8,10
     200 DATA 5,10,15,20,25
     210 DATA 10,20,30,40,50
     220 DATA 20,40,60,80,100
     230 DATA 30,60,90,120,150
     240 DATA 40,80,120,160,200
     250 DATA 50,100,150,200,250
     260 DATA 100,200,300,400,500
     270 DATA 500,1000,1500,2000,2500
     280 END


4.4 PROGRAMMING SUBROUTINES

4.4.1 The GOSUB-RETURN Commands

Until now, the only method you have had to tell the computer to jump to
another part of your program is to use the GOTO command. What if you want
the computer to jump to another part of the program, execute the statements
in that section, then return to the point it left off and continue execu-
ting the program?

The part of program that the computer jumps to and executes is called a
subroutine. Clear your computer's memory and enter the program below.

     10 A$="SUBROUTINE":B$="PROGRAM"
     20 FOR J=1 TO 5
     30 INPUT "ENTER A NUMBER";X
     40 GOSUB 100
     50 PRINT B$:PRINT
     60 NEXT
     70 END
     100 PRINT A$:PRINT
     110 Z=X^2:PRINT Z
     120 RETURN

This program will square the numbers you type and print the result. The
other print messages tell you when the computer is executing the subroutine
or the main program. Line 40 tells the computer to jump to line 100, exe-
cute it and the statements following it until it sees a RETURN command. The
RETURN statement tells the computer to go back in the program to the line
immediately following the GOSUB command and continue executing. The subrou-
tine can be anywhere in the program - including after the END statement.
Also, remember that the GOSUB and RETURN commands must always be used to-
gether in a program (like FOR-NEXT and IF-THEN), otherwise the computer
will give an error message.


4.4.2 The ON GOTO/GOSUB Commands

There is another way to make the computer jump to another section of your
program (called branching). Using the ON statement, you can have the com-
puter decide what part of the program to branch to, based on a calculation
or keyboard input.

The ON statement is used with either the GOTO or GOSUB-RETURN commands,
depending on what you need the program to do. A variable or calculation
should be after to ON command. After the GOTO or GOSUB command, there
should be a list of line numbers. Type in the program below to see how the
ON command works.

     10 ?"ENTER A NUMBER BETWEEN ONE AND FIVE"
     20 INPUT X
     30 ON X GOSUB 100,200,300,400,500
     40 END
     100 ?"YOUR NUMBER WAS ONE":RETURN
     200 ?"YOUR NUMBER WAS TWO":RETURN
     300 ?"YOUR NUMBER WAS THREE":RETURN
     400 ?"YOUR NUMBER WAS FOUR":RETURN
     500 ?"YOUR NUMBER WAS FIVE":RETURN

When the value of X is 1, the computer branches to the first line number in
the list (100). When X is 2, the computer branches to the second number in
the list (200), and so on.


4.5 USING MEMORY LOCATION


4.5.1 Using PEEK and POKE for RAM Access

Each area of the computer's memory has a special function. For instance,
there is a very large area to store your programs and the variables asso-
ciated with them. This part of memory, called RAM, is cleared when you use
the NEW command. Other areas are not as large, but they have very specia-
lized functions. For instance, there is an area of memory locations that
controls the music features of the computer.

There are two BASIC keywords - PEEK and POKE - that you can use to access
and manipulate the computer's memory. Use of the PEEK function and the POKE
command can be a powerful programming device because the contents of the
computer's memory locations determine exactly what the computer should be
doing at a specific time.


4.5.1.1 Using PEEK

PEEK can be used to make the computer tell you what value is being stored
in a memory location (a memory location can store any value between 0 and
255). You can PEEK the value of any memory location (RAM or ROM) in DIRECT
or PROGRAM mode. Type:

     P=PEEK(2594) {return}
     ? P {return}

The computer assigns the value in memory location 2594 to the variable P
when you press {return} after the first line. Then it prints the value when
you press {return} after entering the ? P command. Memory location 2594
determines whether or not keys like the SPACEBAR and CRSR repeat when you
hold them down. A 128 in location 2594 tells the computer to repeat these
keys when you hold them down. Hold down the SPACEBAR and watch the cursor
move across the screen.


4.5.1.2 Using POKE

To change the value stored in a RAM location, use the POKE command. Type:

     POKE 2594,96 {return}

The computer stores the value after the comma (i.e. 96) in the memory loca-
tion before the comma (i.e. 2594). A 96 in memory location 2594 tells the
computer not to repeat keys like the SPACEBAR and CRSR keys when you hold
them down. Now hold down the SPACEBAR and watch the cursor. The cursor
moves one position to the right, but it does not repeat. To return your
computer to its normal state, type:

     POKE 2594,128 {return}

You cannot alter the value of all the memory locations in the computer -
the values in ROM can be read, but not changed.

     NOTE: These examples assume you are in bank 0. See also the descrip-
     tion of the BANK command in chapter V, BASIC 7.0 Encyclopaedia for
     details on banks.


4.6 BASIC FUNCTIONS

4.6.1 What is a Function?

A function is a predefined operation of the BASIC language that generally
provides you with a single value. When the function provides the value, it
is said to "return" the value. For instance, the SQR (square) function is a
mathematical function that returns the value of a specific number when it
is raised to the second power - i.e., squared.

There are two kinds of functions:

    Numeric - returns a result which is a single number.
        Numeric functions range from calculating mathematical values to
        specifying the numeric value of a memory location.
    String - returns a result which is a character.

Following are descriptions of some of the more commonly used functions. For
a complete list, see Section 18 of Chapter V, BASIC 7.0 Encyclopaedia.


4.6.2 The INTEGER Function (INT)

What if you want to round off a number to the nearest integer? You'll need
to use INT, the integer function. The INT function takes away everything
after the decimal point. Try typing these examples:

     ? INT(4.25) {return}
     ? INT(4.75) {return}
     ? INT(SQR(50)) {return}

If you want to round off to the nearest whole number, then the second
example should return a value of 5. In fact, you should round up any number
with a decimal above 0.5. To do this, you have to add 0.5 to the number
before using the INT function. In this way, numbers with decimal portions
equal to or above 0.5 will be increased by 1 before rounding down by the
INT function. Try this:

     ? INT(4.75+0.5) {return}

The computer added 0.5 to 0.75 before it executed the INT function, so that
it rounded 5.25 down to 5 for the result. If you want to round off the
result of a calculation, do this:

     ? INT((100/6)+0.5) {return}

You can substitute any calculation for the division shown in the inner
parenteses.

What if you want to round off numbers to the nearest of 0.01? Instead of
adding 0.5 to your number, add 0.005, then multiply by 100. Let's say you
want to round 2.876 to the nearest 0.01. Using this method, you start with:

     ?(2.876 + 0.005)*100 {return}

Now use the INT function to get rid of everything after the decimal point
(which moves two places to the right when you multiply by 100). You are
left with:

     ?INT((2.876 + 0.005)*100) {return}

which gives you a value of 288. All that's left to do is divide by 100 to
get the value of 2.88, which is the answer you want. Using this technique,
you can round off calculations like the following to the nearest of 0.01:

     ?INT(((2.876+1.29+16.1-9.534) + 0.005)*100) {return}


4.6.3 Generating Random Numbers - The RND Function

The RND function tells the computer to generate a random number. This can
be useful in simulating games of chance, and in creating interesting
graphics or music programs. All random (RND) numbers are nine digits, in
decimal form, between the value 0.000000001 and 0.999999999. Type:

     ? RND(0) {return}

Multiplying the randomly generated number by six makes the range of gene-
rated numbers increase to greater than 0 and less than six. In order to in-
clude 6 (and exclude zero) among the numbers generated, we add one to the
result of RND(0)*6. This makes the range 1

     10 R=(INT(RND(1)*6+1)
     20 ? R
     30 GOTO 10

Each number generated represents one toss of a die. To simulate a pair of
dice, use two commands of this nature. Each number is generated separately,
and the sum of the two numbers represents the total of the dice.


4.6.4 The ASC and CHR$ Functions

Every character that the Commodore 128 can display (including graphic
characters) has a number assigned to it. This number is called a character
string code (CHR$) and there are 255 of them in the Commodore 128. There
are two functions associated with this concept that are very useful.

The first is the ASC function. Type:

     ? ASC(Q) {return}

The computer responds with 81. 81 is the character string code for the {q}
key. Substitute any key for {q} in the command above to find out the Com-
modore ASCII code number for any character.

The second function is the CHR$ function. Type:

     ? CHR$(81) {return}

The computer responds with Q. In effect, the CHR$ function is the opposite
of the ASC function. They both refer to the table of character string codes
in the computer's memory. CHR$ values can be used to program function keys.
See Section 5 for more information about the use of these functions. See
Appendix E of this Guide for a listing of ASC and CHR$ codes.


4.6.5 Converting Strings and Numbers

Sometimes you may need to perform calculations on numeric characters that
are stored as string variables in your program. Other times, you may want
to perform string operations on numbers. There are two BASIC functions you
can use to convert your variables from numeric to string type and vice
versa.


4.6.5.1 The VAL Function

The VAL function returns a numeric value for a string argument. Clear the
computer's memory and type in this program:

     10 A$="64"
     20 A=VAL(A$)
     30 ? "THE VALUE OF ";A$;" IS";A
     40 END


4.6.5.2 The STR$ Function

The STR$ function returns the string representation of a numeric value.
Clear the computer's memory and type this program:

     10 A=65
     20 A$=STR$(A)
     30 ? A"IS THE VALUE OF ";A$


4.6.6 The Square Root Function (SQR)

The square root function is SQR. For example, to find the square root of
50, type:

     ? SQR(50) {return}

You can find the square root of any positive number in this way.


4.6.7 The Absolute Value Function (ABS)

The absolute value (ABS) is very useful in dealing with negative numbers.
You can use this function to get the positive value of any number, positive
or negative. Try these examples:

     ? ABS(-10) {return}
     ? ABS(5)"IS EQUAL TO"ABS(-5) {return}


4.7 THE STOP AND CONT (CONTINUE) COMMANDS

You can make the computer stop a program, and resume running it when you
are ready. The STOP command must be included in the program. You can put a
STOP command anywhere you want to in a program. When the computer "breaks"
from the program (that is, stops running the program), you can use DIRECT
mode commands to find out exactly what is going on in the program.

For example, you can find the value of a loop counter or other variable.
This is a powerful device when you are "debugging" or fixing your program.
Clear the computer's memory and type the progam below.

     10 X=INT(SQR(630))
     20 Y=(.025*80)^2
     30 X=INT(X*Y)
     40 STOP
     50 FOR J=0 TO Z STEP Y
     60 ? "STOP AND CONTINUE"
     70 NEXT
     80 END

Now RUN this program. The computer responds with BREAK IN 40. At this
point, the computer has calculated the values of X, Y and Z. If you want to
be able to figure out what the rest of the program is supposed to do, tell
the computer to PRINT X;Y;Z.

Often when you are debugging a large program (or a complex small one),
you'll want to know the value of a variable at a certain point in the
program.

Once you have all the information you need, you can type CONT (for
CONTinue) and press {return} assuming you have not editing anything on the
screen. The computer then CONTinues with the program, starting with the
statement after the STOP command.


***************************************************************************


This section and the preceding one have been designed to familiarize you
with the BASIC programming language and its capabilities. The remaining
four sections of this chapter describe commands that are unique to Com-
modore 128 mode. Some Commodore 128 mode commands provide capabilities that
are not available in C64 mode. Other Commodore 128 mode commands let you do
the same things as a certain C64 command, but more easily. The syntax for
all Commodore 7.0 commands is given in Chapter V, BASIC 7.0 Encyclopaedia.



SECTION 5

5. Some BASIC Commands and Keyboard Operations Unique to C128



5.1 INTRODUCTION

5.2 ADVANCED LOOPING

  5.2.1 The DO/LOOP Statement
    5.2.1.1 UNTIL
    5.2.1.2 WHILE
    5.2.1.3 EXIT
  5.2.2 The ELSE Clause with IF-THEN
  5.2.3 The BEGIN/BEND Sequence with IF-THEN
  5.2.4 The SLEEP Command

5.3 FORMATTING OUTPUT

  5.3.1 The PRINT USING Command
  5.3.2 The PUDEF Command

5.4 SAMPLE PROGRAM

5.5 INPUTTING DATA WITH THE GETKEY COMMAND

5.6 PROGRAMMING AIDS

  5.6.1 Entering Programs
    5.6.1.1 AUTO
    5.6.1.2 RENUMBER
    5.6.1.3 DELETE
  5.6.2 Identifying Problems in Your Programs
    5.6.2.1 HELP
    5.6.2.2 Error Trapping - The TRAP Command
    5.6.2.3 Program Tracing - The TRON and TROFF Commands

5.7 WINDOWING

  5.7.1 Using the WINDOW Command to Create a Window
  5.7.2 Using the ESC Key to Create a Window

5.8 2 MHZ OPERATION

  5.8.1 The FAST and SLOW Commands

5.9 KEYS UNIQUE TO C128 MODE

  5.9.1 Function Keys
  5.9.2 Redefining Function Keys
  5.9.3 Other Keys Used in C128 Mode Only
    5.9.3.1 HELP
    5.9.3.2 NO SCROLL
    5.9.3.3 CAPS LOCK
    5.9.3.4 40/80 DISPLAY
    5.9.3.5 ALT
    5.9.3.6 TAB
    5.9.3.7 LINE FEED



5.1 INTRODUCTION

This section introduces you to some powerful BASIC commands and statements
that you probably have not seen before, even if you are an experienced
BASIC programmer. If you are familiar with programming in BASIC, you have
probably encountered many situations in which you could have used these
commands and statements. This section explains the concepts behind each
command and gives examples of how to use each command in a program. (A com-
plete list and an explanation of these commands and statements may be found
in Chapter V, BASIC 7.0 Encyclopaedia.) This section also describes how to
use the special keys that are available to you in C128 mode.


5.2 ADVANCED LOOPING

5.2.1 The DO/LOOP Statement

The DO/LOOP statement provides more sophisticated ways to create a loop
than do the GOTO, GOSUB or FOR/NEXT statements. The DO/LOOP statement com-
bination brings to the BASIC language a very powerful and versatile tech-
nique normally only available in structured programming languages. We
discuss just a few possible uses of DO/LOOP in this explanation.

If you want to create an infinite loop, you start with a DO statement, then
enter the line or lines that specify the action you want the computer to
perform. Then end with a LOOP statement like this:

     100 DO
     110 PRINT "REPETITION"
     120 LOOP

Press the {run/stop} key to stop the program.

The directions following the DO statement are carried out until the program
reaches the LOOP statement (line 120); control is then transferred back to
the DO statement (line 100). Thus any statements in between DO and LOOP are
performed indefinitely.

5.2.1.1 UNTIL

Another useful technique is to combine the DO/LOOP with the UNTIL state-
ment. The UNTIL statement sets up a condition that directs the loop. The
loop will run continually unless the condition for UNTIL happens.

     100 DO:INPUT "DO YOU LIKE YOUR COMPUTER";A$
     110 LOOP UNTIL A$="YES"
     120 PRINT "THANK YOU"

The DO/LOOP statement is often used to repeat an entire routine indefinite-
ly in the body of a program, as in the following:

     10 PRINT "PROGRAM CONTINUES UNTIL YOU TYPE 'QUIT'"
     20 DO UNTIL A$="QUIT"
     30 INPUT "DEGREES FAHRENHEIT";F
     40 C=(5/9)*(F-32)
     50 PRINT F;"DEGREES FAHRENHEIT EQUALS ";C;"DEGREES CELCIUS"
     60 INPUT "AGAIN OR QUIT";A$
     70 LOOP
     80 END

Another use of DO/LOOP is as a counter, where the UNTIL statement is used
to specify a certain number of repetitions.

     10 N=2*2
     20 PRINT"TWO DOUBLED EQUALS";N
     30 DO UNTIL X=25
     40 X=X+1
     50 N=N*2
     60 PRINT"DOUBLED";X+1;"TIMES...";N
     70 LOOP
     80 END

Notice that if you leave the counter statement out (the UNTIL X=25 part in
line 30), the number is doubled indefinitely until an OVERFLOW error
occurs.


5.2.1.2 WHILE

The WHILE statement works in a similar way to UNTIL, but the loop is re-
peated only while the condition is in effect, such as in the reworking of
the last brief program:

     100 DO:INPUT "DO YOU LIKE YOUR COMPUTER";A$
     110 LOOP WHILE A<>"YES"
     120 PRINT "THANK YOU"


5.2.1.3 EXIT

An EXIT statement can be placed within the body of a DO/LOOP. When the EXIT
statement is encountered, the program jumps to the next statement following
the LOOP statement.


5.2.2 The ELSE Clause with IF-THEN

The ELSE clause provides a way to tell the computer how to respond if the
condition of the IF-THEN statement is false. Rather than continuing to the
next program line, the computer will execute the command or branch to the
program line mentioned in the ELSE clause. For example, if you wanted the
computer to print the square of a number, you could use the ELSE clause
like this:

     10 INPUT "TYPE A NUMBER TO BE SQUARED";N
     20 IF N<100 THEN PRINT N*N:ELSE 40
     30 END
     40 ?"NUMBER MUST BE < 100":GOTO 10

Notice that you must use a colon (:) between the IF-THEN statement and the
ELSE clause.


5.2.3 The BEGIN/BEND Sequence with IF-THEN

BASIC 7.0 allows you to take the IF-THEN condition one step further. The
BEGIN/BEND sequence permits you to include a number of program lines to be
executed if the IF condition is true, rather than one simple action or
GOTO. The command is constructed like this:

     IF condition THEN BEGIN:
     (program lines):
     BEND:ELSE

Be sure to place a colon (:) between BEGIN and any instruction to the com-
puter, and again between the last command in the sequence and the word
BEND. BEGIN/BEND can be used without an ELSE clause, or can be used fol-
lowing the ELSE clause when only a single command follows THEN and multiple
commands follow the ELSE clause (of course BEGIN/BEND can also be used both
after THEN and ELSE). Try this program:

     10 INPUT A
     20 IF A<100 THEN BEGIN: ?"YOUR NUMBER WAS"A
     30 SLEEP 2:REM DELAY
     40 FOR X=1 TO A
     50 ?"THIS IS AN EXAMPLE OF BEGIN/BEND"
     60 NEXT X
     70 ?"THAT'S ENOUGH":BEND:ELSE ?"TOO MANY"
     80 END

This program asks for a number from the user. IF the number is less than
100, the statement between the keywords BEGIN and BEND are performed, along
with any statements on the same line as BEND (except for ELSE). The message
"YOUR NUMBER WAS" n appears on the screen. Line 30 is a delay used to keep
the message on the screen long enough so it can be read easily. Then a
FOR/NEXT loop is used to display a message the number of times specified by
the user. If the number is greater than or equal to 100, the part after the
THEN condition is skipped, and part after the ELSE condition (printing
"TOO MANY") is carried out. The ELSE keyword must be on the same line as
BEND.


5.2.4 The SLEEP Command

Note the use of the SLEEP command in line 30 of the program just discussed.
SLEEP provides an easier, more accurate way of inserting and timing a delay
in program operation. The format of the SLEEP command is:

     SLEEP n

where n indicates the number of seconds (rounded down to a whole number of
seconds), in the range of 0 to 65535, that you want the program to delay.
In the command shown in line 30, the 2 specifies a delay of two seconds.


5.3 FORMATTING OUTPUT

5.3.1 The PRINT USING Command

Suppose you were writing a sales program that calculated a dollar amount.
Total sales divided by number of salespeople equals average sales. But per-
forming this calculation might result in dollar amounts with four or five
decimal places! You can format the result the computer prints so that only
two decimal places are displayed. The command which performs this function
is PRINT USING.

PRINT USING lets you create a format for your output, using spaces, commas,
decimal points and dollar signs. Hash marks (the {#} sign) are used to re-
present spaces or characters in the displayed result. For example:

     PRINT USING "#$######.##";A

tells the computer that when A is printed, it should be in the form given,
with up to six places to the left of the decimal point, and two places to
the right. The hash mark in front of the dollar sign indicates that the {$}
should float, that is, it should always be placed next to the left-most
number in the format.

If you want a comma to appear before the last three dollar places (as in
$1,000.00), include the comma in the PRINT USING statement. Remember you
can format output with spaces, commas, decimal points, and dollar signs.
There are several other special characters for PRINT USING, see paragraph
17.68 of the BASIC Encyclopaedia for more information.


5.3.2 The PUDEF Command

If you want formatted output representing something other than dollars and
cents, use the PUDEF (Print Using DEFine) command. You can replace any of
four format characters with any character on the keyboard.

The PUDEF command has four positions, but you do not have to redefine all
four. The command looks like this:

     PUDEF " ,.$"
            1234

Here:
     * position 1 is the filler character. A blank will appear if you do
       not redefine this position.
     * position 2 is the comma character. Default is the comma.
     * position 3 is the decimal point.
     * position 4 is the dollar sign.

If you wrote a program that converted a dollar amount to English pounds,
you could format the output with these commands:

     10 PUDEF " ,.{pound}"
     20 PRINT USING "#$####.##";X


5.4 SAMPLE PROGRAM

This program calculates interest and loan payments, using some of the com-
mands and statements you just learned. It sets a minimum value for the loan
using the ELSE clause with an IF-THEN statement, and sets up a dollar and
cents format with PRINT USING.

     10 INPUT "LOAN AMOUNT IN DOLLARS";A
     20 IF A<100 THEN 70:ELSE P=.15
     30 I=A*P
     40 ?"TOTAL PAYMENT EQUALS";
     50 PRINT USING "#$#####.##";A+1
     60 GOTO 80
     70 ?"LOANS UNDER $100 ARE NOT AVAILABLE"
     80 END


5.5 INPUTTING DATA WITH THE GETKEY COMMAND

You have learned to use the INPUT and GET commands to enter DATA during a
program. Another way for you to enter data while a program is being RUN is
with the GETKEY statement. The GETKEY statement accepts only one key at a
time. GETKEY is usually followed by a string variable (A$ for example). Any
key that is pressed is assigned to that string variable. GETKEY is useful
because it allows you to enter data one character at a time without having
to press the RETURN key after each character. The GETKEY statement may only
be used in a program.

Here is an example of using GETKEY in a program:

     1000 PRINT "PLEASE CHOOSE A, B, C, D, E OR F"
     1010 GETKEY K$
     1020 PRINT A$;" WAS THE KEY YOU PRESSED."

The computer waits until a single key is pressed; when the key is pressed,
the character is assigned to variable A$, and printed out in line 1020.

The following program features the GETKEY in more complex and useful
fashions: for answering multiple-choice question and also asking if the
question should be repeated. If the answer given is incorrect, the user has
the option to try again by pressing the {y} key (line 80). The key pressed
for the multiple choice answer is assigned to variable A$ while the "TRY
AGAIN" answer is assigned to B$, through the GETKEY statements in line 60
and 90. IF/THEN statements are used for loops in the program to get the
proper computer reaction to the different keyboard inputs.

     10 PRINT "WHO WROTE 'THE RAVEN'?"
     20 PRINT "A. EDGAR ELLEN POE"
     30 PRINT "B. EDGAR ALLEN POE"
     40 PRINT "C. IGOR ALLEN POE"
     50 PRINT "D. ROB RAVEN"
     60 GETKEY A$
     70 IF A$="B" THEN 150
     80 PRINT "WRONG. TRY AGAIN? (Y OR N)"
     90 GETKEY B$
     100 IF B$="Y" THEN PRINT "A,B,C OR D": GOTO 60
     110 IF B$="N" THEN 140
     120 PRINT "TYPE EITHER Y OR N - TRY AGAIN"
     130 GOTO 90
     140 PRINT "THE CORRECT ANSWER IS B."
     145 GOTO 160
     150 PRINT "CORRECT!"
     160 END

GETKEY is very similar to GET, except GETKEY will wait for a key to be
pressed.


5.6 PROGRAMMING AIDS

In earlier sections you learned how to make changes in your programs, and
correct typing mistakes with {inst/del}. BASIC also provides other commands
and functions which help you locate actual programming errors, and commands
which you can use to make programming sessions flow more smoothly.


5.6.1 Entering Programs

5.6.1.1 AUTO

C128 BASIC provides an auto-numbering process. You determine the increment
for the line numbers. Say you want to number your program in the usual man-
ner, by tens. Before you begin to program, while in DIRECT mode, type:

     AUTO 10 {return}

The computer automatically numbers your programs by tens. After you enter a
line and press the {return} key, the next line number appears, and the cur-
sor is in the correct place for you to type the next statement. You can
choose to have the computer number the commands with any increment; you
might choose 5 or even 50. Just place the number after the word AUTO and
press {return}. To turn off the auto-numbering feature, type AUTO with no
increment, and press {return}.


5.6.1.2 RENUMBER

If you write a program and later add statements to it, sometimes the line
numbering can be awkward. Using the RENUMBER command you can change the
line numbers to an even increment for part or all of your program. The
RENUMBER command has several optional parameters, as listed below in
brackets:

     RENUMBER [new starting line] [,[increment] [,old starting line]]

The new starting line is what the first program line wil be numbered after
the RENUMBER command is used. If you do not specify, the default is 10. The
increment is the spacing between line numbers, and it also defaults to 10.
The old starting line number is the line number where the renumbering is to
begin. This feature allows you to renumber a portion of your program,
rather than all of it. It defaults to the first line of the program. For
example:

     RENUMBER 40,,80

tells the computer to renumber the program starting at line 80, in incre-
ments of 10. Line 80 becomes line 40.

Notice that this command, like AUTO, can only be executed in DIRECT mode.


5.6.1.3 DELETE

You know how to delete program lines by typing the line number and pressing
the {return} key. This can be tedious if you want to erase an entire por-
tion of your program. The DELETE command can save you time because you can
specify a range of program lines to erase all at once. For example:

     DELETE 10-50

will erase line 10, 50, and any in between. The use of DELETE is similar to
that of LIST, in that you can specify a range of lines up to a given line,
or following it, or a single line only, as in these examples:

     DELETE -120
     erases all lines up to and including 120
     DELETE 120-
     erases line 120 and any line after it
     DELETE 120
     erases line 120 only


5.6.2 Identifying Problems in Your Programs

When a program does not work the way you expected, an error message usual-
ly occurs. Sometimes the messages are vague, however, and you still do not
understand the problem. The Commodore 128 computer has several ways of
helping you locate the problem.


5.6.2.1 HELP

The Commodore 128 provides a HELP command that specifies the line in which
a problem has occurred. To actuate the HELP command, just press the special
{help} key on the row of keys located above the main keyboard.

Type the following statement. It contains an intentional error, so type it
just as is:

     10?3;4:5;6

When you RUN this one-line program, the computer prints 3 and 4 as expec-
ted, but then responds ?SYNTAX ERROR IN 10. Suppose you cannot see the
error (a colon instead of a semicolon between 4 and 5). You press the
{help} key. (You can also type HELP and press {return}.) The computer dis-
plays the line again, but the 5;6 is highlighted to show the error is in
that part of the line:

     10?3;4:5;6


5.6.2.2 Error Trapping - The TRAP Command

Usually, if an error occurs in a program, the program "crashes" (stops run-
ning). At that point, you can press the {help} key to track down the error.
However, you can use the BASIC 7.0 TRAP command to include an error-
trapping capability within your program. The TRAP command advises you to
locate and correct an error, then resume program operation. Usually, the
error trapping function is set in the first line of a program:

     5 TRAP 100

tells the computer that if an error occurs to go to a certain line (in this
case, line 100). Line 100 appears at the end of the program, and sets up a
contingency. Neither line is executed UNLESS there is an error. When an
error occurs, the line with the TRAP statement is enacted, and control is
directed to another part of the program. You can uses these statements to
catch anticipated errors in entering data, resume execution, or return to
text mode from graphics mode, to name just a few options. If you run the
last DO/LOOP example (with doubled numbers) without an UNTIL statement, you
can get an OVERFLOW error and the program crashes. You can prevent that
from happening by adding two lines, one at the beginning and one at the
end. For example, you might add these two lines:

     5 TRAP 100
     100 IF N<1 THEN END

Even though N has been much greater than one for the entire program, the
statement is not considered until there is an error. When the number
"overflows" (is greater than the computer can accept), the TRAP statement
goes into effect. Since N is greater than one, the program is directed to
END (rather than crashing).

Here is an example in which trapping is used to prevent a zero from being
input for division.

     10 TRAP 1000
     100 INPUT "I CAN DIVIDE BY ANY NUMBER, GIVE ME A NUMBER TO DIVIDE";D
     110 INPUT "WHAT SHOULD I DIVIDE IT BY";B
     120 A=D/B
     130 PRINT D;"DIVIDED BY ";B;"EQUALS ";A
     140 END
     1000 IF B=0 THEN PRINT"EVEN I CAN'T DO THAT"
     1100 INPUT "PICK A DIFFERENT NUMBER";B:RESUME 120

Notice the RESUME in line 1100. This tells the computer to return to the
line mentioned (in this case, 120) and continue. Depending on the error
that was trapped, resuming executing may or may not be possible.

For additional information on error trapping, see the error functions ERR$
(paragraph 18.8), EL and ER (paragraph 19.1), described in Chapter V, BASIC
7.0 Encyclopaedia.


5.6.2.3 Program Tracing - The TRON and TROFF Commands

When a problem in a program occurs, or you do not get the result you ex-
pect, it can be useful to methodically work through the program and do
exactly what the computer would do. This process is called tracing. Draw
variable boxes and update the values according to the program statements.
Perform calculations and print results following each instruction. (All
done by hand, using the program listing as a guideline.)

This kind of tracing may show you, for example, that you have used a GOTO
with an incorect line number, or calculated a result but never stored it in
a variable. Many program errors can be located by pretending to be the com-
puter, and following only one instruction at a time.

Your C128 can perform a type of trace using the special commands TRON and
TROFF (short for TRace ON and TRace OFF). When the program is run, with
TRace ON, the computer prints the line numbers in the order they are exe-
cuted. In this way, you may be able to see why your program is not giving
the results you expected.

Type any short program we have used so far, or use one of your own design.
To activate trace mode, type TRON in DIRECT mode. When you run the program,
notice how line numbers appear in brackets before any results are dis-
played. Try to follow the line numbers and see how many steps the computer
needed to arrive at a certain point. TRON will be more interesting if you
pick a program with many branches, such as GOTO, GOSUB and IF-THEN-line
number. Type TROFF to turn trace mode off before continuing.

You do not have to trace an entire program. You can place TRON within a
program as a line prior to the program section causing problems. Put the
word TROFF as a program line after the troublesome section. When you run
the program, only the lines between TRON and TROFF will be bracketed in the
results.


5.7 WINDOWING

Windows are a specific area on the screen that you define as your work-
space. Everything you type (lines you type, listings of programs, etc.)
after setting a window, appears within the window's bounderies, not affec-
ting the screen outside the window area. The Commodore 128 provides two
methods of creating windows: the WINDOW command and {esc} key functions.


5.7.1 Using the WINDOW Command to Create a Window

The Commodore 128 BASIC 7.0 language features a command that allows you to
create and manipulate windows: the WINDOW command. The command format is:

     WINDOW top-left column, top-left row, bottom-right column,
     bottom-right row [,clear option]

The first two numbers after WINDOW specify the column and row number of
where you want the top left corner of the window to be; the next two num-
bers are the coordinates for the bottom right corner. Remember that the
screen format (40- or 80-columns) dictates the acceptable range of these
coordinates. You can also include a clear option with this command. If you
add 1 onto the end of the command, the window screen area is cleared, as in
this example:

     WINDOW 10,10,20,20,1

Here's a sample program that creates four windows on the screen, in either
40- or 80-column format.

 10 SCNCLR                               :REM CLEAR SCREEN
 20 WINDOW 0,0,39,24                     :REM SET WINDOW TO FULL SCREEN
 30 COLOR 0,13:COLOR 4,13                :REM SET 40 SCREEN TO MED. GREY
 40 A$="ABCDEFGHIJKLMNOPQRST"
 50 COLOR 5,5                            :REM SELECT PURPLE TEXT
 60 FOR I=1 TO 25                        :REM FILL SCREEN WITH CHARACTERS
 70 PRINT A$;A$:NEXT I
 80 WINDOW 1,1,7,20                      :REM DEFINE WINDOW 1
 90 COLOR 5,3                            :REM SELECT RED TEXT
 100 PRINT CHR$(18);A$;                  :REM PRINT A$ IN REVERSE RED TEXT
 110 WINDOW 15,15,39,20,1                :REM DEFINE SECOND WINDOW
 120 COLOR 5,7                           :REM SELECT BLUE TEXT
 130 FOR I=1 TO 6:PRINT A$;: NEXT        :REM FILL WINDOW 2 WITH CHARACTERS
 140 WINDOW 30,1,39,22,1                 :REM DEFINE THIRD WINDOW
 150 COLOR 5,8:LIST                      :REM LIST IN YELLOW TEXT
 160 WINDOW 5,5,33,18,1                  :REM DEFINE FOURTH WINDOW
 170 COLOR 5,2                           :REM SELECT WHITE TEXT
 180 PRINT A$:LIST                       :REM PRINT A$ AND LIST IN WHITE TEXT
 190 END


5.7.2 Using the ESC Key to Create a Window

To set a window with the {esc} (Escape) key, follow these steps:

     1. Move the cursor to the screen position you want as the top left
        corner of the window.
     2. Press the {esc} key and release it, and then press {t}.
     3. Move the cursor to the position you want to be the bottom right
        corner of the window.
     4. Press {esc} and release, then {b}. Your window is now set.

You can manipulate the window and the text inside using the {esc} key.
Screen editing functions, such as inserting and deleting text, scrolling,
and changing the size of the window, can be performed by pressing {esc}
followed by another key. To use a specific function, press {esc} and re-
lease it. Then press any of the following keys listed for the desired func-
tion:

     @ Erase everything from cursor to end of screen window.
     A Automatic insert mode.
     B Set the bottom right corner of the screen window (at the current
       cursor location)
     C Cancel automatic insert mode.
     D Delete current line.
     E Set cursor to non-flashing mode.
     F Set cursor to flashing mode.
     G Enable bell (by {ctrl g}).
     H Disable bell.
     I Insert a line.
     J Move to the beginning of the current line.
     K Move to the end of the current line.
     L Turn on scrolling.
     M Turn off scrolling.
     N Return to normal (non-reverse video) screen display (80-column
       only).
     O Cancel insert and quote modes.
     P Erase everything from the beginning of the line to the cursor.
     Q Erase everything from the cursor to the end of the line.
     R Reverse screen display (80-column only).
     S Change to block cursor.
     T Set the top left corner of the screen window (at the current cursor
       location).
     U Change to underline cursor.
     V Scroll screen up one line.
     W Scroll screen down one line.
     X Toggles between 40- and 80-columns
     Y Restore default TAB stops.
     Z Clear all TAB stops.

Experiment with the {esc}ape key functions. You will probably find certain
functions more useful than others. Note that you can use the usual
{inst/del} key to perform text editing inside a window as well.

When a window is set up, all screen output is continued to the "box" you
have defined. If you want to clear the window area, press {shift} and
{clr/home} together. To cancel the window, press the {clr/home} twice. The
window is then restored to its maximum size and the cursor is placed in the
top left corner of the screen. If you subsequently want to clear the screen,
press {shift} and {clr/home} together. Windows are particularly useful in
writing, listing and running programs, because they allow you to work in
one area of the screen, while the rest of the screen stays as it is.


5.8 2 MHZ OPERATION

5.8.1 The FAST and SLOW Commands

The 2 Mhz operation mode allows you to run non-graphic programs in 80-
column format at twice the normal speed. You can switch normal and fast
operation by using the FAST and SLOW commands.

The FAST command places the Commodore 128 in 2 Mhz mode. The format of this
command is:

     FAST

The SLOW command returns the Commodore 128 to 1 Mhz mode. The format of
this command is:

     SLOW


5.9 KEYS UNIQUE TO C128 MODE

5.9.1 Function Keys

The four keys on the Commodore 128 keyboard on the right side above the
numeric keypad are special function keys that let you save time by per-
forming repetitive tasks with the stroke of just one key. The first key
reads F1/F2, the second F3/F4, the third F5/F6 and the last F7/F8. You can
use functions 1, 3, 5 and 7 by pressing the key itself. To use the func-
tions 2, 4, 6 and 8, press {shift} and the function key.

Here are the standard functions for each key:

  F1         F2        F3         F4
GRAPHIC    DLOAD"   DIRECTORY   SCNCLR

  F5         F6        F7         F8
 DSAVE"     RUN       LIST      MONITOR

Here is what each function involves:

     KEY 1  enters one of the GRAPHICs modes when you supply the number of
            the graphics area and press {return}. The GRAPHICs command is
            necessary for giving graphics commands such as CIRCLE or PAINT.
            For more on graphics, see Section 6.
     KEY 2  prints DLOAD" on the screen. All you do is enter the program
            name and hit {return} to load the program from disk, instead of
            typing out DLOAD yourself.
     KEY 3  lists a DIRECTORY of files on the disk in the disk drive.
     KEY 4  clears the screen using the SCNCLR command.
     KEY 5  prints DSAVE" on the screen. All you do is enter the program
            name, and press {return} to save the current program on disk.
     KEY 6  RUNs the current program.
     KEY 7  displays a LISTing of the current program.
     KEY 8  lets you enter the Machine Language Monitor.


5.9.2 Redefining Function Keys

You can redefine or program any of these keys to perform a function that
suits your needs. Redefining is easy, using the KEY command. You can re-
define the keys from BASIC programs, or change them at any time in DIRECT
mode. A situtation where you might want to redefine a function key is when
you use a command frequently, and want to save time instead of repeatedly
typing in the command. The new definitions are erased when you turn off the
computer. You can redefine any of the function keys ans as many times as
you want.

If you want to reprogram the F7 function key to return you to text mode
from high resolution or multicolor graphics modes, for example, you would
use the key command in this fashion:

     KEY 7,"GRAPHIC 0" + CHR$(13)

CHR$(13) is the ASCII code character for {return}. So when you press the
{f7} key after redefining the key, what happens is the command "GRAPHIC 0"
is automatically typed out and entered into the computer with {return}.

Entire commands or series of commands may be assigned to a function key.


5.9.3 Other Keys Used in C128 Mode Only

5.9.3.1 HELP

As noted previously, when you make an error in a program, your computer
displays an error message to tell you what you did wrong. These error mes-
sages are further explained in Appendix A of this manual. You can get more
assistance with errors by using the {help} key. After an error message,
press the {help} key to locate the exact point where the error occurred.
When you press {help}, the line with the error is highlighted on the screen
in reverse video (in 40-column) or underlined (in 80-column).

For example:

   ?SYNTAX ERROR IN LINE 10         Your computer displays this.

   HELP                             You pressed the {help} key.

   10 PRONT "COMMODORE COMPUTERS"   The line with the mistake is high-
                                    lighted in reverse if in 40-column out-
                                    put or underlined in 80-column output.


5.9.3.2 NO SCROLL

Press this key down to stop the text from scrolling when the cursor reaches
the bottom of the screen. This key turns off scrolling until you press a
key (any character key will do).


5.9.3.3 CAPS LOCK

This key lets you type in all capital letters without using the {shift}
key. The {caps lock} key locks in when you press it, and must be pressed
again to be released. {caps lock} only effects the lettered keys.


5.9.3.4 40/80 DISPLAY

The 40/80 key selects the main (default) screen format: either 40- or 80-
column. The selected screen displays all the messages and output at power-
up, or when the {reset} button, or the key combination {run/stop restore}
is pressed. The 40/80 key may be used to set the display format only before
turning on or resetting the computer. You cannot change modes with this key
after the computer is turned on, unless you use the {reset} button at the
right side of the computer, or the key combination {run/stop restore}. Sec-
tion 8 provides an explanation of 40/80 column modes.

5.9.3.5 ALT

The {alt} allows programs to assign a special meaning to a given key or set
of keys.

Unless the specific application program redefines it, holding down the
{alt} key and any other key has no effect.

5.9.3.6 TAB

This key works like the TAB key on a typewriter. It may be used to set or
clear tab stops on the screen and to move the cursor to the columns where
the tabs are set.


5.9.3.7 LINE FEED

Pressing this key advances the cursor to the next line, similar to the
{crsr down} key.


***************************************************************************


FOR MORE INFORMATION

This section covers only some of the concepts, keys and commands that make
the Commodore 128 a special machine. You can find further explanation of
the BASIC language in the BASIC 7.0 Encyclopaedia in Chapter V.



SECTION 6

6. Color, Animation and Sprite Graphics Statements Unique to the C128



6.1 GRAPHICS OVERVIEW

  6.1.1 Graphics Features
  6.1.2 Command Summary

6.2 GRAPHICS PROGRAMMING ON THE COMMODORE 128

  6.2.1 Choosing Colors
        Figure 6-1. Source Numbers.
        Figure 6-2. Color Numbers in 40-Column Format.
        Figure 6-3. Color Numbers in 80-Column Format.
  6.2.2 Types of Screen Display
  6.2.3 Selecting the Graphic Mode
        Figure 6-4. Graphic Modes.
        Figure 6-5. Clear Parameters.
  6.2.4 Displaying Graphics on the Screen
    6.2.4.1 Drawing a Circle - The CIRCLE Command
            Figure 6-6. Arrangement of x and y coordinates.
    6.2.4.2 Drawing a Box - The BOX Command
    6.2.4.3 Drawing Lines, Points and Other Shapes - The DRAW Command
    6.2.4.4 Painting Outlined Areas - The PAINT Command
    6.2.4.5 Displaying Characters on a Bit-Mapped-Screen - The CHAR Command
    6.2.4.6 Creating a Graphics Sample Program
    6.2.4.7 Changing the Size of Graphics Images - The SCALE Command

6.3 SPRITES: PROGRAMMABLE, MOVABLE OBJECT BLOCKS

  6.3.1 Sprite Creation
  6.3.2 Using Sprite Statements in a Program
  6.3.3 Drawing the Sprite Image
  6.3.4 Storing the Sprite Data with SSHAPE
  6.3.5 Saving the Picture Data in a Sprite
  6.3.6 Turning on Sprites
  6.3.7 Moving Sprites with MOVSPR
        Figure 6-7. Visible Sprite coordinates.
  6.3.8 Creating a Sprite Program
  6.3.9 Sprite Definition Mode - The SPRDEF Command
  6.3.10 Sprite Creation Procedure in SPRite DEFinition Mode
  6.3.11 Adjoining Sprites
  6.3.12 Storing Sprite Data in Binary Files
         Figure 6-8. Sprite Data Requirements.
         Figure 6-9. Memory Address Ranges for Sprite Storage.
    6.3.12.1 BSAVE
    6.3.12.2 BLOAD



6.1 GRAPHICS OVERVIEW

In C128 mode, the Commodore 128 BASIC 7.0 language provides may new and
powerful commands and statements that make graphics programming much
easier. Each of the two screen formats available in C128 mode (40 columns
and 80 columns) is controlled by a seperate microprocessor chip. The 40-
column chip is called the Video Interface Controller, or VIC for short. The
80-column chip is referred to as the 8563, or Video Display Controller
(VDC). The VIC chip, which provides 16 colors, controls all the highly de-
tailed graphics called bit-mapped graphics. The 80-column chip, which also
offers 16 colors, only displays characters and character graphics. Thus,
all detailed graphic programs in C128 mode must be done in 40-column
format.


6.1.1 Graphics Features

As part of its impressive C128 mode graphics capabilities, the Commodore
128 provides:


     * 13 specialized graphics commands
     * 16 colors
     * Six different display modes
     * Eight programmable movable objects called SPRITES
     * Combined graphics/text displays


All these formats can be integrated to provide a versatile, easy to use
graphics system.


6.1.2 Command Summary

Here is a brief explanation of each graphic command:

     BOX     - Draws rectangles on the bit map screen.
     CHAR    - Displays characters on the bit map screen.
     CIRCLE  - Draws circles, ellipses and other geometric shapes on the
               bit map screen.
     COLOR   - Selects colors for screen border, foreground, background and
               characters.
     DRAW    - Draws lines and points on the bit map screen.
     GRAPHIC - Selects a screen display (text, bit map or split screen bit
               map).
     GSHAPE  - Places the image stored into a text string variable on the
               bit map screen.
     PAINT   - Fill areas on the bit map screen with color.
     SCALE   - Sets the relative size of the images on the bit map screen.
     SPRDEF  - Enters sprite definitions mode to edit sprites.
     SPRITE  - Enables, colors, sets sprite screen priorities, and expands
               a sprite.
     SPRSAV  - Stores a text string variable into a sprite storage area and
               vice versa.
     SSHAPE  - Stores the image of a portion of the bit map screen into a
               text string variable.

Most of these commands are described in the examples in this section. See
Chapter V, BASIC 7.0 Encyclopaedia for detailed format and information on
all graphic commands, and BASIC Functions for all graphic functions discus-
sed in this section.


6.2 GRAPHICS PROGRAMMING ON THE COMMODORE 128

This following section describes a step-by-step graphics programming
example. As you learn each graphics command, add it to a program, you will
build as you read this section. When you are finished, you will have a com-
plete graphics program.


6.2.1 Choosing Colors

The first step in graphics programming is to choose colors for the screen
background, foreground and border. To select colors, type:

     COLOR source, color

where source is the section of the screen you are coloring (background,
foreground, border, etc.) and color is the color code for the source.
See Figure 6-1 for source numbers, Figure 6-2 for 40-column-format color
numbers, and Figure 6-3 for 80-column-format color numbers.

Number  Source

  0     40-column background color (VIC)
  1     Foreground for the graphics screen (VIC)
  2     Foreground color 1 for the multicolor screen (VIC)
  3     Foreground color 2 for the multicolor screen (VIC)
  4     40-column (VIC) border (whether in text or graphics mode)
  5     Character color for 40- or 80-column text screen
  6     80-column background color (8563)

                       Figure 6-1. Source Numbers.

Color Code  Color           Color Code  Color

    1       Black               9       Orange
    2       White               10      Brown
    3       Red                 11      Light Red
    4       Cyan                12      Dark Gray
    5       Purple              13      Medium Gray
    6       Green               14      Light Green
    7       Blue                15      Light Blue
    8       Yellow              16      Light Gray

             Figure 6-2. Color Numbers in 40-Column Format.

Color Code  Color           Color Code  Color

    1       Black               9       Dark Purple
    2       White               10      Brown
    3       Dark Red            11      Light Red
    4       Light Cyan          12      Dark Cyan
    5       Light Purple        13      Medium Gray
    6       Dark Green          14      Light Green
    7       Dark Blue           15      Light Blue
    8       Light Yellow        16      Light Gray

             Figure 6-3. Color Numbers in 80-Column Format.


6.2.2 Types of Screen Display

Your C128 has several different ways of displaying information on the
screen; the parameter "source" in the COLOR command pertains to different
modes of screen display. The types of video display fall into three cate-
gories.

The first one is text display, which displays only characters, such as let-
ters, numbers, special symbols and the graphics characters on the front
faces of most C128 keys. The C128 can display text in both 40-column and
80-column screen formats.

The second category of display mode is used for highly detailed graphics,
such as pictures and intricate drawings. This type of display mode includes
standard bit map mode and multicolor bit map mode. Bit map modes allow you
to control each and every individual screen dot or pixel (picture element).
This allows considerable detail in drawing pictures and other computer art.
The 80 column display is intended to display text.

The difference between text and bit map lies in the way in which each
screen addresses and stores information. The text screen can only manipu-
late entire characters, each of which covers an area of 8 by 8 pixels on
your screen. The more powerful bit map mode exercises control over each and
every pixel on your screen.

The third type of screen display, split screen, is a mixture of the first
two types. The split screen display outputs part of the screen as text and
part in bit map mode (either standard or multicolor). The C128 is capable
of this because it uses two seperate and different parts of the computer's
memory to store the two screens: one part for the text, and the other for
the graphics screen.

Type the following short program:

     10 COLOR 0,1:REM TEXT BACKGROUND COLOR = BLACK
     20 COLOR 1,3:REM FOREGROUND COLOR FOR BIT MAP SCREEN = RED
     30 COLOR 4,1:REM BORDER COLOR = BLACK

This example colors the background black, the foreground red and the border
black.


6.2.3 Selecting the Graphic Mode

The next graphics programming step is to select the appropriate graphic
mode. This is done using the GRAPHIC command, whose format is as follows:

     GRAPHIC <mode[,c] [,s] / CLR>

where mode is a digit between 0 and 5, c is either an 0 or 1 and s is a
value between 0 and 25. Figure 6-4 shows the values corresponding to the
graphic modes.

           Mode          Description

           0    40-column (VIC) standard text
           1    Standard bit map
           2    Standard bit map (split screen)
           3    Multicolor bit map
           4    Multicolor bit map (split screen)
           5    80-column text

                       Figure 6-4. Graphic Modes.

The parameter c stands for CLEAR. Figure 6-5 explains the values associated
with CLEAR.

        C Value          Description

           0     Do not clear the graphics screen
           1     Clear the graphics screen

                     Figure 6-5. Clear Parameters.

When you first run your program, you still want to clear the graphics
screen for the first time, so set c equal to 1 in the GRAPHIC command. If
you run it a second time, you may want your picture on the screen, instead
of drawing it all over again. In this case, set c equal to 0.

The s parameter specifies in split screen mode at which line number the
text screen starts (line numbers start counting at zero, so line 10 is the
eleventh line). If you omit the s parameter and select a split screen
graphic mode (2 or 4), the text screen portion is displayed in rows 19
through 24; the portion above is bit mapped. The s parameter allows you to
change the starting line of the text screen to any line on the screen,
ranging from 1 through 24. A zero as s parameter indicates the screen is
not split, and all is text.

The final GRAPHIC command parameter is CLR. When you first issue a bit map
GRAPHIC command, the Commodore 128 allocates a 9K area for your bit mapped
screen information. 8K is reserved for the data for your bit map and the
additional 1K is dedicated for the color data (video matrix). Since 9K is a
substantial block of memory, you may want to use it again for another pur-
pose later in your program. This is the purpose of CLR. It reorganizes the
Commodore 128 memory and gives you back the 9K of memory that was dedicated
to the bit map screen, so you can use it for other purposes.

The format for CLR is as follows:

     GRAPHIC CLR

When using this format, omit all other GRAPHIC command parameters.

Add the following command to your program. It places the C128 in standard
bit map mode and allocates an 8K bit map screen (and 1K of color data) for
you to create graphics.

     40 GRAPHIC 1,1

The second 1 in this command clears the bit map screen. If you do not want
to clear the screen, change to second 1 to 0 (or omit it completely).

     NOTE: If you are in bit map mode and are unable to return to the text
     screen, press the {run/stop} and {restore} keys at the same time, or
     press the {esc} key followed by {x}, to return to the 80-column
     screen. Even though you can only display graphics with the VIC (40-
     column) chip, you can still write graphic programs in 80-column
     format. If you have the Commodore 1901 and you want to view your
     graphics program while it is running, you must select the 40-column
     output by switching the slide switch on the monitor to 40-column
     output.


6.2.4 Displaying Graphics on the Screen

So far, you have selected a graphics mode and the colors you want. Now you
can start displaying graphics on the screen. Start with a circle.


6.2.4.1 Drawing a Circle - The CIRCLE Command

To draw a circle, use the CIRCLE statement as follows:

     60 CIRCLE 1,160,100,40,40

This displays a circle in the center of the screen. The CIRCLE statement
has nine parameters you can select to achieve various types of circles and
geometric shapes. For example, by changing the numbers in the CIRCLE state-
ment in line 60 you can obtain different size circles or variations in the
shape (e.g. an oval). The CIRCLE statement adds power and versatility in
programming Commodore 128 graphics in BASIC. The meaning of the numbers in
the CIRCLE statement is explained under the CIRCLE listing in Chapter V,
BASIC 7.0 Encyclopaedia.


On your Commodore 128 screen, the point where x=0 and y=0 is at the top
left corner of the screen and is referred as the HOME position. In stan-
dard geometry however, the point where x and y equal 0 is in the bottom
left corner of a graph. Figure 6-6 shows the arrangement of x (horizontal)
and y (vertical) screen coordinates and the four points at the corners of
the C128 screen.

                           X Coordinate
     0,0     +----------------------------------------+   319,0
             |                                        |
             |                                        |
             |                                        |
             |                                        |
Y Coordinate |                                        |
             |                                        |
             |                                        |
             |                                        |
    0,199    +----------------------------------------+   319,199

        Figure 6-6. Arrangement of x and y coordinates.

Here's what the numbers mean:

     * 1 is the color source (in this case the foreground).
     * 160 is the starting x (horizontal) coordinate.
     * 100 is the starting y (vertical) coordinate.
     * 40 is the radius.


6.2.4.2 Drawing a Box - The BOX Command

Now try a box. To draw a box, type:

     80 BOX 1,20,60,100,140,0,1

This draws a solid box to the left of the circle. To find out what the
numbers in the BOX statement mean, consult Commands and Statements. The BOX
statement has seven parameters you can select and modify to produce dif-
ferent types of boxes. Change the foreground color an draw the outline of a
box to the right of the CIRCLE with these statements:

     90 COLOR 1,9:REM CHANGE FOREGROUND COLOR
     100 BOX 1,220,60,300,140,0,0

Experiment with the BOX statement to produce different variations of rec-
tangles and boxes.


6.2.4.3 Drawing Lines, Points and Other Shapes - The DRAW Command

You now know how to select graphic modes and colors and how to display cir-
cles and boxes on the screen. Another graphics statement, DRAW, lets you
draw lines on the screen just as you would with a pencil and a piece of
paper. The following statement draws a line below the boxes and circle.

     120 DRAW 1,20,180 TO 300,180

To erase a drawn line, change the source (1) in the DRAW statement to 0.
The line is drawn with the background color which actually erases the line.
Try using different coordinates and other sources to become accustomed to
the DRAW statement.

The DRAW statement can take another form that allows you to DRAW a line,
change direction and then DRAW another line, so the lines are continuous.
For example, try this statement:

     130 DRAW 1,250,0 TO 30,0 TO 40,40 TO 250,0

This statement DRAWs a triangle on the top of the screen. The four pairs of
number represent the x and y coordinates for the three points on the tri-
angle. Notice the first and last coordinates are the same, since you must
finish drawing the triangle on the same point you started. This form of
DRAW statement gives you the power to DRAW almost any geometric shape, such
as trapezoids, parallellograms and polygons.

The DRAW statement also has a third form.

You can DRAW one point at a time by specifying the starting x and y values
as follows:

     150 DRAW 1,160,160

As you can see, the DRAW statement has versatile features which give you
the capability to create shapes, lines, points and a virtually unlimited
number of computer drawings on your screen.


6.2.4.4 Painting Outlined Areas - The PAINT Command

The DRAW statement allows you to outline areas on the screen. What if you
want to fill areas within your drawn lines? That's where the PAINT state-
ment comes in. The PAINT statement does exactly what the name implies -
it fills in, or PAINTs, outlined areas with color. Just as a painter
covers the canvas with paint, the PAINT statement covers the areas of the
screen with one of the 16 colors. For example, type:

     160 PAINT 1,150,97

Line 160 PAINTS the circle you have drawn in line 60. The PAINT statement
fills a defined area until a specific boundery is detected according to
which color source is indicated. When the Commodore 128 finishes PAINTing,
it leaves the pixel cursor at the point where PAINTing began (in this case,
at point 150,97).

Here are two more PAINT statements:

     180 PAINT 1,50,25
     200 PAINT 1,255,125

Line 180 PAINTs the triangle and line 200 PAINTs the empty box.

     * IMPORTANT PAINTING TIP: If you choose a starting point in you PAINT
     statement which is already colored from the same color source, Com-
     modore 128 will not PAINT the area. You must choose a starting point
     which is entirely inside the boundery of the shape you want to PAINT.
     The starting point cannot be on the boundery line of a pixel that is
     colored from the same source. If you specify a PAINT coordinate that
     is the same color you are PAINTing, nothing happens.


6.2.4.5 Displaying Characters on a Bit-Mapped-Screen - The CHAR Command

So far, the example program has operated in standard bit map mode. Bit map
mode uses a completely different area of memory to store the screen data
than text mode (the mode in which you enter programs and text). If you
enter bit map mode, and try to type characters onto the screen, nothing
happens. This is because the characters you are typing are being displayed
on the text screen and you are looking at the bit map screen. Sometimes it
is necessary to display characters on the bit map screen, when you are
creating an plotting charts and graphs. The CHAR command is designed
especially for this purpose. To display standard characters on a bit map
screen, use the CHAR statement as follows:

     220 CHAR 1,11,24,"GRAPHIC EXAMPLE"

This displays the text "GRAPHIC EXAMPLE" starting at line 25, column 12.
The CHAR command can also be used in text mode, however it is primarily
designed for the bit map screen.


6.2.4.6 Creating a Graphics Sample Program

So far, you have learned several graphic statements. Now tie the program
together and see how the statements work at the same time. Here's how the
program looks now. The color statements in lines 70, 110, 140, 170, 190 and
210 are added to display each object in a different color.

     10 COLOR 0,1                            :REM SELECT BACKGROUND COLOR
     20 COLOR 1,3                            :REM SELECT FOREGROUND COLOR
     30 COLOR 4,1                            :REM SELECT BORDER COLOR
     40 GRAPHIC 1,1                          :REM SELECT BIT MAP MODE
     60 CIRCLE 1,160,100,40,40               :REM DRAW A CIRCLE
     70 COLOR 1,6                            :REM CHANGE FOREGROUND COLOR
     80 BOX 1,20,60,100,140,0,1              :REM DRAW A BLOCK
     90 COLOR 1,9                            :REM CHANGE FOREGROUND COLOR
     100 BOX 1,220,62,300,140,0,0            :REM DRAW A BOX
     110 COLOR 1,9                           :REM CHANGE FOREGROUND COLOR
     120 DRAW 1,20,180 TO 300,180            :REM DRAW A LINE
     130 DRAW 1,250,0 TO 30,0 TO 40,40 TO 250,0:REM DRAW A TRIANGLE
     140 COLOR 1,15                          :REM CHANGE FOREGROUND COLOR
     150 DRAW 1,160,160                      :REM DRAW A POINT
     160 PAINT 1,150,97                      :REM PAINT IN CIRCLE
     170 COLOR 1,5                           :REM CHANGE FOREGROUND COLOR
     180 PAINT 1,50,25                       :REM PAINT IN TRIANGLE
     190 COLOR 1,7                           :REM CHANGE FOREGROUND COLOR
     200 PAINT 1,225,125                     :REM PAINT IN EMPTY BOX
     210 COLOR 1,11                          :REM CHANGE FOREGROUND COLOR
     220 CHAR 1,11,24,"GRAPHIC EXAMPLE"      :REM DISPLAY TEXT
     230 FOR I=1 TO 5000:NEXT:GRAPHIC 0,1:COLOR 1,2

Here's what the program does:

     * Lines 10 through 30 select a COLOR for the background, foreground
       and border, respectively.
     * Line 40 chooses a graphic mode.
     * Line 60 displays a CIRCLE.
     * Line 80 draws a colored-in BOX.
     * Line 100 draws a outline of a BOX.
     * Line 120 DRAWs a straight line at the bottom of the screen.
     * Line 130 DRAWs a triangle.
     * Line 150 DRAWs a single point below the circle.
     * Line 160 PAINTs the circle.
     * Line 180 PAINTs the triangle.
     * Line 200 PAINTs the empty box.
     * Line 220 prints the CHARacters "GRAPHICS EXAMPLE" at the bottom of
       the screen.
     * Line 230 delays the program so you can watch the graphics on the
       screen, switches back to text mode and colors the characters black.

If you want the graphics to remain on the screen, omit the GRAPHIC state-
ment in line 230.


6.2.4.7 Changing the Size of Graphics Images - The SCALE Command

The Commodore 128 has another graphics statement which offers additional
power to your graphics system. The SCALE statement offers the ability to
scale down (reduce) the size of graphic images on your screen. The SCALE
statement also accomplishes another task, which can be explained as fol-
lows.

In standard bit map mode, the 40 column screen has 320 horizontal coordi-
nates and 200 vertical coordinates. In multicolor bit map mode, the 40
column screen has only half the horizontal resolution of standard bit map
mode, which is 160 by 200. This reduction in resolution is compensated for
by the additional capability of using two additional colors for a total of
four colors, within an 8 by 8 character matrix. Standard bit map mode can
only display two colors within an 8 by 8 character matrix.

When you use the SCALE statement, both standard bit map and multicolor bit
map modes have coordinates which are proportional to another. The scale
ranges for 0 through a maximum of 1023 horizontal coordinates. This is true
regardless of whether you are in standard bit map or multicolor mode.

The SCALE your screen, use:

     SCALE 1,x,y

and the screen coordinates range from 65535 whether you are in standard or
multicolor hires mode.

To turn off SCALEing, type:

     SCALE 0

and the coordinates return to their normal values.

To see the effect of SCALEing on your program add in line 50:

     50 SCALE 1,500,500

and RUN to see the effect.

See Section 17, paragraph 17.81, of Chapter V for more details on the SCALE
command.

NOTE: SCALE comes after GRAPHIC and does not affect CHAR.

Here are some additional example programs using the graphics statements you
just learned:

     10 COLOR 0,1
     20 COLOR 1,8
     30 COLOR 4,1
     40 GRAPHIC 1,1
     50 FOR I=80 TO 240 STEP 10
     60 CIRCLE 1,I,100,75,75
     70 NEXT I
     80 COLOR 1,5
     90 FOR I=80 TO 250 STEP 10
     100 CIRCLE 1,I,100,50,50
     110 NEXT I
     120 COLOR 1,7
     130 FOR I=50 TO 280 STEP 10
     140 CIRCLE 1,I,100,25,25
     150 NEXT I
     160 FOR I=1 TO 7500:NEXT I
     170 GRAPHIC 0,1:COLOR 1,2
    

     10 GRAPHIC 1,1
     20 COLOR 0,1
     30 COLOR 4,1
     40 FOR I=1 TO 50
     50 Z=INT (((RND (1))*16)+1)*1
     60 COLOR 1,Z
     70 X=INT (((RND (1))*30)+1)*10
     80 Y=INT (((RND (1))*20)+1)*10
     90 U=INT (((RND (1))*30)+1)*10
     100 V=INT (((RND (1))*20)+1)*10
     110 DRAW 1,X,Y TO U,V
     120 NEXT I
     130 SCNCLR
     140 GOTO 40


     10 COLOR 4,7:COLOR 0,7:COLOR 1,1
     20 GRAPHIC 1,1
     30 FOR I=400 TO 1 STEP -5
     40 DRAW 1,150,100 TO I,1
     50 NEXT I
     60 FOR I=1 TO 400 STEP 5
     70 DRAW 1,150,100 TO 1,I
     80 NEXT I
     90 FOR I=40 TO 320 STEP 5
     100 DRAW 1,150,100 TO I,320
     110 NEXT I
     120 FOR I=320 TO 30 STEP -5
     130 DRAW 1,150,100 TO 320,I
     140 NEXT I
     150 FOR I=1 TO 7500:NEXT I
     160 GRAPHIC 0,1:COLOR 1,1

Type the examples into your computer. RUN and SAVE them for future refe-
rence. One of the best ways to learn programming is to study program exam-
ples and see how the statements perform their functions. You'll soon be
able to use graphics statements to create impressive graphics with your
Commodore 128.

If you need more information on any BASIC statement or command, consult
Chapter V, BASIC 7.0 Encyclopaedia.

You now have a set of graphic commands that allows you to create an almost
unlimited number of graphics displays. But Commodore 128 graphics abilities
do not end here. The Commodore 128 has another set of statements, known as
SPRITE graphics, which make the creation and control of graphic images
fast, easy and sophisticated. These high-level statements allow you to
create sprites - movable graphic objects - the C128 has its own built-in
SPRite DEFinition ability. These statements represent the new technology
for creating and controlling sprites. Read the next section and take you
first step in learning computer animation.


6.3 SPRITES: PROGRAMMABLE, MOVABLE OBJECT BLOCKS

You already have learned about some of the Commodore 128's exceptional
graphic capabilities. You've learned how to use the first set of high-level
graphics statements to draw circles, boxes, lines and dots. You have also
learned how to color the screen, switch graphic modes, paint objects on the
screen and scale them. Now it's time to take the next step in graphics
programming - sprite animation.

If you have worked with the Commomdore 64, you already know something about
sprites. For those of you who are not familiar with the subject, a sprite
is a movable object that you can form into any shape or image. You can
color sprites in up to one of 16 colors. Sprites can even be multicolor.
The best part is that you can move them on the screen. Sprites open the
door to computer animation.

Here is the set of sprite statements you will learn about in this section:

     MOVSPR
     SPRDEF
     SPRITE
     SPRSAV
     SSHAPE


6.3.1 Sprite Creation

The first step in programming sprites is designing the way the sprites
look. For example, suppose you want to design a rocket ship or a racing car
sprite. Before you can color or move the sprite, you must first design the
image. In C128 mode, you can create sprites in these three ways:

     1. Using SPRITE statements within a program
     2. Using SPRite DEFinition mode (SPRDEF)
     3. Using the same method as the Commodore 64


6.3.2 Using Sprite Statements in a Program

This method uses built-in statements so you don't have to use any aids out-
side your program to design your sprites as the other two methods require.
This method uses some of the graphics statements you learned in the pre-
vious section. Here's the general procedure. The details will be added as
you progress.


     1. Draw a picture with the graphics statements you learned in the last
        section, such as DRAW, CIRCLE, BOX and PAINT. Make the dimensions
        of the picture 24 pixels wide by 21 pixels tall in standard bit map
        mode or 12 pixels wide by 21 tall in multicolor bit map mode.
     2. Use the SSHAPE statement to store the picture data into a string
        variable.
     3. Tranfser the picture data from the string variable into a sprite
        with the SPRSAV statement.
     4. Turn on the sprite, color it, select either standard or multicolor
        mode and expand it, all with the SPRITE statement.
     5. Move the sprite with the MOVSPR statement.


6.3.3 Drawing the Sprite Image

Here are the actual statements that perform the sprite operations. When you
are finished with this section, you will have written your first sprite
program. You'll be able to RUN the program as much as you like, and SAVE it
for future reference.

The first step is to draw a picture (24 by 21 pixels) on the screen using
DRAW, CIRCLE, BOX or PAINT. This example is performed in standard bit map
mode, using a black background. Here's the statements that set the graphic
mode and color the screen background black.

     5 COLOR 0,1:REM COLOR BACKGROUND BLACK
     10 GRAPHIC 1,1:REM SET STND BIT MAP MODE

The following statements DRAW a picture of a racing car in the upperleft
corner of the screen. You already learned these statements in the last sec-
tion.

     5 COLOR 0,1:COLOR 4,1:COLOR 1,2         : REM SET COLORS
     10 GRAPHIC 1,1                          : REM SET HI-RES GRAPHIC MODE
     15 BOX 1,2,2,45,45                      : REM PICTURE FRAME
     20 DRAW 1,17,10 TO 28,10 TO 26,30       : REM CAR BODY
     22 DRAWTO 19,30 TO 17,10                : REM CAR BODY
     24 BOX 1,11,10,15,18                    : REM UPPER LEFT WHEEL
     26 BOX 1,30,10,34,18                    : REM UPPER RIGHT WHEEL
     28 BOX 1,11,20,15,28                    : REM LOWER LEFT WHEEL
     30 BOX 1,30,20,34,28                    : REM LOWER RIGHT WHEEL
     32 DRAW 1,26,28 TO 19,28                : REM GRILLE
     34 BOX 1,20,14,26,18,90,1               : REM CAR SEAT
     36 BOX 1,150,35,195,40,90,1             : REM WHITE LINES
     38 BOX 1,150,135,195,140,90,1           : REM WHITE LINES
     40 BOX 1,150,215,195,220,90,1           : REM WHITE LINES
     42 BOX 1,50,180,300,195                 : REM FINISH OUTLINE
     44 CHAR 1,18,23,"FINISH"                : REM DISPLAY FINISH


RUN the program. You have drawn a white racing car, enclosed in a box, in
the upperleft corner of the screen. You have also drawn a raceway with a
finish line at the bottom of the screen. At this point, the racing car is
still only a stationary picture. The care isn't a sprite yet, but you have
just completed the first step in sprite programming - creating the image.


6.3.4 Storing the Sprite Data with SSHAPE

The next step is to save the picture into a text string. Here's the SSHAPE
statement that does it:

     45 SSHAPE A$,11,10,34,30:REM SAVE THE PICTURE IN A STRING

The SSHAPE command stores the screen image (bit pattern) into a string
variable for later processing, according to the specified screen coordi-
nates.


The numbers 11, 10, 34, 30 are the coordinates of the picture. You must
position the coordinates in the correct place or the SSHAPE statement can't
store your picture data correctly into the string variable A$. If you posi-
tion the SSHAPE statement on an empty screen location, the data string is
empty. When you later transfer it into a sprite, you'll realize there is no
data present.

Make sure you position the SSHAPE statement correctly on the correct coor-
dinates. Also be sure to create the picture with the dimensions 24 pixels
wide by 21 pixels tall, the size of a single sprite.

The SSHAPE statement transforms the picture of the racing car into a data
string that the computer interprets as picture data. The data string, A$,
stores a string of zeros and ones in the computer's memory that make up the
picture on the screen.

As in all computer graphics, the computer has a way it can represent visual
graphics with bits in its memory. Each dot on the screen, called a pixel,
has a bit in the computer's memory that controls it. In standard bit map
mode, if the bit in memory in equal to an 1 (on), then the pixel on the
screen is turned on. If the controlling bit in memory is equal to 0 (off),
then the pixel is turned off.


6.3.5 Saving the Picture Data in a Sprite

Your picture is now stored in a string. The next step is to transfer the
picture data from the data string (A$) into the sprite data area so you can
turn it on and animate it. The statement that does this is SPRSAV. Here are
the statements:

     50 SPRSAV A$,1:REM STORE DATA STRING IN SPRITE 1
     55 SPRSAV A$,2:REM STORE DATA STRING IN SPRITE 2

Your picture is transferred into sprite 1 and sprite 2. Both sprites have
the same data, so they look exactly the same. You can't see the sprites
yet, because you have to turn them on.


6.3.6 Turning on Sprites

The SPRITE statement turns on a specific sprite (numbered 1 through 8),
colors it, specifies its screen priority, expands the sprite's size and
determines the type of sprite display. The screen priority refers to
whether the sprite passes in front of or behind the objects on the screen.
Sprites can be expanded to twice their original size in either horizontal
or vertical directions. The type of sprite display determines whether the
sprite is a standard bit mapped sprite or a multicolor bit mapped sprite.
Here are the two statements that turn on sprites 1 and 2.

     60 SPRITE 1,1,7,0,0,0,0:REM TURN ON SPR 1
     70 SPRITE 2,1,3,0,0,0,0:REM TURN ON SPR 2

Here's what each of the numbers in the SPRITE statements mean:

     SPRITE #,O,C,P,X,Y,M

# -  Sprite number (1 to 8)
O -  Turn On (O=1) or Off (O=0)
C -  Color (1-16)
P -  Priority  - if P=0, sprite is in front of objects on the screen
               - if P=1, sprite is behind objects on the screen
X -  if X=1, expands sprite in horizontal (X) direction
     if X=0, sprite in normal horizontal size
Y -  if Y=1, expands sprite in vertical (Y) direction
     if Y=0, sprite in normal vertical size
M -  if M=1, sprite is multicolor
     if M=0, sprite is standard

As you can see, the SPRITE statement is powerful, giving you control over
many sprite qualities.


6.3.7 Moving Sprites with MOVSPR

Now that your sprite is on the screen, all you have to do is move it. The
MOVSPR statement controls the motion of a sprite and allows you to animate
it on the screen. The MOVSPR statement can be used in two ways. First, the
MOVSPR statement can place a sprite at an absolute location on the screen,
using the vertical and horizontal coordinates. Add the following state-
ments to your program:

     70 MOVSPR 1,240,70:REM POSITION SPRITE 1 - X=240,Y=70
     80 MOVSPR 2,120,70:REM POSITION SPRITE 2 - X=120,Y=70

Line 70 positions sprite 1 at sprite coordinates (240,70). Line 80 places
sprite 2 at sprite coordinates (120,70). You can also use the MOVSPR state-
ment to move sprites relative to their original locations. For example,
place sprites 1 and 2 at the coordinates as in lines 70 and 80. You want to
move them from their original locations to another location on the screen.
Use the following statements to move the sprites along a specific route on
the screen:

     85 MOVSPR 1,180 #6:REM MOVE SPRITE 1 FROM THE TOP TO THE BOTTOM
     87 MOVSPR 2,180 #7:REM MOVE SPRITE 2 FROM THE TOP TO THE BOTTOM

The first number in this statement is the sprite number. The second number
is the direction expressed as the number of degrees to move in clockwise
direction, relative to the original position of the sprite. The hash sign
(#) signifies that the sprite is moved at the specific angle and speed
relative to a starting position, instead of an absolute location, as in
lines 70 and 80. The final number specifies the speed in which the sprite
moves along its route on the screen, which ranges from 0 through 15.

The MOVSPR command has two alternative forms. See Section 17, paragraph
17.59, of Chapter V, BASIC 7.0 Encyclopaedia for these notations.

Sprites use an entirely different coordinate plane from bit map coordi-
nates. The bit map coordinates range from points (0,0) (the top left cor-
ner) to 319,199 (the bottom right corner). The visible sprite coordinates
start at point (50,24) and end at point (250,344). The rest of the sprite
coordinates are off the screen and are not visible, but the sprite still
moves according to them. The OFF-screen locations allow sprites to move
smoothly onto and off the screen. Figure 6-7 illustrates the sprite coor-
dinates and the visible sprite positions.

        0 ($00)  24 ($18)                     296 ($128)    344 ($158)
                                                       |    |
              |  |                                     +----+ 8 ($08)
     29 ($1D) |  +--+                                  |    |
              |  |  |                                  |    |
     50 ($32) +--+-------------------------------------+----+----+ 50 ($32)
              |  |  |                                  |    |    |
              +--+--+                                  |    |    |
                 |          VISIBLE VIEWING AREA       |    |    |
                 |                                     +----+----+
                 |               40 COLUMNS                 |
                 |               25 ROWS                    |
  208 ($D0) +----+----+                                     |
            |    |    |                                     |
            |    |    |                                  +--+--+ 229 ($E5)
            |    |    |                                  |  |  |
  250 ($FA) +----+----+----------------------------------+--+--+ 250 ($FA)
            |    |    |                                  |  |
            |    |    |                                  +--+
                 +----+                                  |  |
    488 ($1E8)
                 |                              320 ($140)  344 ($158)
                 24 ($18)

                 Figure 6-7. Visible Sprite coordinates.

Now RUN the entire program with all the steps included. You have just writ-
ten you first sprite program. You have created a raceway with two racing
cars. Try adding more cars and more objects on the screen. Experiment by
drawing other sprites and include them in the raceway. You are now wel on
the way in sprite programming. Use your imagination and think of other
scenes and objects you can animate. Soon you can create all kinds of ani-
mated computer "movies".


6.3.8 Creating a Sprite Program

You now have a working sprite program example. Here's the complete program
listing.


     5 COLOR 0,1:COLOR 4,1:COLOR 1,2         : REM SET COLORS
     10 GRAPHIC 1,1                          : REM SET HI-RES GRAPHIC MODE
     15 BOX 1,2,2,45,45                      : REM PICTURE FRAME
     20 DRAW 1,17,10 TO 28,10 TO 26,30       : REM CAR BODY
     22 DRAWTO 19,30 TO 17,10                : REM CAR BODY
     24 BOX 1,11,10,15,18                    : REM UPPER LEFT WHEEL
     26 BOX 1,30,10,34,18                    : REM UPPER RIGHT WHEEL
     28 BOX 1,11,20,15,28                    : REM LOWER LEFT WHEEL
     30 BOX 1,30,20,34,28                    : REM LOWER RIGHT WHEEL
     32 DRAW 1,26,28 TO 19,28                : REM GRILLE
     34 BOX 1,20,14,26,18,90,1               : REM CAR SEAT
     36 BOX 1,150,35,195,40,90,1             : REM WHITE LINES
     38 BOX 1,150,135,195,140,90,1           : REM WHITE LINES
     40 BOX 1,150,215,195,220,90,1           : REM WHITE LINES
     42 BOX 1,50,180,300,195                 : REM FINISH OUTLINE
     44 CHAR 1,18,23,"FINISH"                : REM DISPLAY FINISH
     45 SSHAPE A$,11,10,34,30                : REM SAVE PICTURE INTO A$
     50 SPRSAV A$,1                          : REM STORE A$ IN SPRITE 1
     55 SPRSAV A$,2                          : REM STORE A$ IN SPRITE 2
     60 SPRITE 1,1,7,0,0,0,0                 : REM TURN ON SPRITE 1
     65 SPRITE 2,1,3,0,0,0,0                 : REM TURN ON SPRITE 2
     70 MOVSPR 1,240,70                      : REM SPRITE 1 X=240, Y=70
     80 MOVSPR 2,120,70                      : REM SPRITE 2 X=120, Y=70
     85 MOVSPR 1,180 #6                      : REM MOV SPR 1 DOWN SCREEN
     87 MOVSPR 2,180 #7                      : REM MOV SPR 2 DOWN SCREEN
     90 FOR I=1 TO 5000:NEXT I
     99 GRAPHIC 0,1

Here's what the program does:

     * Line 5 COLORs the screen black.
     * Line 10 sets standard high resolution GRAPHIC mode.
     * Line 15 draws a BOX in the top left corner of the screen.
     * Lines 20 to 32 draw the racing car.
     * Lines 35 to 44 draw the racing car lanes and a finish line.
     * Line 45 transfers the picture data from the racing car into a string
       variable.
     * Lines 50 and 55 transfer the contents of the string variable into
       sprites 1 and 2.
     * Lines 60 and 65 turn on sprites 1 and 2.
     * Lines 70 and 80 positions the sprites at the top of the screen.
     * Lines 85 and 87 animate the sprites as though the two cars are
       racing each other across the finish line.

In this section, you have learned how to create sprites, using the built-in
C128 graphics statements such as DRAW and BOX. You learned how to control
the sprites, using the Commodore 128 sprite statements. The Commodore has
two other ways of creating sprites. The first is the built-in SPRite
DEFinition ability, as described in the following paragraphs. The other
method of creating sprites is similar to that used for the Commodore 64;
see the C64 Programmer's Reference Guide for details on this sprite-
creation technique.


6.3.9 Sprite Definition Mode - The SPRDEF Command

The Commodore 128 has a built-in SPRite DEFinition mode which enables you
to create sprites on your Commodore 128. You may be familiar with the
Commodore 64 method of creating sprites, in which you required to either
have an additional sprite editor, or design a sprite on a piece of graph
paper and then READ the coded sprite DATA and POKE it into an available
sprite block. With the new Commodore sprite definition command SPRDEF, you
can construct and edit your own sprites in a special sprite work area.

To enter the SPRDEF mode, type:

     SPRDEF

and press {return}. The Commodore 128 displays a sprite grid on the 40
column screen. In addition, the computer displays the prompt:

     SPRITE NUMBER ?

Enter a number between 1 and 8. The computer displays the corresponding
sprite in the upper right corner of the screen. From now on, we will refer
to the sprite grid as the work area.

The work area has the dimensions of 24 characters wide by 21 characters
tall. Each character position within the work area corresponds to 1 pixel
within the sprite, since a sprite is 24 pixels wide by 21 pixels tall.

While within the work area in SPRDEF mode, you have several editing com-
mands available to you. Here's a summary of the commands:

Sprite Defintion Mode Command Summary


     {clr} key - Erases the entire work area
     {m} key - Turns on/off multicolor sprite
     {ctrl} {1}-{8} - Selects sprite foreground color 1-8
     {C=} {1}-{8} - Selects sprite foreground color 9-16
     {1} key - Turns on pixels in background color
     {2} key - Turns on pixels in foreground color
     {3} key - Turns on areas in multicolor 1
     {4} key - Turns on areas in multicolor 2
     {a} key - Turns on/off automatic cursor movement
     {crsr} keys - Moves the cursor (+) within the work area
     {return} - moves cursor to the start of the next line
     {home} key - Moves cursor to the top left corner of the work area
     {x} key - Controls horizontal expansion
     {y} key - Controls vertical expansion
     {shift} {return} - Saves sprite from work area and returns to SPRITE
       NUMBER prompt
     {c} key - copies one sprite to another
     {stop} key - Turns off displayed sprite and returns to SPRITE NUMBER
       prompt without changing the sprite
     {return} key - (at the SPRITE NUMBER prompt) Exits SPRDEF mode


6.3.10 Sprite Creation Procedure in SPRite DEFinition Mode

Here's the general procedure to create a sprite in SPRite DEFinition mode:

1.  Clear the work area by pressing the {shift} and {clr/home} keys at the
    same time.
2.  If you want a multicolor sprite, press the {m} key and an additional
    cursor appears next to the original one. Two cursors appear since
    multicolor mode actually turns on two pixels for every one in standard
    sprite mode. This is why multicolor mode is only half the horizontal
    resolution of standard hires mode.
3.  Select a color for your sprite. For colors between {1} and {8}, hold
    down the {ctrl} key and press a key between {1} and {8}. To select
    color codes between 9 and 16, hold down the Commodore ({C=}) key and
    press a key between {1} and {8}.
4.  Now your are ready to start creating the shape of your sprite. The num-
    bered keys {1} through {4} fill in the sprite and give it shape. For a
    single color sprite, use the {2} to fill a character position within
    the work area. Press the {1} key to erase what you have drawn with the
    {2} key. If you want to fill one character position at a time, press
    the {a} key. Now you have to move the cursor manually with the cursor
    keys. If you want the cursor to move automatically to the right while
    you hold it down, do not press the {a} key since it is already set to
    automatic cursor movement. As you fill in a character position within
    the work area, you can see the corresponding pixel in the displayed
    sprite turn on. Sprite editing occurs as soon as you edit the work
    area.

    In multicolor mode, the {3} key fills two character positions within
    the work area with the multicolor 1 color, the {4} key fills two
    character positions with the multicolor 2.

    You can turn off (color the pixel in the background color) filled areas
    within the work area with the {1} key. In multicolor mode, the {1} key
    turns off two character positions at a time.
5.  While constructing your sprite, you can move freely in the work area
    without turning on or off any pixels using the {return}, {home} and
    cursor keys.
6.  At any time, you may expand your sprite in both the vertical and hori-
    zontal directions. To expand vertically, press the {y} key. To expand
    horizontally, press the {x} key. To return to the normal size sprite
    display, press the {x} or {y} key again.

    When a key turns on AND off the same control, it is referred to as
    toggling, so the {x} and {y} keys toggle the vertical and horizontal
    expansion of the sprite.
7.  When you are finished creating your sprite and happy with the way it
    looks, save it by holding down the {shift} key and pressing the
    {return} key. The Commodore 128 SAVEs the sprite data in the appro-
    priate sprite storage area. The displayed sprite in the upper right
    corner of the screen is turned off and control is returned to the
    SPRITE NUMBER prompt. If you want to display the original sprite in the
    work area again, enter the original sprite number. If you want to exit
    SPRite DEFinition mode, simply press {return} at the SPRITE NUMBER
    prompt.
8.  You can copy one sprite into another with the {c} key.
9.  If you do not want to SAVE your sprite, press the {stop} key. The Com-
    modore 128 turns off the displayed sprite and returns to the SPRITE
    NUMBER prompt.
10. To EXIT SPRite DEFinition mode, press the {return} key while the SPRITE
    NUMBER prompt is displayed on the screen when no sprite number follows
    it. You can exit under either of the following conditions:
   
     Immediately after you SAVE your sprite ({shift} {return}).
     Immediately after you press the {stop} key.

Once you have created a sprite and have exited SPRite DEFinition mode, your
sprite data is stored in the appropriate sprite storage area in the Com-
modore 128's memory. Since you are now back in control of the BASIC lan-
guage, you have to turn on your sprite in order to see it on the screen. To
turn it on again, use the SPRITE command you learned previously. For
example if you created sprite 1 in SPRDEF mode. To turn it on in BASIC,
color it blue and expand it in both the X and Y directions enter this
command:

     SPRITE 1,1,7,0,1,1,0

Now use the MOVSPR command to move it as follows:

     MOVSPR 1, 45 # 5

Now you know all about SPRDEF mode. First, create the sprite, save the
sprite data and exit from SPRDEF mode to BASIC. Next turn on your sprite
with the SPRITE command. Move it with the MOVSPR command. When you're
finished programming, SAVE your sprite data in a binary file with the BSAVE
command as follows:

     BSAVE "filename", B0, P3584 TO P4096

When you want to use the sprite data again from disk, load the previously
BSAVEd binary file with the BLOAD command as follows:

     BLOAD "filename"[, B0, P3584]

The portion in brackets is optional. BLOAD loads data into the address from
which it was saved if the optional portion is not specified.

Now you know the new method for creating sprites. So you can use the fol-
lowing two methods: 1) SSHAPE, SPRSAV, SPRITE, MOVSPR, 2) SPRDEF mode.
Experiment with both methods and master sprite animation.

See paragraph 16.3.12, "Storing Sprite Data in Binary Files", later in this
section for more information.


6.3.11 Adjoining Sprites

You have learned how to create, color, turn on and animate a sprite. An oc-
casion may arise when you want to create a picture that is too detailed or
too large to fit into a single sprite. In this case, you can join two or
more sprites so the picture is larger and more detailed than with a single
sprite. By joining sprites, each one can move independently of one another.
This gives you much more control over animation than with a single sprite.

This section includes an example using adjoining sprites. Here's the gene-
ral procedure (algorithm) for writing a program with two or more adjoining
sprites.

1.  Draw a picture on the screen with Commodore 128 graphics statements,
    such as DRAW, BOX and PAINT, just as you did in the raceway program in
    the last section. This time, make the picture twice as large as a
    single sprite with the dimensions 48 pixels wide by 21 pixels tall.
2.  Use two SSHAPE statements to store the sprites into two separate data
    strings. Position the first SSHAPE statement coordinates over the 24 by
    21 pixels area of the first half of the picture you drew. Then posi-
    tion the second SSHAPE statement coordinates over the second 24 by 21
    pixel area. Make sure you store each half of the picture data in a dif-
    ferent string. For example, the first SSHAPE statement stores the first
    half of the picture into A$, and the second SSHAPE statement stores the
    second half of the picture into B$.
3.  Transfer the picture data from each data string into a separate sprite
    with the SPRSAV statement.
4.  Turn on each sprite with the SPRITE statement.
5.  Position the sprites so the beginning of one sprite starts at the pixel
    next to where the first sprite ends. This is the step that actually
    joins the sprites. For example, draw a picture 48 by 21 pixels. Posi-
    tion the first sprite (1, for example) at location 10,10 with this
    statement:

      100 MOVSPR 1,10,10

    where the first number is the sprite number, the second number is the
    horizontal (X) coordinate and the third number is the vertical (Y)
    coordinate. Position the second sprite 24 pixels to the right of
    sprite 1 with this statement:

      200 MOVSPR 2,34,10

At this point, the two sprites are displayed directly next to each other.
They look exactly like the picture you drew in the beginning of the pro-
gram, using the DRAW, BOX and PAINT statements.

6.  Now you can move the sprites any way you like, again using the MOVSPR
    statement. You can move them together along the same path or in dif-
    ferent directions. As you learned in the last section, the MOVSPR
    statement allows you to move sprites to a specific location on the
    screen, or to a location relative to the sprite's original position.

The following program is an example of adjoining sprites. The program
creates an outer space environment. It draws stars, a planet and a space-
craft similar to Apollo. The spacecraft is drawn, then stored into two data
strings, A$ and B$. The front of the spaceship, the capsule, is stored in
sprite 1. The back half of the spaceship, the retro rocket, is stored in
sprite 2. The spacecraft flies slowly across the screen. Since it is tra-
veling so slowly and is very far from Earth, it needs to be launched earth-
ward with the retro rockets. After a while, the retro rockets fire and
propel the capsule safely to Earth.

Here's the program listing:

     5 COLOR 4,1:COLOR 0,1:COLOR 1,2         :REM SELECT COLORS
     10 GRAPHIC 1,1                          :REM SET HIRES MODE
     17 FOR I=1 TO 40
     18 X=INT (RND (1)*320)+1
     19 Y=INT (RND (1)*200)+1
     21 DRAW 1,X,Y:NEXT I                    :REM DRAW STARS
     22 BOX 0,0,5,70,40,,1                   :REM CLEAR BOX
     23 BOX 1,1,5,70,40:COLOR1,8             :REM BOX-IN SPACESHIP
     24 CIRCLE1,190,90,35,25:PAINT1,190,95   :REM DRAW AND PAINT THE PLANET
     25 FOR I=90 TO 96 STEP 3:CIRCLE 1,190,I,65,10:NEXT I
     26 DRAW 1,10,17TO16,17TO32,10TO33,20TO32,30TO16,23TO10,23TO10,17
     28 DRAW 1,19,24TO20,21TO27,25TO26,28    :REM BOTTOM WINDOW
     35 DRAW 1,20,19TO20,17TO29,13TO30,18TO28,23TO20,19:REM TOP WINDOW
     38 PAINT 1,13,20                        :REM PAINT SPACESHIP
     40 DRAW 1,34,10TO36,20TO34,30TO45,30TO46,20TO45,10TO34,10
     42 DRAW 1,45,10TO51,12TO57,10TO57,17TO51,15TO46,17:REM ENGINE 1
     43 DRAW 1,46,22TO51,24TO57,22TO57,29TO51,27TO45,29:REM ENGINE 2
     44 PAINT1,40,15:PAINT1,47,12:PAINT1,47,26:DRAW0,45,30TO46,20TO45,10
     45 DRAW 0,34,14TO44,14:DRAW 0,34,21TO44,21:DRAW 0,34,28TO44,28
     47 SSHAPE A$,10,10,33,32                :REM SAVE SPRITE IN A$
     48 SSHAPE B$,34,10,57,32                :REM SAVE SPRITE IN B$
     50 SPRSAV A$,1                          :REM SPRITE1 DATA
     55 SPRSAV B$,2                          :REM SPRITE2 DATA
     60 SPRITE 1,1,3,0,0,0,0                 :REM ENABLE SPRITE 1 IN RED
     65 SPRITE 2,1,7,0,0,0,0                 :REM ENABLE SPRITE 2 IN BLUE
     82 MOVSPR 1,150,150                     :REM POSITION SPRITE 1
     83 MOVSPR 2,172,150                     :REM POSITION SPRITE 2
     85 MOVSPR 1,270 # 5                     :REM ANIMATE SPRITE 1
     87 MOVSPR 2,270 # 5                     :REM ANIMATE SPRITE 2
     90 FOR I=1 TO 5000:NEXT I
     92 MOVSPR 1,150,150                     :REM RETRO POSITION
     93 MOVSPR 2,174,150
     95 MOVSPR 1,270 #10                     :REM SPLIT SPRITES 1 & 2
     96 MOVSPR 2,90 #5                       :REM
     97 FOR I=1 TO 1200:NEXT I
     98 SPRITE 2,0                           :REM TURN OFF SPRITE 2
     99 FOR I=1 TO 5000:NEXT I
     100 GRAPHIC 0,1                         :REM RETURN TO TEXT

Here's an explanation of the program:

     * Line 5 COLORs the background black and the foreground white.
     * Line 10 selects standard high resolution mode and clears the hires
       screen.
     * Line 23 BOXes in a display area for the picture of the spacecraft in
       the top left corner of the screen.
     * Lines 17 through 21 DRAW the stars.
     * Line 24 draws and PAINTS the planet.
     * Line 25 draws the CIRCLEs around the planet.
     * Line 26 DRAWs the outline of the capsule portion of the spacecraft.
     * Line 28 DRAWs the bottom window of the space capsule.
     * Line 35 DRAWs the top window of the space capsule.
     * Line 38 PAINTs the space capsule white.
     * Line 40 DRAWs the outline of the retro rocket portion of the space-
       craft.
     * Lines 42 and 43 DRAW the retro rocket engines on the back of the
       spacecraft.
     * Line 44 PAINTs the retro rocket engines and DRAWs an outline of the
       back of the retro rocket in the background color.
     * Line 45 DRAWs lines on the retro rocket portion of the spacecraft in
       the background color. (At this point, you have displayed only pic-
       tures on the screen. You have not used any sprite statements, so
       your rocketship is not yet a sprite.)
     * Line 47 positions the SSHAPE coordinates above the first half (24 by
       21 pixels) - of the capsule - of the spacecraft and stores it in a
       data string, A$.
     * Line 48 positions the SSHAPE coordinates above the second half (24
       by 21 pixels) of the spacecraft and stores it in a data string, B$.
     * Line 50 transfers the data from A$ into sprite 1.
     * Line 55 transfers the data from B$ into sprite 2.
     * Line 60 turns on sprite 1 and colors it red.
     * Line 65 turns on sprite 2 and colors it blue.
     * Line 82 positions sprite 1 at coordinates (150,150).
     * Line 83 positions sprite 2 24 pixels to the right of the starting
       coordinate of sprite 1.
     * Lines 82 and 83 actually join the two sprites.
     * Lines 85 and 87 move the joined sprites across the screen.
     * Line 90 delays the program. This time delay is necessary for the
       sprites to complete the two trips across the screen. If you leave
       out the delay, the sprites do not have enough time to move across
       the screen.
     * Lines 92 and 93 position the sprites in the center of the screen,
       and prepare the spacecraft to fire the retro rockets.
     * Line 95 propels sprite 1, the space capsule, forward. The number 10
       in line 95 specifies the speed at which the sprite moves. The speed
       ranges from 1, which is stop, to 15, which is lightning fast.
     * Line 96 moves the expired retro rocket portion of the spacecraft
       backwards and off the screen.
     * Line 97 is another time delay so the retro rocket, sprite 2, has
       time to move off the screen.
     * Line 98 turns off sprite 2, once it is off the screen.
     * Line 100 returns you to text mode.

Working with adjoining sprites can be more interesting than working with a
single sprite. The main points to remember are: (1) Make sure you position
the SSHAPE coordinates at the correct locations on the screen, so you save
the picture data properly; and (2) be certain to position the sprite coor-
dinates in the correct location when you are joining them with the MOVSPR
statement. In this example you positioned sprite 2 at a location 24 pixels
to the right of sprite 1.

Once you master the technique of joining two sprites, try more than two.
The more sprites you join, the better the detail and animation will be in
your programs.

The C128 has two additional sprite commands, SPRCOLOR and COLLISION, which
are not covered in the section. To learn about these commands, refer to
Chapter V, BASIC 7.0 Encyclopaedia.


6.3.12 Storing Sprite Data in Binary Files

     NOTE: The following explanation assumes some knowledge of machine
     language, memory locations, binary files and object code files.

The Commodore 128 has two new commands BLOAD and BSAVE, which make handling
sprite data neat and easy. The "B" in BLOAD and BSAVE stands for BINARY.
The BSAVE and BLOAD commands save and load binary files to and from disk.
A binary file consists of either a portion of machine language program, or
a collection of data within a specified address range.

You may be familiar with the SAVE command within the built-in machine
language monitor. when you use this SAVE command, the resulting file on
disk is considered a binary file. A binary file is easier to work with than
an object code file since you can load a binary file without any further
preparation. An object code file must be loaded with a loader, as in the
Commodore 64 Assembler Development System; then the SYSTEM command (SYS)
must be used to execute it.

When loading binary files, remember to load them in either of these two
ways:

     LOAD "binary filename",8,1

     or

     BLOAD "binary filename",B0,PStart

where start is 3584 if you are loading sprite data files.

In the first method you must specify the ,1 at the end or else the computer
treats it as a BASIC program file and loads it at the beginning of BASIC
text. The ,1 tells the computer to load the binary file into the same place
from which it was stored.

You're probably wondering what this has to do with sprites. Here's the con-
nection. The Commodore 128 has a dedicated portion of memory ranging from
the address 3584 ($0E00) throught 4095 ($0FFF), where sprite data is
stored. This portion of memory takes up 512 bytes. As you know, a sprite is
24 pixels wide and 21 pixels tall. Each pixel requires one bit of memory.
If the bit in a sprite is off (equal to 0), the corresponding pixel on the
screen is considered off and takes the color of the background. If a pixel
within a sprite is on (equal to 1), the corresponding pixel on the screen
is turned on in the foreground color. The combination of zeroes and ones
produce the image you see on the screen.

Since a sprite is 24 by 21 pixels and each pixel requires a bit of storage
in memory, one sprite uses 63 bytes of memory. See Figure 6-8 to understand
the storage requirements for a sprite's data.


                         12345678   12345678   12345678
                     1   ........   ........   ........
                     2   ........   ........   ........
                     3   ........   ........   ........
                     4   ........   ........   ........
                     5   ........   ........   ........
                     6   ........   ........   ........
                     7   ........   ........   ........
                     8   ........   ........   ........
                     9   ........   ........   ........
                    10   ........   ........   ........
                    11   ........   ........   ........
                    12   ........   ........   ........
                    13   ........   ........   ........
                    14   ........   ........   ........
                    15   ........   ........   ........
                    16   ........   ........   ........
                    17   ........   ........   ........
                    18   ........   ........   ........
                    19   ........   ........   ........
                    20   ........   ........   ........
                    21   ........   ........   ........

                       Each Row = 24 bits = 3 bytes

                  Figure 6-8. Sprite Data Requirements.


A sprite requires 63 bytes of data. Each sprite block is actually made up
of 64 bytes; the extra byte is not used. Since the Commodore 128 has eight
sprites and each one consists of an 64-byte sprite block, the computer
needs 512 (8 x 64) bytes to represent the data of all eight sprite images.

The entire area where all eight sprite blocks reside starts at memory loca-
tion 3584 ($0E00) and ends at location 4095 ($0FFF). Figure 6-9 lists the
memory address ranges where each individual sprite stores its data:


                          $0FFF (4095 decimal)
                                 ]- Sprite 8
                          $0FC0
                                 ]- Sprite 7
                          $0F80
                                 ]- Sprite 6
                          $0F40
                                 ]- Sprite 5
                          $0F00
                                 ]- Sprite 4
                          $0EC0
                                 ]- Sprite 3
                          $0E80
                                 ]- Sprite 2
                          $0E40
                                 ]- Sprite 1
                          $0E00 (3584 Decimal)

          Figure 6-9. Memory Address Ranges for Sprite Storage.


6.3.12.1 BSAVE

Once you exit from the SPRDEF mode, you can save your sprite data in binary
sprite files. This way, you can load any collection of sprites back into
the Commodore 128 neatly and easily. Use this command to save your sprite
data into a binary file:

     BSAVE "filename", B0, P3584 TO P4096

The "B0" specifies that you are saving the sprite data from bank 0. The para-
meters P3584 TO P4096 signify you are saving the address range 3584 ($0E00)
through 4095 ($0FFF), which is the range where all the sprite data is
stored.

You do not have to define all of the sprites when you BSAVE them. The
sprites you do define are BSAVEd from the correct sprite block. The unde-
fined sprites are also BSAVEd in the binary file from the appropriate
sprite block, but they do not matter to the computer. It is easier to BSAVE
the entire 512 bytes of all eight sprites, regardless if all the sprites
are used, rather than BSAVE each sprite block individually.


6.3.12.2 BLOAD

Later on, when you want to use the sprites again, just BLOAD the entire
512 bytes for all of the sprites into the range starting at 3584 ($0E00)
and ending at 4095 ($0FFF). Here's the command to accomplish this:

     BLOAD "filename"[, B0, P3584]

Use the same filename which you BSAVEd your original sprite data. The B0
stands for bank number 0 and the P3584 specifies the starting location
where the binary sprite data is loaded. The last two parameters are
optional.



***************************************************************************



In this section you have seen how much the new Commodore 7.0 BASIC commands
can simplify the usually complex process of creating and animating graphic
images. The next section describes some other new BASIC 7.0 commands that
do the same for music and sound.




SECTION 7

7. Sound and Music in C128 Mode



7.1 INTRODUCTION

7.2 THE SOUND STATEMENT

  7.2.1 Writing a SOUND Program
  7.2.2 Random Sounds

7.3 ADVANCED SOUND AND MUSIC IN C128 MODE

  7.3.1 A brief background: The Characteristics of Sound
        Figure 7-1. Sine Wave.
        Figure 7-2. Frequencies and harmonics.
        Figure 7-3. Sound Waveform Types.
  7.3.2 Making Music on the Commodore 128
    7.3.2.1 The ENVELOPE Statement
            Figure 7-4. ADSR Phases.
            Figure 7-5. Default Parameters for ENVELOPE Statement.
    7.3.2.2 The TEMPO Statement
    7.3.2.3 The PLAY Statement
            Figure 7-6. Sound Synthesizer Control Characters.
    7.3.2.4 The SID Filter
            Figure 7-7. Low-pass Filter.
            Figure 7-8. High-pass Filter.
            Figure 7-9. Band-pass Filter.
    7.3.2.5 The FILTER Statement
  7.3.3 Tying your Music Program Together
  7.3.4 Advanced Filtering
        Figure 7-10. Notch Reject Filter.

7.4 CODING A SONG FROM SHEET MUSIC
    Figure 7-11. Musical Staff.
    Figure 7-12. Part of Bach's Invention 13.



7.1 INTRODUCTION

The Commodore 128 has one of the most sophisticated built-in sound synthe-
sizers available in a microcomputer. The synthesizer, called Sound Inter-
face Device (SID), is a chip capable of producing three independent voices
(sounds) simultaneously. Each of the voices can be played in one of four
types of sounds, called waveforms. The SID chip also has programmable
Attack, Decay, Sustain and Release (ADSR) parameters. These parameters de-
fine the quality of a sound. In addition, the synthesizer has a filter you
can use to choose certain sounds. In this section you will learn how to
control these parameters to produce almost any kind of sound.

To make it easy for you to select and manipulate the many capabilities of
the SID chip, Commodore has develloped new and powerful BASIC music state-
ments.

Here are the new sound and music statements available on the Commodore 128:

     SOUND
     ENVELOPE
     VOL
     TEMPO
     PLAY
     FILTER


This section explains these sound statements, one at a time, in the process
constructing a sample musical program. When you are finished with this sec-
tion, you will know the ingredients that go into a musical program. You'll
be able to expand on the example and write programs that play intricate
musical compositions. Eventually, you'll be able to program your own musi-
cal scores, make your own sound effects and play works of the great clas-
sical masters such as Beethoven and contemporary artists like the Beatles.
You can even add computer-generated music to your graphics programs to
create your own "videos."


7.2 THE SOUND STATEMENT

The SOUND statement is designed primarily for quick and easy sound effects
in your programs. You will learn a more intricate way of playing complete
musical arragements with the other sound statements later in this section.

The format for the SOUND statement is as follows:

     SOUND vc, freq, dur [, dir [, min [, sv [, wf [, pw]]]]]

Here's what the parameters mean:

     VC   - Select voice 1, 2 or 3

     FREQ - Set the frequency level of sound (0-65535)

     DUR  - Set duration of the sound (in sixtieths of a second)

     DIR  - Set the direction in which the sound is incremented/decre-
            mented:
            0 = Increment the frequency upward
            1 = Decrement the frequency downward
            2 = Oscillate the frequency up and down

     MIN  - Select the minimum frequency (0-65535) if the sweep (DIR) is
            specified

     SV   - Choose the step value for the sweep (0-65535)

     WF   - Select the waveform (0-3):
            0 = Triangle
            1 = Sawtooth
            2 = Variable Pulse (square)
            3 = White Noise

     PW   - Set the pulse width, the width of the variable pulse waveform

Note that the DIR, MIN, SV and PW parameters are optional.

The first parameter (VC) in the SOUND statement selects which voice will be
played. The second parameter (FREQ) determines the frequency of the sound,
which ranges from 0 through 65535. The third setting (DUR) is measured in
60ths of a second. If you want to play a sound for one second, set the
duration to 60, since 60 times 1/60 equals 1. To play the sound for two
seconds, specify the duration to be 120. To play the sound ten seconds,
make the duration 600, and so on.

The fourth parameter (DIR) selects the direction in which the frequency or
the sound is incremented or decremented. This is referred to as the sweep.
The fifth setting (MIN) sets the minimum frequency where the sweep begins.
The sixth parameter (SV) is the step value of the sweep. It is similar to
the step value in a FOR... NEXT loop. If the DIR, MIN and SV values are
specified in the SOUND command, the sound is played first at the original
level specified by the freq parameter. Then the synthesizer sweeps through
and plays each level of the entire range of frequency values starting at
the min frequency. The sweep is incremented or decremented by the step
value (SV) and the frequency is played at the new level.

The seventh parameter (WF) in the SOUND command selects the waveform for
the sound. (Waveforms are explained in detail in paragraph titled, "Ad-
vanced Sound and Music in C128 Mode.")

The final setting in the SOUND command determines the width of the pulse
waveform if it is selected as the waveform parameter. (See the discussion in
paragraph 7.3, "Advanced Sound and Music in C128 Mode", for an illustration
of the pulse waveform.)


7.2.1 Writing a SOUND Program

Now it's time to write your first SOUND program. Here's an example of the
SOUND statement:

     10 VOL 5
     20 SOUND 1,4096,60

RUN this program. The Commodore 128 plays a short beep. You must set the
volume before you can play the sound statement, so line 10 sets the VOLume
of the sound chip. Line 20 plays voice 1 at a frequency of 4096 for a dura-
tion of 1 second (60 times 1/60). Change the frequency with this statement:

     30 SOUND 1,8192,60

Notice line 30 plays a higher tone than line 20. This shows the direct
relationship between the frequency setting and the actual frequency of the
sound. As you increase the frequency setting, the Commodore 128 increases
the pitch of the tone. Now try this statement:

     40 SOUND 1,0,60

This shows that a FREQ value of 0 plays the lowest frequency (which is so
low it is inaudible). A FREQ value of 65535 plays the highest possible
frequency.

Now try placing the sound statement within a FOR... NEXT loop. This allows
you to play the complete range of frequencies within the loop. Add these
statements to your program:

     50 FOR I=1 TO 65535 STEP 100
     60 SOUND 1,I,1
     70 NEXT

This program segment plays the variable pulse waveform in the range of
frequencies from 1 to 65535, in increments of 100, from the lowest frequen-
cy to the highest. If you don't specify the waveform, the computer selects
the default value of waveform 2, the variable pulse waveform.

Now change the waveform with the following program line (60) and try the
program again:

     60 SOUND 1,I,1,0,0,0,0,0

Now the program plays voice 1, using the triangle waveform, for the range
of frequency between 1 and 65535 in increments of 100. This sounds like a
typical sound effect in popular arcade games. Try waveform 1, the sawtooth
waveform, and see how it sounds with this line:

     60 SOUND 1,I,1,0,0,0,1,0

The sawtooth waveform sounds similar to the triangle waveform though it has
less buzz. Finally, try the white noise waveform (3). Substitute line 60
for this line:

     60 SOUND 1,I,1,0,0,0,3,0

Now the program loop plays the white noise generator for the entire range
of frequencies. As the frequency increases in the loop the pitch increases
and sounds like a rocket taking off.

Notice that so far we have not specified all of the parameters in the SOUND
statement. Take line 60 for example:

     60 SOUND 1,I,1,0,0,0,3,0

The three zeros following 1,I,1 pertain to the sweep parameters within the
SOUND statement. Since none of the parameters is specified, the SOUND does
not sweep. Add this line to your program:

     100 SOUND 1, 49152, 240, 1, 0, 100, 1, 0
               ^    ^     ^   ^  ^   ^   ^  ^
               |    |     |   |  |   |   |  |
Voice ---------+    |     |   |  |   |   |  |
Frequency ----------+     |   |  |   |   |  |
Duration -----------------+   |  |   |   |  |
Sweep Direction --------------+  |   |   |  |
Minimum Sweep Frequency ---------+   |   |  |
Step Value for Sweep ----------------+   |  |
Waveform --------------------------------+  |
Pulse Width for variable width              |
   waveform --------------------------------+


Line 100 starts the sweep frequency at 49152 and decrements the sweep by
100 in the downward direction, until it reaches the minimum sweep frequency
at 0. Voice 1, using the sawtooth waveform (#1), plays each SOUND for four
seconds (240 * 1/60 s). Line 100 sounds like a bomb dropping, as in may
"shoot 'em up" arcade games.

Now try changing some of the parameters in line 100. For instance, change
the direction of the sweep to 2 (oscilate); change the minimum frequency of
the sweep to 32768; and increase the step value to 3000. Your new SOUND
command looks like this:

     110 SOUND 1,49152,240,2,32768,3000,1

Line 110 makes a siren sound as though the police were right on your tail.
For a more pleasant sound, try this:

     110 SOUND 1,65535,250,0,32768,3000,2,2600

This should remind you of a popular space-age TV show, when the space crew
unleashed their futuristic weapons on the unsuspecting aliens.

Until now, you have been programming only one voice. You can produce inter-
esting sound effects with the SOUND statement using up to three voices.
Experiment and create a program which utilizes all three voices.

Here's a sample program that will help you understand how to program the
Commodore 128 synthesizer chip. The program, when RUN, asks for each para-
meter, and then plays the sound. Here's the program listing. Type it into
your computer and RUN it.

     10 SCNCLR:PRINT "           SOUND PLAYER":PRINT:PRINT:PRINT
     20 PRINT "     INPUT SOUND PARAMETERS TO PLAY":PRINT:PRINT
     30 INPUT "VOICE (1-3)";V
     40 INPUT "FREQUENCY (0-65535)";F
     50 INPUT "DURATION (0-32767)";D
     60 INPUT "DO YOU WANT TO SPECIFY OPTIONAL PARAMETERS Y/N";B$:PRINT
     70 IF B$="N" THEN 130
     80 INPUT "SWEEP DIRECTION (0=UP,1=DOWN,2=OSCILL)";DIR
     90 INPUT "MINIMUM SWEEP FREQUENCY (0-65535)";M
     100 INPUT "SWEEP STEP VALUE (0-32767)";S
     110 INPUT "WAVEFORM (0=TRI,1=SAW,2=VAR PUL,3=NOISE)";W
     120 IF W=2 THEN INPUT "PULSE WIDTH (0-4096)";P
     130 SOUND V,F,D,DIR,M,S,W,P
     140 INPUT"DO YOU WANT TO HEAR THE SOUND AGAIN Y/N";A$
     150 IF A$="Y" THEN 130
     160 RUN

Here's a quick explanation of the program. Lines 10 and 20 PRINT the intro-
ductory messages on the screen. Lines 30 through 50 INPUT the voice,
frequency and duration parameters. Line 60 asks if you want to enter the
optional SOUND parameters, such as the sweep settings and waveform. If you
don't want to specify these parameters, press the {n} and then the {return}
key and the program jumps to line 130 and plays the sound. I you do want to
specify the optional SOUND settings, press the {y} and then the {return}
key and the program continues with line 80. Lines 80 through 110 specify
the sweep direction, minimum sweep frequency, sweep step value and wave-
form. Line 120 INPUTs the pulse width of the variable pulse waveform only
if waveform 2 (variable pulse) is selected. Line 130 plays the SOUND accor-
ding to the parameters that you specified earlier in the program.

Line 140 asks if you want to hear the SOUND again. If you do, press the {y}
and then the {return} key. If you did, program control is returned to line
130 and the program plays the SOUND again. If you press any other key as
the {y} key, the program continues with line 160. Line 160 reruns the pro-
gram. To stop the Sound Player program, press the {run/stop} and {restore}
keys at the same time.


7.2.2 Random Sounds

The following program generates random sounds using the RND function. Each
SOUND parameter is calculated randomly. Type the program into your computer
and SAVE it and RUN it. This program illustrates how many thousands of
sounds you can produce by specifying various combinations of the SOUND
parameters.

     10 PRINT "VC  FRQ  DIR  MIN   SV   WF   PW ":VOL 5
     20 PRINT "---------------------------------"
     30 V=INT (RND (1)*3)+1                  :REM VOICE
     40 F=INT (RND (1)*65536)                :REM FREQUENCY
     50 D=INT (RND (1)*240)                  :REM DURATION
     60 DIR=INT (RND(1)*3)                   :REM STEP DIRECTION
     70 M=INT (RND (1)*65536)                :REM MINIMUM FREQUENCY
     80 S=INT (RND (1)*32678)                :REM STEP VALUE
     90 W=INT (RND (1)*4)                    :REM WAVEFORM
     100 P=INT (RND (1)*4096)                :REM PULSE WIDTH
     110 PRINT V;F;DIR;M;S;W;P:PRINT:PRINT   :REM DISPLAY VALUE
     120 SOUND V,F,D,DIR,M,S,W,P             :REM PLAY SOUND
     130 SLEEP 4                             :REM WAIT A BIT
     140 SOUND V,0,0,DIR,0,0,W,P             :REM SWITCH SOUND OFF
     150 GOTO 10

Lines 10 and 20 PRINT parameter column headings and the underline. Lines 30
through 100 calculate each SOUND parameter within its specific range. For
example, line 30 calculates the voice number as follows:

     30 V = INT(RND(1)*3)+1

The notation RND(1) specifies the seed value of the random number. The seed
is the base number generated by the computer. The 1 tells the computer to
generate a new seed each time the command is encountered. Since the Commo-
dore 128 has three voices, the notation * 3 tells the computer to generate
a random number within the range 0 through 3. Notice however there is no
voice 0, so the + 1 tells the computer to generate a random number such
that 1 <= Number < 4. The procedure for generating a random number in a
specific range is to multiply the given random number times the maximum
value of the parameter (in this case, 3). If the minimum value of the para-
meter is greater than zero, add to the random number a value that will
specify the minimum value of the range of numbers you want to generate (in
this case, 1). For instance, line 40 generates a random number such that
0 <= Number < 65535. Since the minimum value is zero in this case, you do
not need to add a value to the generated random number.

Line 110 PRINTs the values of the parameters. Line 120 plays the SOUND
specified by the random numbers generated in lines 30 through 100. Line 130
delays the program for 4 seconds while the sound is playing. Line 140 turns
off the SOUND (after the 4 seconds delay). All sounds generated by this
program are all turned off after 4 seconds with line 140. Finally, line 150
returns control to line 10, and the process is repeated until you press the
{run/stop} and {restore} keys at the same time.

So far you have experimented with sample programs using only the SOUND
statement. Although you can use the SOUND statement to play musical scores,
it is best suited for quick and easy sound effects like the ones in the
dogfight program. The Commodore 128 has other statements designed speci-
fically for song playing. The following paragraphs describe the advanced
sound and music statements that enable you to play complex musical scores
and arrangements with your Commodore 128 synthesizer.


7.3 ADVANCED SOUND AND MUSIC IN C128 MODE


7.3.1 A brief background: The Characteristics of Sound

Every sound you hear is actually a sound wave traveling through the air.
Like any wave, a sound (sine) wave can be represented graphically and
mathematically (see Figure 7-1).

                              +               +
                            +   +           +   +
                           /     \         /     \
                         ./.......\......./.......\.
                                   \     /
                                    +   +
                                      +

                         Figure 7-1. Sine Wave.

The sound wave moves (oscillates) at a particular rate (frequency) which
determines the overall pitch (the highness or lowness of the sound).

The sound is also made up of harmonics, which are accompanying multiples of
the the overall frequency of the sound or note. The combination of these
harmonic sound waves give the note its qualities, called timbre. Figure 7-2
shows the relationship of basic sound frequencies and harmonics.



                           [FIGURE IS MISSING]


                 Figure 7-2. Frequencies and harmonics.

The timbre of a musical tone (i.e. the way a tone sounds) is determined by
the tone's waveform. The Commodore 128 can generate four types of wave-
forms: triangle, sawtooth, variable pulse and noise. See Figure 7-3 for a
graphic representation of these four waveforms.

                            +               +
                           / \             / \
                          /   \           /   \
                         /     \         /     \
     TRIANGLE          ./.......\......./.......\.
                                 \     /
                                  \   /
                                   \ /
                                    +

                              +       +       +
                             /|      /|      /|
                            / |     / |     / |
                           /  |    /  |    /  |
     SAWTOOTH            ./...|.../...|.../...|.....
                              |  /    |  /    |  /
                              | /     | /     | /
                              |/      |/      |/
                              +       +       +

                       +----+  +----+  +----+  |
                       |    |  |    |  |    |  |
                       |    |  |    |  |    |  |
                       |    |  |    |  |    |  |
     VARIABLE         .|....|..|....|..|....|..|.
     PULSE             |    |  |    |  |    |  |
                       |    |  |    |  |    |  |
                       |    |  |    |  |    |  |
                       |    +--+    +--+    +--+
                                <-->
                                PULSE WIDTH

                                   .   .       .
                          .     . .          .   .
                           .  .     .       .
     NOISE               ...........................
                             . . .        .
                                      .  . .  .
                            .                   . .



                    Figure 7-3. Sound Waveform Types.


7.3.2 Making Music on the Commodore 128


7.3.2.1 The ENVELOPE Statement

The volume of a sound changes throughout the duration of the note, from
when you first hear it until it is no longer audible. These volume quali-
ties are referred to as Attack, Decay, Sustain and Release (ADSR). Attack
is the rate at which a musical note reaches its peak volume. Decay is the
rate at which a musical not decreases from its peak volume to its midranged
(sustain) level. Sustain is the level at which a musical note is played at
its midranged volume. Release is the rate at which a musical note decreases
from its sustain level to zero volume. The ENVELOPE generator controls the
ADSR parameters of sound. See Figure 7-4 for a graphical representation of
ADSR. The Commodore 128 can change each ADSR parameter to 16 different
rates. This gives you absolute flexibility over the envelope generator and
the resulting properties of the volume when the sound is originated.

                              +
                             / \
                            /   \
                           /     \
         SUSTAIN LEVEL . ./. . . .+--------+
                         /                  \
                        /                    \
                       /                      \

                       |      |   |        |   |
                       |   A  | D |    S   | R |

                        Figure 7-4. ADSR Phases.


One of the most powerful Commodore 128 sound statements - the one that con-
trols the ADSR and waveform - is the ENVELOPE statement. The ENVELOPE
statement sets the different controls in the synthesizer chip which makes
each sound unique. The ENVELOPE gives you the power to manipulate the SID
synthesizer. With ENVELOPE, you can select particular ADSR settings and
choose a waveform for you own music and sound effects. The format for the
ENVELOPE statement is as follows:

     ENVELOPE e[,a[,d[,s[,r[,wf[,pw]]]]]]

Here's what the letters mean:

     e - envelope number (0-9).
     a - attack rate (0-15)
     d - decay rate (0-15)
     s - sustain level (0-15)
     r - release rate (0-15)
     wf - waveform - 0 = triangle
                     1 = sawtooth
                     2 = pulse (square)
                     3 = noise
                     4 = ring modulation
     pw - pulse width (0-4095)

Here are the definitions of the parameters not previously defined:

Envelope - The properties of a musical note specified by the waveform and
the attack, decay, sustain and release setting of the note. For example,
the envelope for a guitar not has a different ADSR and waveform than a
flute.

Waveform - The type of sound wave created by the combination of accom-
panying musical harmonics of a tone. The accompanying harmonic sound waves
are multiples of, and are based on the overall frequency of the tone. The
qualities of the tone generated by each waveform are recognizably different
from one another and are represented graphically in Figure 7-3.

Pulse width - The length of time between notes, generated by pulse waveform.

Now you can realize the power of the ENVELOPE statement. It controls most
of the musical qualities of the notes being played by the sound synthe-
sizer. The Commodore 128 has 10 predefined envelopes for 10 different
musical instruments. In using the predefined envelopes you do not have to
specify the ADSR parameters, waveform and pulse width settings - this is
already done for you. All you have to do is specify the envelope number.
The rest of the parameters are chose automatically by the Commodore 128.
Here are the preselected envelopes for different types of musical instru-
ments:

Envelope                                               Wave-
Number    Instrument  Attack  Decay  Sustain  Release  form   Width

0         Piano       0       9      0        0        2      1536
1         Accordion   12      0      12       0        1
2         Calliope    0       0      15       0        0
3         Drum        0       5      5        0        3
4         Flute       9       4      4        0        0
5         Guitar      0       9      2        1        1
6         Harpsicord  0       9      0        0        2      512
7         Organ       0       9      9        0        2      2048
8         Trumpet     8       9      4        1        2      512
9         Xylophone   0       9      0        0        0

         Figure 7-5. Default Parameters for ENVELOPE Statement.

Now that you have a little background on the ENVELOPE statement, begin an-
other example by entering this statement into your Commodore 128:

     10 ENVELOPE 0, 5, 9, 2, 2, 2, 1700

This ENVELOPE statement redefines the default piano envelope (0) to the
following: Attack = 5, Decay = 9, Sustain=2, Release=2, waveform remains
the same (2) and pulse width of the variable pulse waveform is now 1700.
The piano envelope will not take on these properties until it is selected
by a PLAY statement, which you will learn later in this section.

The next step in programming music is setting the volume of the sound chip
as follows:

     20 VOL 8

The VOL statement sets the volume of the sound chip between 0 and 15, where
15 is the maximum and 0 is off (no volume).


7.3.2.2 The TEMPO Statement

The next step in Commodore 128 music programming is controlling the tempo,
or speed of your tune. The TEMPO statement does this for you. Here's the
format:

     TEMPO n

where n is a digit between 0 and 255 (and 255 is the fastest tempo). If you
do not specify the TEMPO statement in your program, the Commodore 128 auto-
matically sets the tempo to 8. Add this statement to your musical example
program:

     30 TEMP 10


7.3.2.3 The PLAY Statement

Now it's time to learn how to play the notes in your song. You already know
how the PRINT statement works. You play the notes in your tune the same way
as PRINTing a text string to the screen, except you use the PLAY statement
in place of PRINT. PRINT outputs text, PLAY outputs musical notes.

Here's the general format for the play statement:

     PLAY "string of synthesizer control
     characters and musical notes"

The total number of characters (including the musical notes and synthesizer
control characters) that can be put into a PLAY command is 255. However,
since this exceeds the maximum number of characters (160) allowed for a
single program line in BASIC 7.0, you have to concatenate (that is, add to-
gether) at least two strings to reach this length. You can avoid the need
to concatenate strings by making sure your PLAY commands do not exceed 160
characters, i.e. one program line length. (This is equivalent with four
screen lines in 40-column mode, and two screen lines in 80-column mode.) By
doing this, you will produce PLAY command strings that are easier to under-
stand and use.

To play musical notes, enclose the letter of the note you want to play
within quote. For example, here's how to play the musical scale (also known
as do-re-mi-fa-sol-la-si):

     40 PLAY "CDEFGAB"

This plays the notes C, D, E, F, G, A and B in the piano envelope, which is
envelope 0. After each time you RUN this example program your are creating,
hold down the {run/stop} key and press the {restore} key to reset the syn-
thesizer chip.

You have the option of specifying the duration of the note by preceding it
in quotes with one of the following notations:

     W - Whole note
     H - Half note
     Q - Quarter note
     I - Eighth note
     S - Sixteenth note

The default setting, if the duration is not specified, is the Whole (W)
notes.

You can PLAY a rest (no sound) by including the following in the PLAY
string:

     R - Rest

You can instruct the computer to wait until all voices currently playing
reach the end of a measure by including the following in quotes:

     M - Wait for end of measure

The Commodore 128 also has synthesizer control characters you can include
in a PLAY string. This gives you absolute control over each note and allows
you to change synthesizer controls within a string of notes. Follow the
control character with a number in the allowable range for that character.
The control characters and the range of numbers are shown in Figure 7-6.
The {n} following the control character refers to the number you select
from the specified range.

          Control                              Default
          Character    Description    Range    Setting
          ----------------------------------------------------
          V n          Voice          1-3      1
          O n          Octave         0-6      4
          T n          Envelope       0-9      0
          U n          Volume         0-15     9
          X n          Filter         0=off    0
                                      1=on

            Figure 7-6. Sound Synthesizer Control Characters.

Although the SID chip can process these control characters in any order,
for best results, place the control characters in your string in the order
that they appear in Figure 7-6.

You don't absolutely have to specify any of the control characters, but you
should to maximize the power from your synthesizer. The Commodore 128 auto-
matically sets the synthesizer controls to the default settings in Figure
7-6. If you don't assign special control characters, the SID chip can PLAY
only one envelope, one voice and one octave without any FILTERing. Specify
the control characters to exercise the most control over the notes within
your PLAY string.

If you specify an ENVELOPE statement and select your own settings instead
of using the default parameters from Figure 7-5, the envelope control
character number in your PLAY string must match the number in your ENVELOPE
statement in order to assume the parameters you assigned. You don't have
the specify the ENVELOPE statement at all if you just want to PLAY the
default settings from Figure 7-6. In this case, simply select an envelope
number with the (T) control character in the PLAY statement.

Here's an example of the PLAY statement using the SID chip control charac-
ters within a string. Add this line to your program and notice the dif-
ference between this statement and the PLAY statement in line 40.

     50 PLAY "M V2 O5 T7 U5 X0 C D E F G A B"

This statement PLAYs the same notes as in line 40, but voice 2 is selected,
the notes are played one octave higher (5) than line 40, the volume set-
ting is turned down to 5 and the FILTER is specified as off. For now, leave
the filter off. When you learn about FILTERing in the next section, you can
come back and turn the filter on to see how it affects the notes being
played. Notice line 50 selects a new instrument, the organ envelope, with
the T7 control character. Now your program PLAYs two different instruments
in two of the independent voices. Add this statement to PLAY the third
voice:

     60 PLAY "M V3 O6 U7 T6 X0 C D E F G A B"

Here's how line 60 controls the synthesizer. The V3 selects the third
voice, O6 places voice 3 one octave higher (6) than voice two, T6 selects
the harpsichord envelope, U7 sets the volume to 7 and X0 leaves the filter
off for all three voices. Now your program plays three voices, each one oc-
tave higher thant the other, in three seperate instruments, piano, organ
and harpsichord.

So far, your PLAY statements only played whole notes. Add notes of diffe-
rent duration by placing control characters in you PLAY string as follows:

     70 PLAY "MV2O6T0U7X0HCDQEFIGASB"

Line 70 PLAYs voice 2 in octave 6 at volume level 7 with the redefined
piano envelope (0) on and filter turned off. This statement PLAYs the note
C and D as half notes, E and F as quarter notes, G and A as eighth notes
and B as a sixteenth note. Notice the difference between the piano envelope
in line 40 and the redefined piano envelope in line 70. Line 40 actually
sounds more like a piano than line 70.

You can PLAY sharp, flat and dotted notes by preceding the notes within
quotes with the following characters:

     #  -  Sharp (half a tone higher).
     $  -  Flat (half a tone lower).
     .  -  Dotted (half a duration longer).

A dotted note plays one-and-a-half times the duration of a note that is not
dotted.

Now try adding sharp, flat and dotted notes with this statement:

     80 PLAY "MV1O4T4U8X0.HCDQ#EFI$GA.S#B"

Line 80 PLAYs voice 1 in octave 4 at volume level 8 with the flute envelope
turned on and the filter turned off. It also PLAYs C and D as dotted half
notes, E and F as sharp quarter notes, G and A as flat eighth notes and B
as a sharp dotted sixteenth note. You can add rests (R) at any place within
your PLAY string.

Up until now your statement examples have left the filter off within the
sound synthesizer and have not realized the true power behind it. Now that
you have digested most of the sound and music statements and the SID con-
trol characters, move on to the next section to learn how to enhance your
musical quality with the FILTER statement.


7.3.2.4 The SID Filter

Once you have selected the ENVELOPE, ADSR, VOLume and TEMPO, use the FILTER
to perfect your synthesized sounds. In your program, the FILTER statement
will precede the PLAY statement. First you should become comfortable with
generating the sound and worry about FILTERing last. Since the SID chip has
only one filter, it applies to all three voices. Your computerized tunes
will play without FILTERing, but to take full advantage of your music syn-
thesizer, use the FILTER statement to increase the sharpness and quality of
the sound.

In the first paragraph of this section (The Characteristics of Sound) we
defined a sound as a sound wave traveling (oscilating) through the air at a
particular rate. The rate at which a sound oscillates is called the wave's
frequency. Recall that a sound wave is made up of an overall frequency and
accompanying harmonics, which are multiples of the overall frequency. See
Figure 7-2. The accompanying harmonics give the sound its timbre, the qua-
lities of the sound which are determined by the waveform. The filter within
the SID chip gives you the ability to accent and eliminate the harmonics of
a waveform and change its timbre.

The SID chip filters sounds in three ways: low-pass, high-pass and band-
pass filtering. These filters are additive, meaning you can use more than
one filter at a time. This is discussed in the next section. Low-pass fil-
ters out frequencies above a certain level you specify, called the cutoff
frequency. The cutoff frequency is the dividing line that marks the boun-
dery of which frequency level will be played and which will not. In low-
pass filtering, the SID chip plays all frequencies below the cutoff
frequency and filters out the frequencies above it. As the name implies,
the low frequencies are allowed to pass through the filter and high ones
are not. The low-pass filter produces full, solid sounds. See Figure 7-7.


                             |
                      AMOUNT | -----+
                      PASSED |       \
                             |        \
                             |         \
                             +------|-------
                                FREQUENCY

                      Figure 7-7. Low-pass Filter.

Conversly, the high-pass filter allows all frequencies above the cutoff
frequency to pass through the chip. All the ones below it are filtered out.
See Figure 7-8. The high-pass filter produces tinny, hollow sounds.

                             |
                      AMOUNT |      +-----
                      PASSED |     /
                             |    /
                             |   /
                             +------|-------
                                FREQUENCY

                      Figure 7-8. High-pass Filter.

The band-pass filter allows a range of frequencies partially above and
below the cutoff frequency to pass through the SID chip. All other frequen-
cies above and below the band surrounding the cutoff frequency are filtered
out. See Figure 7-9.

                             |
                      AMOUNT |      +
                      PASSED |     / \
                             |    /   \
                             |   /     \
                             +------|-------
                                FREQUENCY

                      Figure 7-9. Band-pass Filter.


7.3.2.5 The FILTER Statement

The FILTER statement specifies the cutoff frequency, the type of filter
being used and the resonance. The resonance is the peaking effect of the
sound wave frequency as it approaches the cutoff frequency. The resonance
determines the sharpness and clearness of a sound: the higher the reso-
nance, the sharper the sound.

This is the format of the FILTER statement:

     FILTER cf, lp, bp, hp, res

Here's what the parameters mean:

cf   -  Cutoff frequency (0 - 2047)
lp   -  Low-pass filter (0=off, 1=on)
bp   -  Band-pass filter (0=off, 1=on)
hp   -  High-pass filter (0=off, 1=on)
res  -  Resonance (0 - 15)

You can specify the cutoff frequency to be any value between 0 and 2047.
Turn on the low-pass filter by specifying a 1 as the second parameter in
the FILTER statement. Turn on the band-pass filter by specifying a 1 as the
third parameter and enable the high-pass filter with a 1 in the fourth
parameter position. Turn off any of the three filters by placing a 0 in the
respective position of the filter you want to disable. You can enable or
disable one, two or all three of the filters at the same time.

Now that you have some background on the FILTER statement, add this line to
your sound program, but do not RUN the program yet:

     45 FILTER 1200, 1, 0, 0, 10

Line 45 sets the cutoff frequency at 1200, turns on the low-pass filter,
disables  the high-pass and band-pass filters and assigns a 10 to the reso-
nance level. Now go back and turn the filter on in your PLAY statements by
changing all the X0 control characters to X1. Reset the sound chip by pres-
sing the {run/stop} and {restore} keys and RUN your sound program again.
Notice the difference between the way the notes sound and how they sounded
without the filter. Change line 45 to:

     45 FILTER 1200, 0, 1, 0, 10

The new line 45 turns off the low-pass filter and enables the band-pass fil-
ter. Press {run/stop} and {restore} and RUN your sound program again.
Notice the difference between the low-pass and band-pass filters. Change
line 45 again to:

     45 FILTER 1200, 0, 0, 1, 10

Reset the sound chip and RUN your example program again. Notice the diffe-
rence between the high-pass filter and the low-pass and band-pass filters.
Experiment with different cutoff frequencies, resonance levels and filters
to perfect the music and sound in you own programs.


7.3.3 Tying your Music Program Together

Your first musical program is complete. Now you can program your favorite
songs. Let's tie all the components together. Here's the program listing.
Don't be alarmed, this is the same program you built in this section except
the print statements are added so you know which program lines are being
played.

     10 ENVELOPE 0,5,9,2,2,2,1700
     15 VOL 8
     20 TEMPO 10
     25 PRINT "LINE 30"
     30 PLAY "CDEFGAB"
     35 FILTER 1200,0,0,1,10
     40 PRINT "LINE 45 - FILTER OFF"
     45 PLAY "V2 O5 T7 U5 X0 CDEFGAB"
     50 PRINT "SAME AS LINE 45 - FILTER ON"
     55 PLAY "V2 O5 T7 U5 X0 CDEFGAB"
     60 PRINT "LINE 65 - FILTER OFF"
     65 PLAY "V3 O6 T6 U7 X0 CDEFGAB"
     70 PRINT "SAME AS LINE 65 - FILTER ON"
     75 PLAY "V3 O6 T6 U7 X1 CDEFGAB"
     80 PRINT "LINE 85 - FILTER OFF"
     85 PLAY "V2 O6 T0 U7 X0 HCD QEF IGA SB"
     90 PRINT "SAME AS LINE 85 - FILTER ON"
     95 PLAY "V2 O6 T0 U7 X1 HCD QEF IGA SB"
     100 PRINT "LINE 105 - FILTER OFF"
     105 PLAY "V1 O4 T4 U8 X0 H.CD Q#EF I$GA S.B"
     110 PRINT "SAME AS LINE 105 - FILTER ON"
     115 PLAY "V1 O4 T4 U8 X1 H.CD Q#EF I$GA S.B"


Line 10, the ENVELOPE statement, specifies the envelope for the piano (0),
which sets the attack to 5, decay to 9, sustain to 2 and release to 2. It
also selects the variable pulse waveform (2), with a pulse width of 1700.
Line 15 sets the VOLume to 8. Line 20 chooses the TEMPO to be 10.

Line 35 FILTERs the notes that are played in lines 30 to 115. It sets the
FILTER cutoff frequency to 1200. In addition, line 35 turns off the low-
pass and band-pass filters with the two zeros following the cutoff frequen-
cy (1200). The high-pass filter is turned on with the 1 following the two
zeros. The resonace is set to 10 by the last parameter in the FILTER
statement.

Line 30 PLAYs the notes C, D, E, F, G, A, B in that order. Line 45 PLAYs
the same notes as line 30, but it specifies the SID control character U5 as
volume level 5, V2 as voice 2 and O5 as octave 5. Remember, the SID control
characters allow you to change the synthesizer controls within a string and
exercise the most control over the synthesizer. The control character T7
selects the organ envelope. Line 65 specifies the control characters U7 for
volume level 7, V3 for voice 3, O6 for octave 6, T6 for the harpsichord
envelope and X0 to turn off the filter. Line 65 PLAYs the same notes as
line 30 and 45, but in a different volume, voice, octave and instrument
envelope.

Line 85 has the same volume, voice, octave and envelope as line 65, and it
specifies half notes for the notes C and D, quarter notes for the notes E
and F, eighth notes for the notes G and A and a sixteenth note for the B
note. Line 105 sets the volume at 8, voice 1, octave 4, flute envelope (4)
and turns off the filter. It also specifies the C and D notes as dotted
half notes, E and F as sharp quarter notes, G and A as flat eighth notes
and B as a dotted sixteenth note. Line 115 is the same as line 105, but
with the filter turned on.


7.3.4 Advanced Filtering

Each of the previous FILTERing examples used only one filter at a time.
You can combine the SID chip's three filters with each other to achieve
different filtering effects. For example, you can enable the low-pass and
high-pass filters at the same time to form a notch reject filter. A notch
reject filter allows the frequencies below and above the cutoff to pass
through the SID chip, while frequencies close to the cutoff frequency are
filtered. See Figure 7-10 for a graphical representation of a notch reject
filter.


                             |
                      AMOUNT | --+     +---
                      PASSED |    \   /
                             |     \ /
                             |      +
                             +------|-------
                                FREQUENCY

                    Figure 7-10. Notch Reject Filter.

You can also add either the low-pass or high-pass filter to the band-pass
filter to obtain interesting effects. By mixing the band-pass filter with
the low-pass filter, you can select the band of frequencies beneath the
cutoff frequency and below. The rest are filtered out.

By mixing the band-pass and the high-pass filters, you can select the band
of frequencies above the cutoff frequency and higher. All frequencies below
the cutoff frequency are filtered out.

Experiment with the different combinations of filters to see all the dif-
ferent types of accents you can place on your musical notes and sound
effects. The filters are designed to perfect the sounds created by other
components of the SID chip. Once you have created the musical notes or
sound effects with the SID chip, go back and add FILTERing to your programs
to make them as crisp and clean as possible.

Now you have all the information you need to write your own musical pro-
grams in Commodore 128 BASIC. Experiment with the different waveforms, ADSR
settings, TEMPOs and FILTERing. Look in a book of sheet music and enter the
notes from a musical scale in sequence within a play string. Accent the
notes in the string with the SID control characters. You can combine your
Commodore 128 Music Synthesizer with C128 mode graphics to make your own
videos or "movies", complete with sound tracks.


7.4 CODING A SONG FROM SHEET MUSIC

This section provides a sample piece of sheet music and illustrates hoe to
decode notes from a musical staff and translate them into a form the Com-
modore 128 can understand. This exercise is substantially faster and easier
if you know how to read music. However, you don't have to be a musician to
be able to play the tune on your Commodore 128. For those of you who cannot
read music, Figure 7-11 shows how a typical musical staff is arranged and
how the notes on the staff are related to the keys on a piano.

     **-**-**--+-**-**--+-**-**-**--+-**-**--+-**-**-**--+-**-**--+-**
     ** ** **  | ** **  | ** ** **  |M** **  | ** ** **  | ** **  | **
     ** ** **  | ** **  | ** ** **  |i** **  | ** ** **  | ** **  | **
      |  |  |  |  |  |  |  |  |  |  |d |  |  |  |  |  |  |  |  |  |  |
      |  |  |  |  |  |  |  |  |  |  |  |  |  |  |  |  |  |  |  |  |  |
      |G |A |B |C |D |E |F |G |A |B |C |D |E |F |G |A |B |C |D |E |F |
      +--+--+--+--+--+--+--+--+--+--+--+--+--+--+--+--+--+--+--+--+--+
       :  :  :  :  :  :  :  :  :  :  ^  :  :  :  :  :  :  :  :  :  : 
       :  :  :  :  :  :  :  :  :  :  :  :  :  :  :  :  :  :  :  :  : 
[ +----------------------------------------------------------------o------+
[ |    :  :  :  :  :  :  :  :  :  :  :  :  :  :  :  :  :  :  :  o         |
[ +----------------------------------------------------------o------------+
[ |    :  :  :  :  :  :  :  :  :  :  :  :  :  :  :  :  :  o               |
[ +----------------------------------------------------o------------------+
[ |    :  :  :  :  :  :  :  :  :  :  :  :  :  :  :  o                     |
[ +-G:-------------------------------------------o------------------------+
[ |    :  :  :  :  :  :  :  :  :  :  :  :  :  o                           |
[ +----------------------------------------o------------------------------+
[      :  :  :  :  :  :  :  :  :  :  v  o
[      :  :  :  :  :  :  :  :  :  : -o-
[      :  :  :  :  :  :  :  :  :  o
[ +----------------------------o------------------------------------------+
[ |    :  :  :  :  :  :  :  o                                             |
[ +-F:-------------------o------------------------------------------------+
[ |    :  :  :  :  :  o                                                   |
[ +----------------o------------------------------------------------------+
[ |    :  :  :  o                                                         |
[ +----------o------------------------------------------------------------+
[ |    :  o                                                               |
[ +----o------------------------------------------------------------------+
                                   Middle
                                     C

                       Figure 7-11. Musical Staff.

Figure 7-12 is an excerpt from a composition titled Invention 13 (Inventio
13 in Italian), by Johann Sebastian Bach. Although this composition was
written a few hundred years ago, it can be played and enjoyed on most mo-
dern computer synthesizers, such as the SID chip, in the Commodore 128.
Here are the opening measures of Invention 13.



                           [IMAGE IS MISSING]


                Figure 7-12. Part of Bach's Invention 13.

The best way to start coding a song into your Commodore 128 is by breaking
down the notes down into intermediate code. Write down the upper staff
notes on a piece of paper. Now write down the notes for the lower staff.
Precede the note values with a duration code. For instance, precede an
eighth note with an 8, precede a sixteenth note with a 16 and so on. Next,
separate the notes so the notes on the upper staff for one measure are
propertional in time with the notes for one measure on the lower staff.

If the musical composition has a third staff, you would separate it so the
duration is proportional to the two other upper staffs. Once the notes for
all the staffs are separated into equal durations, a separate dedicated
voice would play each note for a particular staff. For example, voice 1
would play the upper staff, voice 2 will play the second staff and voice 3
would play the lowest staff if it existed.

Let's say the upper staff begins with a string of four eighth notes. In ad-
dition, say the lower staff begins with a string of eight sixteenth notes.
Since a eighth note is proportional in time to two sixteenth notes, sepa-
rate the notes as shown in Figure 7-13.

         V1 =       8A          8B          8C          8C

         V2 =       16D 16E     16F 16G     16A 16B     16C 16D

            Figure 7-13. Synchronizing Notes for Two Voices.

Since the synchronization and timing in a musical composition is critical,
you must make sure the notes in the upper staff for voice 1, for example,
are in time agreement with the notes in the lower staff for voice 2. The
first note in the upper staff in Figure 7-12 is an A eighth note. The first
two notes for voice 2 are D and E sixteenth notes. In this case, you must
enter the voice 1 eighth note in the PLAY string first, then follow the
voice 2 sixteenth notes immediately after it. To continue the example, the
second note in Figure 7-12 for voice 1 (the upper staff) is a B eighth
note. The B eighth note is equal in time to the two sixteenth notes, F and
G, which appear in the bottom staff for voice 2. In order to coordinate the
timing, enter the B eighth note in the string for voice 1 and follow it
with the two sixteenth notes F and G for voice 2.

As a rule, always start with the note with the longer duration. For
example, if a bar starts with a series of two sixteenth notes on the lower
staff for voice 2 and the upper staff starts with an eighth note for voice
1, enter the eighth note in the string first since it must play for the du-
ration while the two sixteenth notes are being fetched by the Commodore
128. You must give the computer time to play the longer note first, the
PLAY the notes of shorter duration, or else the composition will not be
synchronized.

Here's the program that plays Invention 13. Enter it into your C128, SAVE
it for future use and then RUN it.

     10 REM INVENTION 13 BY J.S. BACH
     20 TEMPO 6
     30 A$="V1O4T7U8X0 V2O4T7U8X0":REM V1=ORGAN, V2=PIANO
     40 DO
     50 PLAY A$
     60 READ A$
     70 LOOP UNTIL A$="END OF MUSIC"
     80 END
     90 REM **** FIRST MEASURE
     100 DATA V2O1IA V1O3IE V2O2QA V1O3SAO4CO3BEM
     110 DATA V2O2I#G V1O3SBO4DO4IC V2O2SAEM
     120 DATA V1O4IE V2O2SAO3C V1O3I#G V2O2SBEM
     130 DATA V1O4IE V2O2SBO3DM
     140 REM **** SECOND MEASURE
     150 DATA V2O3IC V1O3SAE V2O2IA V1O3SAO4CM
     160 DATA V2O2I#G V1O3SBE V2O2IE V1O3SBO4DM
     170 DATA V1O4IC V2O2SAE V1O3IA V2O2SAO3CM
     180 DATA V1O4QR V2O2SBEBO3DM
     190 REM **** THIRD MEASURE
     200 DATA V2O3IC V1O4SRE V2O2IA V1O4SCEM
     210 DATA V2O3IC V1O3SAO4C V2O2IA V1O2SEGM
     220 DATA V1O3IF V2O3SDO2A V1O3IA V2O2SFAM
     230 DATA V1O4ID V2O2SDF V1O4IF V2O1SAO2CM
     240 REM **** FOURTH MEASURE
     250 DATA V2O1IB V1O4SFD V2O2ID V1O3SBO4DM
     260 DATA V2O2IG V1O3SGB V2O2IB V1O3SDFM
     270 DATA V1O3IE V2O2SGE V1O3IG V2O2SEGM
     280 DATA V1O4IC V2O2SCE V1O4IE V2O1SGBM
     290 REM **** FIFTH MEASURE
     300 DATA V2O1IA V1O4SEC V2O2IC V1O3SAO4CM
     310 DATA V1O3IF V2O2SDF V1O4ID V2O1SBO2DM
     320 DATA V2O1IG V1O3SDB V2O1IB V1O3SGBM
     330 DATA V1O3IE V2O2SCE V1O4IC V2O1SAO2CM
     340 REM **** SIXTH MEASURE
     350 DATA V2O1IF V1O4SCO3A V2O1ID V1O3SFAM
     360 DATA V1O3ID V2O1SGO2G V1O3IB V2O2SFGM
     370 DATA V2O1IA V1O4SCO3A V2O2I#F V1O4SCEM
     380 DATA V2O1IB V1O4SDO3B V2O2I#G V1O4SDFM
     390 REM **** SEVENTH MEASURE
     400 DATA V2O2IC V1O4SEC V2O2IA V1O4SEGM
     410 DATA V2O2ID V1O4SFE V2O2I$B V1O4SDCM
     420 DATA V2O2I#G V1O3SBO4C V2O2IF V1O4SDEM
     430 DATA V2O2ID V1O4SFD V2O1IB V1O4S#GDM
     440 REM **** EIGHTH MEASURE
     450 DATA V2O2I#G V1O4SBD V2O2IA V1O4SCAM
     460 DATA V2O2ID V1O4SFD V2O2IE V1O3SBO4DM
     470 DATA V2O2IF V1O3S#GB V2O2I#D V1O4SCO3AM
     480 DATA V2O2IE V1O3SEA V2O2IE V1O3SB#GM
     490 REM **** NINTH MEASURE
     500 DATA V2O1HA V1O3SAECEO2QAM
     510 REM **** END OF MUSIC ****
     520 DATA END OF MUSIC


You can use the technique described in this section to code your favorite
sheet music and play it on your Commodore 128.

***************************************************************************

You now have been introduced to most of the powerful new commands of the
BASIC 7.0 language that you can use in C128 mode. In the following section
you will learn to use both 40- and 80-column screen displays with the Com-
modore 128.



SECTION 8

8. Using 80-Columns


8.1 INTRODUCTION

8.2 THE 40/80 KEY

8.3 USING PREPACKAGED 80 COLUMN SOFTWARE

8.4 CREATING 80 COLUMN PROGRAMS

8.5 USING 40 AND 80 COLUMNS TOGETHER



8.1 INTRODUCTION

In C128 and CP/M modes, you can choose between a 40- en 80-column screen
display. You could even use both in a single program.

Each screen size has special uses. The 40-column screen is the same size
the Commodore 64 uses. With the 40-column screen you can use the Commodore
128's full graphic capabilities. You can draw circles, graphs, sprite
characters, boxes and other shapes in high resolution or multicolor graphic
modes. You can also use sprites.

If you are using 80-columns, you get twice the number of characters per
program line. In 80-column mode you can use the standard graphic characters
and colors available through the keyboard.

You can also write programs using two monitors to take advantage of both
screen display formats with each monitor screen performing different as-
pects of the program. For example, text output could be displayed on the
80-column monitor while graphics output could be seen on the 40-column
monitor.


8.2 THE 40/80 KEY

You can use the {40/80 display} key to set the screen width as either 40 or
80 columns. Pressing this key will only have an effect when one of the fol-
lowing actions is taken:

1. The power is turned ON.
2. The {reset} button is pressed.
3. The {run/stop} and {restore} buttons are pressed simultaneously.

The {40/80 display} key acts like a {shift lock} key: it locks when you
press it, and does not release until you press it again. If this key is up
(not pressed) when one of the three conditions above occurs, the screen is
set to 40 columns. If you press the key down, causing it to lock, and one
of the three conditions listed above then occurs, the screen is set to 80
columns. Once the computer is running in one screen format (40- or 80-
columns), you cannot switch to the other format using the {40/80 display}
key. In this case you must press and release the {esc} key and then press
the {X} key.


8.3 USING PREPACKAGED 80 COLUMN SOFTWARE

Most CP/M programs utilize an 80-column screen, as do many of the other
business application packages you can use in C128 mode. Since the width of
a normal printed page is 80 columns, an 80-column wordprocessor can display
information on the screen exactly as that information will appear on paper.
Spreadsheet programs often specify an 80-column format, in order to provide
enough space for the necessary columns and categories of information. Many
database packages and telecommunications programs also require or can use
an 80-column screen.


8.4 CREATING 80 COLUMN PROGRAMS

In addition to running prepackaged software, the 80-column screen width can
be useful in designing you own programs. You've probably noticed what hap-
pens when you type a line that is wider than 40 columns on a 40-column
screen. The lines "wrap around", that is, the continue onto the next screen
line. This may cause confusion in reading the line, and can even lead to
progamming errors. An 80-column screen helps eliminate these problems. In
general, an 80-column screen allows for a clearer screen and better organi-
zation.


8.5 USING 40 AND 80 COLUMNS TOGETHER

The main advantage of 40-column composite video is the availability of bit
mapped graphics, while 80-columns gives you output for word processing and
other business applications. If you have two monitors, you can write pro-
grams that are "shared", using the text features 80-columns affords you and
the graphics of 40-columns. A special command (GRAPHIC 1,1) can be used
within a program to transfer the execution of graphics commands to the 40-
column display. If you have a dual monitor (one that can display both 40-
and 80-columns format) you can place GRAPHIC 1,1 statements in your program
so that graphics will be output in 40-column screen format. In order to
view the graphic output, however, you will need to change the video switch
on the monitor to 40-columns. If you write a program like this, it might
be a good idea to include on-screen directions to the user to change the
video switch.

For example, you might write a program which asked the user to input data,
then create a bar graph based on the user's input. The message "CHANGE TO
40 COLUMN TO VIEW GRAPH" would tell the user to switch modes and see the
results.

As noted previously, you can switch between 80- and 40-column formats after
power-up, with the {esc x} sequence.

The following example shows how dual screens can be used within a program:

  10 GRAPHIC 5,1:SCNCLR                   :REM SWITCH TO 80 COLUMN AND
     CLEAR IT
  20 PRINT "START IN 40 COLUMN BY SELECTING THE COMPOSITE VIDEO"
  30 PRINT "INPUT OF YOUR DUAL MONITOR."
  40 PRINT
  50 PRINT "PRESS THE RETURN KEY WHEN READY."
  60 GETKEY A$:IF A$ <> CHR$(13) THEN 60
  70 GRAPHIC 2,1                          :REM SELECT SPLIT SCREEN MODE
  80 CHAR 1,8,18,"BIT MAP/TEXT SPLIT SCREEN"
  90 FOR I = 70 TO 220 STEP 20:CIRCLE 1,I,50,30,30:NEXT I
  100 PRINT
  110 PRINT " SWITCH TO 80 COLUMN BY SELECTING THE"
  120 PRINT " RGBI VIDEO INPUT OF YOUR DUAL MONITOR,"
  130 PRINT " THEN PRESS THE RETURN KEY WHEN READY."
  140 GETKEY A$:IF A$ <> CHR$(13) THEN 140
  150 GRAPHIC 5,1                         :REM SWITCH OUTPUT TO THE 80
      COLUMN
  160 FOR J = 1 TO 10
  170 PRINT "YOU ARE NOW IN 80 COLUMN TEXT MODE."
  180 NEXT J:PRINT
  190 PRINT "NOW SWITCH BACK TO 40 COLUMN OUTPUT."
  200 PRINT "PRESS THE RETURN KEY WHEN READY."
  210 GETKEY A$:IF A$ <> CHR$(13) THEN 210
  220 GRAPHIC 0,1                         :REM SWITCH OUTPUT TO THE 40
      COLUMN
  230 PRINT
  240 FOR J = 1 TO 10
  250 PRINT " YOU ARE NOW IN 40 COLUMN TEXT OUTPUT."
  260 NEXT J
  270 END

Each screen display format offers certain advantages; yet the two types of
displays can be combined in a program to complement each other. Using a 40-
column screen, you can get the full power of advanced BASIC graphics. The
80-column display gives you more space for your own programs. In addition,
it lets you run the wide variety of software designed to run on an 80-
column screen.



***************************************************************************



This section of this chapter have introduced you to the many features and
capabilities provided by the Commodore 128 in C128 mode. The following
chapter tells you how to use the Commodore 128 in C64 mode.



                                   CHAPTER

                                      3

                                USING C64 MODE



SECTION 9

9. Using the Keyboard in C64 Mode



9.1 USING BASIC 2.0

9.2 KEYBOARD CHARACTER SETS

9.3 USING THE TYPEWRITER-STYLE KEYS

9.4 USING THE COMMAND KEYS

9.5 MOVING THE CURSOR IN C64 MODE

9.6 PROGRAMMING FUNCTION KEYS IN C64 MODE



9.1 USING BASIC 2.0

The entire BASIC 2.0 language built into the Commodore 64 computer has been
incorporated into the BASIC 7.0 language of the Commodore 128. You can use
BASIC 2.0 commands in both C128 and C64 modes. Refer to Sections 3 and 4 in
Chapter 2 for a description of these commands.


9.2 KEYBOARD CHARACTER SETS

In the keyboard illustration in Section 3 the outlined key areas contain the
keys that can be used in C64 Mode. The keyboard in C64 Mode has the same two
character states as in C128 Mode:

     - Upper case/graphic character set
     - Upper/lower case character set

When you enter C64 Mode, the keyboard is in the upper case/graphic charac-
ter set, so that everything you type is in capital letters. In C64 Mode you
can only use one character set at a time. To switch back and forth between
character sets, press the {shift} key and the {C=} key (the COMMODORE key)
at the same time.


9.3 USING THE TYPEWRITER-STYLE KEYS

As in C128 Mode, you can use the typewriter-style keys in C64 Mode to type
both upper case letters (capitals) and lower case letters (small letters).
You can also type the numerals shown in the top row on the main keyboard.
In addition, you can type the graphic symbols on the front of the keys.


9.4 USING THE COMMAND KEYS

Most COMMAND keys (i.e. the keys that send messages to the computer, like
{return}, {shift}, {ctrl}, etc.) work the same in C64 Mode as they do in
C128 Mode.

The only difference is that in C64 Mode, you can only move the cursor by
using the two {crsr} keys at the bottom right corner of the main keyboard.
In C128 Mode, you can also use the four arrow keys located just above the
top right side of the main keyboard.


9.5 MOVING THE CURSOR IN C64 MODE

In C64 Mode, you use two {crsr} keys on the main keyboard and the {shift}
key to move the cursor, as described in Section 3.


9.6 PROGRAMMING FUNCTION KEYS IN C64 MODE

The four keys to the right side of the keyboard, just above the numeric
keypad, are called function keys. The keys are marked F1, F3, F5 and F7 on
the tops and F2, F4, F6 and F8 on the fronts. These keys can be programmed
- that is, they can be instructed to perform a specific task or function.
For this reason these keys are often called programmable function keys.

You must hold down the {shift} key to perform the functions associated with
the markings on the front of the keys - that is, F2, F4, F6 and F8. There-
fore, these keys are sometimes called the SHIFTed programmable function
keys.

The function keys in C64 Mode do not have a printed character assigned to
them. They do, however, have CHR$ codes assigned. In fact, each of them has
two CHR$ codes - one for when you press the key by itself, and one for when
you press the key while holding down the {shift} key. To get the even-
numbered function keys, hold down the {shift} key while pressing the func-
tion key. For example, to get {f2}, hold down {shift} and press {f1}.

The CHR$ codes for the F1-F8 keys range from 133 to 140. However, the codes
are not assigned to the keys in numerical order. The keys and their corres-
ponding CHR$ codes are as follows:

     {f1}   CHR$(133)
     {f2}   CHR$(137)
     {f3}   CHR$(134)
     {f4}   CHR$(138)
     {f5}   CHR$(135)
     {f6}   CHR$(139)
     {f7}   CHR$(136)
     {f8}   CHR$(140)

You can use the function keys in your program in several ways. To do this,
you need to use the GET statement. (See paragraph 4.3.2 of Section 4 for a
description of the GET statement.) As an example, the program below prepares
the {f1} key to print a message on the screen.

     10 ?"PRESS F1 TO CONTINUE"
     20 GET A$:IF A$="" THEN 20
     30 IF A$<>CHR$(133) THEN 20
     40 ?"YOU HAVE PRESSED F1"

Lines 20 and 30 do most of the work in this program. Line 20 makes the com-
puter wait until a key is pressed before executing any more of the program.
Note that when the command immediately after THEN is a GOTO, only the line
number is necessary. Also note that a GOTO command can GOTO the same line
it is on. Line 30 tells the computer to go back and wait for another key to
be pressed unless the {f1} key has been pressed.




SECTION 10

10. Storing and Reusing Your Programs in C64 Mode



10.1 FORMATTING A DISK IN C64 MODE

10.2 THE SAVE COMMAND

  10.2.1 SAVEing on Disk
  10.2.2 SAVEing on Cassette

10.3 THE LOAD AND RUN COMMANDS

  10.3.1 LOADing and RUNning from Disk
  10.3.2 LOADing and RUNning from Cassette

10.4 OTHER DISK-RELATED COMMANDS

  10.4.1 Verifying a Program
  10.4.2 Displaying Your Disk Directory
  10.4.3 Initializing a Disk Drive



Once you have edited a program, you will probably want to store it
permanently so that you will be able to recall and use it at some later
time. To do this you need either a Commodore disk drive or the Commodore
Datassette.


10.1 FORMATTING A DISK IN C64 MODE

To store programs on a new (or blank) disk, you must first prepare the disk
to receive data. This is called formatting the disk. Make sure that you
turn on the disk drive before inserting any disk.

To format a blank disk, in C64 Mode, you type this command:

     OPEN 15,8,15:PRINT#15,"N0:NAME,ID" {return}

In place of NAME, type a disk name of your choice; you can use up to 16
characters to identify the disk. In place of ID, type a two character code
of your choice (such as W2 or 10).

The cursor disappears during the formatting process. When the cursor blinks
again, type the following command:

     CLOSE 15 {return}

NOTE: Once a disk is formatted in C64 or C128 mode, that disk can be used
in either mode.


10.2 THE SAVE COMMAND

You can use the SAVE command to store your programs on disk or tape.


10.2.1 SAVEing on Disk

If you have a Commodore single disk drive, you can store your program on
disk by typing:

     SAVE "PROGRAM NAME",8 {return}

The {8} indicates to the computer that your are using a disk drive to store
your program.

The same rules apply for the PROGRAM NAME whether you are using disk or
tape. The PROGRAM NAME can be anything you want it to be. You can use let-
ters, numbers and/or symbols - up to 16 characters in all. Note that you
must enclose the PROGRAM NAME in quotation marks. The cursor on your com-
puter disappears while the program is being SAVEd, but it returns when the
process is completed.


10.2.2 SAVEing on Cassette

If you are using a Datassette to store your program, insert a blank tape in
the recorder, rewind the tape (if necessary) and type:

     SAVE "PROGRAM NAME" {return}


10.3 THE LOAD AND RUN COMMANDS

Once a program has been SAVEd, you can LOAD it back into the computer's
memory and RUN it anytime you wish.


10.3.1 LOADing and RUNning from Disk

To load your program from a disk, type:

     LOAD "PROGRAM NAME",8 {return}

Again, the {8} indicates to the computer that you are working with a disk
drive.

To RUN the program, type RUN and press {return}


10.3.2 LOADing and RUNning from Cassette

To LOAD your program from cassette tape, type:

     LOAD "PROGRAM NAME" {return}

If you do not know the name of the program, you can type:

     LOAD {return}

and the next progam on the tape will be retrieved.

You can use the counter on the Datassette to identify the starting position
of the programs. Then, when you want to retrieve a program, simply wind the
tape forward from 000 to the program's start location, and type:

     LOAD {return}

In this case, you do not have to specify the PROGRAM NAME; your program
will load automatically because it is the next program on the tape.

     NOTE: During the LOAD process, the program being LOADed is not erased
     from the tape; it is simply copied into the computer. However, LOADing
     a program automatically erases any BASIC program that may have been in
     the computer's memory.


10.4 OTHER DISK-RELATED COMMANDS

10.4.1 Verifying a Program

To verify that a program has been correctly saved or loaded, type:

     VERIFY "PROGRAM NAME",8 {return}

If the program in the computer is identical to the one on the disk, the
screen display will respond with the letters {OK}.

The VERIFY command also works for tape programs. You type:

     VERIFY "PROGRAM NAME" {return}

Note that you do not enter the comma and the number 8, since 8 indicates
that you are working with a disk program.


10.4.2 Displaying Your Disk Directory

To see a list of the programs on your disk, first type:

     LOAD "$",8 {return}

The cursor disappears during this process. When the cursor reappears, type:

     LIST {return}

A list of the programs on your disk then will be displayed. Note that when
you load the directory, any program that was in memory is erased.


10.4.3 Initializing a Disk Drive

If the disk drive's ready light is blinking, it indicates a disk error. You
can restore the disk drive to the condition it was in before the error oc-
curred by using a procedure called INTITIALIZING. To initialize a drive,
you type:

     OPEN 1,8,15,"I":CLOSE 1 {return}

If the light is still blinking, remove the disk and turn the drive off,
then on.


For further information on SAVEing and LOADing your programs, refer to your
disk drive or Datassette manual. Also consult the LOAD and SAVE command
descriptions in the Chapter V, BASIC 7.0 Encyclopaedia.



                                   CHAPTER

                                      4

                               USING C/PM MODE



SECTION 11

11. Introduction to CP/M 3.0



11.1 WHAT CP/M 3.0 IS

11.2 WHAT YOU NEED TO RUN CP/M 3.0

11.3 WHAT IS ON YOUR CP/M 3.0 DISK

  11.3.1 CP/M+.SYS
  11.3.2 CCP.COM
  11.3.3 .COM Files
  11.3.4 Other Files

11.4 GETTING STARTED WITH CP/M 3.0

  11.4.1 Loading or Booting CP/M 3.0
  11.4.2 The Opening CP/M Screen Display

11.5 THE COMMAND LINE

  11.5.1 Types of Commands
  11.5.2 How CP/M Reads Command Lines

11.6 HOW TO COPY YOUR CP/M 3.0 DISK

  11.6.1 Formatting a Disk
  11.6.2 Copying Files

11.7 LANGUAGES AND APPLICATION SOFTWARE

  11.7.1 What To Buy
  11.7.2 How To Install It on Your C128



11.1 WHAT CP/M 3.0 IS

CP/M is a product of Digital Research, Inc. The version of CP/M used on the
Commodore 128 is CP/M Plus Version 3.0. In this chapter, CP/M is generally
referred to as CP/M 3.0, or simply CP/M. This chapter summarizes CP/M on
the Commodore 128. For detailed information on CP/M 3.0, follow the
instructions on the coupon enclosed in the box in which the Commodore 128
is supplied.

CP/M 3.0 is a popular operating system for microcomputers. As an operating
system, CP/M 3.0 manages and supervises your computer's resources, inclu-
ding memory and disk storage, the console (screen and keyboard), printer,
and communication devices. CP/M 3.0 also manages information stored in disk
files. CP/M 3.0 can copy files from a disk to your computer's memory, or to
a peripheral device such as a printer. To do this, CP/M 3.0 places various
programs in memory and executes them in response to commands you enter at
your console. Once in memory, a program executes a set of steps that
instruct your computer to perform a certain task.

You can use CP/M to create your own programs, or you can choose from the
wide variety of available CP/M 3.0 application programs.


11.2 WHAT YOU NEED TO RUN CP/M 3.0

The general hardware requirements for CP/M 3.0 are a computer containing a
Z80 microprocessor, a console consisting of a keyboard and a display
screen, and at least one floppy disk drive. For CP/M 3.0 on the Commodore
128 Personal Computer, the Z80 microprocessor is built-in; the console
consists of the full Commodore 128 keyboard, and an 80-column monitor; and
the disk drive is the new Commodore 1571 fast disk drive. In addition,
there is either one or two CP/M disks packed with the computer. If two CP/M
disks are supplied, one contains the CP/M 3.0 system and an extensive HELP
utility program, and the other contains a number of other utility programs.
If one CP/M disk is supplied, the system and HELP utility are on one side
of that disk and the utility programs are on the other.

Note: Although CP/M can be used with a 40-column monitor, the display
is 80 column but with only 40 columns displayed at one time. To view
all 80 columns of the display, you must scroll the screen
horizontally by pressing the {ctrl} key and the appropriate cursor
key ({crsr left} or {crsr right}).


11.3 WHAT IS ON YOUR CP/M 3.0 DISK

11.3.1 CP/M+.SYS

This is the main CP/M Plus system file. It contains all parts of the system
that remain permanently resident in memory: the Basic Input/Output System
(BIOS) which loads into the top of memory, the Basic Disk Operating System
(BDOS) which loads into memory immediately below BIOS, and the System Para-
meters which load into the bottom page of memory.


11.3.2 CCP.COM

On booting CP/M the Console Command Processor (CCP) is loaded into memory
immediately below the BDOS. The remaining memory, below CCP and above page
0, is known as the Transient Program Area (TPA) and is where applications
are loaded to. CCP is the program which processes any input (usually en-
tered from the keyboard) in response to the system prompt (A>). It contains
6 built-in commands (listed in Table 14-1), and also supports the 14 console
editing commands (listed in Table 13-1).

Any word entered in response to the system prompt which is not one of the
built-in commands is treated by CCP as a transient command, so CCP attempts
to find and execute a file named as that word with the .COM extension. If
it does not find such a file on the currently logged disk, it displays the
word followed by a question mark then brings back the system prompt.

If more than one word is entered in response to the system prompt, all
words after the first are treated as parameters to be passed to the tran-
sient command.

A language or application program is loaded and run by invoking it as if it
was a command. All CP/M programs include a .COM file


WHAT IS ON YOUR CP/M 3.0 DISK

show b:
B: RW, Space       336k

A>dir [full]

Scanning Directory...
Sorting  Directory...
Directory for Drive A: User  0

    Name     Bytes   Recs   Attributes      Name     Bytes   Recs   Attrib.
------------ ------ ------ ------------ ------------ ------ ------ --------
CCP     .COM     4k     25  Dir RW      CPM+    .SYS    23k    182  Dir RW
DIR     .COM    15k    114  Dir RW      FORMAT  .COM     5k     35  Dir RW
HELP    .COM     7k     56  Dir RW      HELP    .HLP    83k    664  Dir RW
KEYFIG  .COM    10k     75  Dir RW      KEYFIG  .HLP     9k     72  Dir RW
PIP     .COM     9k     68  Dir RW

Total Bytes     =    165k  Total Records =     1291  Files Found =    9
Total 1k Blocks =    165   Used/Max Dir Entries For Drive A:    15/  64

A>dir b: [full]

Scanning Directory...
Sorting  Directory...
Directory for Drive B: User  0

    Name     Bytes   Recs   Attributes      Name     Bytes   Recs   Attrib.
------------ ------ ------ ------------ ------------ ------ ------ --------
DATE    .COM     8k     25  Dir RW      DATEC   .ASM     2k      5  Dir RW
DATEC   .RSX     2k      3  Dir RW      DEVICE  .COM    16k     58  Dir RW
DIR     .COM    30k    114  Dir RW      DIRLBL  .RSX     4k     12  Dir RW
DUMP    .COM     2k      8  Dir RW      ED      .COM    20k     73  Dir RW
ERASE   .COM     8k     29  Dir RW      GENCOM  .COM    30k    116  Dir RW
GET     .COM    14k     51  Dir RW      INITDIR .COM    64k    250  Dir RW
PATCH   .COM     6k     19  Dir RW      PIP     .COM    18k     68  Dir RW
PUT     .COM    14k     55  Dir RW      RENAME  .COM     6k     23  Dir RW
SAVE    .COM     4k     14  Dir RW      SET     .COM    22k     81  Dir RW
SETDEF  .COM     8k     32  Dir RW      SHOW    .COM    18k     66  Dir RW
SUBMIT  .COM    12k     42  Dir RW      TYPE    .COM     6k     24  Dir RW

Total Bytes     =    314k  Total Records =     1168  Files Found =   22
Total 1k Blocks =    314   Used/Max Dir Entries For Drive A:    23/  64

11.3.3 .COM Files

The other .COM files all contain transient commands (listed in Table 14-2).

HELP.COM displays messages, held in HELP.HLP (whose extension indicates it
is a data file, not a program file), about the C128 CP/M system and its
commands. If you are not familiar with CP/M and have no other manuals or
books about it, you may find it useful to print out any HELP you look at.
Pressing {ctrl} and {p} CAUSES any screen output also to go to the printer:
pressing {ctrl}{p} again turns off this facility.

Enter HELP for the list of subjects covered, or HELP C128_CP/M for informa-
tion specific to this implementation. (The character in the middle of
C128_CP/M is obtained by pressing the {left arrow} key at the top left of
the keyboard.) If you are printing and do not want pauses after each
screenful, then enter HELP C128_CP/M [NOPAGE].


11.3.4 Other Files

.ASM indicates an Assembler source file.

.RSX indicates a Resident System eXtension, which is a file automatically
loaded by a command file as and when it is needed.


11.4 GETTING STARTED WITH CP/M 3.0

The following paragraphs tell you how to start or "boot" CP/M 3.0, how to
enter and edit the command line, and how to make back-up copies of your
CP/M 3.0 disks.


11.4.1 Loading or Booting CP/M 3.0

Loading or "booting" CP/M 3.0 means reading a copy of the operating system
from your CP/M 3.0 System Disk into your computer's memory.

You can boot CP/M 3.0 in several ways. If your computer is off, you can
boot CP/M by first turning on your disk drive and inserting the CP/M 3.0
system disk, and then turning on the computer. CP/M 3.0 then loads automa-
tically. If you are already in C128 BASIC mode, you can boot CP/M 3.0 by
inserting the CP/M system disk into the drive, typing the BASIC command
BOOT and then pressing {return}. CP/M 3.0 then loads. In C128 mode, you can
also boot CP/M by inserting the System Disk and pressing the {reset}
button.

If you are in C64 mode, and you want to enter CP/M mode, first turn off the
computer. The insert the CP/M System Disk into the drive and turn on the
computer.

Caution: Always make sure that the disk is fully inserted in the drive
before you close the drive door.

In CP/M 3.0 on the Commodore 128, the user has a 59K TPA (Transient Program
Area), which is, in effect, user RAM.


11.4.2 The Opening CP/M Screen Display

After CP/M is loaded into memory, a message similar to the following is
displayed on your screen:

+-------------------------------------------------------------------------+
| CP/M 3.0 On the Commodore 128  3 JUNE 85                                |
|           80 column display                                             |
|                                                                         |
| A>_                                                                     |
|                                                                         |
|                                                                         |
|                                                                         |
|                                                                         |
|                                                                         |
|                                                                         |
|                                                                         |
|                                                                         |
|                                                                         |
|                                                                         |
|                                                                         |
|                                                                         |
|                                                                         |
|                                                                         |
|                                                                         |
|                                                                R A01 10 |
+-------------------------------------------------------------------------+

An important part of the opening display is the following two-character
message:

     A>

This is the CP/M 3.0 system prompt. The system prompt tells you that CP/M
is ready to read a command entered by you from your keyboard. The prompt
also tells you that drive A is your default drive. This means that until
you tell CP/M to do otherwise, it looks for program and data files on the
disk in drive A. It also tells you that your are logged in as user 0, sim-
ply by the absence of any user number other than 0.

Note: In CP/M a single disk drive is identified as drive A. This is equi-
valent to unit 8, drive 0 in C128 and C64 modes. Usually, the maximum
number of drives in CP/M is four. Additional drives are identified as
drives B, C, etc.


11.5 THE COMMAND LINE

CP/M 3.0 performs tasks according to specific commands that your type at
your keyboard. These Commands appear on the screen in what is called a
command line. A CP/M 3.0 command line is composed of a command keyword and
an optional command tail. The command keyword identifies a command (pro-
gram) to be executed. The command tail can contain extra information for
the command, such as a filename or parameters. The following example shows
a command line.

     A>DIR MYFILE

In this example, DIR is the command keyword and MYFILE is the command tail.
To send the command line to CP/M 3.0 for processing, press the {return}
key.

As you type characters at the keyboard, the appear on your screen. The
cursor moves to the right as you type. If you make a typing error, press
either the {inst/del} key or CTRL-H to move the cursor to the left and
correct the error. CTRL is the abbreviation for the {ctrl} key. To specify
a control character, hold down the {ctrl} key and press the appropriate
letter key. (A list of control characters and their uses is given in
Section 13.)

You can type the keyword and command tail in any combination of upper-case
and lower-case letters. CP/M 3.0 interprets all letters in the command line
as being upper case.

Generally, you must type a command line directly after the system prompt.
However, CP/M 3.0 does allow spaces between the prompt and the command
keyword.


11.5.1 Types of Commands

CP/M 3.0 recognizes two different types of commands: built-in commands and
transient utility commands. Built-in commands execute programs that reside
in memory as a part of the CP/M operating system. Built-in commands can be
executed immediately. Transient utility commands are stored on disk as pro-
gram files. They must be loaded from disk to perform their task. You can
recognize transient utility program files when a directory is displayed on
the screen, because their filenames are followed by a period (full stop)
and COM (.COM). Section 14 presents lists of CP/M built-in and transient
utility commands.

For transient utilities, CP/M 3.0 checks only the command keyword. Many
utilities require unique command tails. If you include a command tail, CP/M
3.0 passes it to the utility without checking it. A command tail cannot
contain more than 128 characters.


11.5.2 How CP/M Reads Command Lines

Use the DIR command to demonstrate how CP/M reads command lines. DIR, which
is an abbreviation for directory, tells CP/M to display a directory of disk
files on your screen. Type the DIR keyword after the system prompt, and
press the {return} key:

     A>DIR {return}

CP/M responds to this command by displaying the names of all the files that
are stored on whatever disk is in drive A. For example, if the CP/M system
disk is in the disk drive A, a list of filenames like this appears on your
screen:

A: PIP COM:ED COM:CCP COM:HELP COM:HELP HLP
A: DIR COM:CPM SYS

CP/M recognizes only correctly spelled command keywords. If you make a
typing error and press {return} before correcting your mistake, CP/M 3.0
repeats or "echoes" the command line followed by a question mark. For
example, suppose you mistype the DIR command, as in the following example:

     A>DJR {return}

CP/M replies with:

     DJR?

This tells you the CP/M cannot find a command keyword spelled DJR. To cor-
rect typing errors like this, you can use the {inst/del} key to delete the
incorrect letters. Another way to delete characters is to hold down the
{ctrl} key and press {h} to move the cursor to the left. CP/M provides a
number of other control characters that help you edit command lines.
Section 13 tells how to use the control characters to edit command lines
and other information you enter at your console.

DIR accepts a filename as a command tail. You can use DIR with a filename
to see if a specific file is on the disk. For example, to check that the
file MYFILE is on your disk, type:

     A>DIR MYFILE {return}

CP/M 3.0 performs this task by displaying either the name of the file you
specify, or the message:

     No File

Be sure you type at least one space after DIR to separate the command
keyword from the command tail. If you do not, CP/M 3.0 responds as follows:

     A>DIRMYFILE {return}
     DIRMYFILE?


11.6 HOW TO COPY YOUR CP/M 3.0 DISK

Before doing anything else you should back-up your CP/M system disk. This
can be done using either one or two disk drives. If using two disk drives
these may be 1541s, 1571s, or one of each. The back-up disks can be new or
used. You can either format new disks, or reformat used disks. To make
back-ups use the FORMAT and PIP utility programs found on you CP/M system
disk.

1)   Format the diskette using the FORMAT program, as either C128 single
     sided (if using a 1541) or C128 double sided (if using a 1571). (The
     C64 single sided option is for formatting disks compatible with the
     CP/M 2.2 package once sold for the Commodore 64.)
        Enter the command FORMAT, select the required disk type with the
     {crsr down} key, press {return}, and follow the onscreen instructions.
     Press {y} (Yes) or {n} (No) in response to the 'Do you want to format
     another disk' question.
2)   Use the Peripheral Interchange Program (PIP) - on the second surface
     of the original disk - to copy files. Enter PIP and the usual system
     prompt (A>) will be replaced by the PIP prompt (*).

If you have a single disk drive use drive A as the source drive and drive E
as the destination drive. Drive E is referred to as a virtual drive - that
is, it does not exist as an actual piece of hardware. Put the disk to be
copied from in the drive and enter

     E:=A:*.*

(You will be prompted each time the source disk and the destination disk
have to be swopped.)

If you have two disk drives, put the source disk in drive A (which is
device 8) and the newly formatted disk in drive B (device 9 - set by put-
ting the left DIP switches on the back of the 1571 down while the drive is
switched off) and enter

     B:=A:*.*

to copy all the files.

Your original CP/M disk is a flippy - i.e. recorded as 2 single sides, so
it must be taken out of the drive and turned over to get at the second
side. This is required for use in a 1541, which is a single sided drive. If
you have a 1541 you should copy the 2 surfaces onto 2 separate disks. How-
ever, if you have a 1571 you will find it convenient to copy both surface
onto a standard double sided disk: after copying the first side, turn over
the original disk and copy the second side onto the same destination disk
by again entering the copy instruction in response to the PIP prompt.

You may sometimes want to make disks that just have the system files on
them. To do this use PIP to copy the files CPM+.SYS and CCP.COM to the
newly formatted disk.

Note: Only disks that you intend to use to boot CP/M need these 2
files on them - putting them on other disks wastes space.

With a single drive, enter

     E:=A:CPM+.SYS

to copy the first file and then

     E:=A:CCP.COM

to copy the second file.

When you have finished PIP, press {return} to return from the PIP prompt to
the system prompt.

A full description of PIP can be obtained by entering HELP PIP, HELP
PIP_OPTIONS and HELP PIP_EXAMPLES.


11.7 LANGUAGES AND APPLICATION SOFTWARE

CP/M is just an operating system, that is a means to an end - not an end in
itself. On its own it does not do anything useful. If you want to write
your own programs you will need a language, either assembler or high level,
in which to write them. If you want to play games or do business work you
will need application programs.


11.7.1 What To Buy

Because CP/M has been implemented on almost every computer ever designed
that used the Intel 8080 or the Zilog Z80 cpu, there is a very large
amount of software available for running on CP/M systems. The most compre-
hensive catalogue of commercial software is the 'CP/M Software Finder' pu-
blished for Digital Research by Que Corporation and available through good
software retailers (ISBN 0-88-022-021-X). Since it is not convenient for
the CP/M Users Group to supply its library on Commodore format disks, a
selection of public domain CP/M software has been made available through
the independent Commodore Products Users Group (ICPUG), for which member-
ship application forms can be obtained by sending an s.a.e. to Membership
Secretary, ICPUG, 30 Brancaster Rood, Newbury Park, Ilford, IG2 7EP,
England.

CP/M normally uses Modified Frequency Modulation (MFM) ot record on disks.
Commodore DOS normally uses Group Code Recording (GCR). The Commodore 1571
disk drive can read both, but the older 1541 can only read GCR. Off-the-
shelf CP/M software packages only come as MFM disks. Even with MFM there
are many different formats: the 1571 can read disks formatted for:

Epson QX10          (512 byte sectors, double sided,
                    10 sectors per track)
IBM-8 SS (CP/M-86)  (512 byte sectors, single sided,
                    8 sectors per track)
IBM-8 DS (CP/M-86)  (512 byte sectors, double sided,
                    8 sectors per track)
IBM-9 SS (CP/M-86)  (512 byte sectors, single sided,
                    9 sectors per track)
IBM-9 DS (CP/M-86)  (512 byte sectors, double sided,
                    9 sectors per track)
KayPro II           (512 byte sectors, single sided,
                    10 sectors per track)
KayPro IV           (512 byte sectors, double sided,
                    10 sectors per track)
Osborne DD SS       (1024 byte sectors, single sided,
                    5 sectors per track)
Osborne DD DS       (1024 byte sectors, single sided,
                    5 sectors per track)

Therefore when buying CP/M software you must buy it on a disk in one of the
above formats. Also, be aware that your C128 will run software written to
run under either CP/M 2.2 or CP/M Plus (which is the newer name for what
was originally known as version 3). However, CP/M-86 is the version of CP/M
designed for use on 16-bit processors: CP/M-86 software will not run on
your C128's 8-bit Z80 processor, although the 1571 drive will let you read
CP/M-86 data files.

If you only have a 1541 disk drive you will have to get any software you
buy transferred from MFM format to (Commodore) GCR format. Some software
retailers may be willing to do this for you, but there will probably be a
copying charge. Alternatively, you may find that your local ICPUG group
provides facilities to do this at its meetings.


11.7.2 How To Install It on Your C128

Because there are so many different computers using the CP/M operating sys-
tem, many CP/M programs have to be configured for the particular hardware
on which they are to be used. The process of installing a program on your
C128 involves setting parameters within the software. The program manual
will describe how to install the program if this is required. Most programs
provide a list of common terminals which they support. If ADM31 appears in
this list, select it. If not, your will have to do a custom installation.

Listed below are the entries that should be made when running WINSTALL.COM
(the installation program that is part of the Wordstar package). These also
provide the information that will be needed for installing other programs,
although not all packages ask the same questions.

Terminal name                            Commodore 128
Screen size
  Screen height                          24
  Screen width                           80
Cursor positioning
  Function code sequence                 1Bh 3Dh
  Characters to be sent between line
    number and column number             none
  Characters to be sent after line
    number and column number             none
  Is the column number sent before
    the line number?                     NO
  What character is sent to the
    terminal to signify line 1?          20h
  What character is sent to the
    terminal to signify column 1?        20h
  What types of code are sent to
    signify line and column numbers?     Single byte BINARY value
  Terminal start-up
    Function code sequence               1Bh 59h 1Bh 1Bh 1Bh 60h
  Terminal exit
    Function code sequence               none
  Highlight-on
    Function code sequence               1Bh 1Bh 1Bh 52h
  Highlight-off
    Function code sequence               1Bh 1Bh 1Bh 51h
  Erase to End of Line                   1Bh 54h
  Delete Line                            1Bh 52h
  Insert Line                            1Bh 45h
  Does your terminal use last character
    on screen as a scroll command?       YES

Most Commodore printers require installation as a Standard Printer with NO
Communications Protocol and Primary list device as the Printer Driver.

Note: The h against the numbers above indicate that they are hexadecimal
numbers (using base 16 instead of the decimal base 10).




SECTION 12

12. Files, Disks, and Drives in CP/M 3.0


12.1 WHAT IS A FILE?

12.2 CREATING A FILE

12.3 NAMING A FILE

  12.3.1 File Specification
    12.3.1.1 Drive Specifier
    12.3.1.2 Filename
    12.3.1.3 Filetype
    12.3.1.4 Password
    12.3.1.5 Sample File Specification
  12.3.4 User Number
  12.3.5 Using Wildcard Characters to Access More Than One File
  12.3.6 Reserved Characters
         Table 12-1. CP/M Reserved Characters.
  12.3.7 Reserved Filetypes
         Table 12-2. CP/M 3.0 Reserved Filetypes.



12.1 WHAT IS A FILE?

One of CP/M's most important tasks is to access and maintain files on your
disks. Files in CP/M are fundamentally the same as in C128 or C64 modes -
that is, they are collections of information. However, CP/M handles files
somewhat differently than do C128 and C64 modes. This section defines the
two types of files used in CP/M, tells how to create, name, and access a
file, and describes how files are stored on your CP/M disks.

As noted above, a CP/M 3.0 file is a collection of information. Every file
must have a unique name by which CP/M identifies the file. A directory is
also stored on each disk. The directory contains a list of the filenames
stored on that disk and the locations of each file on the disk.

There are two kinds of CP/M files: program (command) files, and data files.
A program file contains a series of instructions that the computer follows
step-by-step to achieve some desired result. A data file is usually a col-
lection of related information (e.g. a list of names and addresses, the
inventory of a store, the accounting records of a business, the the text
of a document).


12.2 CREATING A FILE

There are several ways to create a CP/M file. One way is to use a text edi-
tor. The CP/M text editor ED is used to create and name a file. You can
also create a file by copying an existing file to a new location; you can
rename the file in the process. Under CP/M you can use the PIP command to
copy and rename files. Finally, some programs (such as MAC, a CP/M machine
language program) create output files as they process input files.

The ED and PIP commands are summarized in Section 14, together with other
commonly used CP/M commands. Details on these and all other CP/M 3.0 com-
mands may be found in the CP/M Plus User's Guide, which you can obtain by
following the instructions on the coupon enclosed in the box in which the
C128 computer is supplied.


12.3 NAMING A FILE


12.3.1 File Specification

CP/M identifies every file by a unique file specification. A file  specifi-
cation can have four parts: a drive specifier, a filename, a filetype, and
a password. The only mandatory part is the filename.


12.3.1.1 Drive Specifier

The drive specifier is a single letter (A-P) followed by a colon. Each disk
drive in your system is assigned a letter. When you include a drive speci-
fier as part of the file specification, you are telling CP/M to look for
the file on the disk currently in the specified drive. For example, if you
enter:

     B:MYFILE {return}

CP/M looks in drive B for the file MYFILE. If you omit the drive specifier,
CP/M 3.0 looks for the file in the default drive (usually A).


12.3.1.2 Filename

A filename can be from one to eight characters long, such as:

     MYFILE

A file specification can consist simply of a filename. When you make up a
filename, try to let the name tell you something about what the file con-
tains. For example, if you have a list of customer names for your business,
you could name the file:

     CUSTOMER

so that the name gives you some idea of what is in the file.


12.3.1.3 Filetype

To help you identify files belonging to the same category, CP/M allows you
to add an optional one- to three-character extension, called filetype, to
the filename. When you add a filetype to the filename, separate the file-
type from the filename with a period.

Try to use letters that tell something about the file's category. For
example, you could add the following filetype to the file that contains a
list of customer names:

     CUSTOMER.NAM

When CP/M displays file specifications, it adds blanks to short filenames
so that you can compare filetypes quickly. The program files that CP/M
loads into memory from a disk have the filetype COM. DO NOT use this file-
type in your own file specifications.


12.3.1.4 Password

In the Commodore 128's CP/M 3.0 you can include a password as part of the
file specification. The password can be from one to eight characters. If
you include a password, separate if from the filetype (or filename, if no
filetype is included) with a semicolon, as follows:

     CUSTOMER.NAM;ACCOUNT

A password is optional. However, if a file has been protected with a pass-
word, you MUST enter the password as part of the file specification to
access the file.


12.3.1.5 Sample File Specification

A file specification containing all four possible elements consists of a
drive specification, a primary filename, a filetype, and a password, all
separated by the appropriate characters or symbols as in the following
example:

     A:DOCUMENT.LAW;SUSAN {return}


12.3.4 User Number

CP/M 3.0 further identifies all files by assigning each one a user number
which ranges from 0 to 15. CP/M 3.0 assigns the user number to a file when
the file is created. User numbers allow you to separate your files into 16
file groups.

The user number always precedes the drive identifier except for user 0,
which is the default user number and is not displayed in the prompt. Here
are some examples of user numbers and their meanings.

     4A> User number 4, drive A
     A>  User number 0, drive A
     2B> User number 2, drive B

You can use the built-in command USER to change the current user number
like this:

     A>USER 3 {return}
     3A>

You can change both the user number and the drive by entering the new user
number and drive specifier together at the system prompt:

     A>3B: {return}
     3B>

Most commands can access only those files that have the current user num-
ber. However, if a file resides in user 0 and is marked with a special file
attribute, the file can be accessed from any user number.


12.3.5 Using Wildcard Characters to Access More Than One File

Certain CP/M 3.0 built-in and transient commands can select and process
several files when special wildcard characters are included in the filename
or filetype. A wildcard is a character that can be used in place of some
other characters. CP/M 3.0 uses the asterisk (*) and the question mark (?)
as wildcards. For instance, if you use a {?} as the third character in a
filename, your are telling CP/M to let the {?} stand for any character that
may be encountered in that position. Similarly, an {*} tells CP/M to fill
the filename with {?} question marks as indenticated.

A file specification containing wildcards is called an ambiguous filespec
and can refer to more than one file, because it gives CP/M 3.0 a pattern to
match. CP/M 3.0 searches the disk directory and selects any file whose
filename or filetype matches the pattern. For example, if you type:

     ?????TAX.LIB {return}

then CP/M 3.0 selects all files whose filename ended in TAX and whose file-
type is LIB.


12.3.6 Reserved Characters

The characters in Table 12-1 have special meaning in CP/M 3.0, so do not use
these characters in file specifications except as indicated.


Table 12-1. CP/M Reserved Characters.

Character

< $ , ! | > [ ]   file specification delimiters
{tab} {space}       ,,
{carriage return}   ,,

:                 drive delimiter in file specification

.                 filetype delimiter in file specification

;                 password delimiter in file specification

* ?               wildcard characters in an ambiguous file specification

< > & ! | \ + -   option list delimiters

[ ]               option list delimiters for global and local options

( )               delimiters for multiple modifiers inside square brackets
                  for options that have modifiers

/ $               option delimiters in a command line

;                 comment delimiter at the beginning of a command line


12.3.7 Reserved Filetypes

CP/M 3.0 has already established several file groups. Table 12-2 lists some
of their filetypes with a short description of each.


Table 12-2. CP/M 3.0 Reserved Filetypes.

Filetype  Meaning

ASM       Assembler source file

BAS       BASIC source program

COM       8080, 8085, Z80 or equivalent machine language program

HEX       Output file from MAC (used by HEXCOM)

HLP       HELP message file

$$$       Temporary file

PRN       Print file from MAC or RMAC

REL       Output file from RMAC (used by LINK)

SUB       List of commands to be executed by SUBMIT

SYM       Symbol file from MAC, RMAC or LINK

SYS       System file




SECTION 13

13. Using the Console and Printer in CP/M 3.0


13.1 CONTROLLING CONSOLE OUTPUT

13.2 CONTROLLING PRINTER OUTPUT

13.3 CONSOLE LINE EDITING

13.4 USING CONTROL CHARACTERS FOR LINE EDITING
     Table 13-1. Banked CP/M 3.0 Line Editing Control Characters.




This section describes how CP/M 3.0 communicates with your console and
printer. It tells how to start and stop console and printer output, and
edit commands you enter at your console.


13.1 CONTROLLING CONSOLE OUTPUT

Sometimes CP/M 3.0 displays information on your screen too quickly for you
to read it. To ask the system to wait while you read the display, hold down
the {ctrl} key and press {s}. A CTRL-S keystroke sequence causes the dis-
play to pause. When you are ready, press CTRL-Q to resume the display.

Pressing the {no scroll} key will also pause the system and place a pause
window on the status line at the bottom of the screen (line 25). To resume
the display, press {no scroll} again. If you press any key besides CTRL-Q
or {no scroll} during a display pause, CP/M 3.0 sounds the console bell.

Some CP/M 3.0 utilities (like DIR and TYPE) support automatic paging at the
console. This means that if the program's output is longer than the screen
can display at one time, the display automatically halts when the screen is
filled. When this occurs, CP/M 3.0 prompts you to press {return} to con-
tinue. This option can be turned on or off using the SETDEF command.


13.2 CONTROLLING PRINTER OUTPUT

You can also use a control command to echo (that is, display) console out-
put to the printer. To start printer echo, press CTRL-P. A beep occurs to
tell you that echo is on. To stop, press CTRL-P again. (There is no beep at
this point.) While echo is in effect, any characters that appear on your
screen are listed at your printer.

You can use printer echo with a DIR command to make a list of files stored
on a floppy disk. You can also use CTRL-P with CRTL-S and CTRL-Q to make a
hard copy of part of a file. Use a TYPE command to start a display of the
file at the console. When the display reaches the part you need to print,
press CTRL-S to stop the display, CTRL-P to enable printer echo, and then
CTRL-Q to resume the display and start printing. You can use another
CTRL-S, CTRL-P, CTRL-Q sequence to terminate printer echo.


13.3 CONSOLE LINE EDITING

As noted previously, you can correct simple typing errors by using the
{inst/del} key or CTRL-H. CP/M 3.0 also supports additional line editing
functions that you perform with control characters. You can use the con-
trol characters to edit command lines or input lines to most programs.


13.4 USING CONTROL CHARACTERS FOR LINE EDITING

Using the line editing control characters listed in Table 13-1, you can
move the cursor left and right to insert and delete characters in the mid-
dle of a command line. In this way you do not have to retype everything to
the right of your correction.

In the following example, the user mistypes PIP, and CP/M 3.0 returns an
error message. The user recalls the erroneous command line by pressing
CTRL-W and corrects the error.

     A>POP A:=B:*.*  (PIP mistyped)
     POP?

     A>POP A:=B:*.*  (CTRL-W recalls the line)

     A>POP A:=B:*.*  (CTRL-B moves the cursor to beginning of line)

     A>POP A:=B:*.*  (CTRL-F moves cursor to right)

     A>PP A:=B:*.*   (CTRL-G deletes error)

     A>PIP A:=B:*.*  (type I corrects the command name)

After the command line is corrected, the user can press {return} even
though the cursor is in the middle of the line. A {return} keystroke, (or
one of the equivalent control characters) not only executes the command,
but also stores the command in a buffer so that you can press CTRL-W to
recall it for editing or re-execution.

When you insert a character in the middle of a line, characters to the
right of the cursor move to the right. If the line becomes longer than your
screen is wide, characters disappear off the right side of the screen.
These characters are not lost. They reappear if you delete characters from
the line or if you press CTRL-E when the cursor is in the middle of the
line. CTRL-E moves all characters to the right of the cursor to the next
line on the screen.

Table 13-1 gives a complete list of line editing control characters for the
CP/M 3.0 system on the Commodore 128.


Table 13-1. Banked CP/M 3.0 Line Editing Control Characters.

Character  Meaning

CTRL-A     Moves the cursor one character to the left.

CTRL-B     Moves the cursor to the beginning of the command line without
           having any effect on the contents of the line. If the cursor is
           at the beginning, CTRL-B moves it to the end of the line.

CTRL-E     Forces a physical carriage return but does not send the command
           line to CP/M 3.0.
           Moves the cursor to the beginning of the next line without era-
           sing the previous input.

CTRL-F     Moves the cursor one character to the right.

CTRL-G     Deletes the character above the cursor. The cursor does not
           move. Characters to the right of the cursor move left one
           position.

CTRL-H     Deletes the character to the left of the cursor and moves the
           cursor left one character position. Characters to the right of
           the cursor move left one position.

CTRL-I     Moves the cursor to the next tab stop. Tab stops are automati-
           cally set at each eighth column. Has the same effect as pressing
           the {tab} key.

CTRL-J     Sends the command line to CP/M 3.0 and returns the cursor to the
           beginning of a new line. Has the same effect as a {return} or a
           CTRL-M keystroke.

CTRL-K     Deletes from the cursor to the end of the line.

CTRL-M     Sends the command line to CP/M 3.0 and returns the cursor to the
           beginning of a new line. Has the same effect as a {return} or a
           CTRL-J keystroke.

CTRL-R     Retypes the command line. Place a # character at the current
           cursor location, moves the cursor to the next line, and retypes
           any partial command you typed so far.

CTRL-U     Discards all the characters in the command line, places a {#}
           character at the current cursor position, and moves the cursor
           to the next line. However, you can use CTRL-W to recall any
           characters that were to the left of the cursor when you pressed
           CTRL-U.

CTRL-W     Recalls and displays previously entered command line both at the
           operating system level and within executing programs, if the
           CTRL-W is the first character entered after the prompt. CTRL-J,
           CTRL-M, CTRL-U, and {return} define the command line you can
           recall. If the command line contains characters, CTRL-W moves
           the cursor to the end of the command line. If you press
           {return}, CP/M 3.0 executes the recalled command.

CTRL-X     Discards all the characters to the left of the cursor and moves
           the cursor to the beginning of the current line. CTRL-X saves
           any characters to the right of the cursor.




SECTION 14

14. Summary of Major CP/M 3.0 Commands



14.1 THE TWO TYPES OF CP/M 3.0 COMMANDS

14.2 BUILT-IN COMMANDS
     Table 14-1. Built-in Commands.

14.3 TRANSIENT UTILITY COMMANDS
     Table 14-2. Transient Utility Commands.

14.4 REDIRECTING INPUT AND OUTPUT
     Figure 14-1. PUT Command Example.

14.5 ASSIGNING LOGICAL DEVICES
     Table 14-3. CP/M 3.0 Logical Devices.

14.6 FINDING PROGRAM FILES

14.7 EXECUTING MULTIPLE COMMANDS

14.8 TERMINATING PROGRAMS

14.9 GETTING HELP




As noted in section 11, a CP/M 3.0 command line consists of a command key-
word, an optional command tail and a {return} keystroke. This section
describes the two kinds of commands the command keyword can identify, and
summarizes individual commands and their functions. The section also gives
examples of the use of some of the more commonly used commands. In
addition, the section explains the concept of logical and physical devices
under CP/M 3.0. This section then tells how CP/M 3.0 searches for a program
file on a disk, tells how to execute multiple commands, and how to reset
the disk system. Finally, the section explains how to use the HELP command
to get information on various CP/M topics including command formats and
usage, right at the keyboard.


14.1 THE TWO TYPES OF CP/M 3.0 COMMANDS

There are two types of commands on CP/M 3.0:

     * Built-in commands - which identify programs in memory
     * Transient utility commands - which identify program files on a disk

CP/M 3.0 has six built-in commands and over 20 transient utility commands.
You can add utilities to your system by purchasing various CP/M 3.0-
compatible application programs. If you are an experienced programmer, you
can also write your own utilities that operate with CP/M 3.0.


14.2 BUILT-IN COMMANDS

Built-in commands are part of CP/M 3.0 that are always available for your
use, regardless of which disk your have in which drive. Built-in commands
are entered in the computer's memory when CP/M 3.0 is loaded, and are,
therefore, executed more quickly than the transient utilities. Table 14-1
lists the Commodore 128 CP/M 3.0 built-in commands.

Some built-in commands have options that require support from a related
transient utility. The related transient utility command has the same name
as the built-in command and has a filetype of COM.

                     Table 14-1. Built-in Commands.

Command  Function

DIR      Displays filenames of all files in the directory except those
         marked with the SYS attribute.

DIRSYS   Displays filenames of file marked with the SYS (system) attribute
         in the directory.

ERASE    Erases a filename from the disk directory and releases the storage
         space occupied by the file.

RENAME   Renames a disk file.

TYPE     Displays contents of an ASCII (TEXT) file at your screen.

USER     Changes to a different user number.


14.3 TRANSIENT UTILITY COMMANDS

The CP/M 3.0 transient utilities are listed in Table 14-2. When you enter a
command keyword that identifies a transient utility, CP/M 3.0 loads the
program file from the disk and passes to that file any filenames, data, or
parameters you entered in the command tail.

DIR, RENAME and TYPE are built-in commands which have optional transient
extensions.


               Table 14-2. Transient Utility Commands.

DATE     Sets or displays the date and time.

DEVICE   Assigns logical CP/M devices to one or more physical devices,
         changes device driver protocol and baud rates, or sets console
         screen size.

DIR      Displays directory with files and their characteristics.

DUMP     Displays a file in ASCII and hexadecimal format.

ED       Creates and alters ASCII files.

ERASE    Used for wildcard erase.

FORMAT   Formats a CP/M disk. Clears data from previous used disks.

GENCOM   Creates a special COM file with attached RSX file.

GET      Temporarily gets console input from a disk file rather than the
         keyboard.

HELP     Displays information on how to use CP/M 3.0 commands.

INITDIR  Initializes a disk directory to allow time and date stamping.

KEYFIG   Allows alteration of the definition of the keyboard keys.

PATCH    Displays or installs patches to the CP/M system.

PIP      Copies files and combines files.

PUT      Temporarily directs printer or console output to a disk file.

RENAME   Changes the name of a file, or a group of files using wildcard
         characters.

SAVE     Copies the contents of memory to a file.

SET      Sets file options including disk labels, file attributes, type of
         time and date stamping and password protection.

SETDEF   Sets system options including the drive search chain.

SHOW     Displays disk and drive statistics.

SUBMIT   Automatically executes multiple commands.

TYPE     Displays contents of text file (or group of files, if wildcard
         characters are used) on screen (and printer if desired).


14.4 REDIRECTING INPUT AND OUTPUT

CP/M 3.0's PUT Command allows you to redirect console or printer output to
a disk file. You can use a GET command to make CP/M 3.0 or a utility pro-
gram take console input from a disk file. The following examples illustrate
some of the capabilities offered by GET and PUT.

You can use a PUT command to direct console output to a disk file as well
as to the console. With PUT, you can create a disk file containing a
directory of all files on that disk, as shown in Figure 14-1.

A>PUT CONSOLE OUTPUT TO FILE DIR.PRN
PUTTING CONSOLE OUTPUT TO FILE: DIR.PRN

A>DIR
A: FILENAME TEX : FRONT    TEX : FRONT    BAK : ONE      BAK : THREE    TEX
A: FOUR     TEX : ONE      TEX : LINEDIT  TEX : EXAMP1   TXT : TWO      BAK
A: TWO      TEX : THREE    BAK : EXAMP2   TXT

A>TYPE DIR.PRN
A: FILENAME TEX : FRONT    TEX : FRONT    BAK : ONE      BAK : THREE    TEX
A: FOUR     TEX : ONE      TEX : LINEDIT  TEX : EXAMP1   TXT : TWO      BAK
A: TWO      TEX : THREE    BAK : EXAMP2   TXT

                    Figure 14-1. PUT Command Example.

A GET command can direct CP/M 3.0 or a program to read console input from a
disk file instead of from the keyboard. If the file is to be read by CP/M
3.0, it must contain standard CP/M 3.0 command lines. If the file is to be
read by a utility program, it must contain input appropriate for that pro-
gram. A file can contain both CP/M 3.0 command lines and program input if
it also includes a command to start a program.


14.5 ASSIGNING LOGICAL DEVICES

The minimal Commodore 128 CP/M 3.0 hardware includes a console consisting
of a keyboard and screen display and a 1571 disk drive. You may want to add
another device to your system, such as a printer or a modem. To help keep
track of these physical different input and output devices, Table 14-3
gives the names of CP/M 3.0 logical devices. It also shows the physical
devices assigned to these logical devices in the Commodore 128 CP/M 3.0
system.

                  Table 14-3. CP/M 3.0 Logical Devices.

     Logical                                  Physical Device
     Device Name       Device Type            Assigment

     CONIN:            Console input          Keyboard

     CONOUT:           Console output         80-column Screen

     AUXIN:            Auxiliary input        Null

     AUXOUT:           Auxiliary output       Null

     LST:              List output            PTR1 or PTR2


You can change these assigments with a DEVICE command. For example, you
can, assign AUXIN and AUXOUT to a modem so that your computer can use tele-
phone lines to communicate with other computer users, with information ser-
vice like Compunet and View Data Systems.


14.6 FINDING PROGRAM FILES

If a command keyword identifies a utility, CP/M 3.0 looks for that program
file on the default or specified drive. It looks under the current user
number, and then under user number 0 for the same file marked with the SYS
attribute. At any point in the search process, CP/M 3.0 stops the search if
it finds the program file. CP/M 3.0 then loads the program into memory and
executes it. When the program terminates, CP/M 3.0 displays the system
prompt and waits for your next command. However, if CP/M 3.0 does not find
the command file, it repeats the command line followed by a question mark,
and waits for your next command.


14.7 EXECUTING MULTIPLE COMMANDS

In the examples so far, CP/M 3.0 executed only one command at a time. CP/M
3.0 can also execute a sequence of commands. You can enter a sequence of
commands at the system prompt, or you can put a frequently needed sequence
of commands in a disk file, using the filetype of SUB. Once you have stored
the sequence in a disk file, you can execute the sequence whenever you need
to with a SUBMIT command.


14.8 TERMINATING PROGRAMS

You can use the two keystroke command CTRL-C to terminate program execution
or reset the  disk system. To enter a CTRL-C command, hold down the {ctrl}
key and press {c}.

Most application programs that run under CP/M and most CP/M transient uti-
lities can be terminated by a CTRL-C. However, if you try to terminate a
program while it is sending a display to the screen, you may need to press
a CTRL-S to halt the display before you enter CTRL-C.


14.9 GETTING HELP

CP/M 3.0 includes a transient utility command called HELP that displays a
summary of the format and use for the most common CP/M commands. To access
HELP, simply enter the command:

     A>HELP {return}

You can press the {help} key instead of typing the word HELP and pressing
the {return} key.

The list of available topics is then displayed, like this:

Topics available:

   COMMANDS  CNTRLCHARS  DATE     DEVICE    DIR
   DUMP      ED          ERASE    FILESPEC  GENCOM  GET
   HELP      HEXCOM      INITDIR  LIB       LINK    MAC
   PATCH     PIP (COPY)  PUT      RENAME    RMAC    SAVE
   SET       SETDEF      SHOW     SID       SUBMIT  TYPE
   USER      XREF

Suppose you type:

     HELP>PIP {return}

CP/M then displays the following information:

     PIP (COPY)

     Syntax:

     DESTINATION SOURCE


     PIP d: Gn filespec [Gn] =filespec [o],... d: [o]


Explanation:

The file copy program PIP copies files, combines files, and transfers files
between disks, printers, consoles, or other devices attatched to your
computer. The first filespec is the destination. The second filespec is the
source. Use two or more source filespecs separated by commas to combine two
or more source files into one file. [o] is any combination of available
options. The [Gn] option in the destination filespec tells PIP to copy your
file to that user number.

PIP with no command tail displays an * prompt and awaits your series of
commands, entered and processed one line at a time. The source or
destination can be any CP/M 3.0 logical device.

The HELP facility provides information like this on all CP/M 3.0 built-in
and transient utility commands. If you want information on a specific area,
you can type HELP subject after the system prompt, where the subject is a
command tail describing the subject you are interested in. For example:

     A>HELP PIP
     A>HELP DIRSYS

You can refer to HELP any time you need information on a specific command.
Or you can just browse through HELP to broaden your knowledge of CP/M 3.0.




SECTION 15

15. Commodore Enhancements to CP/M 3.0


15.1 KEYBOARD ENHANCEMENTS

  15.1.1 Defining a Key
  15.1.2 Defining a String
  15.1.3 Using ALT Mode

15.2 SCREEN ENHANCEMENTS




15.1 KEYBOARD ENHANCEMENTS

Commodore has added a number of enhancements to CP/M 3.0. These enhance-
ments tailor the capabilities of the Commodore 128 to those of CP/M 3.0.
This section describes these enhancements.

Any key on the keyboard can be defined to generate a code or function,
except the following keys:

     {left shift} key
     {right shift} key
     {C=} key
     {ctrl} key
     {restore} key
     {40/80 display} key
     {caps lock} key

In defining a key, the keyboard recognizes the following special functions.
To indicate these functions, hold down the {ctrl} key and the {right shift}
key and press the desired function key simultaneously.

        Key                          Function

  {crsr left} key     Defines key
  {crsr right} key    Defines string (points to function keys)
  {alt} key           Toggles key filter


15.1.1 Defining a Key

A user can define the code that a key can produce. Each key has four pos-
sible definitions: Normal, Alpha Shift, Shift and Control. The Alpha Shift
is toggle on/off by pressing the {C=} key. After entering this mode a small
box appears on the bottom of the screen. The first key that is pressed is
the key to be defined. The current HEX (hexadecimal) value assigned to this
key is displayed and the user can then type the new HEX code for the key,
or abort by typing a non-HEX key. The following is a definition of the
codes that can be assigned to a key. (In ALT mode, codes are returned to
the application; see "Using ALT Mode" below, in paragraph 15.1.3)

     Code               Function

  00h         Null (same as not pressing a key)
  01h to 7Fh  Normal ASCII codes
  80h to 9Fh  String assigned
  A0h to AFh  80 column character color
  B0h to BFh  80 column background color
  C0h to CFh  40 column character color
  D0h to DFh  40 column background color
  E0h to EFh  40 column border color
  F0h         Toggle disk status on/off
  F1h         System Pause
  F2h         (undefined)
  F3h         40 column screen window right
  F4h         40 column screen window left
  F5h to FFh  (undefined)


15.1.2 Defining a String

This function allows the user to assign more than one key code to a single
key. Any key that is typed in this mode is placed in the string. The user
can see the result of typing in a long box at the bottom of the screen.

Note: Some keys may not display what they are. To provide the user with
control over the process of entering data, the following five special key
functions are available. To access these functions, press the {ctrl} and
{right shift} keys and the desired function keys.

        Key                       Function

  {return}                Complete string definition
  {+} (on main keyboard)  Insert space into string
  {-} (on main keyboard)  Delete cursor character
  {left arrow}            Cursor left
  {right arrow}           Cursor right


15.1.3 Using ALT Mode

ALT mode is a toggle function (that is, it can be switched between ON and
OFF). The default value is OFF. This function allows the user to send 8-bit
codes to an application.


15.2 SCREEN ENHANCEMENTS

The screen in CP/M 3.0 emulates an ADM31 terminal. The following screen
functions emulate ADM 3A operation, which is a subset of ADM31 operation.

     CTRL-G    Sound Bell
     CTRL-H    Cursor left
     CTRL-J    Cursor down
     CTRL-K    Cursor up
     CTRL-L    Cursor right
     CTRL-M    Move cursor to start of current line (CR)
     CTRL-Z    Home and clear screen
     ESC = RC  Cursor position where R is the row location
               (with values from space to 8) and C is the column location
               (next values from space to 0), referenced to the status
               line.

Additional functions in ADM31 mode include:

     ESC T}
     ESC t}    Clear to end of line
     ESC Y}
     ESC y}    Clear to end of screen
     ESC :}
     ESC *}    Home and clear screen (including the status line)
     ESC Q     Insert character
     ESC W     Delete character
     ESC E     Insert line
     ESC R     Delete line

* {esc} {esc} {esc} [color#] sets a screen color from a table of 16 pos-
sible color entries. The [color#] is set as follows:

     20h to 2Fh  character color
     30h to 3Fh  background color
     40h to 4Fh  border color (40 column only)

The visual effects associated with following functions are visible only in
80-column screen format:

     ESC >     Half intensity

     ESC <     Full intensity

     ESC G4    Reverse video ON

     * ESC G3  Turn underline ON

     ESC G2    Blink ON

     * ESC G1  Select the alternate character set

     ESC G0    All ESC G attributes OFF

* Note: This is NOT a normal ADM31 sequence.


* * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * *


The sections in this chapter provide a summary of the structure and wide-
ranging capabilities of CP/M 3.0. Detailed information on any facet of CP/M
is given in the Digital Research, Inc. book, CP/M Plus User's Guide. To ob-
tain a copy of this, refer to the coupon enclosed in the box in which the
Commodore 128 is supplied.





                                   CHAPTER

                                      5

                                  BASIC 7.0
                                ENCYCLOPAEDIA




SECTION 16

16. Introduction




16.1 ORGANIZATION OF ENCYCLOPAEDIA

16.2 COMMAND AND STATEMENT FORMAT

16.3 GRAPHIC AND SOUND COMMAND FORMAT

16.4 DISK COMMAND FORMAT




16.1 ORGANIZATION OF ENCYCLOPAEDIA

This chapter lists BASIC 7.0 language elements and describe how to use
those elements. It gives a complete list of the rules (syntax) of Commodore
128 BASIC 7.0, along with a concise description of each.

Basic 7.0 includes all the elements of BASIC 2.0. The new commands, state-
ments, functions and operators provided in Basic 7.0 are underlined and
commands which have been modified are printed in plain and underlined text.

The different types of BASIC operations are listed in individual sections,
as follows:

     1. COMMANDS AND STATEMENTS: the commands used to edit, store and erase
        programs; and the BASIC program statements used in the numbered
        lines of a program.

     2. FUNCTIONS: the string, numeric and print functions.

     3. VARIABLES AND OPERATORS: the different types of variables, legal
        names, arithmetic operators and logical operators.

     4. RESERVED WORDS, SYMBOLS AND ABBREVIATIONS: the words, symbols and
        abbreviations reserved for use in the BASIC 7.0 language, and which
        cannot be used for any other purpose.


16.2 COMMAND AND STATEMENT FORMAT

+-------------------------------------------------------------------------+
| command name ->       AUTO                                              |
|                       ----                                              |
|                                                                         |
| brief description ->  Enable/disable automatic line numbering           |
| command format ->          AUTO [line#]                                 |
|                                                                         |
| Discussion of         This command turns on the automatic line-number-  |
| format and use ->     ing feature. This eases the job of entering pro-  |
|                       grams, by automatically typing the line numbers   |
|                       for the user. As each program line is entered by  |
|                       pressing {return}, the next line number is prin-  |
|                       ted on the screen, and the cursor is positioned   |
|                       two spaces to the right of the line number. The   |
|                       line number argument refers to the desired incre- |
|                       ment between line numbers. AUTO without an argu-  |
|                       ment turns off the auto line numbering, as does   |
|                       RUN. This statement can be used only indirect     |
|                       mode (outside of a program).                      |
|                                                                         |
|                            EXAMPLES:                                    |
|                            AUTO 10  Automatically numbers program lines |
|                                     in increments of 10.                |
| Example(s) ->              AUTO 50  Automatically numbers lines in      |
|                                     increments of 50.                   |
|                            AUTO     Turns off automatic line numbering. |
+-------------------------------------------------------------------------+
The boldface line that defines the format consists of the following
elements:

     DLOAD "program name" [D0,U8]
       ^             ^         ^
       |             |         |   additional arguments
     keyword      argument     +--  (possibly optional)

The parts of the command or statement that must be typed exactly are shown
in capital letters. Words the user supplies, such as the name of a program,
are not capitalized.

When quote marks (" ") appear (usually around a program name or file name),
the user should include them in the appropriate place, according to the
format example.

KEYWORDS, also called reserved words, appear in upper case letters. Key-
words may be typed using the full word or the approved abbreviation (a full
list is given in Appendix K). The keyword or abbreviation must be entered
correctly or an error will result. The BASIC  and DOS error messages are
defined in Appendices A and B, respectively.

Keywords are words that are part of the BASIC language. The are the central
part of a command or statement, and the tell the computer what kind of
action to take. These words cannot be used as variable names. A complete
list of reserved words is given in Section 20.

ARGUMENTS, also called parameters, appear in lower case letters. Arguments
complement keywords by providing specific information to the command or
statement. For example, the keyword LOAD tells the computer to load a pro-
gram while the argument tells the computer which specific program to load.
A second argument specifies from which drive to load the program. Arguments
include filenames, variables, line numbers, etc.

SQUARE BRACKETS [ ] show optional arguments. The user selects any or none
of the arguments listed, depending on requirements. The user should not
type the SQUARE BRACKETS, which are only there to describe the format.

ANGLE BRACKETS < > indicate the user MUST choose one of the arguments lis-
ted. The user should not type the ANGLE BRACKETS, which are only there to
describe the format.

A VERTICAL BAR | seperates items in a list of arguments when the choices
are limited to those arguments listed. When the vertical bar appears in a
list enclosed by SQUARE BRACKETS, the choices are limited to the items in
the list, but the user still has the option not to use any arguments.

ELIPSIS ...  a sequence of three dots means an option or argument can be
repeated more than once. The user should not type the ELIPSIS, which is
only there to describe the format.

QUOTATION MARKS " " enclose character strings, filenames and other expres-
sions. When arguments are enclosed in quotation marks, the quotation marks
must be included in the command or statement. Quotations marks are not con-
ventions used to describe formats; they are required parts of a command or
statement.

PARENTHESES ( ) When arguments are enclosed in parentheses, they must be
included in the command or statement. Parentheses are not conventions used
to describe formats; they are required parts of a command or statement.

VARIABLE refers to any valid BASIC variable name, such as X, A$, T%, etc.

EXPRESSION refers to any valid BASIC expression, such as A+B+2, 5*(X+3),
etc.

COMMAS (,) COLONS (:) and SEMICOLONS (;) These MUST be included, they are
required parts of the command or statement.


16.3 GRAPHIC AND SOUND COMMAND FORMAT

Optional parameters in Graphics and Sound commands are represented like
this:

     [,parameter]

When parameters are omitted the comma MUST be included, this is because the
parameters are position dependent. You must not, however, include commas
after the last specified parameter.

EXAMPLE:

     ENVELOPE n [,atk] [,dec] [,sus] [,rel] [,wf] [,pw]

To alter just the rel parameter, use:

     ENVELOPE n,,,,rel

The first three commas mark the positions of atk, dec, sus and the fourth
is the comma for rel. The commas for wf and pw must not be entered.

In  the GRAPHICS commands whenever there is a coordinate specified by (X,Y)
it is possible to replace this with a vector (X;Y). In this case:

     X is the distance (scaled)
     Y is the angle in degrees (0 = up; 90 = right etc.)

For example:

     LOCATE 160,100
     DRAW TO 40;45

will draw a line at 45 degrees of length 40.


16.4 DISK COMMAND FORMAT

Optional parameters in disk commands are shown thus:

     [,parameter]

The comma is not required if the parameter is the first after the command
itself. If other parameters which require commas are omitted the commas
should be omitted too.

EXAMPLE:

     DIRECTORY [Ddrive][<ON | ,>Udevice number] [,wildcard]

would in full produce:

     DIRECTORY D0 ON U8,"AB*"

To specify only the wild card, no comma is required, i.e.

     DIRECTORY "AB*"

Whenever variables are used in disk commands the MUST be enclosed in paren-
theses ( ). For example:

     DIRECTORY D(DV),(A$)



SECTION 17

17. Basic Commands and Statements




17.1 APPEND
     ------

Append new data to the end of a sequential file.

APPEND #logical file number, "filename" [,Ddrive number]
[<ON | ,> Udevice]

This command opens the file having the specified filename, and positions
the pointer at the end of the file. Subsequent PRINT# (write) statements
will cause data to be appended to the end of this file. Default values for
drive number and device number are 0 and 8 respectively.

Variables or Expressions used as filenames must be enclosed within paren-
theses.


EXAMPLES:

     APPEND#8,"MYFILE"

OPEN logical file 8 called "MYFILE" for appending with subsequent PRINT#
statements.

     APPEND#7,(A$),D0,U9

OPEN logical file named by the variable A$ on drive 0, device number 9 and
prepare to APPEND.


17.2 AUTO
     ----

Enable/disable automatic line numbering.

AUTO [line#]

This command turns on the automatic line-numbering feature. This eases the
job of entering programs, by automatically typing the line numbers for the
user. As each program line is entered by pressing {return}, the next line
number is printed on the screen, and the cursor is positioned on the second
space to the right of the line number. The line number argument refers to
the desired increment between line numbers. AUTO without an argument turns
off the auto line numbering, as does RUN. This statement can be used only
in direct mode (outside of a program).


EXAMPLES:

     AUTO 10   Automatically numbers program lines in increments of 10.

     AUTO 50   Automatically numbers lines in increments of 50.

     AUTO      Turns off automatic line numbering.


17.3 BACKUP
     ------

Copy the entire contents from one disk to another on a dual disk drive.

BACKUP source Ddrive number TO destination Ddrive number
[<ON | ,>Udevice]

This command copies all the data from the source diskette onto the desti-
nation diskette using a dual diskdrive. With the BACKUP command, a new dis-
kette can be used without first formatting it. This is because the BACKUP
command copies all the information on the diskette, including the format.
Because of this, the BACKUP command destroys any information already on the
destination disk. Therefore, when backing up onto a previously used disket-
te, make sure it contains no programs you mean to keep. As a precaution the
computer asks "ARE YOU SURE?" before it starts the operation. Press the {y}
key to perform the BACKUP, or any other key to stop it. You should always
create a backup of all your disks, in case the original diskette is lost or
damaged. Also see the COPY command in paragraph 17.21. The default device
number is unit 8.

NOTE: This command can be used only with a dual-disk drive. It will not
allow you to make copies of protected disks (most prepackaged software).


EXAMPLES:

     BACKUP D0 TO D1

Copies all data from the disk in drive 0 to the disk in drive 1, in dual
disk drive unit 8.

     BACKUP DO TO D1 ON U9

Copies all data from drive 0 to drive 1, in disk drive unit 9.


17.4 BANK
     ----

Select one of the 16 banks, numbered 0-15.

BANK bank number

This statement specifies the bank number and corresponding memory configu-
ration for the Commodore 128 memory. The default bank is 15. Here is a
table of available BANK configurations in the Commodore 128 memory:

BANK   CONFIGURATION

0      RAM(0) only
1      RAM(1) only
2      RAM(2) only*
3      RAM(3) only*
4      Internal ROM, RAM(0), I/O
5      Internal ROM, RAM(1), I/O
6      Internal ROM, RAM(2), I/O*
7      Internal ROM, RAM(3), I/O*
8      External ROM, RAM(0), I/O
9      External ROM, RAM(1), I/O
10     External ROM, RAM(2), I/O*
11     External ROM, RAM(3), I/O*
12     Kernal and Internal ROM(LOW), RAM(0), I/O
13     Kernal and External ROM(LOW), RAM(0), I/O
14     Kernal and BASIC ROM, RAM(0), Character ROM
15     Kernal and BASIC ROM, RAM(0), I/O

* For use on extended C128s with a larger internal memory eg: 256K. In un-
expanded machines there is no RAM in these BANKs and 2 echoes 0 and 3
echoes 1.

To access a particular bank, type BANK n (n=0-15) and then use PEEK/POKE or
SYS. From within the monitor, precede the four-digit hexadecimal number of
the address range you are viewing with a hexadecimal digit (0-F).


17.5 BEGIN/BEND
     ----------

A structure used with IF... THEN ELSE so that you can include several pro-
gram lines between the start (BEGIN) and end (BEND) of the structure. Here
is the format:

   IF Condition THEN BEGIN : statement
   statement
   statement BEND : ELSE BEGIN
   statement
   statement BEND


EXAMPLE:

     10 IF X=1 THEN BEGIN: PRINT "X=1 is True"
     20 PRINT "So this part of the statement is performed"
     30 PRINT "When X equals 1"
     40 BEND: PRINT "End of BEGIN/BEND structure":GOTO 60
     50 PRINT "X does not equal 1":PRINT "The statements between
     BEGIN/BEND are skipped"
     60 PRINT "Rest of Program"

If the Conditional (IF... THEN) statement in line 10 is true, the state-
ments between the keywords BEGIN and BEND are performed, including all the
statements on the same line as BEND. If the (IF... THEN) conditional state-
ment in line 10 is False, all statements between the BEGIN and BEND, inclu-
ding the ones on the same program line as BEND are skipped, and the program
resumes with the first program line immediately following the line con-
taining BEND. The BEGIN/BEND essentially treats line 10 through 40 as one
long line.

The same rules are true if the ELSE:BEGIN clause is specified. If the con-
dition is true all statements between ELSE:BEGIN and BEND are performed,
including all statements on the same line as BEND. If False, the program
resumes with the line immediately following the line containing BEND.


17.6 BLOAD
     -----

Load a binary file starting at the specified memory location.

BLOAD "filename" [,Ddrive number] [<ON | ,>Udevice number]
[,Bbank number] [,Pstart address]

where:

*  filename is the name of your file
*  bank number lets you select one of the 16 banks
*  start address is the memory location where loading begins

A binary file is a file, whether a program or data, that has been SAVEd
either within the machine language monitor or by the BSAVE command. The
BLOAD command loads the binary file into the location specified by the
start address.


EXAMPLES:

     BLOAD "SPRITES", B0, P3584

LOADs the binary file "SPRITES" starting in location 3584 in BANK 0.

     BLOAD "DATA1", D0, U8, B1, P4096

LOADs the binary file "DATA1" into location 4096 (BANK 1) from Drive 0,
unit 8.

If start address is not specified the file will load at the same address
it was saved from.


17.7 BOOT
     ----

Load and execute a program which has been saved as a binary file.

BOOT ["filename"] [,Ddrive number] [<ON | ,>Udevice]

The command loads an executable binary file and begins execution at the
predefined starting address. The default device number is 8 drive 0.


EXAMPLES:

     BOOT

BOOT an executable program, (CP/M Plus for example). This is a special case
and requires setting up a specific sector on the disk.

     BOOT"GRAPHICS 1", D0, U9

BOOTs the program "GRAPHICS 1" from unit 9, drive 0 and executes it. Execu-
tion begins at the start address of the program (i.e. where it starts
loading).


17.8 BOX
     ---

Draw a box at specific position on screen.

BOX [color source], x1, y1 [, x2, y2] [,angle] [,paint]

where:

color source  0=Background color
              1=Foreground color
              2=Multicolor 1 }
              3=Multicolor 2 }   Only in Graphics modes 3 and 4

x1, y1        Top left corner coordinate (scaled).

x2, y2        Bottom right corner opposite x1, y1 (scaled); default is the
              PC location.

angle         Rotation in clockwise degrees; default is zero degrees.

paint         Paint shape with color
              0=Do not paint
              1=Paint
              (default 0)

This statement allows the user to draw a rectangle of any size on the
screen. Rotation is based on the centre of the rectangle. The pixel cursor
(PC) is located at x2, y2 after the BOX statement is executed. The color
source number must be zero (0) or one (1) if in standard bit map or a 2 or
3 if in multicolor bit map mode.

Also see the GRAPHIC command, in paragraph 17.47, for selecting the appro-
priate graphic mode to be used with the BOX color source number.

Also see the LOCATE command, in paragraph 17. for information on the pixel cursor.


EXAMPLES:

     BOX 1, 10, 10, 60, 60

Draws the outline of a rectangle.

     BOX 1, 10, 10, 60, 45, 1

Draws a painted, rotated box (a diamond).

     DRAW , 30, 90, , 45, 1

Draws a filled, rotated polygon (see note).

     BOX 1, 20, 20, , ,1

Draws a filled rectangle from 20, 20 to the current pixel cursor.

Any parameter can be omitted but you must include a comma in its place, as
in the last two examples.

NOTE: x2, y2 count as one parameter so only one extra comma is required.
Wrapping occurs if the degree is greater than 360, i.e. 360=0 (450=90).


17.9 BSAVE
     -----

Save a binary file from the specified memory locations.

BSAVE "filename" [,Ddrive number] [<ON | ,>Udevice number] [,Bbank number],
Pstart address TO Pend address+1

where:

*  filename is the name you give the file
*  drive number is either 0 or 1 on a dual drive (0 is the default)
*  device number is the number of disk drive unit (default is 8)
*  bank number is the number of the bank you specify (0-15)
*  start address is the starting address where the program is SAVEd from
*  end address+1 is the end address of the program plus one, i.e. the end
   address you specify in BSAVE is one byte higher than the end address of
   the memory range

This is the same as the SAVE command in the machine language monitor.


EXAMPLES:

     BSAVE "SPRITE DATA",B0,P3584 TO P4096

Saves the binary file named "SPRITE DATA" starting at location 3584 through
4095 (BANK 0).

     BSAVE "PROGRAM.SCR",D0,U9,B0,P3182 TO P8000

Saves the binary file named "PROGRAM.SCR" in the memory address range 3182
through 7999 (BANK 0) on drive 0, unit 9.


17.10 CATALOG
      -------

Displays the disk directory.

CATALOG [Ddrive number] [<ON | , >Udevice number] [,wildcard string]

The CATALOG command displays the directory on the specified drive just as
the directory command. See this command, in paragraph 17.28, for more
examples (DIRECTORY and CATALOG are completely interchangeable).


EXAMPLE:

     CATALOG
Displays the disk directory on drive 0 of unit 8.


17.11 CHAR
      ----

Displays characters at the specific position on the screen.

CHAR [color source], x, y [,string] [,rvs]

This is primarily designed to display characters on a bit mapped screen,
but it can also be used on a text screen. Here is what the parameters mean:

color source  0=Background color
              1=Foreground color
              2=Multicolor 1
              3=Multicolor 2
x             Character column (0-79) (wraps around to the next line in
              40-column mode)
y             Character row (0-24)
string        String to print
RVS           Reverse field flag (0=off, 1=on, default=0)

Text (alphanumeric strings) can be displayed on any screen at a given loca-
tion by the CHAR statement. Character data is read from Commodore 128
character ROM area. The user supplies the x and y coordinates of the star-
ting position and the text string to be displayed. Color source and reverse
imaging are optional.

The string is continued on the next line if it attempts to print past the
right hand edge of the screen. When used in text mode, the string printed
by the CHAR command works just like a PRINT string, including cursor and
color control. These control functions inside the string do not work when
the CHAR command is used to display text in bit map mode. Upper/Lower case
controls (CHR$(142) or CHR$(14)) also operate in bit map mode.

Multicolor characters are handled differently from standard characters. The
following table shows how to generate the possible combinations.

          +------------------------------------------+
          |                             Reverse Flag |
          |                             ------------ |
          |                             0(OFF) 1(ON) |
          +---------------------------+--------------+  
          |                Text       |   1      1   |
          | Color source 0            |              |
          |                Background |   2      3   |
          +---------------------------+--------------+
          |                Text       |   1      0   |
          | Color source 1            |              |
          |                Background |   0      1   |
          +---------------------------+--------------+
          |                Text       |   2      0   |
          | Color source 2            |              |
          |                Background |   0      2   |
          +---------------------------+--------------+
          |                Text       |   3      0   |
          |  Color source 3           |              |
          |                Background |   0      3   |
          +---------------------------+--------------+
EXAMPLE:

     10 COLOR 2,3: REM multicolor 1=Red
     20 COLOR 3,7: REM multicolor 2=Blue
     30 GRAPHIC 3,1
     40 CHAR 0,10,10,"TEXT",0
     50 CHAR 0,10,11,"TEXT",1


17.12 CIRCLE
      ------

Draws circles, ellipses, arcs, etc. at specific positions on the screen.

CIRCLE [color source],x,y,xr [,yr] [,sa] [,ea] [,angle] [,inc]

where:

color source  0=Background color
              1=Foreground color
              2=Multicolor 1 }
              3=Multicolor 2 }   Only in Graphics modes 3 and 4
x,y           Centre coordinates of the CIRCLE.
xr            X radius (scaled).
yr            Y radius (scaled).
sa            Starting arc angle (default 0 degrees).
ea            Ending arc angle (default 360 degrees).
angle         Rotation in clockwise degrees (default is 0 degrees).
inc           Degrees between segments (default is 2 degrees).


                           +++            +++ sa
                          +   +          +   /
                         +     +        +     +
                        + xy  xr+      + xy    +
                        +   +---+      +   +   +
                        +   |   +      +       +
                         +  |yr+        +     +
                          + | +          +   \
                           +++            +++ ea


With the CIRCLE statement, the user can draw a circle, ellipse, arc, tri-
angle, octagon, or other polygon. The final pixel cursor (PC) is left at
the circumference of the circle at the ending arc angle. Any rotation is
relative to the centre. Arcs are drawn from the starting angle clockwise to
the ending angle. The increment controls the smoothness of the shape; using
lower values results in more nearly circular shapes. Specifying the inc
greater than 2 creates a rough-edged boxed-in shape.

Also see the LOCATE command, in paragraph 17.57, for information on the
pixel cursor.


EXAMPLES:

   CIRCLE 1,160,100,65,10        Draws an ellipse
   CIRCLE 1,160,100,65           Draws a circle
   CIRCLE 1,60,40,20,18,,,,45    Draws an octagon
   CIRCLE 1,260,40,20,30,,,,90   Draws a diamond
   CIRCLE 1,60,140,20,18,,,,120  Draws a triangle

You may omit a parameter, but you must still place a comma in the appro-
priate position. Omitting parameters take on the default values.


17.13 CLOSE

Close logical file.

CLOSE file number

This statement closes any files used by DOPEN or OPEN statements. The num-
ber following the word CLOSE is the file number to be closed.


EXAMPLE:

  CLOSE 2    Logical file 2 is closed.


17.14 CLR

Clear program variables.

CLR

This statement erases any variables in memory, but leaves the program in-
tact. This statement is automatically executed when a RUN or NEW command
is given.


17.15 CMD

Redirect screen output.

CMD logical file number [,write list]

This command sends the output, which normally goes to the screen (i.e.
PRINT statements, LIST, but not POKES into the screen) to another device,
such as a disk data file or printer. This device or file must be OPENed
first. The CMD command must be followed by a number or numeric variable
referring to the file or device. The write list can be any alphanumeric
string or variable. This command is useful for printing at the top of
program listings.


EXAMPLES:

   OPEN 1,4   OPENs device #4, which is the printer.

   CMD 1      All normal output now goes to the printer.

   LIST       The LISTing goes to the printer, not the screen - even the
              word READY.

   PRINT#1    Sends output back to the screen.

   CLOSE 1    Close the file.


17.16 COLLECT
      -------

Free inaccessible disk space.

COLLECT [Ddrive number] [<ON | ,>Udevice]

Use this command to make available any disk space that has been allocated
to improperly closed (splat) files, and to delete references to these files
from the directory. Splat files are files that appear on the directory with
an asterisk next to them. Defaults to device number 8.


EXAMPLE:

     COLLECT D0

Free all available space which has been incorrectly allocated to improperly
closed files.

NOTE: It will also free space allocated for direct access and any boot
sector. See your disk drive manual for more information.


17.17 COLLISION
      ---------

Define handling for sprite collision interrupt.

COLLISION type [, statement]

type           Type of interrupt as follows:
               1 = Sprite-to-sprite collision
               2 = Sprite-to-display collision
               3 = Light pen
statement      BASIC line number of a subroutine

When the specified situation occurs, BASIC will finish processing the cur-
rent executing instruction and perform a GOSUB to the line number given.
When the subroutine terminates (it must end with a RETURN), BASIC will re-
sume processing where it left off. Interrupt action continues until a
COLLISION of the same type without a line number is specified. More than
one type of interrupt may be enabled at the same time, but only one inter-
rupt can be handled at a time (i.e. there can be no recursion and no nes-
ting of interrupts). The cause of an interrupt may continue causing
interrupts for some time unless the situation is altered or the interrupt
is disabled.

To determine which sprites have collided since the last check, use the BUMP
function.


EXAMPLES:

     COLLISION 1, 5000   Detects a sprite-to-sprite collision and program
                         control sent to subroutine at line 5000.

     COLLISION 1         Stops interrupt action which was initiated in
                         above example.

     COLLISION 2,1000    Detect sprite-to-display collision and program
                         control directed to subroutine in line 1000.

NOTE: Sprites can still collide even if they are set off the screen, but
not if they are switched off.


17.18 COLOR
      -----

Define colors for each screen area.

COLOR source number, color number

This statement assigns a color to one of the seven color areas:

Source Numbers

Area     Source
0        40-column (VIC) background
1        40-column (VIC) foreground
2        multicolor 1
3        multicolor 2
4        40-column (VIC) border
5        character color (40- or 80-column screen)
6        80-column (VDC) background color

Colors that are usable are in the range 1-16:

Color Code   Color             Color Code   Color

1            Black             9            Orange
2            White             10           Brown
3            Red               11           Light Red
4            Cyan              12           Dark Gray
5            Purple            13           Medium Gray
6            Green             14           Light Green
7            Blue              15           Light Blue
8            Yellow            16           Light Gray

                   Color Numbers in 40-Column Format

1            Black             9            Dark Purple
2            White             10           Brown
3            Dark Red          11           Light Red
4            Light Cyan        12           Light Purple
5            Dark Cyan         13           Medium Gray
6            Dark Green        14           Light Green
7            Dark Blue         15           Light Blue
8            Light Yellow      16           Light Gray

                   Color Numbers in 80-Column Format


EXAMPLES:

     COLOR 0,1   Change background color of 40-column screen to black.

     COLOR 5,8   Change character color to yellow.


17.19 CONCAT
      ------

Concatenates two data files.

CONCAT "file 2" [,Ddrive number] TO "file 1" [,Ddrive number]
[<ON | ,>Udevice]

The CONCAT command attaches file 2 to the end of file 1 and retains the
name of file 1. The device number defaults to 8 and the drive number
defaults to 0.


EXAMPLES:

     CONCAT "FILE B" TO "FILE A"   FILE B is attached to FILE A and the
                                   combined file is designated FILE A.

     CONCAT (A$) TO (B$), D1, U9   The file named by B$ becomes a new file
                                   of the same name, with the file named by
                                   A$ attached to the end of B$ - this is
                                   performed on Unit 9, Drive 1 (a dual
                                   disk drive).

Whenever a variable is used as a filename as in the last example, the file-
name variable must be surrounded by parentheses.

NOTE: Keep the filenames short (10 characters) because the command buffer
is limited in some disk drives.


17.20 CONT

Continue program execution.

CONT

This command is used to restart a program that has been stopped by either
using the {stop} key, a STOP statement, or an END statement. The program
resumes execution where it left off. CONT will not resume with the program
if lines have been changed or added to the program or if any editing of the
program is performed on the screen. If the program stopped due to an error,
or if you have caused an error before trying to restart the program, CONT
will not work. The error message in this case is CAN'T CONTINUE ERROR.


17.21 COPY
      ----

Copy files from one drive to another in a dual disk drive or within a
single drive.

COPY <["source filename"] [,Ddrive number]> TO <["destination filename"]
[,Ddrive number]> [<ON | ,>Udevice]

This command copies files from one disk (the source file) to another (the
destination file) on a dual-disk drive. It can also create a copy of a file
on the same disk within a single drive, but the filename must be different.
When copying from one drive to another, the filename may be the same.

The COPY command can also COPY all files from one drive to another on a
dual disk drive. In this case the drive numbers are specified and the
source and destination filenames are omitted.

The default parameters for the COPY command are device number 8, drive 0.

NOTE: Copying between two single or double drive units cannot be done. See
BACKUP, in paragraph 17.3.


EXAMPLES:

   COPY "TEST",D0 TO "TEST PROG",D1  Copies "TEST" from drive 0 to drive 1,
                                     renaming it "TEST PROG" on drive 1.

   COPY "STUFF",D0 TO "STUFF",D1     Copies "STUFF" from drive 0 to drive 1.

   COPY D0 TO D1                     Copies all files from drive 0 to drive
                                     1.

   COPY "WORK.PROG" TO "BACKUP"      Copies "WORK.PRG" as a file called
                                     "BACKUP" on the same disk (drive 0).


17.22 DATA

Define data to be used by a program.

DATA list of constants

This statement is followed by a list of data items to be input into the
computer's memory by READ statements. The items may be numeric or string
and are seperated by commas. String data need not be inside quote marks,
unless they contain any of the following characters: {space}, {colon}, or
{comma}. If two commas have nothing between them, the value is READ as a
zero if numeric or as an empty string. Also see the RESTORE statement, in
paragraph 17.75, which allows the Commodore 128 to reREAD data.


EXAMPLE:

     DATA 100,200, FRED, "HELLO MUM", , 3, 14, ABC123


17.23 DCLEAR
      ------

Clear all open channels on disk drive.

DCLEAR [Ddrive number] [<ON | ,>Udevice]

This statement closes and clears all open channels on the specified device
number. Default is U8. This command is analogous to OPEN 0,8,15,"I0":
CLOSE 0.


EXAMPLES:

   DCLEAR D0       Clears all open channels on drive 0, device number 8.

   DCLEAR D1,U9    Clears all open channels on drive 1, device number 9.

NOTE: Files will be aborted, data may not be recoverable from files which
were being written to. See CLOSE/DCLOSE, in paragraphs 17.13/17.24.


17.24 DCLOSE
      ------

Close disk file.

DCLOSE [#logical file number] [<ON | ,>Udevice]

This statement closes a single file or all the files currently open on a
disk unit. If no logical file number is specified, all currently open files
are closed. The default device number is 8. Note the following examples:


EXAMPLES:

   DCLOSE        Closes all files currently open on unit 8.

   DCLOSE #2     Closes the file associated with the logical file number 2.

   DCLOSE ON U9  Closes all files curently open on unit 9.


17.25 DEF FN

Define a user-defined function.

DEF FN name(variable) = expression

This statement allows definition of a complex calculation as a function. In
the case of a long formula that is used several times within a program,
this keyword can save valuable program space. The name given to the func-
tion begins with the letters FN, followed by any legal numeric variable
name (not integer or array). First, define the function by using the state-
ment DEF, followed by the name given to the function. Following the name is
a set of parentheses ( ) with a local variable name enclosed. This variable
only has a value if it appears in the expression on the right of the equal
sign. The same variable name can be used elsewhere in a program but it will
be completely seperate from its use in the function. Other variables and/or
functions can be used in the expression and these are evaluated as their
value at the time the function is called. Next is an equal sign, followed
by the formula to be defined. The function can be performed by sustituting
any number for variable, using the format shown in lines 40 and 50 of the
example below.


EXAMPLE:

10 DEF FNEG(LO)=INT((V1*LO^2)*100)/100
   LO is local to this line
20 LO=15
   A normal program variable
30 V1=3.14159
   Approximation of {pi}
40 PRINT FNEG(5)
   Assign 5 to the local value LO in the function.
50 PRINT FNEG(1)
   Use 1 in the function instead of LO.
60 PRINT INT(V1*LO^2)*100)/100
   Variable LO used
70 PRINT LO
   Remains unchanged


17.26 DELETE
      ------

Delete lines of a BASIC program in the specified range.

DELETE <start line | start line -  | start line - end line | - end line>

This command can be executed only in direct mode.


EXAMPLES:

   DELETE 75     Deletes line 75.

   DELETE 10-50  Deletes lines 10 through 50, inclusive.

   DELETE-50     Deletes all lines from the beginning of the program up to
                 and including line 50.

   DELETE 75-    Deletes all lines from 75 to the end of the program,
                 inclusive.


17.27 DIM

Declare number of elements in an array.

DIM variable(subscripts) [, variable(subscripts)] [...]

Before arrays of variables can be used, the program must first execute a
DIM statement to establish DIMensions of the array (unless there are 11 or
fewer elements in each DIMension of the array). The DIM statement is fol-
lowed by the name of the array, which may be any legal variable name. Then,
enclosed in parantheses, the number (or numeric variable) of elements in
each dimension. An array with more than one dimension is called a matrix.
Any number of dimensions may be used, but keep in mind the whole list of
variables being created takes up space in memory, and it is easy to run out
of memory if too many are used. Here's how to calculate the amount of memo-
ry used by an array:

     5 bytes for the array name
     2 bytes for each dimension
     2 bytes/element for integer variables
     5 bytes/element for normal numeric variables
     3 bytes/element for string variables
     1 byte for each character in each string element

Integer arrays take up two-fifths the space of floating point arrays (e.g.
DIM A%(100) requires 209 bytes; DIM A(100) requires 512 bytes).

NOTE: Elements are numbered from 0, e.g. DIM A(100) gives 101 elements.

More than one array can be dimensioned in a DIM statement by seperating the
array variable names by commas. If the program executes a DIM statement for
any array more than once, the message RE'DIM ARRAY ERROR is posted. It is
good programming practice to place DIM statements near the beginning of the
program.


EXAMPLE:

     10 DIM A$(40),B7(15),CC%(4,4,4)

     41 elements, 16 elements, 125 elements.


17.28 DIRECTORY
      ---------

Displays the contents of the disk directory on the screen.

DIRECTORY [Ddrive number] [<ON | ,>Udevice] [, wildcard]

The {f3} function key in C128 mode displays the DIRECTORY for device number
8, drive 0. Use CONTROL S or NOSCROLL to pause the display.

The DIRECTORY command should not be used to print a hard copy, because some
printers interfere with the data coming from the disk drive. The disk
directory should be loaded (LOAD "$",8) destroying the current program in
memory in order to print a hard copy.

The default device number is 8, and the default drive number is 0.


EXAMPLES:

   DIRECTORY                   Lists all files on the disks in unit 8.

   DIRECTORY D1, U9, "WORK"    Lists the file named "WORK" on drive 1 of
                               unit 9.

   DIRECTORY "AB*"             Lists all files starting with the letters
                               "AB" like ABOVE, ABOARD, etc. on all drives
                               of unit 8. The asterisk specifies a wild
                               card, where all files starting with "AB" are
                               displayed.

   DIRECTORY D0, "FILE ?.BAK"  The ? is a wild card that matches a single
                               character in that position. For example:
                               FILE 1.BAK, FILE 2.BAK, FILE 3.BAK all mat-
                               ching the string.

   DIRECTORY D1,U9,(A$)        Lists the filename stored in the variable
                               A$, on device number 9, drive 1. Remember
                               whenever a variable is used as a filename,
                               surround the variable in parentheses.

NOTE: To print the DIRECTORY of the disk in drive 0, unit 8, use the fol-
lowing example:

     LOAD"$0",8
     OPEN4,4:CMD4:LIST
     PRINT#4:CLOSE4


17.29 DLOAD
      -----

Load a BASIC program from disk.

DLOAD "filename" [,Ddrive number] [< ON | ,>Udevice number]

This command loads a BASIC program from disk into current memory. (Use
LOAD to load programs from tape.) The program must be specified by a file-
name of up to 16 characters. DLOAD assumes device number 8, drive 0.


EXAMPLES:

   DLOAD "BANKRECS"  Searches the disk for the program "BANKRECS" and LOADs
                     it.

   DLOAD (A$)        LOADs a program from disk whose name is stored in the
                     variable A$. An error message is given if A$ is empty.
                     Remember, when a variable is used as a filename, it
                     must be enclosed in parentheses.

The DLOAD command can be used within a BASIC program to find another pro-
gram on disk. This is called chaining.


17.30 DO/LOOP/WHILE/UNTIL/EXIT
      ------------------------

Define and control progam loop.

DO [UNTIL condition | WHILE condition] statement [EXIT]
LOOP [UNTIL condition | WHILE condition]

This loop structure performs the statements between the DO statement and
the LOOP statement. If no UNTIL or WHILE statements modifies either the DO
or the LOOP statement, execution of the statements in between continues
indefinitely. If an EXIT statement is encountered in the body of a DO loop,
execution is transferred to the first statement following the LOOP state-
ment. DO loops may be nested, following the rules defined by the FOR...
NEXT structure. If the UNTIL parameter is specified, the program continues
looping until the condition is satisfied (becomes true). The WHILE para-
meter is basically the oposite of the UNTIL parameter: the program conti-
nues looping as long as the condition is true. As soon as the condition is
no longer true, program control resumes with the statement immediately fol-
lowing the LOOP statement. An example of a condition (boolean operation)
is A=1, or G>65.


EXAMPLES:

     10 X=25
     20 DO UNTIL X=0
     30 X=X-1
     40 PRINT "X=";X
     50 LOOP
     60 PRINT "END OF LOOP"

This example performs the statement X=X-1 and PRINTs "X=";X until X=0. When
X=0 the program resumes with the statement following LOOP,
PRINT "END OF LOOP"

     10 DO WHILE A$="":GET A$:LOOP
     20 PRINT "THE ";A$;" KEY HAS BEEN PRESSED"

A$ remains null as long as no key is pressed. As soon as a key is pressed
program control passes to the statement immediately following LOOP,
PRINT "THE ";A$;" KEY HAS BEEN PRESSED". The example performs a GET A$ as
long as A$ is a null character. This loop constantly checks to see if a key
on the keyboard is being pressed. Note that the statement GETKEY A$ has the
same effect as line 10.

     10 OPEN #8,"SEQFILE"
     20 DO
     30 GET #8,A$
     40 PRINT A$;
     50 LOOP UNTIL ST
     60 DCLOSE #8

This program opens the file "SEQFILE" and gets data until the ST system
variable indicates all data is input. A value of 0 indicates a FALSE con-
dition, nonzero is true. ST is normally 0.


17.31 DOPEN
      -----

Open a disk file for a read and/or write operation.

DOPEN #logical file number,"filename[,<S | P>]" [,Lrecord length]
[,Ddrive number] [<ON | ,>Udevice number] [,w]

where:

S = Sequential file type.
P = Program file type.
L = Record length = the length of records in a relative file only.
w = Write operation (if not specified a read operation occurs).

This statement opens a sequential, program or relative file for a read or
write operation. The record length (L) pertains to a relative file, which
can be as long as 254. The w parameter is specified only during a write
(PRINT#) operation in a sequential file. If not specified, the disk drive
assumes the disk operation to be a read operation. Relative file are open
for both read and write operations at the same time.

The logical file number associates a number to a file for future disk
operations such as a read (INPUT# or GET#) or write (PRINT#) operation. The
logical file number can range from 1 to 255. Logical file numbers greater
than 128 automatically send a carriage return and linefeed with each PRINT#
command. Logical file number less than 128 send only a carriage return,
which can be suppressed with a semicolon at the end of the PRINT# command.
The default device number is 8, and the default drive is 0.


EXAMPLES:

   DOPEN#1,"ADDRESS",W      Open the sequential file number 1 (ADDRESS) for
                            a write operation.

   DOPEN#2,"RECIPES",D1,U9  Open the sequential file number 2 (RECIPES) for
                            a read operation on device number 9, drive 1.

   DOPEN#3,"BOOKS",L128     Open the relative file number 3 (BOOKS) for
                            read and write on unit 8 drive 0. Record length
                            is 128 characters.


17.32 DRAW
      ----

Draw dots, lines and shapes at specified positions on screen.

DRAW [color source], x1,y1 [TO x2,y2] ...

This statement draws individual dots, lines, and shapes. Here are the para-
meter values:

color source=  0 Background color
               1 Foreground color
               2 Multicolor 1 }
               3 Multicolor 2 }   Only in Graphics modes 3 and 4
x1, y1         Starting coordinate, scaled
x2, y2         Ending coordinate, scaled

Also see the LOCATE command, in paragraph 17.57, for information on the
pixel cursor.


EXAMPLES:

   DRAW 1,100,50                             Draw a dot

   DRAW ,10,10 TO 100,60                     Draw a line

   DRAW ,10,10 TO 10,60 TO 100,60 TO 10,10   Draw a triangle

You may omit a parameter but you still must include the comma that would
have followed the unspecified parameter.


17.33 DSAVE
      -----

Save a BASIC program file to disk.

DSAVE "filename" [,Ddrive number] [<ON | ,>Udevice number]

This command stores (SAVEs) a BASIC program on disk. (See SAVE, in paragraph
17.80, to store programs on tape.) A filename up to 16 characters long must
be supplied. The default device number is 8, while the default drive number
is 0.

EXAMPLES:

   DSAVE "BANKRECS"       SAVEs the program "BANKRECS" to disk.

   DSAVE (A$)             SAVEs the disk program named in the variable A$.

   DSAVE "PROG 3",D1,U9   SAVEs the program "PROG 3" to disk on unit 9,
                          drive 1 (on a dual drive unit).


17.34 DVERIFY
      -------

Verify the program in memory against the one on disk.

DVERIFY "filename" [,Ddrive number] [<ON | ,>Udevice number]

This command causes the Commodore 128 to check the program on the specified
drive against the program in memory. The default drive number is 0 and the
default device number is 8.

NOTE: If graphic area is allocated or deallocated after a SAVE, an error
occurs. Technically this is correct. Because BASIC text is moved from its
original (SAVEd) location when a bit mapped graphics area is allocated or
deallocated, the original location where the C128 verified the SAVEd pro-
gram changes. Hence, VERIFY, which performs byte-to-byte comparisons,
fails, even though the program is valid.

To verify binary data, see VERIFY "filename",8,1 format, under VERIFY
command description.


EXAMPLES:

   DVERIFY "C128"            Verifies program "C128" on drive 0, unit 8.

   DVERIFY "SPRITES",D0,U9   Verifies program "SPRITES" on drive 0,
                             device 9.


17.35 END

Define the end of program execution.

END

When the program encounters the END statement, it stops RUNning immediate-
ly. The CONT command can be used to restart the program at the next state-
ment (if any) following the END statement.


17.36 ENVELOPE
      --------

Define a musical instrument envelope.

ENVELOPE n [,atk] [,dec] [,sus] [,rel] [,wf] [,pw]

where:

    n            Envelope number (0-9)
    atk          Attack rate (0-15)
    dec          Decay rate (0-15)
    sus          Sustain level (0-15)
    rel          Release rate (0-15)
    wf           Waveform: 0 = triangle
                           1 = sawtooth
                           2 = variable pulse (square)
                           3 = noise
                           4 = ring modulation
    pw           Pulse width (0-4095)

A parameter that is not specified will retain its predefined or currently
redefined value. Pulse width applies to the width of the variable pulse
waveform (wf=2) only and is determined by the formula: pwout = pw/40.95, so
that pw=2048 produces a square wave and values 0 and 4095 produce constant
DC output. The Commodore 128 has initialized the following 10 envelopes:

         n,  A,  D,  S,  R, wf,  pw      instrument

ENVELOPE 0,  0,  9,  0,  0,  2,  1536    piano
ENVELOPE 1,  12, 0,  12, 0,  1           accordion
ENVELOPE 2,  0,  0,  15, 0,  0           calliope
ENVELOPE 3,  0,  5,  5,  0,  3           drum
ENVELOPE 4,  9,  4,  4,  0,  0           flute
ENVELOPE 5,  0,  9,  2,  1,  1           guitar
ENVELOPE 6,  0,  9,  0,  0,  2,  512     harpsicord
ENVELOPE 7,  0,  9,  9,  0,  2,  2048    organ
ENVELOPE 8,  8,  9,  4,  1,  2,  512     trumpet
ENVELOPE 9,  0,  9,  0,  0,  0           xylophone

To play predefined musical instrument envelopes, you simply specify the
envelope number in the PLAY command (see PLAY, paragraph 17.64). You do not
need to use the ENVELOPE command. The ENVELOPE command is used only when you
need to change the envelope.


17.37 FAST
      ----

Put machine in 2 Mhz mode of operation.

FAST

This command initiates 2 Mhz mode, causing VIC's 40 column screen to be
turned off. All operartions (except I/O) are speeded up considerably.
Graphics may be used, but will not be visible until a SLOW command is
issued.


17.38 FETCH
      -----

Get data from expansion (RAM module) memory.

FETCH #bytes, intsa, expsa, expb

where #bytes =   number of bytes to get from expansion memory (0-65535)
      intsa  =   starting address of host RAM (0-65535)
      expsa  =   starting address of expansion RAM (0-65535)
      expb   =   64K expansion RAM bank number (0-15)


17.39 FILTER
      ------

Define sound (SID chip) filter parameters.

FILTER [freq] [,lp] [,bp] [,hp] [,res]

where:

   freq        Filter cut-off frequency (0-2047).
   lp          Low-pass filter on (1), off (0).
   bp          Band-pass filter on (1), off (0).
   hp          High-pass filter on (1), off (0).
   res         Resonance (0-15).

Unspecified parameters result in no change to the current value.

You can use more than one type of filter at a time. For example, both low-
pass and high-pass filters can be used together to produce a notch (or band-
reject) filter response. For the filter to have an audible effect, at least
one type of filter must be selected and at least one voice must be routed
through the filter.


EXAMPLES:

   FILTER 1024,0,1,0,2    Set the cutoff frequency at 1024, select the band
                          pass filter and a resonance level of 2.

   FILTER 2000,1,0,1,10   Set the cutoff frequency at 2000, select both the
                          low pass and high pass filters (to form a notch-
                          reject) and set the resonance level at 10.


17.40 FOR/TO/STEP/NEXT

Define a repetitive program loop structure.

FOR variable = start value TO end value [STEP increment]

NEXT [variable]

The FOR statement works with the NEXT statement to set up a section of the
program that repeats for a set number of times (i.e. a loop). This is use-
ful when something needs to be counted or something must be done a certain
number of times (such as printing).

This statement executes all the commands enclosed between the FOR and NEXT
statements repetitively, according to the start and end values. The start
value and end value are the beginning and ending counts for the loop
variable. The loop variable is added to or subtracted from during the
FOR... NEXT loop.

The logic of the FOR... NEXT statement is as follows. First, the loop
variable is set to the start value. When the program reaches a program line
containing the NEXT statement, it adds the STEP increment (default = 1) to
the value of the loop variable and checks to see if it is higher than the
end value of the loop. If the loop variable is less than or equal to the
end value, the loop is executed again, starting with the statement imme-
diately following the FOR statement. If the loop variable is greater than
the end value, the loop terminates and the program resumes immediately fol-
lowing the NEXT statement. The opposite is true if the step size is nega-
tive.

EXAMPLE A                            EXAMPLE B

10 FOR L=1 TO 10                     10 FOR L=10 TO 1 STEP-1
20 PRINT L                           20 PRINT L
30 NEXT L                            30 NEXT L
40 PRINT "I'M DONE! L =";L           40 PRINT "I'M DONE! L =";L

Program A prints the number from one to 10, followed by the message
I'M DONE! L = 11. Program B prints the numbers down to one and them I'M
DONE! L = 0.

The end value of the loop may be followed by the word STEP and another num-
ber or variable. In this case, the value following the word STEP is added
each time, instead of the default value one. This allows counting back-
wards, by fractions, or increments other than one.

The user can set up loops inside one another. These are known as nested
loops. Care must be taken when nesting loops so, that the last loop to
start is the first one to end.


EXAMPLE:

     10 FOR L = 1 TO 100
     20 FOR A = 5 TO 11 STEP .5
     30 NEXT A
     40 NEXT L

The FOR... NEXT loop in lines 20 and 30 are nested inside the one in line
10 and 40. The STEP increment of .5 is used to illustrate the fact that
floating point indices are valid.


17.41 GET

Receive input data from the keyboard, one character at a time without
waiting for a key to be pressed.

GET variable list

The GET statement reads each key typed by the user. As the user types, the
characters are stored in the computer's memory (in an area called the key-
board buffer). Up to 10 characters can be stored here1, any characters
typed after the 10th character are lost. The GET statement reads the first
character from the buffer and moves the rest up, allowing room for more. If
there are no characters in the buffer a null (empty) character is returned.
The word GET is followed by a variable name, either numeric or string. GET
will not pause the program if no characters are in the buffer (see GETKEY,
in paragraph 17.42).

If the C128 intends to GET a numeric key and a key other than a number is
pressed, the program stops and a TYPE MISMATCH error message is displayed.
The GET statement may also be put into a loop, checking for an empty
result. The GETKEY statement could also be used in this case. See GETKEY, in
paragraph 17.42, for more information. The GET and GETKEY statements can be
executed only within a program.


EXAMPLES:

   10 DO:GET A$:LOOP UNTIL A$="A"   This line waits for the A key to be
                                    pressed to continue.

   20 GET B, C, D                   Get numeric variables B, C and D from
                                    the keyboard without waiting for a key
                                    to be pressed.


17.42 GETKEY
      ------

Receive input data from the keyboard, one character at a time and wait for
a key to be pressed.

GETKEY variable list

The GETKEY statement is very similar to the GET statement. Unlike the GET
statement, GETKEY, if there is no character in the keyboard buffer, will
wait for the user to type a character on the keyboard. This lets the com-
puter wait for a single character to be typed. This statement can be exe-
cuted only within a program.


EXAMPLES:

   10 GETKEY A$         This line waits for a key to be pressed. Typing any
                        key continues the program.

   10 GETKEY A$,B$,C$   This line waits for three alphanumeric characters
                        to be entered from the keyboard. GETKEY can also be
                        used to READ numeric keys.

   NOTE: GETKEY cannot return a null (empty) character.

17.43 GET#

Receive input data from a tape, disk or RS232.

GET#file number, variable list

This statement inputs one character at a time from a previously opened
file. Otherwise, it works like the GET statement. This statement can be
executed only within a program.


EXAMPLE:

   GET#1,A$   This example receives one character, which is stored in the
              variable A$, from file number 1. This example assumes that
              file 1 was previously opened. See the OPEN and DOPEN state-
              ments, in paragraphs 17.62 and 17.31,respectively.


17.44 GO64
      ----

Switch to C64 mode.

GO64

This statement switches from C128 mode to C64 mode. The question "Are You
Sure?" is displayed in response to the GO64 statement. If {y} is typed, then
the currently loaded program is lost and control is given to the C64 mode;
otherwise, if any other key is pressed, the computer remains in C128 mode.
This statement can be used in direct mode or within a program. The prompt
is not displayed in program mode.


17.45 GOSUB

Call a subroutine from the specified line number.

GOSUB line number

This statement is similar to the GOTO statement, except the Commodore 128
returns from where it came when the subroutine is finished. When a line
with a RETURN statement is encountered, the program jumps back to the
statement immediately following the GOSUB statement.

The target of a GOSUB statement is called a subroutine. A subroutine is
useful if a task is repeated several times within a program. Instead of
duplicating the section of program over and over, set up a subroutine, and
GOSUB to it at the appropriate time in the program. See also the RETURN
statement, in paragraph 17.77.


EXAMPLE:

     20 GOSUB 800
     :
     :
     799 END
     800 PRINT "HI THERE": RETURN

This example calls the subroutine beginning at line 800 and executes it.
All subroutines terminate with a RETURN statement.

Line 799 stops the program accidentally falling into the subroutine.


17.46 GOTO/GO TO

Transfer program execution to the specified line number.

GOTO line number

After a GOTO statement is encountered in a program, the computer executes
the statement specified by the line number in the GOTO statement. When used
in direct mode, GOTO executes (RUNs) the program starting at the specified
line number, without clearing the variables. This is the same as the RUN
command except it does not clear variable values.


EXAMPLES:

     10 PRINT"COMMODORE"
     20 GOTO 10

The GOTO in line 20 makes line 10 repeat continuously until {run/stop} is
pressed.

     GOTO 100

Starts (RUNs) the program starting at line 100, without clearing the
variable storage area.


17.47 GRAPHIC
      -------

Select a graphic mode.

GRAPHIC mode [,clear] [,s]

GRAPHIC CLR

This statement puts the Commodore 128 in one of the six graphic modes:

Mode Description

 0   40-column (VIC) standard text
 1   Standard bit map
 2   Standard bit map (split screen)
 3   Multicolor bit map
 4   Multicolor bit map (split screen)
 5   80-column text

The clear parameter specifies whether the bit mapped screen is cleared
(equal to 1) upon running the program, or left intact (equal to 0). The s
parameter indicates the starting line number of the split screen when in
graphic mode 2 or 4 (standard or multicolor bit map split screen modes).
The default starting line number of the split screen is 19.

When executed, GRAPHIC 1-4 allocated a 9K bit mapped area. The start of
BASIC text area is moved above the bit map area, and any BASIC program is
automatically relocated. This area remains allocated even if the user
returns to TEXT mode (GRAPHIC 0). If the clear option is specified as 1,
the screen is cleared. The GRAPHIC CLR command deallocates the 9K bit
mapped area, making it available again for BASIC text. Any BASIC program
is relocated.


EXAMPLES:

   GRAPHIC 1,1      Select standard bit map mode and clear the bit map.

   GRAPHIC 4,0,10   Select split screen multicolor bit map mode, do not
                    clear the bit map and start the split screen at line 10.

   GRAPHIC 0        Select 40 column text.

   GRAPHIC 5        Select 80 column text.

   GRAPHIC CLR      Clear and deallocate the bit map screen.


17.48 HEADER
      ------

Formats a diskette.

HEADER diskname [,I i.d.] [,Ddrive number] [<ON | ,>Udevice number]

where:

diskname - Any name up to 16 characters.

i.d.     - Any two alphanumeric characters. You must use two - you may not
           leave a space.

Before a new disk can be used for the first time, it must be formatted with
the HEADER command. The HEADER command can also be used to erase a pre-
viously formatted disk, which can then be reused.

When you enter a HEADER command in direct mode, the prompt ARE YOU SURE?
appears. In program mode, the prompt does not appear.

The command divides the disk into sections called blocks. It creates a
table of contents of files, called a directory. Give each disk a unique
i.d. number. Be careful when using the HEADER command because it erases
all stored data.

You can HEADER a diskette more quickly if it was already formatted (by a
HEADER command), by omitting the new disk i.d. The old i.d. is used in-
stead. The quick HEADER can be used only if the disk was previously format-
ted, since it clears out the directory rather than formatting the disk. The
default device number is 8 and the default drive is 0.

As a precaution, the system asks ARE YOU SURE? before the Commodore 128
completes the operation. Press the {y} key to perform the HEADER, or press
any other key to cancel it.

The HEADER command reads the disk command error channel, and if any error
is encountered, the error message ?BAD DISK is displayed.

The HEADER command is analogous to the BASIC 2.0 command:

OPEN 1,8,15,"N0:diskname,i.d." : CLOSE 1


EXAMPLES:

     HEADER "MYDISK",I51,D0   This HEADERs "MYDISK" using i.d. 51 on drive
                              0, (default) device number 8.

HEADER "RECS",I45,D1 ON U9    This HEADERs "RECS" using i.d. 45, on Drive
                              1, device number 9.

HEADER "C128 PROGRAMS",D0     This is a quick HEADER on drive 0, device
                              number 8, assuming the disk in the drive was
                              already formatted. The old i.d. is used.


17.49 HELP
      ----

Highlight the line where the error occurred.

HELP

The HELP command is used after an error has been reported in a program.
When HELP is typed in 40-column format, the line where the error occurs is
listed, with the portion containing the error displayed in reverse field.
In 80-column format, the portion of the line where the error occurs is
underlined. Pressing the {help} key types HELP{return} automatically.


17.50 IF/THEN/ELSE
              ----

Evaluate a conditional expression and execute portions of a program depen-
ding on the outcome of the expression.

IF expression THEN statements                                   (BASIC 2.0)
IF expression THEN statements [:ELSE else-clause]               (BASIC 7.0)

The IF... THEN statement evaluates a BASIC expression and takes one or two
possible courses of action depending upon the outcome of the expression. If
the expression is true, the statement(s) following THEN is executed. This
may be any BASIC statement. If the expression if false, the program resumes
with the program line immediately following the program line containing the
IF statement, unless an ELSE clause is present. The entire IF... THEN
statement must be contained within 160 characters (80 in C64 mode). Also
see BEGIN/BEND, in paragraph 17.5.

The ELSE clause, if present, must be on the same line as the IF... THEN
portion of the statement, and separated from the THEN clause by a colon
{:}. When an ELSE clause is present, it is executed only when the expres-
sion if false. The expression being evaluated may be a variable or a for-
mula, in which case it is considered true if nonzero, and false if zero.
In most cases, there is an expression involving relational operators (=,
<, >, >=, <>).

The IF... THEN statement can take two alternate forms:

     IF expression THEN line number
     or
     IF expression THEN GOTO line number

These forms transfer program execution to the specific line number if the
expression is true. Otherwise, the program resumes with the program line
number immediately following the line containing the IF statement.


EXAMPLES:

     50 IF X>0 THEN PRINT "OK": ELSE END

This line checks the value of X. If X is greater than 0, the statement im-
mediately following the keyword THEN (PRINT"OK") is executed and the ELSE
clause is ignored. If X is less than or equal to 0, the ELSE clause is exe-
cuted and the statement immediately following THEN is ignored.

     10 IF X=10 THEN 100
     20 PRINT"X does not equal 10"
     .
     .
     99 STOP
     100 PRINT "X equals 10"

This example evaluates the value of X. If X equals 10, the program control
is transferred to line 100 and the message "X EQUALS 10" is printed. If X
does not equal 10, the program resumes with line 20, the C128 prints the
prompt "X DOES NOT EQUAL 10" and the program stops.

NOTE: The ELSE extension cannot be used in C64 mode.


17.51 INPUT

Receive a data string or a number from the keyboard and wait for the user
to press {return}.

INPUT ["prompt string";] variable list

The INPUT statement asks for data from the user while the program is
RUNning and places the data into a variable or variables. The program
stops, prints a question mark (?) on the screen, and waits for the user to
type the answer and hit the {return} key. The word INPUT is followed by a
prompt string and a variable name or list of variable names separated by
commas. The message in the prompt string inside quotes suggests (prompts)
the information the user should enter. If this message is present, there
must be a semicolon (;) after the closing quote of the prompt.

When more than one variable is INPUT, seperate them by commas. The compu-
ter asks for the remaining values by typing two question marks (??). If the
{return} key is pressed without INPUTting a value, the INPUT variable
retains its previous value. The INPUT statement can be executed only with-
in a program.

EXAMPLE:

     10 INPUT "PLEASE TYPE TWO NUMBER";A,B
     20 INPUT "AND YOUR NAME";A$
     30 PRINT A$;", YOU TYPED THE NUMBER"A;"AND";B


17.52 INPUT#

Inputs data from a file into the computer's memory.

INPUT#file number, variable list

This statement works like input, but takes the data from a previously
OPENed file usually on a disk or tape instead of the keyboard. No prompt
string is used. This statement can be used only within a program.


EXAMPLE:

     10 OPEN 2,8,2,"DATAFILE,S,R"
     20 INPUT#2,A$, C, D$
     30 CLOSE 2

In line 20 data is INPUT from the file "DATAFILE" and stores it in varia-
bles A$, C and D$.


17.53 KEY
      ---

Define or list function key assignments.

KEY [key number, string]

There are eight function keys (F1 - F8) available to the user on the Commo-
dore 128: four unshifted and four shifted. The Commodore 128 allows you to
perform a function or operation for each time the specified function key is
pressed. The definition assigned to a key can consist of data, or a command
or series of commands. KEY with no parameters specified returns a listing
displaying all current KEY assignments. If data is assigned to a function
key, that data is displayed on the screen when that function key is pres-
sed. The maximum length of all the definitions together is 246 characters.


EXAMPLES:

     KEY 7,"GRAPHIC0" + CHR$(13) + "LIST" + CHR$(13)

This tells the computer to select the (VIC) 40-column text screen and list
the program whenever the {f7} key is pressed (in direct mode). CHR$(13) is
the ASCII character for {return} and performs the same action as pressing
the {return} key. Use CHR$(27) for the {esc} key. Use CHR$(34) to incor-
porate the double quote character into a KEY string. The keys may be rede-
fined in a program. For example:

     10 KEY 2,"PRINT DS$" + CHR$(13)

This tells the computer to check and display the disk drive error channel
variable (PRINT DS$) each time the {f2} key is pressed.

To restore all function keys to their BASIC default values, reset the Com-
modore 128 by pressing the {reset} button (or switch off and then on).


17.54 LET

Assigns a value to a variable.

[LET] variable = expression

The word LET is rarely used in programs, since it is not necessary. When-
ever a variable is defined or given a value, LET is always implied. The
variable name that receives the result of a calculation is on the left side
of the equal sign. The number, string or formula is on the right side. You
can only assign one value with each (implied) LET statement. For example,
LET A=B=2 is not (normally) legal.


EXAMPLES:

   LET A = 5      Assign the value 5 to numeric variable A.

   B = 6          Assign the value 6 to numeric variable B.

   C = A * B + 3  Assign the numeric variable C, the value resulting from
                  5 times 6 plus 3.

   D$ = "HELLO"   Assign the string "HELLO" to string variable D$.


17.55 LIST

List the BASIC program currently in memory.

LIST [line | first- | first-last | -last]

The LIST command displays a BASIC program listing that has been typed or
LOADed into the Commodore 128's memory so you can read and edit it. When
LIST is used alone (without numbers following it), the Commodore 128 gives
a complete LISTing of the program on the screen. The listing process may be
slowed down by holding the {C=} key, paused by {ctrl s} or {noscroll} key
(and resumed by pressing any key), or stopped by hitting the {run/stop}
key. If the word LIST is followed by a line number, the Commodore 128 shows
only that line number. If LIST is typed with two line numbers seperated by
a dash all lines from the first to the second number are displayed. If LIST
is typed followed by a number and just a dash, the Commodore 128 shows all
line from that number to the end of the program. And if LIST is typed with
a dash, then a number, all lines from the beginning of the program to that
line number are LISTed. By using these variations, any portion of a program
can be examined or brought to the screen for modification. In Commodore 128
mode, LIST can be used in a program.


EXAMPLES:

   LIST          Shows entire program.

   LIST 100-     Shows from line 100 until the end of the program.

   LIST 10       Shows only line 10.

   LIST -100     Shows all lines from the beginning to line 100 inclusive.

   LIST 10-200   Shows lines from 10 to 200, inclusive.


17.56 LOAD

Load a program from a peripheral device such as the disk drive or Datas-
sette.

LOAD ["filename"] [,device number] [,relocate flag]

This is the command used to recall a program stored on disk or cassette
tape. Here, the filename is a program name up to 16 characters long, in
quotes. The name must be followed by a comma (outside the quotes) and a
number which acts as a device number to determine where the program is
stored (disk or tape). If no number is supplied, the Commodore 128 assumes
device number 1 (the Datassette tape recorder).

The relocate flag is a number (0 or 1) that determines where a program is
loaded in memory. A relocate flag of 0 tells the Commodore 128 to load the
program at the start of the BASIC program area. A flag of 1 tells the com-
puter to LOAD from the point where it was SAVEd. The default value of the
relocate flag is 0. The relocate parameter of 1 is generally used when
loading machine language programs.

The device most commonly used with the LOAD command is the disk drive. This
is device number 8, though the DLOAD command is more convenient to use when
working with disk.

If LOAD is typed with no arguments, followed by {return}, the C128 assumes
you are loading from tape and you are prompted to "PRESS PLAY ON TAPE".
When you press PLAY, the Commodore 128 starts looking for a program on
tape. When the program is found, the Commodore 128 prints FOUND "filename",
where the filename is the name of the first file which the datassette finds
on the tape. Press the {C=} key to LOAD the found filename, or press the
{spacebar} to keep searching on the tape. Once the program is LOADed, it
can be RUN, LISTed or modified.

NOTE: Pressing the {spacebar} does not cause the next file to be searched
for in C64 mode.


EXAMPLES:

   LOAD                 Reads in the next program from tape.

   LOAD "HELLO"         Searches tape for a program called "HELLO", and
                        LOADs it if found.

   LOAD A$,8            LOADs the program from disk whose name is stored in
                        the variable A$. (This is the equivalent to
                        DLOAD(A$).)

   LOAD"HELLO",8        Looks for the program called "HELLO" on disk drive
                        number 8, drive 0. (This is equivalent to DLOAD
                        "HELLO".)

   LOAD"MACHLANG",8,1   LOADs the machine language program called
                        "MACHLANG" into the location from which it was
                        saved.

The LOAD command can be used within a BASIC program to find and RUN the
next program on a tape or disk. This is called chaining.


17.57 LOCATE
      ------

Position the bit map pixel cursor on the screen.

LOCATE x,y

The LOCATE statement places the pixel cursor (PC) at any specified pixel
coordinate on the screen.

The pixel cursor (PC) is the coordinate on the bit map screen where drawing
of circles, boxes, lines and points and where PAINTing begins. The PC
ranges from x,y coordinates 0,0 throught 319,199 (scaled) in hi-res and
159,199 (scaled) in multicolor bit map. The PC is not visible like the text
cursor, but it can be controlled through the graphics statements (BOX,
CIRCLE, DRAW, etc.). The default location of the pixel cursor is the coor-
dinate specified by the x and y portions in each particular graphics com-
mand. So the LOCATE command does not have to be specified.


EXAMPLE:

   LOCATE 160,100   Position the PC in the centre of the standard bit map
                    screen. Nothing will be seen until something is drawn.

The PC can be found by using RDOT(0) function to get the x-coordinate and
RDOT(1) to get the y-coordinate. The color source of the dot at the PC can
be found by PRINTing RDOT(2).


17.58 MONITOR
      -------

Enter the Commodore 128 machine language monitor.

MONITOR

See Appendix J for details on the Commodore 128 Machine Language Monitor.


17.59 MOVSPR
      ------

Position or move sprite on the screen.

MOVSPR number,x1,y1              Place the specified sprite at absolute
                                 coordinate x,y (scaled).

MOVSPR number,+/- x, +/- y       Move sprite relative to its current posi-
                                 tion.

MOVSPR number,X;Y                Move sprite distance X at angle Y relative
                                 to its current position.

MOVSPR number,x angle #y speed   Move sprite at an angle relative to its
                                 original coordinates, in the specified
                                 clockwise direction and speed.

where:

number   is sprite's number (1 through 8)

<,x,y>   is the coordinate of the sprite location (scaled)

angle    is the angle (0-360) of motion in the clockwise direction relative
         to the sprite's original coordinates

speed    is a speed (0-15) at which the sprite moves

This statement locates a sprite at a specific location on the screen accor-
ding to the SPRITE coordinate plane (not the bit map plane) or initiates
sprite motion at a specific rate. See MOVSPR in paragraph 6.3.7 of Section 6
for a diagram of the sprite coordinate system.


EXAMPLES:

   MOVSPR 1,150,150   Position sprite 1 near the centre ot the screen, x,y
                      coordinate 150, 150.

   MOVSPR 1,+20,-30   Move sprite 1 to the right 20 coordinates and up 30
                      coordinates.

   MOVSPR 4,-50,+100  Move sprite 4 to the left 50 coordinates and down
                      100.

   MOVSPR 5,45 #15    Move sprite 5 at an 45 degree angle in the clockwise
                      direction, relative to its original x and y coor-
                      dinate. The sprite moves at the fastest rate (15).

NOTE: Once you specify an angle and a speed in the fourth form of the
MOVSPR statement, you must set a speed of zero to stop the sprite moving.


17.60 NEW

Clear (erase) program and variable storage.

NEW

This command erases the entire program in memory and clears any variables
that may have been used. Unless the program was stored on disk or tape, it
is lost. Be careful with the use of this command. The NEW command also can
be used as a statement in a BASIC program. However, when the Commodore 128
gets to this line, the program is erased and everything stops.


17.61 ON

Conditional branch to a specified program line number according to the re-
sults of the specified expression.

ON expression <GOTO | GOSUB> line #1 [,line #2, ...]

This statement can make the GOTO and GOSUB statements operate like special
versions of the (conditional) IF statement. The word ON is followed by an
expression, then either of the keywords GOTO or GOSUB and a list of line
numbers separated by commas. If the result of the expression is 1, the
first line number in the list is executed. If the result is 2, the second
line number is executed on so on. If the result is 0, or larger than the
number of line numbers in the list, the program resumes with the statement
immediately following the ON statement. If the number is negative, an
ILLEGAL QUANTITY error results.


EXAMPLE:

     10 INPUT X:IF X<0 THEN 10
     20 ON X GOSUB 30, 40, 50, 60
     25 GOTO 10
     30 PRINT "X=1":RETURN
     40 PRINT "X=2":RETURN
     50 PRINT "X=3":RETURN
     60 PRINT "X=4":RETURN
When X=1, ON sends control to the first line number in the list (30). When
X=2, ON sends control to the second line (40), etc.


17.62 OPEN

Open files for input or output.

OPEN logical file number, device number [,secundary address]
[<,"filename, filetype, mode" | cmd string>]

The OPEN statement allows the Commodore 128 to access files within devices
such as a disk drive, a Datassette cassette recorder, a printer or even the
screen of the Commodore 128.

The word OPEN is followed by a logical file number, which is the number to
which all other BASIC input/output statements will refer, such as PRINT#
(write), INPUT# (read), etc. This number is from 1 to 255.

The second number, called the device number follows the logical file num-
ber. Device number 0 is the Commodore 128 keyboard; 1 is the cassette
recorder; 3 is the Commodore 128 screen; 4-7 are normally the printer(s);
8-11 are reserved for disk drives. It is often a good idea to use the same
file number as the device number, because it makes it easy to remember
which is which.

Following the device number may be a third parameter called the secundary
address. In the case of the cassette, this can be 0 for read, 1 for write
and 2 for write with END-OF-TAPE marker at the end. In case of the disk,
the number refers to the channel number. See you disk drive manual for more
information on channels and channel numbers. For the printer, the secundary
addresses are used to select certain programming functions.

There may also be a filename specified for disk or tape OR a string fol-
lowing the secundary address, which could be a command to the disk/tape
drive or the name of the file on tape or disk. If the filename is speci-
fied, the type and mode refer to disk files only. File types are PROGRAM,
SEQUENTIAL, RELATIVE and USER; modes are READ and WRITE.


EXAMPLES:

   10 OPEN 3,3            OPENs the screen as file number 3.

   20 OPEN 1,0            OPENs the keyboard as file number 1.

   30 OPEN 1,1,0,"DOT"    OPENs the cassette for reading, as file number 1,
                          using "DOT" as the filename.

   OPEN 4,4               OPENs the printer as file number 4.

   OPEN 15,8,15           OPENs the command channel on the disk as file 15,
                          with secundary address 15. (Secundary address 15
                          is reserved for the disk drive error command
                          channel.)
                         
   5 OPEN 8,8,12,         OPENs a sequential disk file for writing called
   "TESTFILE,SEQ,WRITE"   "TESTFILE" as file number 8, with secundary
                          address 12.

See also: CLOSE (17.13), CMD (17.15), GET# (17.43), INPUT# (17.52), and
PRINT# (17.67) statements and system variables ST, DS and DS$ (19.1).


17.63 PAINT
      -----

Fill area with color.

PAINT [color source], x, y [,mode]

where:

color source      0 Background color
                  1 Foreground color
                  2 Multicolor 1
                  3 Multicolor 2

x,y               Starting coordinates, scaled (default at pixel cursor
                  (PC)).

mode              0 = Paint an area defined by the color source selected
                  (default).
                  1 = paint an area defined by any non-background source.

The PAINT command fills an area with color, the area is defined by a fully
enclosed shape around, but not including the x,y coordinates specified.
Points where the color source is the same as the source of the pixel are
not PAINTed. (See example 3.)

If mode=0 the area filled must be bounded by the color source, any other
color sources which lie within this boundery are overPAINTed. (See example
1.)

If mode=1 the boundery of the area is any color source (except 0). No color
sources will be overPAINTed; i.e. only non-PAINTed areas can be filled when
mode=1. (See example 2.)


EXAMPLE 1:

10 COLOR 0,1:COLOR 1,2:
   COLOR 2,5:COLOR 3,7
20 GRAPHIC 3,1               multicolor graphics
30 CIRCLE 1,80,100,30        draw circle in color source 1
40 CIRCLE 3,80,100,35        draw circle in color source 3
50 BOX 2,80,100,90,110,45,1  draw filled box in color source 2
60 PAINT 3,70,100,0          paint inner circle in color source 3 bounded
                             only by color source 3

EXAMPLE 2:

As example 1, but change line 60 to:

60 PAINT 3,70,100,1          paint inner circle bounded by non-background
                             color source
EXAMPLE 3:

As example 2, but add lines 70 and 80:
70 COLOR 2,8                 change color source to yellow
80 PAINT 2,90,110,1          attempt to repaint the box fails, because
                             color source in PAINT and at (90,100) are the
                             same (2).


17.64 PLAY
      ----

Define and play musical notes and elements.

PLAY "[Vn] [On] [Tn] [Un] [Xn] [elements] [...]"

where:  Vn = Voice (n=1-3)
        On = Octave (n=0-6)
        Tn = Tune Envelope (n=0-9)
                  0 = piano
                  1 = accordion            For
                  2 = calliope             default envelope
                  3 = drum                 settings
                  4 = flute                (see ENVELOPE
                  5 = guitar               command, paragraph
                  6 = harpsichord          17.36)
                  7 = organ
                  8 = trumpet
                  9 = xylophone

Un = Volume (n=0-9) (0=off; 9=full (VOL 15))
Xn = Filter on (n=1), off (n=0)
Elements:
                  NOTES:              A, B, C, D, E, F, G
                  #                   Sharp*
                  $                   Flat*
                  W                   Whole note
                  H                   Half note
                  Q                   Quarter note
                  I                   Eighth note
                  S                   Sixteenth note
                  .                   Dotted*
                  R                   Rest
                  M                   Wait for all voices currently playing
                                      to end current measure

The PLAY statement gives you the power to select voice, octave and tune
envelope (including ten predefined musical instrument envelopes), the
volume and the notes you want to PLAY. All these controls are enclosed in
quotes.

All elements except R and M precede the musical notes in a PLAY string.

NOTE: * These must precede each musical note.


EXAMPLES:

     PLAY "V1O4T0U5X0CDEFGAB"

Play the notes C, D, E, F, G, A, and B in voice 1, octave 4, tune enve-
lope 0 (piano - assuming you have not altered it with ENVELOPE), at volume
5, with the filter off.

     PLAY "V3O5T6U7X1#B$AW.CHDQEIF"

Play the notes B-sharp, A-flat, a whole dotted-C note, a half D-note, a
quarter E-note and an eighth F-note.

NOTE: You will need to set up a filter before you can hear anything with
this example - try FILTER 1024,1.


17.65 POKE

Change the contents of a RAM memory location.

POKE address, value

The POKE statement allows changing of any value in the Commodore 128 RAM,
and allows modification of many of the Commodore 128 Input/Output
registers. The keyword POKE is always followed by two parameters. The first
is a location inside the Commodore 128 memory, this can be a value from 0
to 65535. The second parameter is a value from 0 to 255, which is placed in
the location, replacing any value that was there previously. The value of
the memory location determines the bit pattern of the memory location. In
C128 mode the POKE occurs into the current selected RAM bank. The POKE
address depends on the BANK number. See BANK in paragraph 17.4 of this Ency-
clopaedia for the appropriate BANK configurations.


EXAMPLE:

     10 POKE 53280,1

Changes VIC border color (BANK 15 in C128 mode).

NOTE: PEEK, a function related to POKE, which returns the contents of the
specified memory location is listed under BASIC Functions.


17.66 PRINT

Output to text screen

PRINT print list

The PRINT statement is the major output statement in BASIC. While the PRINT
statement is the first BASIC statement most people learn to use, there are
many variations of this statement. The word PRINT can be followed by any of
the following:

Characters inside of quotes   ("text" lines)

Variable names                (A, B, A$, X$)

Functions                     (SIN(23), ABS(33))

Punctuation marks             (; ,)

The characters inside quotes are often called literals because they are
printed literally, exactly as they appear. Variable names have the value
they contain (either a number or a string) printed. Functions also have
their number values printed.

Punctuation marks are used to help format the data neatly on the screen.
The comma tabs to the nearest tenth column, while the semicolon prints
items next to each other. Either punctuation mark can be used as the last
symbol in the statement. This results in the next PRINT statement acting as
if it is continuing the previous PRINT statement. PRINT on its own moves to
the start of the next line - leaving a blank line.

EXAMPLES:                           RESULTS

10 PRINT "HELLO"                    HELLO

20 A$=" THERE":PRINT "HELLO";A$     HELLO THERE

30 A=4:B=2:PRINT A+B                 6

40 J=41:PRINT J;:PRINT J-1           41  40

50 PRINT A;B;:D=A+B:PRINTD;A-B       4  2  6  2

See also POS, SPC and TAB Functions, in Section 18, paragraphs 18.24, 18.37,
and 18.40, respectively.


17.67 PRINT#

Output data to files.

PRINT# file number, print list

There are a few differences between this statement and the PRINT. Most im-
portantly, the word PRINT# is followed by a number, which refers to the
data file previously OPENed. The number is followed by a comma and a list
of items to be output to the file. The semicolon acts in the same manner
for spacing in printers as it does in the PRINT statement, commas output 10
spaces. Some devices may not work with TAB and SPC.


EXAMPLES:

     10 OPEN 4,4
     20 PRINT#4,"HELLO THERE!",A$,B$

Outputs the data "HELLO THERE" and the variables A$ and B$ to the printer.

     10 OPEN 2,8,2,"DATAFILES,S,W"
     20 PRINT#2,A,B$,C,D

This example outputs the data variables A, B$, C and D to the disk file
number 2.

NOTE: The PRINT# command is used by itself to clear the channel to a device
after outputting via CMD and before closing the file as follows:

     OPEN 4,4
     CMD 4
     LIST
     PRINT#4
     CLOSE 4

See also the CMD command, in paragraph 17.15.


17.68 PRINT USING
      -----------

Output using format

PRINT[#filenumber,] USING "format list"; print list

This statement defines the format of string and numeric items for printing
to the text screen, printer or other device. The format is put in quotes.
This is the format list. Then add a semicolon and a list of what is to be
printed in the format for the print list. The list can be variables or the
actual values to be printed, separated by commas.

FORMAT STRING USED WITH
CHARACTER               NUMERIC  STRING
Hash sign (#)           X        X
Plus sign (+)           X
Minus sign (-)          X
Decimal point (.)       X
Comma (,)               X
Dollar sign ($)         X
Four Carets (^^^^)      X
Equal sign (=)                   X
Greater than sign (>)            X

The hash sign {#} reserves room for a single character in the output field.
With Numeric Data if the data item contains more characters than there are
# signs in the format field, the entire field is filled with asterisks {*};
no characters are printed.


EXAMPLE:

     10 PRINT USING "####";X

For these values of X, this format displays:

X = 12.34                  12

X = 567.89                 568  Note that the number is rounded up.

X = 123456                 ****

For a STRING item, the string data is truncated at the bounds of the field.
Only as many characters are printed as there are hash signs in the format
item. Truncation occurs on the right.

The plus (+) and minus (-) signs can be used in either the first or the
last position of the format field, but not both. The plus sign is printed
if the number is positive. The minus sign is printed if the number is nega-
tive.

If a minus sign is used and the number is positive, a blank is printed in
the character position indicated by the minus sign.

If neither a plus nor a minus sign is used in the format field for a nume-
ric data item, a minus sign is printed before the first digit or dollar
symbol if the number is negative. No sign is printed if the number is posi-
tive. This means that one additional character, the minus sign, is printed
if the number is negative. If there are too many characters to fit into the
field specified by the hash signs and plus/minus sign, then an overflow oc-
curs and the field is filled with asterisks {*}.

A decimal point {.} symbol designates the position of the decimal point in
the number. There can be only one decimal point in any format field. If a
decimal point is not specified in the format field, the value is rounded to
the nearest integer and printed without decimal places.

When a decimal point is specified, the number of digits preceding the deci-
mal point (including the minus sign, if the value is negative) must not
exceed the number of hash signs before the decimal point. If there are too
many digits, an overflow occurs and the field is filled with asterisks {*}.

A comma {,} allows placing of commas in numeric fields. The position of the
comma in the format list indicates where the commas appear in a printed
number. Only commas within a number are printed. Unused commas to the left
of the first digit appear as filler character. At least one hash sign must
precede the first comma in the field.

If commas are specified in a field and the number is negative, then a minus
sign is printed as the first character, even if the character position is
specified as a comma.

A dollar sign ($) symbol shows that a dollar sign will be printed in the
number. If the dollar sign is to float (always be placed before the num-
ber), at least one hash sign must be specified before the dollar sign. If a
dollar sign is specified without a leading hash sign, the dollar sign is
printed in the position shown in the format field. If a plus or minus sign
are specified in a format field with a dollar sign, the program prints the
sign before the dollar sign.


EXAMPLES:

Field  Expression  Result Comment

##.#   -.1         -0.1   Leading zero added.

##.#   1           1.0    Trailing zero added.

####   -100.5      -101   Rounded to no decimal places.

####   -1000       ****   Overflow because four digits and a minus sign
                          cannot fit in field.

###.   10          10.    Decimal point added.

#$##   1           $1     Leading dollar sign.

The up arrows or caret symbols {^^^^} are used to specify that the number
is to be printed in the E format (scientific notation). A hash sign must be
used in addition to the four carets to specify the field width. The carets
must appear after the hash sign in the format field. Four carets must be
specified when a number is to be printed in E format. If fewer than four
carets are specified, a syntax error results. If more than four carets are
specified, only the first four are used. The fifth and subsequent carets
are interpreted as text symbols. You can specify a {+} or {-} sign after
the carets if you require a trailing sign. An equal {=} sign is used to
centre a string in a field. The field width is specified by the number of
characters (the hash signs and an equal sign) in the format field. If the
string contains fewer characters than the field width, the string is cen-
tered in the field. If the string contains more characters than can be
fitted into the field, then the rightmost characters are truncated and the
string fills the entire field. A greater than {>} sign is used to right
justify a string in a field. Other characters can be included in a format
string, these are treated as literals. This allows you to build up tables
and charts. See line 30 in the program below for a specific example of
this.

EXAMPLE:

     5 X=32: Y=100.23: A$="CAT": B$="COMPUTER"
     6 F$=* #=########## * #$##.## *+CHR$(13)
     10 PRINT USING "$##.##";13.25,X,Y
     20 PRINT USING "###>#";"CBM",A$
     30 PRINT USING F$;A$,X,B$,Y
(CHR$(13) is {return})

When this program is RUN, line 10 prints:

$13.25 $32.00 $*****   Five asterisks {*****} are printed instead of a Y
                       value, because Y has five digits which does not con-
                       form to the format list (as explained above).

Line 20 prints this:

  CBM  CAT

Leaves two spaces before printing the string, as defined in the format
list.

Line 30 prints this:
*      CAT     *  $23.00 *
*   COMPUTER   * $100.23 *


17.69 PUDEF
      -----

Redefine symbols in PRINT USING statements.

PUDEF "nnnn"

Where "nnnn" is any combination of characters, up to four in all, PUDEF
allows you to redefine any of the following four symbols in the PRINT USING
statement: blanks, commas, decimal points and dollar signs. These four sym-
bols can be changed into some other character by placing the new character
in the correct position in the PUDEF control string.

Position 1 is the filler character. The default is a blank. Place a new
character here for another character to appear in place of blanks.

Position 2 is the comma character. Default is a comma.

Position 3 is the decimal point. Default is a decimal point.

Position 4 is the dollar sign. Default is a dollar sign.


EXAMPLE:

     10 PUDEF"*"      PRINTs * in the place of blanks.
     20 PUDEF" <"     PRINTs < in the place of commas.

NOTE: All positions up to the one(s) to be changed must be specified.

For example PUDEF "   $" would print the $ in place of the dollar sign, but
the decimal point, comma and filler character would all be set to space.

PUDEF only affects numeric formats i.e. PUDEF "0" will change filler spaces
in numbers to leading 0s, but will not affect filler spaces in strings.

The character to replace the $ has no effect unless the $ in the format
string of PRINT USING is preceded by a # (i.e. is floating).


17.70 READ

Read data from DATA statements and input it into the computer's memory
(while the program is RUNning)

READ variable list

This statement takes information from DATA statements and stores them in
variables, where the data can be used by the RUNning program. The READ
statement variable list may contain both strings and numbers. Be careful to
avoid reading strings where the READ statement expects a number, this pro-
duces a TYPE MISMATCH ERROR message.

The data in the DATA statements are READ in sequential order. Each READ
statement can read one or more data items. Every variable in the READ
statement requires a DATA item. If one is not supplied, an OUT OF DATA
ERROR occurs.

In a program, you can READ the data and the reREAD by issuing the RESTORE
statement. The RESTORE statement sets the sequential data pointer back to
the beginning, where the data can be READ again. See the RESTORE statement,
in paragraph 17.75.


EXAMPLES:

     10 READ A, B, C
     20 DATA 3, 4, 5

READ 3 data items (which must be numeric or an error will occur) into
variables A, B and C.

     10 READ A$, B$, C$
     20 DATA JOHN, PAUL, GEORGE

READ three strings from DATA statements.

     10 READ A, B$, C
     20 DATA 1200, NANCY, 345

READ a numeric value, a string, and another numeric value.


17.71 RECORD
      ------

Position relative file pointers.

RECORD#logical file number, record number [,byte]

This statement positions a relative file pointer to select any byte
(character) of any record in the relative file. The logical file number can
be in the range between 1 and 255. The record number can be in the range 1
through 65535. Byte number is in the range 1 through 254. See your disk
drive manual for details about relative files.

When the record number value is set higher than the last record number in
the file, the following occurs:

For a write (PRINT#) operation, additional records are created to expand
the file to the desired record number.

For a read (INPUT# or GET#) operation, a null record is returned and a
RECORD NOT PRESENT error occurs.


EXAMPLE:

     10 DOPEN #2,"CUSTOMER"
     20 RECORD#2,10,1
     30 PRINT#2,A$
     40 DCLOSE #2

This example opens an existing relative file called "CUSTOMER" as file
number 2 in line 10. Line 20 positions the relative file pointer at the
first byte in record number 10. Line 30 actually writes the data, A$, to
the file.

The RECORD command accepts variables for its parameters. It is often con-
venient to place the RECORD command within a FOR... NEXT or DO loop. Also
see DOPEN, in paragraph 17.31.


17.72 REM

Comment or remark about the operation of a program line.

REM [message]

The REMark statement is a note to whoever is reading a listing of the pro-
gram. REM may explain a section of the program, give information about the
author, etc. REM statements do not affect the operation of the program,
except to add length to it (and therefore use more memory). Nothing to the
right of the keyword REM is interpreted by the computer as an executable
instruction. Therefore, no other executable statement can follow a REM on
the same line.


EXAMPLE:

     1010 NEXT X: REM END OF MAIN PROGRAM LOOP


17.73 RENAME
      ------

Change the name of a file on disk.

RENAME [Ddrive number,] "old filename" TO "new filename"
[<ON | ,>Udevice number]

This command is used to rename a file on disk, from the old filename to the
new filename. The diskdrive does not RENAME a file if it is OPEN.


EXAMPLES:

   RENAME D0, "TEST" TO "FINAL TEST"  Change the name of the file "TEST" to
                                      "FINAL TEST".

   RENAME D0,(A$) TO (B$),U9          Change the filename specified in A$
                                      to the filename specified in B$ on
                                      drive 0, device number 9. Remember,
                                      whenever a variable name is used as a
                                      filename, it must be enclosed in
                                      parentheses.


17.74 RENUMBER
      --------

Renumber lines of a BASIC program.

RENUMBER [new starting line number] [,increment]
[,old starting line number]

The new starting line is the number of the first line in the program after
renumbering; the default is 10. The increment is the interval between line
numbers (i.e. 10, 20, 30, etc.); the increment default value is also 10.
The old starting line number is the first line number before you renumber
the program. The default in this case is the first line of the program.
This command can only be executed from direct mode.

An UNRESOLVED REFERENCE error occurs if any reference to number that does
not exist is encountered. An OUT OF MEMORY occurs if RENUMBERing expands
the program beyond its limits. A LINE NUMBER TOO LARGE error occurs if
RENUMBER generates a line number of 64000 or higher. These errors leave the
program unharmed.


EXAMPLES:

   RENUMBER           Renumbers the program starting at 10, and increments
                      each additional line by 10.

   RENUMBER 20,20,15  Starting at line 15, renumbers the program. Line 15
                      becomes 20, and other lines are numbered in incre-
                      ments of 20.

   RENUMBER,,65       Starting at line 65, renumbers in increments of 10.
                      Line 65 becomes 10. If you omit a parameter, you must
                      still enter a comma as a placeholder. There must be
                      no line between 10 and 64 inclusive.

ALWAYS SAVE YOUR PROGRAM BEFORE RENUMBERING, because very long programs can
cause a SYSTEM crash when RENUMBERed with larger line numbers.

Also note that long programs should be RENUMBERed in FAST mode as they will
take a long time to renumber (up to 30 minutes for a 55K program in FAST).

If you only have a 40 column display use FAST:RENUMBER... {return}. Then
type SLOW {return}. While RENUMBERing is taking place you will not see any-
thing happening. When RENUMBERing has finished, you display will return.

If you have an 80 column display or 40/80 column display select the 80
column screen before typing FAST.


17.75 RESTORE/RESTORE
              -------

Reset READ pointer to DATA statement so the DATA can be reREAD.

RESTORE (C64 mode)

RESTORE [line #] (C128 mode)

When executed in a program, the pointer to the item in a DATA statement
that is to be READ next is reset to the first item in the DATA statement.
This provides the capability to reREAD the data. If a line number follows
the RESTORE statement the READ pointer is set to the first data item after
the specified program line. Otherwise the pointer is reset to the beginning
of the BASIC program. In C64 mode there is no option to specify the line
number, i.e. you can only RESTORE to the beginning of the program.


EXAMPLES:

     10 FOR I=1 TO 3
     20 READ X
     30 T = X + T
     40 NEXT
     45 PRINT T
     50 RESTORE
     69 GOTO 10
     70 DATA 10,20,30

This example READs the data in line 70 and stores it in numeric variable X.
It adds the total (T) of all the numeric data items. Once all the data has
been READ, three cycles through the loop, the READ pointer is RESTOREd to
the beginning of the program and it returns to line 10 and performs repeti-
tively.

     10 READ A,B,C
     20 DATA 100,500,750
     30 READ X,Y,Z
     40 DATA 36,24,38
     50 RESTORE 40
     60 READ S,P,Q
     70 PRINT A,B,C
     80 PRINT X,Y,Z
     90 PRINT S,P,Q

This example RESTOREs the DATA pointer to the first data item in line 40.
When line 60 is executed, it will READ the DATA 36,24,38 from line 40,
since you don't need to READ line 20's DATA again.

NOTE: If a line number is specified the line must exist! A variable can be
used e.g. RESTORE LR.


17.76 RESUME
      ------

Define where the program will continue (RESUME) after an error has been
trapped.

RESUME [line # | NEXT]

This statement is used to restart program execution after TRAPping an
error. With no parameters, RESUME attempts to re-execute the line in which
the error occurred. RESUME NEXT resumes execution at the statement im-
mediately following the one containing the error; RESUME followed by a line
number will GOTO the specific line and resumes execution from that line
number. RESUME can only be used in program mode.


EXAMPLE:

     10 TRAP 100
     20 INPUT "ENTER A NUMBER";A
     30 B=100/A
     40 PRINT"THE RESULT=",B:PRINT"THE END"
     50 PRINT"DO YOU WANT TO RUN IT AGAIN(Y/N)":GETKEYZ$:IF Z$="Y"THEN 20
     60 STOP
     100 INPUT"ENTER ANOTHER NUMBER (NOT ZERO)";A
     110 RESUME

This example traps a division by zero error in line 30 if 0 is entered in
line 20. If zero is entered, the program goes to line 100, where you are
asked to input another number besides 0. Line 110 returns to line 30 to
complete the calculation. Line 50 asks if you want to repeat the program
again. If you do, press the {y} key.


17.77 RETURN

Return from subroutine.

RETURN

This statement is always paired with the GOSUB statement. When a program
encounters a RETURN statement, it goes to the statement immediately fol-
lowing the last GOSUB command executed. If no GOSUB was previously issued,
the a RETURN WITHOUT GOSUB error message is displayed and the program
stops. All subroutines end with a RETURN statement.


EXAMPLE:

     10 PRINT "ENTER SUBROUTINE"
     20 GOSUB 100
     30 PRINT "END OF SUBROUTINE"
     .
     .
     .
     90 STOP
     100 PRINT "SUBROUTINE 1"
     110 RETURN

This example calls the subroutine at line 100 which prints the message
"SUBROUTINE 1" and RETURNs to line 30, the rest of the program.


17.78 RREG
      ----

Read the contents of the accumulator AC, X register XR, Y register YR and
Status register SR.

RREG [var1] [, [var2] [, [var3] [, [var4] ] ] ]

After a SYS command is issued, the contents of the CPU registers AC, XR,
YR and SR are stored in memory before the C128 returns to BASIC. The memory
locations of these stores are:
     AC -> 6
     XR -> 7
     YR -> 8
     SR -> 5

With the RREG command the values in these memory stores are loaded into the
specified variables. The values range between zero and 255 (inclusive).

Not all variables have to be specified. For instance, it is possible to
only read the contents of YR:

     RREG , ,YR : PRINT YR


EXAMPLE:

     100 FOR I=4864 TO 4870
     110 READ D : POKE I,D
     120 NEXT I
     130 DATA 169,6,162,7,160,8,96
     131 REM ML PRG
     132 REM
     133 REM 01300 LDA #6 ; LOAD AC WITH VALUE 6
     134 REM 01302 LDX #7 ; LOAD XR WITH VALUE 7
     135 REM 01304 LDY #8 ; LOAD YR WITH VALUE 8
     136 REM 01306 RTS ; END ML SUBROUTINE
     140 SYS 4864
     150 RREG AC, XR, YR
     160 PRINT "AC=";AC, "XR=";XR, "YR=";YR
     170 M6 = PEEK(6) : REM MEMORY LOCATION 6
     180 M7 = PEEK(7) : REM MEMORY LOCATION 7
     190 M8 = PEEK(8) : REM MEMORY LOCATION 8
     200 PRINT "MEMORY LOCATIONS 6, 7 AND 8:"; M6;","M7;","M8

Line 160 prints this:

AC= 6    XR= 7    YR= 8

Line 200 prints this:

MEMORY LOCATIONS 6, 7 AND 8: 6 , 7 , 8


17.79 RUN/RUN
          ---

Execute BASIC program.

RUN [line #]
RUN "filename" [,Ddrive number] [<ON | ,>Udevice number]   (BASIC 7.0 only)

Once a program has been typed into memory or LOADed, the RUN command exe-
cutes it. RUN clears all variables in the program before starting program
execution. If there is a number following the RUN command, execution starts
at that line number. If there is a filename following the RUN command, the
named file is loaded from the disk drive and RUN, with no further action
required by the user. RUN may be used within a program. The default drive
number is 0 and default device number is 8.


EXAMPLES:

RUN

Starts execution from the beginning of the program currently in memory.

   RUN 100     Starts program execution at line 100.

   RUN"PRG1"   DLOADs "PRG1" from disk drive 8, and runs it from the first
               line.

   RUN(A$)     DLOADs the program named in the variable A$ and runs it from
               the first line.


17.80 SAVE

Store the program in memory to disk or tape.

SAVE ["filename"] [,device number] [,EOT flag]

This command stores the program currently in memory onto cassette tape or
disk for later retrieval. If SAVE is typed alone an unnamed file will be
saved to tape. Tape is a sequential system and, therefore, it is up to the
user to ensure that there is nothing important on the tape before SAVEing
(see VERIFY, in paragraph 17.100). To give your program a name simply en-
close the chosen name in quotes (or use a string variable) immediately after
typing SAVE. A filename can be up to 16 characters.

NOTE: When SAVEing to disk you must specify a filename or you will get a
MISSING FILE NAME ERROR.

To specify the device number (e.g. 1 for tape) place a comma followed by
the device number after the closing quote following the filename.

The final parameter (EOT) follows the device number and is again seperated
by a comma. It has no significance when used with disk and can have one of
four values when used with tape. These options are:

0    Default - no action.

1    SAVE so that the relocate function of LOAD does not work, i.e. the
     file will always load back at the address from which it was SAVEd.

2    Write an END OF TAPE marker at the end of the file - attempts to LOAD
     beyond the end of a file saved this way will generate a FILE NOT FOUND
     ERROR.

3    SAVEs in non-relocatable format (1) and writes the EOT (2).

     NOTE: If you specify the device number or EOT parameter the filename
     (and device number) must be included. For tape this may be a null
     (""). See the following examples.


EXAMPLES:

   SAVE "HELLO"         Stores a program on tape, under the name HELLO

   SAVE A$,8            Stores on disk, with the name stored in variable
                        A$.

   SAVE "HELLO",8       Stores on disk, with the name HELLO (equivalent to
                        DSAVE "HELLO").

   SAVE "HELLO", 1, 2   Stores on tape, with the name HELLO, and places an
                        END-OF-TAPE marker after the program.
  
   SAVE "",1,3          Stores on tape, with no name, places an EOT marker
                        after the program, does not allow the program to be
                        relocated on loading.


17.81 SCALE
      -----

Alter scaling in graphics mode.

SCALE n [,xmax,ymax]

where:

n =       1 (on) or 0 (off)
xmax is   in the range 320-32767,
            default 1023 (hi-res)
            default 2047 (multicolor)
ymax is   in the range 200-32767,
            default 1023

Changes the scaling of the bit map display coordinates in both multicolor
and high resolution modes. Coordinates for the MOVSPR command are also
scaled. Maps many logical points to one physical point.

This is helpful when you need to plot data over a wide range of values - it
will not help if you have a large cluster of data with only high values.

Because multicolor uses 2 physical pixels on the x-axis per dot, its normal
display is:
                        X=0 to 159 ; Y=0 to 199
as opposed to
                        X=0 to 319 ; y=0 to 199

If you wish to use the same coordinates for multicolor and hi-res use SCALE
1,640,200 after setting up a multicolor screen and use the default SCALE
values for both types of screen.

NOTE: The GRAPHIC command turns scaling off, i.e. using GRAPHIC (something)
is equivalent to GRAPHIC...: SCALE 0.


EXAMPLE:

     10 GRAPHIC 1: GOSUB 100
     20 SCALE 1: GOSUB 100
     30 SCALE 1,5000,5000: GOSUB 100
     40 END
     100 CIRCLE 1,160,100,60: RETURN


17.82 SCNCLR
      ------

Clear screen.

SCNCLR [mode number]

Mode Number   Mode
     0        40 column (VIC) text.
     1        bit map*.
     2        split screen bit map*.
     3        multicolor bit map*.
     4        split screen multicolor bit map*.
     5        80 column (VDC 8563) text.

This statement with no arguments clears the graphics screen, if it is pre-
sent, otherwise the current text screen is cleared**.


EXAMPLES:

   SCNCLR 5   Clears 80 column text screen.

   SCNCLR 1   Clears the (VIC) bit map screen.

   SCNCLR 4   Clears the (VIC) multicolor bit map split screen.

NOTE *: The bit map area is the same for both hi-res and multicolor, the
different mode numbers select other parameters to clear e.g. 40 column text
(2 and 4) and color RAM (3 and 4).

NOTE **: If a graphics screen has been created but is not selected
(GRAPHIC=0) it will not be cleared. If you are using 2 screens (80 column
for text and 40 column for graphics) SCNCLR will clear both text and
graphics screens if called from the 80 column screen.


17.83 SCRATCH
      -------

Delete a file from the disk directory.

SCRATCH "filename" [,Ddrive number] [<ON | ,>Udevice number]

This command deletes a file form the disk directory. As a precaution, the
system asks "Are you sure?" (in direct mode only) before the Commodore 128
starts the operation. Type a {y} to perform the SCRATCH or press any other
key to cancel the operation.

Use this command to erase unwanted files, and to create more space on the
disk. The filename may contain template, or wildcards (?,*). The default
drive number is 0 and default device number is 8.


EXAMPLE:

   SCRATCH "MY BACK",D0   This erases the file "MY BACK" from the disk in
                          drive 0 of unit 8.


17.84 SLEEP
      -----

Delay program for a specific period of time.

SLEEP n

where n is seconds (0 < n < 65536)

If you select a delay which is too long for your program and you want to
halt it, the {stop} key can be used to break into a delay.


17.85 SLOW
      ----

Return the Commodore 128 to 1 Mhz operation.

SLOW

The Commodore 128 is capable of running the 8502 microprocessor at a speed
of 1 or 2 Megahertz (Mhz).

The SLOW command slows down the microprocessor to 1 Megahertz from 2 Mega-
hertz. The FAST command sets the Commodore 128 at 2 Mhz. The Commodore 128
can process commands substantially faster at 2 Mhz than at 1 Mhz. Note,
however, that the 40 column screen cannot be used at 2 Mhz.


17.86 SOUND
      -----

Outputs sound effects and musical notes.

SOUND v, f, d [, dir] [, m] [, s] [, w] [, p]

where:   v =    voice 1, 2 or 3
         f =    frequency value (0-65535)
         d =    duration (0-32767)
         dir =  step direction (0 = up, 1 = down, 2 = oscillate), default=0
         m =    minimum frequency (0-65535) if the sweep is used, default=0
         s =    step value for sweep (0-65535), default=0
         w =    waveform (0 = triangle, 1 = sawtooth, 2 = pulse, 3 =
                noise), default=2
         p =    pulse width (0-4095), default=2048

The SOUND command is a fast and easy way to create sound effects and musi-
cal tones. The three required parameters v, f and d select the voice, fre-
quency and duration of the sound. The duration is in units called jiffies.
Sixty jiffies equals 1 second.

The SOUND command can sweep through a series of frequencies which allows
sound effects to pass through a range of notes. Specify the direction of
the sweep with the dir parameter. Set the minimum frequency of the sweep
with m and the step value of the sweep with s. Select the appropriate wave-
form with w and specify p as the width of the variable pulse waveform if
selected in w.


EXAMPLES:

   SOUND 1,40960,60             Play a SOUND at frequency 40960 in voice 1
                                for 1 second.

   SOUND 2,2000,5,0,2000,100    Output a sound by sweeping through the fre-
                                quencies starting at 2000 and incrementing
                                upward in units of 100.

   SOUND 3,5000,1,2,3000,500,1  This example outputs a range of sounds
                                starting at a minimum frequency of 3000,
                                through 5000, in increments of 500. The di-
                                rection of the sweep is back and forth
                                (oscillating). The selected waveform is saw-
                                tooth and the voice selected is 3.


17.87 SPRCOLOR
      --------

Set multicolor 1 and/or multicolor 2 colors for all sprites.

SPRCOLOR [smcr1] [, smcr2]

where:

smcr1 = multicolor 1 for all sprites.
smcr2 = multicolor 2 for all sprites.

These parameters may be any color from 1 through 16.


EXAMPLES:

   SPRCOLOR 3,7  Sets sprite multicolor 1 to red and multicolor 2 to blue.

   SPRCOLOR 1,2  Sets sprite multicolor 1 to black and multicolor 2 to
                 white.


17.88 SPRDEF
      ------

Enter the SPRite DEFinition mode to create and edit sprite images (40
column display only).

SPRDEF

The SPRDEF command defines sprites interactively.

Entering the SPRDEF command, displays a sprite work area on the screen
which is 24 characters wide by 21 characters tall. Each character position
in the grid corresponds to a sprite pixel in the sprite displayed to the
right of the work area. Here is a summary of the SPRite DEFinition mode
operations and the keys that perform them:

                      At the SPRITE NUMBER? prompt
user      input description

{return}    Exits SPRite DEFinition mode at the SPRITE NUMBER? prompt only.
{1} - {8}   Selects a sprite number and enters sprite edit mode.

                        In the sprite edit mode
user        input description

{a}         Turns on and off Automatic cursor movement.
{crsr}      Moves cursor.
 keys    
{return}    Moves cursor to start of next line.
{home}      Moves cursor to top left corner of sprite work area.
{clr}       Erases entire grid.
{1}-{4}     Selects color source:
            1 = clear
            2 = foreground
            3 = multicolor 1
            4 = multicolor 2
{ctrl 1} -  Selects sprite foreground color (1-8).
   {ctrl 8}
{C= 1}      Selects sprite foreground color (9-16).
   - {C= 8}
{stop}      Cancels changes and returns to the READY prompt.
{shift      Saves sprite in memory and returns to the SPRITE NUMBER?
    return} prompt.
{x}         Expands sprite in X (horizontal) direction - Toggle.
{y}         Expands sprite in Y (vertical) direction - Toggle.
{m}         Standard sprite / Multicolor sprite - Toggle.
{c}         Copies sprite data from one sprite to another.

NOTE: Using SPRDEF will clear the bit map screen.


17.89 SPRITE
      ------

Turn on or off, color, expand and set screen priorities for a sprite.

SPRITE <number> [,on/off] [,fgnd] [,priority] [,x-exp] [,y-exp] [,mode]

The SPRITE statement controls most of the characteristics of a sprite.

Parameter Description

number    Sprite number (1-8).
on/off    Turns sprite on (1) or off (0).
fgnd      Sprite foreground color (1-16).
priority  Priority is 0 if sprites appear in front of object on the screen;
          priority is 1 if sprites appear behind objects on the screen.
x-exp     Horizontal EXPansion on (1) or off (0).
y-exp     Vertical EXPansion on (1) or off (0).
mode      Select standard sprite (0) or multicolor sprite (1). (See
          SPRCOLOR, in paragraph 17.87)

Unspecified parameters in subsequent sprite statements take on the charac-
teristics of the previous SPRITE statement. You can check the characteris-
tics of a SPRITE with the RSPRITE function.


EXAMPLES:

   SPRITE 1,1,3           Turn on SPRITE number 1 and color it red.

   SPRITE 2,1,7,1,1,1     Turn on SPRITE number 2, color it blue, make it
                          pass behind objects on the screen and expand it
                          in horizontal and vertical directions.

   SPRITE 6,1,1,0,0,1,1   Turn on SPRITE number 6, color it black. The
                          first appearing 0 tells the computer display the
                          sprites are in front of objects on the screen.
                          The second 0 and the following 1 tell the C128 to
                          expand the sprite vertically only. The last 1
                          specifies the sprite to be displayed in multico-
                          lor mode. Use the SPRCOLOR command to select the
                          sprite's multicolor.

   SPRITE 7,,,,1          Set the horizontal expansion of SPRITE number 7 -
                          all other options retain their previous settings.


17.90 SPRSAV
      ------

Store a sprite data from a text string variable into a sprite storage area
or vice versa.

SPRSAV origin,destination

This command transfers a sprite image from a string variable to a sprite
storage area. It can also tranfer data from the sprite storage area into a
string variable. Either the origin or the destination can be a sprite num-
ber or a string variable but they both cannot be string variables (they
both CAN be sprite numbers, however). If you are moving a string into a
sprite, only the first 63 bytes of data are used. The rest are ignored,
since a sprite can only hold 63 data bytes.

NOTE: SPRSAV sprite, string produces a string in the same format as SSHAPE
so that it can be used with GSHAPE to 'fix' a sprite onto hi-res screen.
The string will be 67 characters long.


EXAMPLES:

   SPRSAV 1,A$   Transfers the image pattern from sprite 1 to the string
                 named A$.

   SPRSAV B$,2   Transfers the data from the string variable B$ into sprite
                 2.

   SPRSAV 2,3    Transfers the data from sprite 2 to sprite 3.


17.91 SSHAPE/GSHAPE
      -------------

Save/retrieve shapes to/from string variables.

SSHAPE and GSHAPE are used to save and load rectangular areas of multicolor
or standard bit mapped screen to/from BASIC string variables. The command
to save an area of the screen into a string variable is:

SSHAPE string variable, x1, y1 [, x2, y2]

where:

string variable  String name to save data in
x1, y1           Corner coordinates (0,0 through 319,199) (scaled).
x2, y2           Corner coordinates opposite (x1,y1) (default is the PC)


Because BASIC limits strings to 255 characters, the size of the area that
can be saved is limited. The string size required can be calculated using
one of the following (unscaled) formulas:

L(hi-res) = INT( (ABS(x1-x2) + 1) / 8 + .99) * (ABS(y1-y2) + 1) + 4

L(multicolor) = INT( (ABS(x1-x2) + 1) / 4 + .99) * (ABS(y1-y2) + 1) + 4

NOTE: The upper limits of the coordinates (319,199 for standard and 159,199
for multicolor bit mapped graphics) apply to the unSCALEd coordinate
system. When SCALE is turned on, the limit are set by the SCALE command.

The command to retrieve (load) the data from a string variable and display
it on specified screen coordinates is:

GSHAPE string variable, [x,y] [,mode]

where:

string           Contains shape to be drawn.
x,y              Top left coordinates (0,0 through 319,199) telling where
                 to draw the shape (scaled), default is the pixel cursor.
mode             Replacement mode:
                 0: place shape as is (default).
                 1: invert (reverse) shape.
                 2: OR shape with area.
                 3: AND shape with area.
                 4: XOR shape with area.

The replacement mode allows you to change the data in the string variable
so that you can invert it, perform a logical OR, exclusive OR or AND
operation on the image.

Also see the LOCATE command, in paragraph 17.57, for information on the
pixel cursor.


EXAMPLES:

SSHAPE A$,10,10        Saves a rectangular area from the coordinates
                       (10,10) to the location of the pixel cursor, into
                       string variable A$.

SSHAPE B$,20,30,47,51  Saves a rectangular area from top left coordinates
                       (20,30) throught bottom coordinates (47,51) into
                       string variable B$.

GSHAPE A$,120,20       Retrieves shaped contained in string variable A$ and
                       displays it at top left corner at coordinates (120,
                       20).

GSHAPE B$,30,30,1      Retrieves shape contained in string B$ and displays
                       it at top left coordinates (30,30). The shape is
                       inverted due to the replacement mode being selected
                       by the 1.

NOTE: Beware using modes 1-4 with multicolor shapes. You may obtain unpre-
dictable results.


17.92 STASH
      -----

Move contents of host memory to expansion RAM.

STASH #bytes, intsa, expsa, expb

Refer to FETCH command for description of parameters.


17.93 STOP

Halt program execution.

STOP

This statement halts the program. A message, BREAK IN LINE xxx occurs (in
program mode), where xxx is the line number containing the STOP command.
The program can be restarted at the statement following STOP if the CONT
command is used immediately, without any editing occuring in the listing.
The STOP statement is often used while debugging a program.


17.94 SWAP
      ----

Swap contents of host RAM with contents of expansion RAM.

SWAP #bytes, intsa, expsa, expb

Refer to FETCH command for description of parameters.


17.95 SYS/SYS
          ---

Call and execute a machine language subroutine at the specified address.

SYS address                                                      (C64 mode)
SYS address [, [a] [, [x] [, [y] [, [s] ] ] ] ]                 (C128 mode)

This statement performs a call to a machine code subroutine at the given
address in a memory configuration set up according to the BANK command.
Optionally, arguments a, x, y and s are loaded into the accumulator, x, y
and status registers respectively, before the subroutine is called.

The address range is 0 to 65535 (both inclusive). The program begins exe-
cuting the machine language program starting at that memory location. Also
see the BANK command, in paragraph 17.4.


EXAMPLES:

SYS 40960   Calls and executes the machine language routine at location
            40960.

SYS 8192,0  Calls and executes the machine language routine at location
            8192 and loads zero into the accumulator.


17.96 TEMPO
      -----

Define the speed of the song being played.

TEMPO n

where n is a relative duration between 1 and 255 (inclusive).

The actual duration for a whole note is determined by using the formula
given below:

whole note duration = 23.06/n seconds

The default value of n is 8, and note duration decreases with n.


EXAMPLES:

TEMPO 16    Defines the TEMPO at 16.

TEMPO 1     Defines the TEMPO at the slowest speed.

TEMPO 250   Defines the TEMPO at 250.


17.97 TRAP
      ----

Detect and handle program errors while a BASIC program is RUNning.

TRAP [line#]

When turned on, TRAP intercepts all error conditions (excluding DOS error
messages, but including the {stop} key). In the event of any execution er-
ror, the error flag is set and execution is transferred to the line number
specified in the TRAP statement.

The line number in which the error occurred can be found by using the
system variable EL. The specific error condition is contained in system
variable ER. The string function ERR$(ER) gives the error message corres-
ponding to the error condition.

The RESUME statement can be used to resume program execution. TRAP with no
line number turns off error trapping. An error in a TRAP routine cannot be
trapped, unless it contains a TRAP statement of its own.


EXAMPLE:

100 TRAP 1000       If an error occurs, go to line 1000.
1000 ?ERR$(ER);EL   Print the error message, and the error line number.
1010 RESUME         Resume program execution.


17.98 TROFF
      -----

Turn OFF error TRacing mode.

TROFF

This statement turns off trace mode.


17.99 TRON
      ----

Turn ON error TRacing mode.

TRON

TRON is used in program debugging. This statement begins trace mode. When
you RUN the program, the line numbers of the program appear in brackets be-
fore any action for that line occurs.

If you have multistatement lines, the line number will be printed before
each statement is processed.


17.100 VERIFY

Verify program in memory against one saved to disk or to tape.

VERIFY ["filename"] [,device number] [,relocate flag]

This command causes the Commodore 128 to check the program on tape or disk
against the one in memory, to determine if the program is really SAVEd.
This command is also very useful for positioning a tape so that the Commo-
dore 128 writes after the last program on tape.

VERIFY, with no arguments after the command, causes the Commodore 128 to
check the next program on tape, regardless of its name, against the program
now in memory. VERIFY, followed by a program name  in quotes or a string
variable, searches the tape for that program and when found checks it
against the program in memory. VERIFY, followed by a name, a comma and a
number, checks the program on the device with that number (1 for tape, 8
for disk). The relocate flag is the same as in the LOAD command. It veri-
fies the program from the memory location from which it was SAVEd. (See also
DVERIFY, in paragraph 17.34.)


EXAMPLES:

VERIFY "HELLO"       Searches for HELLO on tape, checks it against memory.

VERIFY "HELLO",8,1   Searches for HELLO on disk, then checks it against
                     memory.

VERIFY "LASTFILE"    Searches tape for LASTFILE, checks it, reports an
                     error if there is no match. You can then save you new
                     program after it, without erasing previous programs.

NOTE: If graphic area is allocated or deallocated after a SAVE, VERIFY and
DVERIFY will report an error. Technically this is correct. BASIC text in
this case has moved from its original (SAVEd) location to another address
range. Hence, VERIFY, which performs byte-to-byte comparisons, will fail,
even though the program is valid.


17.101 VOL
       ---

Define output level of sound.

VOL volume level

This statement sets the volume for SOUND and PLAY statements. VOLUME level
can be set from 0 to 15, where 15 is the maximum volume, and 0 is off. VOL
affects all voices.


EXAMPLES:


VOL 0    Turns volume off.

VOL 1    Sets volume to its lowest audible level.

VOL 15   Sets volume for SOUND and PLAY statements to its highest level.


17.102 WAIT

Pause program execution until a data condition is satisfied.

WAIT location, mask1 [, mask2]

The WAIT statement causes program execution to be suspended until a given
memory address recognizes a specific bit pattern or value. In other words,
WAIT can be used to halt the program until some external event has occur-
red. This is done by monitoring the status of bits in the Input/Output re-
gisters. The data items used with the WAIT can be any values. For most pro-
grammers, this statement should never be used. It causes the program to be
halt until a specific memory location's bits change in a specific way.
This is used for certain I/O operations and almost nothing else. The WAIT
statement takes the value in the memory location and performs a logical AND
operation with the value in mask1. If mask2 is specified, the result of the
first operation is exclusively ORed with mask2. In other words, mask1
"filters out" any bits not to be tested. Where the bit is 0 in mask1, the
corresponding bit in the result will always be 0 . The mask2 value flips
any bits, so that an off condition can be tested as well as an on condi-
tion. Any bits being tested for a 0 should have a  1 in the corresponding
bit position in mask2. If corresponding bits of the mask1 and mask2
operands differ, the exclusive-OR operation gives a bit result of 1. If the
corresponding bits get the same the bit is 0. It is possible to enter an
infinite pause with the WAIT statement, in which case the {run/stop} and
{restore} keys can be used to recover. WAIT may require a bank command if
the memory you wish to access is not in the currently selected BANK.

The following examples are for the C128 mode only. The first example WAITs
until a key is pressed on the tape unit to continue with the program. The
second example will WAIT until the {shift} key is pressed and then
released. The third example will WAIT until either bit 7 (128) is on or
bit 4 (16) if off.


EXAMPLES:

WAIT 1,32,32

WAIT 211,1:WAIT 211,1,1

WAIT 36868, 144, 16

(144 and 16 are binary masks. 144=%10010000 in binary and 16 = %10000 in
binary.)


17.103 WIDTH
       -----

Set the width of drawn lines.

WIDTH n

This command sets the width of lines drawn using BASIC's graphic commands
to either single or double width. Giving n a value of 1 defines a single
width line; a value of 2 defines a double width line.


EXAMPLES:

WIDTH 1   Set width for graphic commands.

WIDTH 2   Set double width for drawn lines.


17.104 WINDOW
       ------

Defines a screen window.

WINDOW top left col, top left row, bot right col, bot right row [, clear]

This command defines a logical window within the 40 or 80 column text
screen. The coordinates must be in the range 0-39/79 for column values and
0-24 for row values. The clear flag, if provided (1), causes a screen-clear
to be performed (but only within the limits of the newly described window).


EXAMPLES:

   WINDOW 5,5,35,20   Defines a window with top left corner coordinates
                      (5,5) and bottom right corner coordinates (35,20).

WINDOW 10,2,33,34,1   Defines a window with upper left corner coordinates
                      (10,2) and lower right coordinates (33,24). Also
                      clears the portion of the screen within the window as
                      specified by the 1.

NOTE: If you specify a column greater than 39 on a 40-column display you
will get an "ILLEGAL QUANTITY ERROR".




SECTION 18

18. Basic Functions




The format of the function description is:
     FUNCTION(argument)

where the argument can be a numeric value, variable or string. Each func-
tion description is following by an example.


18.1 ABS

Return absolute value.
     ABS(x)

The absolute value function returns the positive value of the argument.

     EXAMPLE:

     PRINT ABS(7*(-5))
      35


18.2 ASC

Return CBM ASCII code for character.
     ASC(x$)

This function returns the ASCII code for the first character of x$. In C128
mode you no longer have to append CHR$(0) to a null string; ILLEGAL
QUANTITY ERROR is no longer issued.

     EXAMPLE:

     X$="C128":PRINTASC(X$)
      67


18.3 ATN

Return angle whose tangent is X radians.
     ATN(x)

This function returns the angle whose tangent is x, measured in radians.

     EXAMPLE:

     PRINT ATN(3)
      1.24904577


18.4 BUMP
     ----

Return sprite collision information.
     BUMP(n)

To determine which sprites have collided since the last check, use the BUMP
function. BUMP(1) records which sprites have collided with each other and
BUMP(2) records which sprites have collided with other objects on the
screen. COLLISION need not be active to use BUMP. The bit positions (0-7)
in the BUMP value correspond to sprites 1 through 8 respectively. BUMP(n)
is reset to zero after each call.

The value returned by BUMP is the result of two raised to the power of the
bit position. Remember bit position range from zero to seven, so a bit po-
sition corresponds to the sprite number - 1. For example, if BUMP returned
a value of 16, sprite 5 was involved since 2 raised to the power (5 minus
1) equals 16.

     EXAMPLES:

     PRINT BUMP(1)  Indicates that sprites 3 and 4 have collided.
      12

     PRINT BUMP(2)  Indicates that sprite 6 has collided with an object on
      32            the screen.


18.5 CHR$

Return ASCII character for specified CBM ASCII code.
     CHR$(x)

This is the opposite of ASC and returns the string character whose CBM
ASCII code is x. Refer to Appendix E for a table of CHR$ codes.


     EXAMPLES:

     PRINT CHR$(65)  Prints the a character
     A

     PRINT CHR$(147) Clears the text screen.


18.6 COS

Return cosine of angle of x radians.
     COS(x)

This function returns the value of the cosine of x, where x is an angle
measured in radians.

     EXAMPLE:

     PRINT COS({pi})
     -1


18.7 DEC
     ---

Return decimal value of hexadecimal number string.
     DEC(hexadecimal-string)

This function returns the decimal value of hexadecimal-string.

     EXAMPLES:

     PRINT DEC("D020")
      53280

     F$="F":PRINT DEC(F$)
      15


18.8 ERR$
     ----

Return the string describing an error condition.
     ERR$(n)

This function returns a string describing an error condition. Also see
system variables EL and ER, in paragraph 19.1, and Appendix A for a list of
BASIC error messages.

     EXAMPLE:

     PRINT ERR$(10)
     NEXT WITHOUT FOR


18.9 EXP

Return value of an approximation of e (2.7182813) raised to the power x.
     EXP(x)

This function returns a value of e (2.7182813) raised to the power x.

     EXAMPLE:

     PRINT EXP(1)
      2.7182813


18.10 FNxx

Return value from user defined function.
      FNxx(x)

This function returns the value from the user-defined function xx created
by a DEF FNxx statement.

     EXAMPLE:

     10 DEF FNAA(X)=(X-32)*5/9
     20 INPUT X
     30 PRINT FNAA(X)
     RUN
     ? 40                      (? is input prompt)
      4.44444445


18.11 FRE

Return number of available bytes in memory.
     FRE(x)

Where x is the bank number. x=0 BASIC program storage, and x=1 to check
for available BASIC variable storage.

     EXAMPLES:

     PRINT FRE(0)   Returns the number of free bytes for BASIC programs.
      48893

     PRINT FRE(1)   Returns the number of free bytes for BASIC variable
      64256         storage.


18.12 HEX$
      ----

Return hexadecimal number string from decimal number.
     HEX$(x)

This function returns a four-character string containing the hexadecimal
representation of value x (0 <= x < 65536). The decimal counterpart of this
function is DEC.

     EXAMPLE:

     PRINT HEX$(53280)
     D020
     NOTE: HEX$(0) is "0000".


18.13 INSTR
      -----

Return position of string 1 in string 2.
     INSTR(string 1, string 2 [, starting position])

The INSTR function searches for the first occurrance of string 2 within
string 1, and returns the position within string 1 where the match is
found. The optional parameter for starting position establishes the posi-
tion in string 1 where the search begins. The starting position must be in
the range of 1 through 255. If no match is found or, if starting position
is greater than the length of string 1 or if string 1 is null, INSTR re-
turns the value 0. If string 2 is null, INSTR returns 0.

     EXAMPLE:

     PRINT INSTR("COMMODORE 128","128")
      11


18.14 INT

Return integer form (whole number part) of a floating point value.
     INT(x)

This function returns the integer value of the expression. If the expres-
sion is positive, the fractional part is left out. If the expression is
negative, any fraction causes the next lower integer to be returned.

     EXAMPLES:

     PRINT INT(3.14)
      3

     PRINT INT(-3.14)
     -4


18.15 JOY
      ---

Return position of joystick and the status of the fire button.
     JOY(n)
     where n equals:
     1  JOY returns position of joystick 1
     2  JOY returns position of joystick 2

Any value of 128 or more means that the fire button is also pressed. To
find the JOY value, add the direction value of the joystick plus 128, if
the JOY fire button is pressed. The direction is indicated as follows:

                                   1 
                                8     2
                              7    0     3
                                6     4
                                   5 

     EXAMPLES:

     JOY(2) is 135
     When joystick 2 fires and goes to the left.

     IF (JOY(1) AND 128) = 128 THEN PRINT "FIRE"
     Determines whether the fire button of joystick 1 is pressed.


18.16 LEFT$

Return the leftmost characters of string.
     LEFT$(string, length)

This function returns a string comprised of the number of leftmost charac-
ters of the string determined by the length argument. The length argument
must be an integer in the range of 0 to 255. If this integer value is
greater than the length of the string, the entire string is returned. If
the value is equal to zero, then a null string (of zero length) is retur-
ned.

     EXAMPLE:

     PRINT LEFT$("COMMODORE",5)
     COMMO


18.17 LEN

Return the length of a string.
     LEN(string)

This function returns the number of characters in the string expression.
Non-printable characters and blanks are included.

     EXAMPLE:

     PRINT LEN("COMMODORE128")
      12


18.18 LOG

Return natural log of x.
     LOG(x)

This function returns the natural log of x. The natural log is log to the
base e (see EXP(x), in paragraph 18.9). To convert to log base 10, divide by
LOG(10).

     EXAMPLE:

     PRINT LOG(37 / 5)
      2.00148


18.19 MID$

Return a substring from a larger string or overlay a substring into a
larger string.
     MID$(string, starting position [, length])

This function returns a substring specified by the length, starting at the
character specified by the starting position. The starting position of the
substring defines the first character where the substring begins. The
length of the substring is specified by the length argument. Both of the
numeric arguments can have values ranging from 0 to 255. If the starting
position value is greater than the length of the string, or if the length
of the string is zero, then MID$ returns a null string value (of length
zero). If the length argument is left out, all characters to the right of
the starting position are returned (which is equivalent with RIGHT$).

     EXAMPLE:

     PRINT MID$("COMMODORE 128",3,5)
     MMODO

     EXAMPLE using overlay:

     A$="123456":MID$(A$,3,2)="ABCDE":PRINT A$
     12AB56

NOTE: Overlay cannot be used to expand the size of a string, thus in the
example above MID$(A$,3,5) is not possible.


18.20 PEEK

Return contents of a specific memory location.
     PEEK(x)

This function returns the contents of memory location x, where x is
located in the range 0 through 65535, returning a result between 0 and 255
(inclusive). This is the counterpart of the POKE statement. The data will
be returned from the bank selected by the most recent BANK command. See
the BANK command, in paragraph 17.4 of Section 17.

     EXAMPLE:

     10 BANK 15:VIC=DEC("D000")
     20 FOR I=1 TO 47
     30 PRINT PEEK(VIC+I)
     40 NEXT

     This example displays the contents of the registers of the VIC chip.


18.21 PEN
      ---

Return x and y coordinates of the light pen.
     PEN(n)
     where:
     n=0   PEN returns the x coordinate of the light pen position.
     n=1   PEN returns the y coordinate of the light pen position.
     n=2   PEN returns the x coordinate of the light pen position of the
           80 column display.
     n=3   PEN returns the y coordinate of the light pen position of the
           80 column display.
     n=4   PEN returns the light pen trigger value.

Note that, like sprite coordinates, the PEN value is not scaled and uses
real coordinates, not graphic bit map coordinates. The x position is given
as a number, ranging from approximately 60 to 320, while the y position
can be any number from 50 to 250. These are the visible screen coordinate
ranges, where all other values are not visible on the screen. A value of
zero for either position means the light pen is off screen and has not
triggered an interrupt since the last read. Note that COLLISION need not
be active to use PEN. A white background is usually required to stimulate
the light pen. PEN values vary from system to system.

Unlike the 40 column (VIC), the 80 column (VDC 8563) coordinates are
character row and column positions and not pixel coordinates, like the VIC
screen.

Both the 40 and 80 column screen coordinate values are approximate and
vary, due to the nature of light pens. The read values are not valid until
PEN(4) is true.

     EXAMPLES:

     10 PRINT PEN(0);PEN(1)     Display the x and y coordinates of the
                                light pen.
    

     10 DO UNTIL PEN(4):LOOP    Ensure the read values are valid.
     20 X=PEN(2)
     30 X=PEN(3)
     40 REM:REST OF PROGRAM


18.22 {pi}

Return the value of pi (3.14159265).
     {pi}

     EXAMPLE:

     PRINT {pi}
      3.14159265


18.23 POINTER
      -------

Return the address of a variable name.
     POINTER(variable name)

     EXAMPLE:

     PRINT POINTER(Z)

     This example returns the address of variable Z.


18.24 POS

Return the current cursor column position within the current screen window.
     POS(x)

The POS function indicates where the cursor is within the defined screen
window. X is a dummy argument, which must be specified, but the value is
ignored.

     EXAMPLE:

     PRINT "0123456789"POS(1)
     0123456789 10

     This displays the current cursor position within the defined text
     window, in this case 10.


18.25 POT
      ---

Return the value of the game-paddle potentiometer.
     POT(n)

     when:
     n=1, POT returns the position of paddle #1.
     n=2, POT returns the position of paddle #2.
     n=3, POT returns the position of paddle #3.
     n=4, POT returns the position of paddle #4.

The values for POT range from 0 to 255. Any value of 256 or more means
that the fire button is also depressed.

     EXAMPLE:

     10 PRINT POT(1)
     20 IF POT(1) >=256 THEN PRINT"FIRE"

     This example displays the value of the game paddle 1.

     Note: A value of 255 is returned if no paddles are connected.


18.26 RCLR
      ----

Return color of color source.
     RCLR(n)

This function returns the color (1 to 16) assigned to the color source n
(0 <= n <= 6), where the following n values apply:
     0 = RCLR returns the 40-column background color.
     1 = RCLR returns the bit map foreground color.
     2 = RCLR returns multicolor 1.
     3 = RCLR returns multicolor 2.
     4 = RCLR returns the 40-column border color.
     5 = RCLR returns the 40- or 80-column character color.
     6 = RCLR returns the 80-column background color.

The counterpart to the RCLR function is the COLOR command.

     EXAMPLE:

     10 FOR I=0 TO 6
     20 PRINT "SOURCE";I;"IS COLOR CODE";RCLR(I)
     30 NEXT

     This example prints the color codes for all seven color sources.


18.27 RDOT
      ----


Return current position or color of pixel cursor.
     RDOT(n)

     where:
     n=0   returns the x coordinate of the pixel cursor.
     n=1   returns the y coordinate of the pixel cursor.
     n=2   returns the color source of the pixel cursor.

This function returns the location of the current position of the pixel
cursor (PC) or the current color source ot the pixel cursor.

     EXAMPLES:

     PRINT RDOT(0) Returns x position of PC.

     PRINT RDOT(1) Returns y position of PC.

     PRINT RDOT(2) Returns color source of PC (0 to 3).


18.28 RGR
      ---

Return current graphic mode.
     RGR(x)

This function returns the current graphic mode. x is a dummy argument,
which must be specified. The counterpart of the RGR function is the
GRAPHIC command. The value returned by RGR(x) pertains to the following
modes:

     VALUE   GRAPHIC MODE
      0      40 column (VIC) text.
      1      Standard bit map.
      2      Split screen bit map.
      3      Multicolor bit map.
      4      Split screen multicolor bit map.
      5      80 column (VDC 8563) text.

     EXAMPLE:

     PRINT RGR(0)
      1

     This displays the current graphic mode, in this case, standard bit
     map mode.


18.29 RIGHT$

Return substring from rightmost end of string.
     RIGHT$(<string> , <length>)

This function returns a substring taken from the rightmost characters of
the string argument. The length of the substring is defined by the length
argument, which can be any integer in the range of 0 to 255. If the value
of length is zero, then a null string ("") is returned. If the value given
in the length argument is greater than the length of the string, the
entire string is returned. Also see LEFT$ and MID$ functions, in paragraphs
18.16 and 18.19, respectively.

     EXAMPLE:

     PRINT RIGHT$("BASEBALL",5)
     EBALL


18.30 RND

Return a random number.
     RND(x)

This function returns a random number, which value lies between 0 (inclu-
sive) and 1 (exclusive). This is usefull in games, to simulate dice roll
and other elements of chance. It is also used in some statistical appli-
cations.

     If x = 0     RND returns a random number based on the hardware clock.

     If x > 0     RND generates a reproducable pseudo-random number based
                  on the seed value (see below - "If x < 0").

     If x < 0     Produces a random number which is used as a base called
                  a seed.

To simulate the rolling of a dice, use the formula INT(RND(1) * 6 + 1).
First the random number is multiplied by 6, which expands the range to
0-6 (actually, less than six). Then 1 is added, making the range from 1 to
less than 7. The INT function truncates all the decimal places, leaving
the result as a digit from 1 to 6.

     EXAMPLES:

     PRINT RND(0)               This displays a random number.
      .507824123

     PRINT INT(RND(1)*100 + 1)  This displays a random positive number
      89                        less than 100.


18.31 RSPCOLOR
      --------

Return sprite multicolor values.
     RSPCOLOR(n)
When:
     n=1 RSPCOLOR returns the sprite multicolor 1.
     n=2 RSPCOLOR returns the sprite multicolor 2.

The returned color value is a value between 1 and 16 (inclusive). The
counterpart of the RSPCOLOR function is the SPRCOLOR command. Also see the
SPRCOLOR command, in paragraph 17.87 of Section 17.

     EXAMPLE:

     10 SPRITE 1,1,2,0,1,1,1
     20 SPRCOLOR 5,7
     30 PRINT"SPRITE MULTICOLOR 1 IS";RSPCOLOR(1)
     40 PRINT"SPRITE MULTICOLOR 2 IS";RSPCOLOR(2)
     RUN

     SPRITE MULTICOLOR 1 IS 5
     SPRITE MULTICOLOR 2 IS 7

In this example line 10 turns on sprite 1, colors it white, expands it in
both the x and y directions and displays it in multicolor mode. Line 20
selects sprite multicolors 1 and 2. Lines 30 and 40 print the RSPCOLOR
values for multicolor 1 and 2.


18.32 RSPPOS
      ------

Return the speed and position values of a sprite.
     RSPPOS(sprite number, n)

where sprite number identifies which sprite is being checked and n
specifies x and y coordinates or the sprite's speed.

When n equals:
     0   RSPPOS returns the current x position of the specified sprite.
     1   RSPPOS returns the current y position of the specified sprite.
     2   RSPPOS returns the speed (0-15) of the specified sprite.

     EXAMPLE:

     10 SPRITE 1,1,2
     20 MOVSPR 1,45#13
     30 PRINT RSPPOS(1,0);RSPPOS(1,1);RSPPOS(1,2)

     This example returns the current x and y sprite coordinates and the
     speed (13), all of sprite 1.


18.33 RSPRITE
      -------

Return sprite characteristics.
     RSPRITE(sprite number, characteristic)

RSPRITE returns sprite characteristics that were specified in the SPRITE
command. Sprite number specifies the sprite you are checking and the
argument characteristics specifies the sprite's display qualities as
follows:

Characteristic  RSPRITE returns these values:

0               Enabled (1) / Disabled (0).
1               Sprite color (0-16).
2               Sprites are displayed in front of (0) or behind (1).
3               Expand in x direction,              yes=1, no=0.
4               Expand in y direction,              yes=1, no=0.
5               Multicolor,                         yes=1, no=0.

     EXAMPLE:

     10 FOR I=0 TO 5         This example prints all 6 characteristics of
     20 PRINT RSPRITE(1,I)   sprite 1.
     30 NEXT
    

18.34 RWINDOW
      -------

Return the size of the current window.
     RWINDOW(n)

When n equals:
     0 RWINDOW returns the number of lines in the current window.
     1 RWINDOW returns the number of rows in the current window.
     2 RWINDOW returns either of the values 40 or 80, depending on the
       current screen output format you are using.

The counterpart of the RWINDOW function is the WINDOW command.

     EXAMPLE:

     10 WINDOW 1,1,10,10
     20 PRINT RWINDOW(0);RWINDOW(1);RWINDOW(2);
     RUN
      9  9  40

This example returns the number of lines (9) and columns (9) in the current
window. The example assumes you are displaying the window in 40 column
format.


18.35 SGN

Return sign of argument x.
     SGN(x)

This function returns the sign (positive, negative or zero) of x. The
result is +1 if x > 0, 0 if x = 0, and -1 if x < 0.

     EXAMPLE:

     PRINT SGN(4.5);SGN(0);SGN(-2.3)
      1  0 -1


18.36 SIN

Return sine of argument x.
    SIN(x)

This is the trigonometric sine function. The result is the sine of x, where
x is an angle measured in radians.

     EXAMPLE:

     PRINT SIN({pi}/3)
     .866025404


18.37 SPC

Skip spaces on the screen.
    SPC(x)

This function is used in PRINT or PRINT# commands to control the formatting
of data, as either output to the screen or output to a logical file. The
number of SPaCes specified by the x parameter determines the number of
characters to fill with spaces across the screen or in a file. For screen
or tape files, the value of the argument is in the range 0 to 255, and for
disk files the maximum is 254. For printer files, an automatic carriage-
return and line-feed will be performed by the printer if a SPaCe is printed
in the last character position of a line; no SPaCes are printed on the fol-
lowing line.

     EXAMPLE:

     PRINT "COMMODORE";SPC(3);"128"
     COMMODORE   128


18.38 SQR

Return square root of argument.
    SQR(x)

This function returns the value of the SQuare Root of x, where x is a posi-
tive number or 0. The value of the argument must not be negative, or the
BASIC error message ?ILLEGAL QUANTITY ERROR is displayed.

     EXAMPLE:

     PRINT SQR(25)
      5


18.39 STR$

Return string representation of number.
     STR$(x)

This function returns the STRing representation of the numeric value of the
argument x. When the STR$ value is converted, any number displayed is pre-
ceded and followed by a space except for negative numbers, which are
preceded by a minus sign. The counterpart of the STR$ function is the VAL
function.

     EXAMPLES:

     PRINT STR$(123.45)
      123.45

     PRINT STR$(-89.03)
     -89.03

     PRINT STR$(1E20)
      1E+20


18.40 TAB

Moves cursor to tab position in present statement.
     TAB(x)

This function moves the cursor forward if possible to a relative position
on the text screen given by the argument x, starting with the leftmost
position of the current line. The value of the argument can range from 0 to
255. If the current print position is already beyond position x, the TAB
function is ignored. The TAB function should only be used with the PRINT
statement, since it has varied effects if used with the PRINT# to a logical
file, depending on the device being used.

     EXAMPLE:

     10 PRINT"COMMODORE"TAB(25)"128"
     COMMODORE               128


18.41 TAN

Return tangent of argument.
     TAN(x)

This function returns the tangent of x, where x is an angle measured in
radians.

     EXAMPLE:

     PRINT TAN(.785398163)
      1


18.42 USR

Call user-defined subfunction
     USR(x)

When this function is used, the program jumps to a machine language program
whose starting point is contained in memory locations (low order byte
first, high order byte last):
     4633 ($1219) and 4634 ($121A) ... C128 mode
     785 ($0311) and 786 ($0312) ... C64 mode

The parameter x is passed to the machine language program in the floating
point accumulator. A value is returned to the BASIC program through the
calling variable. You must redirect the value into a variable in your
program in order to receive the value back from the floating point accumu-
lator.

An ILLEGAL QUANTITY ERROR results if you don't specify this variable. This
allows the user to exchange a variable between machine code and BASIC.

     EXAMPLE (128 Only):

     10 POKE 4633,0
     20 POKE 4634,192      NOTE: Default Commodore 128 bank is 15.
     30 A = USR(X)
     40 PRINT A

Place starting location ($C000=49152: $00=0: $C0=192) of machine language
routine in location 4633 and 4634. Line 30 stores the returning value from
the floating point accumulator.


18.43 VAL

Return the numeric value of a number string.
     VAL(numeric string)

This function converts the numeric string argument into a number. It is the
inverse operation of STR$. The string is examined from the leftmost
character to the right, for as many characters as are in recognizable num-
ber format. If the Commodore 128 finds illegal characters, only the portion
of the string up to that point is converted. If no numeric characters are
present VAL returns a 0.

     EXAMPLE:

     10 A$ = "120"
     20 B$ = "365"
     30 PRINT VAL(A$) + VAL(B$)
      485


18.44 XOR
      ---

Returns exclusive OR
     XOR(n1,n2)

This function provides the exclusive OR of the argument values n1 and n2.

     x = XOR(n1,n2)

where n1, n2 are 2 unsigned values (0-65535).

     EXAMPLE:

     PRINT XOR(128,64)
      192

NOTE: n1 and n2 need not be whole numbers.




SECTION 19

19. Variables and Operators




19.1 VARIABLES

19.2 OPERATORS



19.1 VARIABLES


The Commodore 128 uses three types of variables in BASIC. These are: normal
numeric, integer numeric, string (alfanumeric).

Normal NUMERIC VARIABLES, also called floating point variables, can have
any exponent value from -10 to +10, with up to nine digits of accuracy.
When a number becomes larger than nine digits can show, the computer dis-
plays it in scientific notation form, with the number normalized to one
digit and eight decimal places, followed by the letter E and the power of
10 by which the number is multiplied. For example, the number 12345678901
is displayed as 1.23456789E+10.

INTEGER VARIABLES can be used when the number is from +32767 to -32768
(inclusive), and with no fractional portion. An integer variable is a num-
ber like 5, 10 or -100. Integers take up less space than floating point
variables, particularly when used in an array (see below).

STRING VARIABLES are those used for character data, which may contain num-
bers, letters and any other characters the Commodore 128 can display. An
example of a string variable is "COMMODORE 128".

VARIABLE NAMES may consist of a single letter, a letter followed by a num-
ber, or two letters. Variable names may be longer than two characters, but
only the first two are significant. An integer is specified by using the
percent sign (%) after the variable name. String variables have a dollar
sign ($) after their names.

     EXAMPLES:

     Numeric Variable Names: A, A5, BZ

     Integer Variable Names: A%, A5%, BZ%

     String Variable Names: A$, A5$, BZ$

ARRAYS are lists of variables with the same name, using an extra number (or
numbers) to specify an element of the array. Arrays are defined using the
DIM statement and may be floating point, integer or string variable arrays.
The array variable name is followed by a set of parentheses () enclosing
the number of the variable in the list.

     EXAMPLE:

     A(7),BZ%(11),A$(87)

Arrays can have more than one dimension. A two-dimensional array may be
viewed as having rows and columns, with the first number identifying the
row and the second number identifying the column (as specifying a certain
grid on the map).

     EXAMPLE:

     A(7,2), BZ%(2,3,4), Z$(3,2)

RESERVED VARIABLE NAMES are names reserved for use by the Commodore 128,
and may not be used for any other purpose. These are the variables: DS,
DS$, ER, EL, ST, TI and TI$.

KEYWORDS such as TO and IF or any other name that contain keywords, such as
RUN, NEW or LOAD cannot be used as variable names.

ST is a status variable for input and output (except normal screen/keyboard
operations). The value of ST depends on the result of the last I/O opera-
tion. In general, if the value of ST is 0, then the operation was success-
ful.

TI and TI$ are variables that relate to the real time clock built into the
Commodore 128. The system clock is updated every 1/60th of a second. It
starts at 0 when the Commodore 128 is turned on, and is reset only by
changing the value of TI$. The variable TI gives the current value of the
clock in 1/60th of a second. TI$ is a string that reads the value of the
real time clock as an 24-hour clock. The first two characters of TI$ con-
tain the hour, the third and fourth characters are minutes and the fifth
and sixth characters are seconds. This variable can be set to any value (so
long as all characters are numbers) and will be updated automatically as a
24-hour clock.

     EXAMPLE:

     TI$="101530" sets the clock to 10:15 and 30 seconds (AM).

The value of the clock is lost when the Commodore 128 is turned off. It
starts at zero when the Commodore 128 is turned on, and is reset to zero
when the value of the clock exceeds 235959 (23 hours, 59 minutes and 59
seconds).

The variable DS reads the disk drive command channel and returns the cur-
rent status of the drive. To get this information in words, PRINT DS$.
These status variables can be used after a disk operation, like DLOAD and
DSAVE, to find out why the red error light on the disk drive is blinking.

ER and EL are variables used in error trapping routines. They are usually
only useful within a program. ER returns the last error encountered since
the program was RUN. EL is the line where the error occurred. ERR$ is a
function that allows the program to print one of the BASIC error messages.
PRINT ERR$(ER) prints out the proper error message.


19.2 Operators

The BASIC OPERATORS include: ARITHMETIC OPERATORS, RELATIONAL OPERATORS and
LOGICAL OPERATORS. The ARITHMETIC OPERATORS include the following signs:

     + addition

     - subtraction

     * multiplication

     / division

     ^ raising to a power (exponentiation)

On a line containing more than one operator, there is a set order in which
operations always occur. If several operators are used together, the compu-
ter assigns priorities as follows: First exponentiation, then multiplica-
tion and division, and last, addition and subtraction. If two operators
have the same priority, then calculations are performed in order from left
to right. If these operations are to occur in a different order, Commodore
128 BASIC allows giving a calculation higher priority by placing parenthe-
ses around it. Operations enclosed with parentheses will be calculated be-
fore any other operation. Make sure the equations have the same number of
left and right parentheses, or a SYNTAX ERROR message is displayed when the
program is run.

There are also operators for equalities and inequalities, called RELATIONAL
OPERATORS. Arithmetic operators always take priority over relational opera-
tors.

     =         is equal to

     <         is less than

     >         is greater than

     <= or =<  is less than or equal to

     >= or =>  is greater than or equal to

     <> or ><  is not equal to

Finally, there are three LOGICAL OPERATORS, with lower priority than both
arithmetic and relational operators:

     AND

     OR

     NOT

These are most often used to join multiple formulas in IF... THEN state-
ments. When they are used with arithmetic operators, they are evaluated
last (i.e. after + and -). If the relationship stated in the expression is
true, the result is assigned an integer value of -1. If false, a value of 0
(zero) is assigned.

     EXAMPLES:

     IF A=B AND C=D THEN 100           Requires both A=B and C=D to be true.

     IF A=B OR C=D THEN 100            Allows either A=B, C=D, or both, to
                                       be true.

     A=5:B=4:PRINT A=B                 Displays a value of zero.

     A=5:B=4:PRINT A>3                 Displays a value of -1.

     PRINT 123 AND 15:PRINT 5 OR 7     Displays 11 and 7.




SECTION 20

20. Reserved Words and Symbols




20.1 Reserved System Words (Keywords)

20.2 Reserved System Symbols



20.1 Reserved System Words (Keywords)

This section lists the words and symbols used to make up the BASIC 7.0
language. These words and symbols cannot be used within a program as other
than a component of the BASIC language. The only exception is that they may
be used within quotes in a PRINT or LET statement.

ABS            DIM             HEX$            PRINT           SPRITE
AND            DIRECTORY       IF              PRINT#          SPRSAV
APPEND         DLOAD           INPUT           PUDEF           SQR
ASC            DO              INPUT#          QUIT**          SSHAPE
ATN            DOPEN           INSTR           RCLR            ST
AUTO           DRAW            INT             RDOT            STASH
BACKUP         DS              JOY             READ            STEP
BANK           DSAVE           KEY             RECORD          STOP
BEGIN          DS$             LEFT$           REM             STR$
BEND           DVERIFY         LEN             RENAME          SWAP
BLOAD          EL              LET*            RENUMBER        SYS
BOOT           ELSE            LIST            RESTORE         TAB(
BOX            END             LOAD            RESUME          TAN
BSAVE          ENVELOPE        LOCATE          RETURN          TEMPO
BUMP           ER              LOG             RGR             THEN
CATALOG        ERR$            LOOP            RIGHT$          TI
CHAR           EXIT            MID$            RND             TI$
CHR$           EXP             MONITOR         RREG            TO
CIRCLE         FAST            MOVSPR          RSPCOLOR        TRAP
CLOSE          FETCH           NEW             RSPPOS          TROFF
CLR            FILTER          NEXT            RSPRITE         TRON
CMD            FN              NOT             RUN             UNTIL
COLLECT        FOR             OFF**           RWINDOW         USING
COLLISION      FRE             ON              SAVE            USR
COLOR          GET             OPEN            SCALE           VAL
CONCAT         GETKEY          OR              SCNCLR          VERIFY
CONT           GET#            PAINT           SCRATCH         VOL
COPY           GO64            PEEK            SGN             WAIT
COS            GOSUB           PEN             SIN             WHILE
DATA           GOTO            {pi}            SLEEP           WIDTH
DCLEAR         GO TO           PLAY            SLOW            WINDOW
DCLOSE         GRAPHIC         POINTER         SOUND           XOR
DEC            GSHAPE          POKE            SPC(
DEF            HEADER          POS             SPRCOLOR
DELETE         HELP            POT             SPRDEF

*  LET may be left out of the statement, so LET A=10 may be written as A=10.
** OFF and QUIT are unimplemented.


20.2 Reserved System Symbols

The following characters are reserved system symbols.

        Symbol             Use(s)

+       Plus sign          Arithmetic addition; string concatenation; rela-
                           tive sprite movement; declare decimal number in
                           machine language monitor.

-       Minus sign         Arithmetic subtraction; negative number; unary
                           minus; relative sprite movement.

*       Asterisk           Arithmetic multiplication.

/       Slash              Arithmetic division.

^       Up arrow           Arithmetic exponentiation.

        Blank space        Separate keywords and variable names.

=       Equal sign         Value assignment; relationship testing.

<       Less than          Relationship testing.

>       Greater than       Relationship testing.

,       Comma              Format output in variable lists; separate mul-
                           tiple function parameters in commands or state-
                           ments.

.       Period             Decimal point in floating constants.

;       Semicolon          Format output in variable lists.

:       Colon              Separate multiple BASIC statements on a program
                           line; logical end of line in machine language
                           monitor.

" "     Quotation mark     Enclose string constants

?       Question mark      Abbreviation for the keyword PRINT; logical end
                           of line in machine language monitor.

(       Left parenthesis   Expression evaluation and functions.

)       Right parenthesis  Expression evaluation and functions.

%       Percent            Declare a variable name as integer; declare
                           binary number in machine language monitor.

#       Hash               Precede the logical file number in input/output
                           statements.

$       Dollar sign        Declare a variable name as a string; declare
                           hexadecimal number in machine language monitor.

&       And sign           Declare octal number in machine language
                           monitor.

{pi}    Pi                 Declare the numeric constant - approximately
                           3.14159265




APPENDICES




APPENDIX A - BASIC LANGUAGE ERROR MESSAGES
APPENDIX B - DOS ERROR MESSAGES
APPENDIX C - CONNECTORS/PORTS FOR PERIPHERAL EQUIPMENT
APPENDIX D - SCREEN DISPLAY CODES
APPENDIX E - ASCII AND CHR$ CODES
APPENDIX F - SCREEN AND COLOR MEMORY MAPS
APPENDIX G - DERIVED MATHEMATICAL FUNCTIONS
APPENDIX H - MEMORY MAP
APPENDIX I - CONTROL AND ESCAPE CODES
APPENDIX J - MACHINE LANGUAGE MONITOR
APPENDIX K - BASIC 7.0 ABBREVIATIONS
APPENDIX L - DISK COMMAND SUMMARY




APPENDIX A

A. BASIC LANGUAGE ERROR MESSAGES


The following error messages are displayed by BASIC. Error messages can
also be displayed with the use of the ERR$() function. The error numbers
below refer only to the number assigned to the error for use with the
ERR$() function.


ERROR#  ERROR NAME              DESCRIPTION

 1      TOO MANY FILES          There is a limit of 10 files OPEN at one
                                time.

 2      FILE OPEN               An attempt was made to open a file using
                                the number of an already open file.

 3      FILE NOT OPEN           The file number specified in an I/O state-
                                ment must be opened before use.

 4      FILE NOT FOUND          Either no file with that name exists (disk)
                                or an end-of-tape marker was read (tape).

 5      DEVICE NOT PRESENT      The required I/O device is not available or
                                buffers deallocated (cassette).
                                Check to make sure the device is connected
                                and turned on.

 6      NOT INPUT FILE          An attempt was made to GET or INPUT data
                                from a file that was specified as output
                                only.

 7      NOT OUTPUT FILE         An attempt was made to send data to a file
                                that was specified as input only.

 8      MISSING FILE NAME       File name missing in command.

 9      ILLEGAL DEVICE          An attempt was made to use a device im-
        NUMBER                  properly (SAVE to the screen, etc.).

10      NEXT WITHOUT FOR        Either loops are nested incorrectly, or
                                there is a variable name in a NEXT state-
                                ment that doesn't correspond with one in
                                FOR.

11      SYNTAX                  A statement not recognized by BASIC. This
                                could be because of a missing or extra
                                parenthesis, misspelled key word, etc.

12      RETURN WITHOUT          A RETURN statement was encountered when no
        GOSUB                   GOSUB statement was active.

13      OUT OF DATA             A READ statement was encountered without
                                data left unREAD.

14      ILLEGAL QUANTITY        A number used as the argument of a function
                                or statement is outside the allowable
                                range.

15      OVERFLOW                The result of a computation is larger than
                                the largest number allowed
                                (1.701411833E+38).

16      OUT OF MEMORY           Either there is no more room for program
                                code and/or program variables, or there are
                                too many nested DO, FOR or GOSUB statements
                                in effect.

17      UNDEF'D STATEMENT       A line number referenced doesn't exist in
                                the program.

18      BAD SUBSCRIPT           The program tried to reference an element
                                of an array out of the range specified by
                                the DIM statement.

19      REDIM'D ARRAY           An array can only be DIMensioned once.

20      DIVISION BY ZERO        Division by zero is not allowed.

21      ILLEGAL DIRECT          INPUT or GET, or INPUT# or GET# statements
                                are only allowed within a program.

22      TYPE MISMATCH           This occurs when a numeric value is used in
                                place of a string or vice versa.

23      STRING TOO LONG         A string can contain up to 255 characters.

24      FILE DATA               Bad data read from a tape or disk file.

25      FORMULA TOO             The computer was unable to understand this
        COMPLEX                 expression. Simplify the expression (break
                                into two parts or use fewer parentheses).

26      CAN'T CONTINUE          The CONT command does not work if the pro-
                                gram was not RUN, there was an error, or a
                                line had been edited.

27      UNDEFINED FUNCTION      A user-defined function was referenced that
                                was never defined.

28      VERIFY                  The program on tape or disk does not match
                                the program in memory.

29      LOAD                    There was a problem loading. Try again.

30      BREAK                   The stop key was hit to halt program exe-
                                cution.

31      CAN'T RESUME            A RESUME statement was encountered without
                                a TRAP statement in effect.

32      LOOP NOT FOUND          The program has encountered a DO statement
                                and cannot find the corresponding LOOP.

33      LOOP WITHOUT DO         LOOP was encountered without a DO statement
                                active.

34      DIRECT MODE ONLY        This command is allowed only in direct
                                mode, not from a program.

35      NO GRAPHICS AREA        A command (DRAW, BOX, etc.) to create
                                graphics was encountered before the GRAPHIC
                                command was executed.

36      BAD DISK                An attempt failed to HEADER a diskette,
                                because the quick header method (no ID) was
                                attempted on a unformatted diskette or the
                                diskette is bad.

37      BEND NOT FOUND          The program encountered an "IF... THEN
                                BEGIN" or "IF... THEN... ELSE BEGIN" con-
                                struct, and could not find a BEND keyword
                                to match the BEGIN.

38      LINE # TOO LARGE        An error has occurred in renumbering a
                                BASIC program. The given parameters result
                                in a line number > 63999 being generated;
                                therefore, the renumbering was not per-
                                formed.

39      UNRESOLVED              An error has occurred in renumbering a
        REFERENCE               BASIC program. A line number referred to by
                                a command (e.g., GOTO 999) does not exist.
                                Therefore the renumbering was not per-
                                formed.

40      UNIMPLEMENTED           A command not supported by BASIC 7.0 was
        COMMAND                 encountered.

41      FILE READ               An error condition was encountered while
                                loading or reading a program or file from
                                the disk drive (e.g., opening the disk
                                drive door while a program was loading).



APPENDIX B

B. DOS ERROR MESSAGES


The following error messages are returned through the DS and DS$
variables. The DS variable contains just the error number and the DS$
variable contains the error number, the error messages and any correspon-
ding track and sector number.

Note: Error message numbers less than 20 should be ignored with the excep-
      tion of 01, which gives information about the number of files
      scratched with the SCRATCH command.



ERROR   ERROR MESSAGE AND
NUMBER  DESCRIPTION

20:     READ ERROR (block header not found)
        The disk controller is unable to locate the header of the requested
        data block. Caused by an illegal sector number, or the header has
        been destroyed.

21:     READ ERROR (no sync character)
        The disk controller is unable to detect a sync mark on the desired
        track. Caused by misalignment of the read/write head, no diskette
        is present, or unformatted or improperly seated diskette. Can also
        indicate a hardware failure.

22:     READ ERROR (data block not present)
        The disk controller has been requested to read or verify a data
        block that was not properly written. This error occurs in conjunc-
        tion with the BLOCK commands and indicates an illegal track and/or
        sector request.

23:     READ ERROR (checksum error in data block)
        This error message indicates there is an error in one or more of
        the data bytes. The data has been read into the DOS memory, but the
        checksum over the data is in error. This message may also indicate
        hardware grounding problems.

24:     READ ERROR (byte decoding error)
        The data or header has been read into the DOS memory but a hardware
        error has been created due to an invalid bit pattern in the data
        byte. This message may also indicate grounding problems.

25:     WRITE ERROR (write-verify error)
        This message is generated if the controller detects a mismatch be-
        tween the written data and the data in DOS memory.

26:     WRITE PROTECT ON
        This message is generated when the controller has been requested to
        write a data block while the write protect switch is depressed.
        This is caused by using a diskette with a write protect tab over
        the notch.

27:     READ ERROR (checksum error in header)
        This message is generated when a checksum error had been detected
        in the header of the requested data block. The block has not been
        read into DOS memory.

28:     WRITE ERROR (long data block)
        This error message is generated when a data block is too long and
        overwrites the sync mark of the next header.

29:     DISK ID MISMATCH
        This message is generated when the controller has been requested to
        access a diskette which has not been initialized. The message can
        also occur if a diskette has a bad header.

30:     SYNTAX ERROR (general syntax)
        The DOS cannot interpret the command sent to the command channel.
        Typically, this is caused by an illegal number of file names, or
        patterns are illegally used. For example, file names appear on the
        left side of the COPY command.

31:     SYNTAX ERROR (invalid command)
        The DOS does not recognize the command. The command must start in
        the first position.

32:     SYNTAX ERROR (long line)
        The command sent is longer than 58 characters. Use abbreviated disk
        commands.

33:     SYNTAX ERROR (invalid file name)
        Pattern matching is invalidly used in the OPEN or SAVE command.
        Spell out the file name.

34:     SYNTAX ERROR (no file given)
        The file name was left out of the command or the DOS does not
        recognize it as such. Typically, a colon {:} has been left out of
        the command.

39:     SYNTAX ERROR (invalid command)
        This error may result if the command sent to the command channel
        (secondary address 15) is unrecognized by the DOS.

50:     RECORD NOT PRESENT
        Result of disk reading past the last record through INPUT# or GET#
        commands. This message will also occur after positioning to a
        record beyond the end-of-file in a relative file. If the intent is
        to expand the file by adding the new record (with a PRINT# com-
        mand), the error message may be ignored. INPUT# or GET# should not
        be attempted after this error is detected without first reposi-
        tioning.

51:     OVERFLOW IN RECORD
        PRINT# statement exceeds record boundery. Information is truncated.
        Since the carriage return which is sent as a record terminator is
        counted in the record size, this message will occur if the total of
        characters in the record (including the final carriage return)
        exceeds the defined size of the record.

52:     FILE TOO LARGE
        Record position within a relative file indicates that disk overflow
        will result.

60:     WRITE FILE OPEN
        This message is generated when a write file that has not been
        closed is being opened for reading.

61:     FILE NOT OPEN
        This message is generated when a file is being accessed that has
        not been opened in the DOS. Sometimes, in this case, a message is
        not generated; the request is simply ignored.

62:     FILE NOT FOUND
        The requested file does not exist on the indicated drive.

63:     FILE EXISTS
        The file name of the file being created already exists on the dis-
        kette.

64:     FILE TYPE MISMATCH
        The requested file access is not possible using files of the type
        named. Reread the chapter covering that file type.

65:     NO BLOCK
        Occurs in conjunction with Block Allocation. The sector you tried
        to allocated is already allocated. The track and sector numbers re-
        turned are the next higher track and sector available. If the track
        number returned zero (0), all remaining sectors are full. If the
        diskette is not full yet, try a lower track and sector.

66:     ILLEGAL TRACK AND SECTOR
        The DOS has attempted to access a track or block which does not
        exist in the format being used. This may indicate a problem reading
        the pointer of the next block.

67:     ILLEGAL SYSTEM T OR S
        This special error message indicates an illegal system track or
        sector.

70:     NO CHANNEL (available)
        The requested channel is not available, or all channels are in use.
        A maximum of five buffers are available for use. A sequential file
        requires two buffers; a relative file requires three buffers; and
        the error/command channel requires one buffer. You may use any com-
        bination of those as long as the combination does not exceed five
        buffers.

71:     DIRECTORY ERROR
        The BAM (Block Availability Map) on the diskette does not match the
        copy on disk memory. To correct, initialize the diskette.

72:     DISK FULL
        Either the blocks on the diskette are used or the directory is at
        its entry limit. DISK FULL is sent when two blocks are still
        available on the diskette, in order to allow the current file to be
        closed.

73:     DOS MISMATCH (VERSION NUMBER)
        DOS 1 and 2 are read compatible but not write compatible. Disks may
        be interchangeably read with either DOS, but a disk formatted on
        one version cannot be written upon with the other version, because
        the format is different. This error is displayed whenever an
        attempt is made to write upon a disk which has been formatted in a
        non-compatible format. This message will also appear after power up
        and is not an error in this case.

74:     DRIVE NOT READY
        An attempt has been made to access the disk drive without any in-
        serted diskette; or the drive lever or door is open.



APPENDIX C

C. CONNECTORS/PORTS FOR PERIPHERAL EQUIPMENT


                   [PICTURES ARE MISSING]


C.1 Side Panel Connections

1.  Power Socket - The five pin square plug from the power supply is con-
    nected here.

2.  Power Switch - Turns on power from the power supply.

3.  Reset Button - Resets computer (warm start).

4.  Controller Ports - There are two Controller ports, numbered 1 and 2.
    Each Controller port can accept a joystick or game controller paddle.
    The light pen can be plugged only into port 1, the port closest to the
    front of the computer. Use the ports as instructed with the software.

Control Port 1
+-----+-------------+-----------+
| Pin |    Type     |   Note    |     +-------------------+
|  1  |    JOYA0    |           |    /  1   2   3   4   5  \
|  2  |    JOYA1    |           |   +   O   O   O   O   O  +
|  3  |    JOYA2    |           |    \                     /
|  4  |    JOYA3    |           |     +   O   O   O   O   +
|  5  |    POT AY   |           |      \  6   7   8   9  /
|  6  | BUTTON A/LP |           |       +---------------+
|  7  |     +5V     | MAX. 50mA |
|  8  |     GND     |           |
|  9  |   POT AX    |           |
+-----+-------------+-----------+

Control Port 2
+-----+-------------+-----------+
| Pin |    Type     |   Note    |
|  1  |    JOYB0    |           |
|  2  |    JOYB1    |           |
|  3  |    JOYB2    |           |
|  4  |    JOYB3    |           |
|  5  |    POT BY   |           |
|  6  |  BUTTON B   |           |
|  7  |     +5V     | MAX. 50mA |
|  8  |     GND     |           |
|  9  |   POT BX    |           |
+-----+-------------+-----------+


C.2 Rear Connections

5.  Expansion Port - This rectangular slot is a parallel port that accepts
    programs or game cartridges as well as special interfaces.

Cartridge Expansion Slot

+----+----------+ +----+----------+ +----+----------+ +----+----------+
| Pin|   Type   | | Pin|   Type   | | Pin|   Type   | | Pin|   Type   |
+----+----------+ +----+----------+ +----+----------+ +----+----------+
|  1 | GND      | | 12 | BA       | |  A | GND      | |  N | A9       |
|  2 | +5V      | | 13 | /DMA     | |  B | /ROMH    | |  P | A8       |
|  3 | +5V      | | 14 | D7       | |  C | /RESET   | |  R | A7       |
|  4 | /IRQ     | | 15 | D6       | |  D | /NMI     | |  S | A6       |
|  5 | R/W      | | 16 | D5       | |  E | 02       | |  T | A5       |
|  6 | Dot Clock| | 17 | D4       | |  F | A15      | |  U | A4       |
|  7 | I/O1     | | 18 | D3       | |  H | A14      | |  V | A3       |
|  8 | /GAME    | | 19 | D2       | |  J | A13      | |  W | A2       |
|  9 | /EXROM   | | 20 | D1       | |  K | A12      | |  X | A1       |
| 10 | I/O2     | | 21 | D0       | |  L | A11      | |  Y | A0       |
| 11 | /ROML    | | 22 | GND      | |  M | A10      | |  Z | GND      |
+----+----------+ +----+----------+ +----+----------+ +----+----------+
                 2 2 2 1 1 1 1 1 1 1 1 1 1
                 2 1 0 9 8 7 6 5 4 3 2 1 0 9 8 7 6 5 4 3 2 1
             +---@-@-@-@-@-@-@-@-@-@-@-@-@-@-@-@-@-@-@-@-@-@---+
             |                                                 |
             +---@-@-@-@-@-@-@-@-@-@-@-@-@-@-@-@-@-@-@-@-@-@---+
                 Z Y X W V U T S R P N M L K J H F E D C B A


6.  Cassette Port - A 1530 Datassette recorder can be attached here to
    store programs and information.

Cassette Port

+-------+--------------------+
|  Pin  |        Type        |
+-------+--------------------+
|  A-1  |  GND               |              1 2 3 4 5 6
|  B-2  |  +5V               |          +---@-@-@-@-@-@---+
|  C-3  |  CASSETTE MOTOR    |          |                 |
|  D-4  |  CASSETTE READ     |          +---@-@-@-@-@-@---+
|  E-5  |  CASSETTE WRITE    |              A B C D E F
|  F-6  |  CASSETTE SENSE    |
+-------+--------------------+


7.  Serial Port - A Commodore Serial printer or disk drive can be attached
    directly to the Commodore 128 through this port.

Serial I/O Port

+-------+----------------------+
|  Pin  |         Type         |               ++ ++
+-------+----------------------+              / +-+ \
|   1   |  /SERIAL SRQ IN      |             /5     1\
|   2   |  GND                 |            +  O   O  +
|   3   |  SERIAL ATN OUT      |            |    6    |
|   4   |  SERIAL CLK IN/OUT   |            |    O    |
|   5   |  SERIAL DATA IN/OUT  |            |         |
|   6   |  /RESET              |            +  O   O  +
+-------+----------------------+             \4  O  2/
                                              \  3  /
                                               +---+

Note: The Commodore Serial Port is not RS-232 compatible. TTL RS-232 levels
      can be obtained from the User Port.


8.  40 Column Video Connector - This DIN connector provides audio and com-
    posite video signals which can be directly connected to suitable audio
    and monitor equipment. These signals can be connected to the Commodore
    monitor or used with separate components.


Audio/Composite Video Connector
+-------+----------------------+
|  Pin  |         Type         |             ++ ++
+-------+----------------------+            /8+-+7\
|   1   |  LUMINANCE/SYNC      |           /O     O\
|   2   |  GND                 |          |    6    |
|   3   |  AUDIO OUT           |          |3O  O  O1|
|   4   |  VIDEO OUT           |          |         |
|   5   |  AUDIO IN            |          +  O   O  +
|   6   |  CHROMINANCE         |           \5  O  4/
|   7   |  NC                  |            \  2  /
|   8   |  NC                  |             +---+
+-------+----------------------+

9.  RF Connector - This connector supplies both picture and sound to your
    television set. (A television can display only a 40 column picture.)

10. 80 Column RGBI Connector - This 9-pin connector supplies an RGBI (Red/
    Green/Blue/Intensity) signal.

80 Column RGBI Connector
+----+-------------------------+
| Pin| Signal                  |     +-------------------+
+----+-------------------------+    /  1   2   3   4   5  \
| 1  | Ground                  |   +   O   O   O   O   O  +
| 2  | Ground                  |    \                     /
| 3  | Red                     |     +   O   O   O   O   +
| 4  | Green                   |      \  6   7   8   9  /
| 5  | Blue                    |       +---------------+
| 6  | Intensity               |
| 7  | Monochrome              |
| 8  | Horizontal Sync         |
| 9  | Vertical Sync           |
+----+-------------------------+


11. User Port - Various interface devices can be attached here.

User I/O

User I/O Port
+-----+---------------+-----------+   +-----+---------------+-----------+
| Pin |      Type     |    Note   |   | Pin |      Type     |    Note   |
+-----+---------------+-----------+   +-----+---------------+-----------+
|   1 |  GND          |           |   |  A  |  GND          |           |
|   2 |  +5V          |MAX. 100 mA|   |  B  |  /FLAG2       |           |
|   3 |  /RESET       |           |   |  C  |  PB0          |           |
|   4 |  CNT1         |           |   |  D  |  PB1          |           |
|   5 |  SP1          |           |   |  E  |  PB2          |           |
|   6 |  CNT2         |           |   |  F  |  PB3          |           |
|   7 |  SP2          |           |   |  H  |  PB4          |           |
|   8 |  /PC2         |           |   |  I  |  PB5          |           |
|   9 |  SER. ATN OUT |           |   |  K  |  PB6          |           |
|  10 |  9 VAC        |MAX. 100 mA|   |  L  |  PB7          |           |
|  11 |  9 VAC        |MAX. 100 mA|   |  M  |  PA2          |           |
|  12 |  GND          |           |   |  N  |  GND          |           |
+-----+---------------+-----------+   +-----+---------------+-----------+


                                             1 1 1
                           1 2 3 4 5 6 7 8 9 0 1 2
                        +--@-@-@-@-@-@-@-@-@-@-@-@--+
                        |                           |
                        +--@-@-@-@-@-@-@-@-@-@-@-@--+
                           A B C D E F H J K L M N



APPENDIX D

D. SCREEN DISPLAY CODES - 40 Columns


The following chart lists all of the characters built into the Commodore
screen character sets. It shows which numbers should be POKED into screen
memory (locations 1024-2023) to get a desired character on the 40-column
screen (Remember, to set color memory, use locations 55296 to 56295). Also
shown is which character corresponds to a number PEEKed from the screen.

Two character sets are available. Both are available simultaneously in 80-
column mode, but only is available at a time on the 40-column screen. The
sets are switched by holding down the {shift} and {C=} (Commodore) keys
simultaneously.

From BASIC, PRINT CHR$(142) will switch to upper case/graphics mode and
PRINT CHR$(14) will switch to upper/lower case mode.

Any number on the chart may also be displayed in REVERSE. The reverse
character code may be obtained by adding 128 to the values shown.



  SET 1   SET 2   POKE  |  SET 1   SET 2   POKE  |  SET 1   SET 2   POKE
------------------------+------------------------+-----------------------
    @               0   |    +              43   |    V              86
    A       a       1   |    ,              44   |    W              87
    B       b       2   |    -              45   |    X              88
    C       c       3   |    .              46   |    Y              89
    D       d       4   |    /              47   |    Z              90
    E       e       5   |    0              48   |                   91
    F       f       6   |    1              49   |                   92
    G       g       7   |    2              50   |                   93
    H       h       8   |    3              51   |                   94
    I       i       9   |    4              52   |  SPACE            95
    J       j      10   |    5              53   |                   96
    K       k      11   |    6              54   |                   97
    L       l      12   |    7              55   |                   98
    M       m      13   |    8              56   |                   99
    N       n      14   |    9              57   |                  100
    O       o      15   |    :              58   |                  101
    P       p      16   |    ;              59   |                  102
    Q       q      17   |    <              60   |                  103
    R       r      18   |    =              61   |                  104
    S       s      19   |    >              62   |                  105
    T       t      20   |    ?              63   |                  106
    U       u      21   |                   64   |                  107
    V       v      22   |    A              65   |                  108
    W       w      23   |    B              66   |                  109
    X       x      24   |    C              67   |                  110
    Y       y      25   |    D              68   |                  111
    Z       z      26   |    E              69   |                  112
    [              27   |    F              70   |                  113
  pound            28   |    G              71   |                  114
    ]              29   |    H              72   |                  115
    ^              30   |    I              73   |                  116
    <-             31   |    J              74   |                  117
  SPACE            32   |    K              75   |                  118
    !              33   |    L              76   |                  119
    "              34   |    M              77   |                  120
    #              35   |    N              78   |                  121
    $              36   |    O              79   |                  122
    %              37   |    P              80   |                  123
    &              38   |    Q              81   |                  124
    '              39   |    R              82   |                  125
    (              40   |    S              83   |                  126
    )              41   |    T              84   |                  127
    *              42   |    U              85   |

      Codes from 128-255 are reversed images of codes 0-127.




APPENDIX E

E. ASCII AND CHR$ CODES


This appendix shows you what characters will appear if you PRINT CHR$(X),
for all possible values of X. It will also show the values obtained by
typing PRINT ASC("x"), where x is any character that can be displayed. This
is useful in evaluating the character received in a GET statement, conver-
ting upper to lower case, and printing character based commands (like
switch to upper/lower case) that could not be enclosed in quotes.


+-----------------+-----------------+-----------------+-----------------+
|  PRINTS   CHR$  |  PRINTS   CHR$  |  PRINTS   CHR$  |  PRINTS   CHR$  |
+-----------------+-----------------+-----------------+-----------------+
|             0   |    0       48   |            96   | {black}   144   |
|             1   |    1       49   |            97   |   {up}    145   |
|             2   |    2       50   |            98   | {rvs off} 146   |
|             3   |    3       51   |            99   | {clear}   147   |
|             4   |    4       52   |           100   |  {inst}   148   |
| {white}     5   |    5       53   |           101   | {brown}   149   |
|             6   |    6       54   |           102   | {lt. red} 150   |
|             7   |    7       55   |           103   | {grey 1}  151   |
| disSHIFT+C= 8   |    8       56   |           104   | {grey 2}  152   |
| enaSHIFT+C= 9   |    9       57   |           105   | {lt.green}153   |
|            10   |    :       58   |           106   | {lt.blue} 154   |
|            11   |    ;       59   |           107   | {grey 3}  155   |
|            12   |    <       60   |           108   | {purple}  156   |
| return     13   |    =       61   |           109   | {left}    157   |
| lower case 14   |    >       62   |           110   | {yellow}  158   |
|            15   |    ?       63   |           111   |  {cyan}   159   |
|            16   |    @       64   |           112   |  SPACE    160   |
|  {down}    17   |    A       65   |           113   |           161   |
| {rvs on}   18   |    B       66   |           114   |           162   |
|  {home}    19   |    C       67   |           115   |           163   |
|  {del}     20   |    D       68   |           116   |           164   |
|            21   |    E       69   |           117   |           165   |
|            22   |    F       70   |           118   |           166   |
|            23   |    G       71   |           119   |           167   |
|            24   |    H       72   |           120   |           168   |
|            25   |    I       73   |           121   |           169   |
|            26   |    J       74   |           122   |           170   |
|            27   |    K       75   |           123   |           171   |
|  {red}     28   |    L       76   |           124   |           172   |
| {right}    29   |    M       77   |           125   |           173   |
| {green}    30   |    N       78   |           126   |           174   |
|  {blue}    31   |    O       79   |           127   |           175   |
|  SPACE     32   |    P       80   |           128   |           176   |
|    !       33   |    Q       81   | {orange}  129   |           177   |
|    "       34   |    R       82   |           130   |           178   |
|    #       35   |    S       83   |           131   |           179   |
|    $       36   |    T       84   |           132   |           180   |
|    %       37   |    U       85   |    f1     133   |           181   |
|    &       38   |    V       86   |    f3     134   |           182   |
|    '       39   |    W       87   |    f5     135   |           183   |
|    (       40   |    X       88   |    f7     136   |           184   |
|    )       41   |    Y       89   |    f2     137   |           185   |
|    *       42   |    Z       90   |    f4     138   |           186   |
|    +       43   |    [       91   |    f6     139   |           187   |
|    ,       44   |  pound     92   |    f8     140   |           188   |
|    -       45   |    ]       93   |shift+ret. 141   |           189   |
|    .       46   |    ^       94   |upper case 142   |           190   |
|    /       47   |{arrow left}95   |           143   |           191   |
+-----------------+-----------------+-----------------+-----------------+

CODES 192-223 SAME AS  96-127
CODES 224-254 SAME AS 160-190
CODE 255 SAME AS 126

Note: The above codes are for C64 mode. See Appendix I for special codes in
      C128 mode.




APPENDIX F

F. SCREEN AND COLOR MEMORY MAPS - C128 Mode, 40 Column and C64 Mode


The following maps display the memory locations used in 40-column mode
(C128 and C64) for identifying the characters on the screen as well as
their color. Each map is separately controlled and consists of 1,000 posi-
tions.

The character displayed on the maps can be controlled directly with the
POKE command.

F.1 SCREEN MEMORY MAP

                                 COLUMN                             1063
      0             10             20             30            39 /
     +------------------------------------------------------------/
1024 |                                                            |  0
1064 |                                                            |
1104 |                                                            |
1144 |                                                            |
1184 |                                                            |
1224 |                                                            |
1264 |                                                            |
1304 |                                                            |
1344 |                                                            |
1384 |                                                            |
1424 |                                                            | 10
1464 |                                                            |
1504 |                                                            |   ROW
1544 |                                                            |
1584 |                                                            |
1624 |                                                            |
1664 |                                                            |
1704 |                                                            |
1744 |                                                            |
1784 |                                                            |
1824 |                                                            | 20
1864 |                                                            |
1904 |                                                            |
1944 |                                                            |
1984 |                                                            | 24
     +------------------------------------------------------------\

The Screen Map is POKEd with a Screen Display Code value (see Appendix D).

For example:

     POKE 1024,13

will display the letter {M} in the upper-left corner of the screen.


F.2 COLOR MEMORY MAP

                                 COLUMN                             55335
      0             10             20             30            39 /
     +------------------------------------------------------------/
55296|                                                            |  0
55336|                                                            |
55376|                                                            |
55416|                                                            |
55456|                                                            |
55496|                                                            |
55536|                                                            |
55576|                                                            |
55616|                                                            |
55656|                                                            |
55696|                                                            | 10
55736|                                                            |
55776|                                                            |   ROW
55816|                                                            |
55856|                                                            |
55896|                                                            |
55936|                                                            |
55976|                                                            |
56016|                                                            |
56056|                                                            |
56096|                                                            | 20
56136|                                                            |
56176|                                                            |
56216|                                                            |
56256|                                                            | 24
     +------------------------------------------------------------\
                                                                   56295

If the color map is POKEd with a color value, this changes the character
color. For example:
     POKE 55296,1
will change the letter {M} inserted above from light green to white.


F.3 Color Codes - 40 Columns

0  Black         8  Orange
1  White         9  Brown
2  Red          10  Light Red
3  Cyan         11  Dark Gray
4  Purple       12  Medium Gray
5  Green        13  Light Green
6  Blue         14  Light Blue
7  Yellow       15  Light Gray


  Border Control Memory 53280
Background Control Memory 53281




APPENDIX G

G. DERIVED TRIGONOMETRIC FUNCTIONS


+------------------------------+------------------------------------------+
|          FUNCTION            |              BASIC EQUIVALENT            |
+------------------------------+------------------------------------------+
| SECANT                       | SEC(X)=1/COS(X)                          |
| COSECANT                     | CSC(X)=1/SIN(X)                          |
| COTANGENT                    | COT(X)=1/TAN(X)                          |
| INVERSE SINE                 | ARCSIN(X)=ATN(X/SQR(-X*X+1))             |
| INVERSE COSINE               | ARCCOS(X)=-ATN(X/SQR(-X*X+1))+{pi}/2     |
| INVERSE SECANT               | ARCSEC(X)=ATN(SQR(X*X-1))                |
| INVERSE COSECANT             | ARCCSC(X)=ATN(1/SQR(X*X-1))              |
| INVERSE COTANGENT            | ARCCOT(X)=ATN(1/X)                       |
| HYPERBOLIC SINE              | SINH(X)=(EXP(X)-EXP(-X))/2               |
| HYPERBOLIC COSINE            | COSH(X)=(EXP(X)+EXP(-X))/2               |
| HYPERBOLIC TANGENT           | TANH(X)=(EXP(X)-EXP(-X))/(EXP(X)+EXP(-X))|
| HYPERBOLIC SECANT            | SECH(X)=2/(EXP(X)+EXP(-X))               |
| HYPERBOLIC COSECANT          | CSCH(X)=2/(EXP(X)-EXP(-X))               |
| HYPERBOLIC COTANGENT         | COTH(X)=EXP(-X)/(EXP(X)-EXP(-X))*2+1     |
| INVERSE HYPERBOLIC SINE      | ARCSINH(X)=LOG(X+SQR(X*X+1))             |
| INVERSE HYPERBOLIC COSINE    | ARCCOSH(X)=LOG(X+SQR(X*X-1))             |
| INVERSE HYPERBOLIC TANGENT   | ARCTANH(X)=LOG((1+X)/(1-X))/2            |
| INVERSE HYPERBOLIC SECANT    | ARCSECH(X)=LOG(SQR(-X*X+1)+1)/X)         |
| INVERSE HYPERBOLIC COSECANT  | ARCCSCH(X)=LOG((SGN(X)*SQR(X*X+1)+1/X)   |
| INVERSE HYPERBOLIC COTANGENT | ARCCOTH(X)=LOG((X+1)/(X-1))/2            |
+------------------------------+------------------------------------------+




APPENDIX H

H. MEMORY MAP

SYSTEM MEMORY MAP


The Commodore 128 BASIC memory map is shown below:


           COMMODORE 128 MODE
               MEMORY MAP
---------------------------------------
        C128 RAM            C128 ROM

FFFF+-------------+ FFFF+-------------+
FFFA|NMI RST IRQ  |     |             |
    |CP/M RAM Code|     |             |
FFD0|             | FF4D+-------------+- - Kernal Jump Table - -
    |krnl RAM Code|     |             |    & Hardware Vectors   |
FF05+-------------+ FF05+-------------+- - Kernal interrupt
    |MMU          |     |             |    Dispatch Code        |
    |Configuration|     |             |
    |Register     |     |             |                         |
FF00+-------------+ FF00|/////////////|- - MMU Configuration
    |             |     |             |    Registers            |\
    |             | FC80| - - - - - - |- - ROM Reserved for       |HIGH
    |             |     |             |    Foreign Lang.        |/ ROM
    |             |     |             |    Versions
    |             | FA00| - - - - - - |- - Editor Tables        |
    |             |     |             |
    |             | E000| - - - - - - |- - Kernal ROM Code      |
    |             |     |/////////////|
    |             | D000|/////////////|- - I/O Space            |
    |             |     |             |
    |             | C000| - - - - - - |- - Editor ROM Code - - -|
    |             |     |             |
    |             | B000| - - - - - - |- - Monitor ROM Code  - -|\_MID
    |             |     |             |                          / ROM
    |             | 8000|             |- - - - - - - - - - - - -|
    |             |     |             |
    |             |     |             |                         |\ LOW
    |             |     |             |                           |ROM
4000+-------------+ 4000+-------------+- - Basic ROM Code  - - -|/


           COMMODORE 128 MODE
               MEMORY MAP
---------------------------------------
                C128 RAM

4000+---------------------------------+
    |       VIC BIT-MAP Screen        |
2000| - - - - - - - - - - - - - - - - |
    |    VIC BIT-MAP Color (VM #2)    |
1C00+---------------------------------+
    |           Reserved for          |
    |      Function Key Software      |
1800+---------------------------------+
    |           Reserved for          |
    |      Foreign Lang.Systems       |
1400+---------------------------------+
    |                                 |
1300+---------------------------------+
    |    Basic Absolute Variables     |
1200+---------------------------------+
    |    Basic DOS/VSP Variables      |
1108+---------------------------------+
    |         CP/M Reset Code         |
1100+---------------------------------+
    |       Function Key Buffer       |
1000+---------------------------------+
    |     Sprite Definition Area      |
0E00+---------------------------------+
    |      RS/232 Output Buffer       |
0D00+---------------------------------+
    |       RS/232 Input Buffer       |
0C00+---------------------------------+
    |        (Disk Boot Page)         |
0BC0| - - - - - - - - - - - - - - - - |
    |         Cassette Buffer         |
0B00+---------------------------------+
    |Monitor & Kernal Absolute Values |
0A00+---------------------------------+
    |      Basic Run-Time Stack       |
0800+---------------------------------+
    |     VIC Text Screen (VM #1)     |
0400+---------------------------------+


           COMMODORE 128 MODE
               MEMORY MAP
---------------------------------------
                C128 RAM


0400+---------------------------------+
    |          Basic RAM Code         |
0380+ - - - - - - - - - - - - - - - - +
    |          Kernal Tables          |
033C+ - - - - - - - - - - - - - - - - +
    |            Indirects            |
02FC+ - - - - - - - - - - - - - - - - +
    |         Kernal RAM Code         |
02A2+ - - - - - - - - - - - - - - - - +
    |  Basic & Monitor Input Buffer   |
0200+ - - - - - - - - - - - - - - - - +
    |          System Stack           |
0149+ - - - - - - - - - - - - - - - - +
    |         Basic DOS Using         |
0110+ - - - - - - - - - - - - - - - - +
    |            F Buffer             |
0100+ - - - - - - - - - - - - - - - - +
    |           Kernal Z.P.           |
0090+ - - - - - - - - - - - - - - - - +
    |            Basic Z.P.           |
0002+ - - - - - - - - - - - - - - - - +
0000+---------------------------------+




APPENDIX I

I. CONTROL AND ESCAPE CODES

I.1 CONTROL CODES

                                                                 Effective
                Key                                               in Mode:
CHR$            Sequence        Function                         C64  C128
---------------------------------------------------------------------------
CHR$(2)         CTRL B          Underline (80)                          *
CHR$(5)         CTRL 2 or       Set character color to white
                CTRL E          (40) and (80)                     *     *
CHR$(7)         CTRL G          Produce bell tone                       *
CHR$(8)         CTRL H          Disable character set change      *
CHR$(9)         CTRL I          Enable character set change       *
                                Move cursor to next tab
                                position                                *
CHR$(10)        CTRL J          Send a carriage return with
                                line feed                         *
                                Send a line feed                        *
CHR$(11)        CTRL K          Disable character set change            *
CHR$(12)        CTRL L          Enable character set change             *
CHR$(13)        CTRL M          Send a carriage return and line
                                feed to the computer and enter
                                a line of BASIC                   *     *
CHR$(14)        CTRL N          Set character set to lower/upper
                                case set                          *     *
CHR$(15)        CTRL O          Turn flash on (80)                      *
CHR$(17)        CRSR DOWN or    Move the cursor down one row      *     *
                CTRL Q
CHR$(18)        CTRL 9          characters to be printed in
                                reverse field                     *     *
CHR$(19)        HOME or         Move the cursor to the home
                CTRL S          position (top left) of the
                                display (the current window)      *     *
CHR$(20)        DEL or          Delete last character typed and
                CTRL T          move all characters to the right
                                one space to the left             *     *
CHR$(24)        CTRL X          Tab set/clear                           *
CHR$(27)        ESC or CTRL [   Send an ESC character                   *
CHR$(28)        CTRL 3 or       Send character color to red
                CTRL /          (40) and (80)                     *     *
CHR$(29)        CRSR RIGHT or   Move cursor one column to the
                CTRL ]          right                             *     *
CHR$(30)        CTRL 6 or       Set character color to green
                CTRL ^          (40) and (80)                     *     *
CHR$(34)        "               Print a double quote on screen
                                and place editor in quote mode    *     *
CHR$(129)       C= 1            Set character color to orange
                                (40); dark purple (80)            *     *
CHR$(130)                       Underline off (80)                      *
CHR$(131)                       Run a program. This CHR$ code
                                does not work in PRINT CHR$(131),
                                but works from keyboard buffer    *
CHR$(133)       F1              Reserved CHR$ code for F1 key     *
CHR$(134)       F3              Reserved CHR$ code for F3 key     *
CHR$(135)       F5              Reserved CHR$ code for F5 key     *
CHR$(136)       F7              Reserved CHR$ code for F7 key     *
CHR$(137)       F2              Reserved CHR$ code for F2 key     *
CHR$(138)       F4              Reserved CHR$ code for F4 key     *
CHR$(139)       F6              Reserved CHR$ code for F6 key     *
CHR$(140)       F8              Reserved CHR$ code for F8 key     *
CHR$(141)       SHIFT RETURN    Send a carriage return and line
                                feed without entering a BASIC
                                line                              *     *
CHR$(142)                       Set the character set to upper
                                case/graphics                     *     *
CHR$(143)                       Turn flash off (80)                     *
CHR$(144)       CTRL 1          Set character color to black
                                (40) and (80)                     *     *
CHR$(145)       CRSR UP         Move cursor or printing position
                                up one row                        *     *
CHR$(146)       CTRL 0          Terminate reverse field display   *     *
CHR$(147)       HOME            Clear the window screen and move
                                the cursor to the top left
                                position                          *     *
CHR$(148)       INST            Move character from cursor
                                position right one column         *     *
CHR$(149)       C= 2            Set character color to brown
                                (40); dark yellow (80)            *     *
CHR$(150)       C= 3            Set character color to light red
                                (40) and (80)                     *     *
CHR$(151)       C= 4            Set character color to dark gray
                                (40); dark cyan (80)              *     *
CHR$(152)       C= 5            Set character color to medium
                                gray (40) and (80)                *     *
CHR$(153)       C= 6            Set character color to light
                                green (40) and (80)               *     *
CHR$(154)       C= 7            Set character color to light
                                blue (40) and (80)                *     *
CHR$(155)       C= 8            Set character color to light
                                gray (40) and (80)                *     *
CHR$(156)       CTRL 5          Set character color to purple
                                (40) and (80)                     *     *
CHR$(157)       CRSR LEFT       Move cursor left one column       *     *
CHR$(158)       CTRL 8          Set character color to yellow
                                (40) and (80)                     *     *
CHR$(159)       CTRL 4          Set character color to cyan
                                (40); light cyan (80)             *     *

Note: (40) ... 40 column screen only; (80) ... 80 column screen only


I.2 ESCAPE CODES

Following are key sequences for the ESCape functions available on the
Commodore 128. ESCape sequences are entered by pressing and releasing the
{ESC} key, following by pressing the key listed below.

ESCAPE FUNCTION                                      ESCAPE KEY
---------------                                      ----------
Cancel quote and insert mode                            ESC O

Erase to end of current line                            ESC Q
Erase to start of current line                          ESC P
Erase to end of screen                                  ESC @

Move to start of current line                           ESC J
Move to end of current line                             ESC K

Enable auto-insert mode                                 ESC A
Disable auto-insert mode                                ESC C

Delete current line                                     ESC D
Insert line                                             ESC I

Set default tab stops (8 spaces)                        ESC Y
Clear all tab stops                                     ESC Z

Enable scrolling                                        ESC L
Disable scrolling                                       ESC M

Scroll up                                               ESC V
Scroll down                                             ESC W

Enable bell (by CTRL G)                                 ESC G
Disable bell                                            ESC H

Set cursor to non-flashing mode                         ESC E
Set cursor to flashing mode                             ESC F

Set bottom of screen window at cursor position          ESC B
Set top of screen window at cursor position             ESC T

Swap 40/80 column display output device                 ESC X


The following ESCape sequences are valid on an 80-column screen only. (See
Section 8 for information on using an 80-column screen.)

Change to underlined cursor                             ESC U
Change to block cursor                                  ESC S

Set screen to reverse video                             ESC R
Set screen to normal (non reverse video) state          ESC N    




APPENDIX J

J. MACHINE LANGUAGE MONITOR


J.1 Introduction

Commodore 128 has a built-in machine language monitor which lets the user
write and examine machine language programs easily. Commodore 128 MONITOR
includes a machine language monitor, a mini-assembler and a disassembler.
The built-in monitor works only in C128 mode; either 40 column or 80
column.

Machine language programs written using Commodore 128 MONITOR can run by
themselves or be used as very fast subroutines for BASIC programs since the
Commodore 128 MONITOR has the ability to coexist peacefully with BASIC.

Care must be taken to position the assembly language programs in memory so
the BASIC program does not overwrite them.

To enter the monitor from BASIC, type:

     MONITOR {return}


Summary of Commodore 128 Monitor Commands

ASSEMBLE       Assembles a line of 8502 code.

COMPARE        Compares two sections of memory and reports differences.

DISASSEMBLE    Disassembles a line of 8502 code.

FILL           Fills a range of memory with the specified byte.

GO             Starts execution at the specified address.

HUNT           Hunts through memory within a specified range for all occur-
               rances of a set of bytes.

JUMP           Jumps to the subroutine.

LOAD           Loads a file from tape or disk.

MEMORY         Displays the hexadecimal values of memory locations.

REGISTERS      Displays the 8502 registers.

SAVE           Saves to tape or disk.

TRANSFER       Transfers code from one section of memory to another.

VERIFY         Compares memory with tape or disk.

EXIT           Exits Commodore 128 MONITOR

(period)       Assembles a line of 8502 code (same as Assemble).

(greater than) Modifies memory.

(semicolon)    Modifies 8502 register displays.

@ (at sign)    Displays disk status, sends disk command, displays direc-
               tory.

The Commodore 128 displays 5-digit hexadecimal addresses within the machine
language monitor. Normally, a hexadecimal number is only four digits,
representing the allowable address range. The extra left-most (high order)
digit specifies the BANK configuration (at the time the given command is
executed) according to the following memory configuration table:

     0 - RAM 0 only                8 - EXT ROM, RAM 0, I/O
     1 - RAM 1 only                9 - EXT ROM, RAM 1, I/O
     2 - RAM 2 only                A - EXT ROM, RAM 2, I/O
     3 - RAM 3 only                B - EXT ROM, RAM 3, I/O
     4 - INT ROM, RAM 0, I/O       C - KERNAL + INT (lo), RAM 0, I/O
     5 - INT ROM, RAM 1, I/O       D - KERNAL + EXT (lo), RAM 0, I/O
     6 - INT ROM, RAM 2, I/O       E - KERNAL + BASIC, RAM 0, CHARROM
     7 - INT ROM, RAM 3, I/O       F - KERNAL + BASIC, RAM 0, I/O


J.2 Summary for Monitor Field Descriptors

The following designators precede monitor data fields (e.g. memory dumps).
When encountered as a command, these designators instruct the monitor to
alter memory or register contents using the given data.

     .  {period}       precedes lines of disassembled code
     >  {right angle}  precedes lines of memory dump
     ;  {semicolon}    precedes line of a register dump

The following designators precede number fields (e.g. addresses) and spe-
cify the radix (number base) of the value. Entered as commands, these
designators instruct the monitor simply to display the given value in each
of the four radices.

        {null}         (default) precedes hexadecimal values.
     $  {dollar}       precedes hexadecimal (base-16) values
     +  {plus}         precedes decimal (base-10) values
     &  {ampersand}    precedes octal (base-8) values
     %  {percent}      precedes binary (base-2) values

The following characters are used by the monitor as field delimiters or
line terminators (unless encountered within an ASCII string).

        {space}        delimiter  seperates two fields
     ,  {comma}        delimiter  seperates two fields
     :  {colon}        terminator logical end of line
     ?  {question}     terminator logical end of line


J.3 Command descriptions

Note: < > enclose required parameters
      [ ] enclose optional parameters

Please note that any number field (e.g. addresses, device number, and data
bytes) may be specified as a based number. This affects the operand field
of the ASSEMBLE command as well. Also note the addition of the directory
syntax to the disk command.

As a further aid to programmers, the Kernel error message facility has been
automatically enabled while in the Monitor. This means the Kernel will
display "I/O ERROR#" and the error code, should there be any failed I/O
attempt from the MONITOR. The message facility is turned off when exiting
the MONITOR.


COMMAND: A
PURPOSE: Enter a line of assembly code
SYNTAX:  A <address> <opcode mnemonic> <operand>

           <address>   A hexadecimal number indicating the location in
                       memory to place the opcode.

           <opcode
           mnemonic>   A standard MOS technology assembly language mne-
                       monic, e.g. LDA, STX, ROR.

           <operand>   The operand, when required, can be any of the legal
                       addressing modes.

A {return} is used to indicate the end of the assembly line. If there are
any errors on the line, a question mark is displayed to indicate an error,
and the cursor moves to the next line. The screen editor can be used to
correct the error(s) on that line.

EXAMPLE:   A01200 LDX #$00
           A 1202

NOTE: A period (.) is equal to the ASSEMBLE command.

EXAMPLE:   .02000 LDA #$23


COMMAND: C
PURPOSE: Compare two areas of memory
SYNTAX:  C <address1> <address 2> <address 3>

           <address 1> A number indicating the start address of the area of
                       memory to compare against.

           <address 2> A number indicating the end address of the area of
                       memory to compare against.

           <address 3> A number indicating the start address of the other
                       area of memory to compare with.

Addresses that do not agree are printed on the screen.


COMMAND: D
PURPOSE: Disassemble machine code into assembly language mnemonics and
         operands.
SYNTAX:  D [<address 1>] [<address 2>]

           <address 1> A number setting the address to start the dis-
                       assembly.

           <address 2> An optional ending address of code to be dis-
                       assembled.

The format of the disassembly differs slightly from the input format of an
assembly. The difference is that the first character of a disassembly is a
period rather than an A (for readability), and the hexadecimal code is
listed as well.

A disassembly listing can be modified using the screen editor. Make any
changes to the mnemonic or operand on the screen, then hit the carriage
return. This enters the line and calls the assembler for further modifi-
cations.

A disassembly can be paged. Typing a D{return} causes the next page of
disassembly to be displayed.

EXAMPLE:   D 3000 3003
           .03000 A9 00      LDA #$00
           .03002 FF         ???
           .03003 D0 2B      BNE $3030


COMMAND: F
PURPOSE: Fill a range of locations with a specified byte.
SYNTAX:  F <address 1> <address 2> <byte>

           <address 1> The first location to fill with the <byte>.

           <address 2> The last location to fill with the <byte>.

           <byte>      Number to be written.

This command is useful for initializing data structures or any other RAM
area.

EXAMPLE:   F 0400 0518 EA

           Fill memory locations from $0400 to $0518 with $EA (a NOP
           instruction).


COMMAND: G
PURPOSE: Begin execution of a program at a specified address.
SYNTAX:  G [<address>]

           <address>   An address where execution is to start. When address
                       is left out, execution begins at the current PC.
                       (The current PC can be viewed using the R command.)

The GO command restores all registers (displayable by using the R command)
and begins execution at the specified starting address. Caution is recom-
mended in using the GO command. To return to Commodore 128 MONITOR mode
after executing a machine language program, use the BRK instruction at the
end of the program.

EXAMPLE:   G 140C

           Execution begins at location $140C.


COMMAND: H
PURPOSE: Hunt through memory within a specified range for all occurrences
         of a set of bytes.
SYNTAX:  H <address 1> <address 2> <data>

           <address 1> Beginning address of hunt procedure.
          
           <address 2> Ending address of hunt procedure.

           <data>      Data set to search for data may be numbers or an
                       ASCII string.

EXAMPLES:  H A000 A101 A9 FF 4C

           Search for data $A9, $FF, $4C, from $A000 to $A101.

           H 2000 9800 'CASH

           Search for the alpha string "CASH".


COMMAND: J
PURPOSE: Begin execution of a program at a specified address.
SYNTAX:  J [<address>]

         <address>     An address where execution is to start. When address
                       is left out, execution begins at the current PC.
                       (The current PC can be viewed using the R command.)

The JUMP command restores all registers (displayable by using the R com-
mand) and begins execution at the specified starting address. Caution is
recommended in using the JUMP command. To return to Commodore 128 MONITOR
mode after executing a machine language program, use the RTS instruction at
the end of the program.

EXAMPLE:   J 1300

           Execution begins at location $1300.


COMMAND: L
PURPOSE: Load a file from cassette or disk.
SYNTAX:  L <"file name"> [,<device> [,alt load address] ]

           <"file name">       Any legal Commodore 128 file name.
           <device>            A hexadecimal number indicating the device
                               to load from, 1 is cassette, 8 is disk (or
                               9, A, etc.).
           [alt load address]  Option to load a file to a specific address
                               (4-digit number), or a bank configuration
                               and address (5-digit number).

The LOAD command causes a file to be loaded into memory. If the alternate
load address is not used, the file will be loaded to the address in bank 0
that is specified in the cassette header, or the first two bytes of a disk
file. The alternate load address is used to specify a different start
address, which may range from $00000 to $FFFFF.

EXAMPLE:   L "PROGRAM", $12000

           Loads the file named PROGRAM in from the disk in to bank 1,
           starting at $2000.


COMMAND: M
PURPOSE: To display memory as a hexadecimal and ASCII dump within the
         specified address range.
SYNTAX:  M [<address 1> [<address 2>]]

           <address 1> First address of memory dump. Optional. If omitted,
                       one page is displayed. The first byte is the bank
                       number to be displayed, the next four bytes are the
                       first address to be displayed.

           <address 2> Last address of memory dump. Optional. If omitted,
                       one page is displayed. The first byte is the bank
                       number to be displayed, the next four bytes are the
                       ending address to be displayed.

Memory is displayed in the following format:

           >03000 45 58 2E 56 41 4C 55 45:EX.VALUE

Memory content may be edited using the screen editor. Move the cursor to
the data to be modified, type the desired correction and hit {return}. If
there is a bad RAM location or an attempt to modify ROM has occurred, an
error flag (?) is displayed.

An ASCII dump of the data is displayed in REVERSE (to contrast with other
data displayed on the screen) to the right of the hex data. When a charac-
ter is not printable, it is displayed as a reverse period (.).

As with the disassembly command, paging down is accomplished by typing M
and {return}.

EXAMPLE:   M F4151 F4201

           >F41F1 20 43 4F 4D 4D 4F 44 4F: COMMODO
           >F41F9 52 45 20 45 4C 45 43 54:RE ELECT
           >F4201 52 4F 4E 49 43 53 2C 20:TRONICS,

           NOTE: The above display is produced by the 40-column editor.


COMMAND: R
PURPOSE: Show important 8502 registers. The program status register, the
         program counter, the accumulator, the X and Y index registers and
         the stack pointer are displayed.
SYNTAX:  R

The values of PC, SR, AC, XR, YR and SP are transfered to the 8502 before
the Go or Jump command is executed.

EXAMPLE:   R
              PC   SR  AC  XR  YR  SP
           ;01002  01  02  03  04  F6

           NOTE: ; {semicolon} can be used to modify register displays in
                 the same fashion as > (greater than) can be used to modify
                 memory registers.


COMMAND: S
PURPOSE: Save an area of memory onto tape or disk.
SYNTAX:  S <"file name">, <device>, <address 1>, <address 2>

           <"file name"> Any legal Commodore 128 file name. To save the
                         data the name must be enclosed in double quotes.
                         Single quotes cannot be used.

           <device>      A hexadecimal number indicating on which device
                         the file is to be placed. Cassette is 1; disk is
                         8, 9, etc.

           <address 1>   Starting address of memory to be saved.

           <address 2>   Ending address of memory to be saved + 1. All data
                         up to, but not including the byte of data at this
                         address, is saved.

The file may be recalled, using the L command. When saving to cassette only
bank 0 can be saved from.

EXAMPLE:   S "GAME",8,0400,0C00

           Saves memory from $0400 to $0C00 onto disk.


COMMAND: T
PURPOSE: Transfer segments of memory from one memory area to another.
SYNTAX:  T <address 1> <address 2> <address 3>

           <address 1> Starting address of data to be moved.

           <address 2> Ending address of data to be moved.

           <address 3> Starting address of of new location where data will
                       be moved.

Data can be moved from low memory to high memory and vice versa. Additional
memory segments of any length can be moved forward or backward. An auto-
matic "compare" is performed as each byte is transferred, and any differen-
ces are listed by address.

EXAMPLE:   T 1400 1600 1401

           Shifts data from $1400 up to and including $1600 one byte higher
           in memory.


COMMAND: V
PURPOSE: Verify a file on cassette or disk with the memory contents.
SYNTAX:  L <"file name"> [,<device> [,alt start address] ]

           <"file name"> Any legal Commodore 128 file name.

           <device>      A hexadecimal number indicating the device to load
                         from, 1 is cassette, disk is 8, 9, etc.).

           [alt start
           address]      Option to start verification at this address (4-
                         digit number), or a bank configuration and address
                         (5-digit number).

The Verify command compares a file to memory contents. The Commodore 128
responds with VERIFYING. If an error is found the word ERROR is added; if
the file is successfully verified the cursor reappears.

EXAMPLE:   V "WORKLOAD", 8


COMMAND: X
PURPOSE: Exit to BASIC.
SYNTAX:  X


COMMAND: . {point}
PURPOSE: Can be used to enter a line of assembly code.
SYNTAX:  see the A command.


COMMAND: > (greater than)
PURPOSE: Can be used to set up to 8 or 16 memory locations.
SYNTAX:  > <address> [<data byte 1... 8/16>]

           <address>   First memory address to set.

           <data byte 1... 8/16>
                       Data to be placed in succesive memory locations
                       following the address, with a space preceding each
                       data byte.

The maximum number of bytes that can be entered is 8 (in 40 column mode) or
16 (in 80 column mode). When the {return} key is pressed the contents of
the 8/16 locations after the address are displayed in hexadecimal value and
as ASCII character.

EXAMPLES:  >2000

           Displays line of bytes following $2000.

           >2000 31 32 38

           Enters values at $2000 and displays line of bytes following
           $2000.


COMMAND: ; {semicolon}
PURPOSE: Can be used to modify the display of important 8502 registers.
SYNTAX:  ; [<PC> [<SR> [<AC> [<XR> [<YR> [<SP>]]]]]]

           <PC>        A 5 digit hexadecimal number, consisting of the
                       (leading) 1-digit bank configuration number and
                       4-digit value of the 8502 Program Counter.

           <SR>        A 2-digit hexadecimal number, indicating the value
                       of the 8502 Status Register.

           <AC>        A 2-digit hexadecimal number, indicating the value
                       of the 8502 Accumulator.

           <XR>        A 2-digit hexadecimal number, indicating the value
                       of the 8502 X index Register.

           <YR>        A 2-digit hexadecimal number, indicating the value
                       of the 8502 Y index Register.

           <SP>        A 2-digit hexadecimal number, indicating the value
                       of the 8502 Stack Pointer.

It is easier to use the R command, because the register labels are listed
above the line containing the register values.

The values of PC, SR, AC, XR, YR and SP are transfered to the 8502 before
the Go or Jump command is executed.


COMMAND: @ {at sign}
PURPOSE: Can be used to display the disk status.
SYNTAX:  @ [<unit#>], <disk cmd string>

           <unit#>     Device unit number (optional).

           <disk cmd string>
                       String command to disk.

           NOTE: @ alone gives the status of the disk drive.

EXAMPLES:  @
           00, OK, 00, 00
           Checks disk status.

           @,I
           Initializes drive 8.

           @,$
           Displays directory of drive 8.




APPENDIX K

K. BASIC 7.0 ABBREVIATIONS


Note: The abbreviations below operate in uppercase/graphic mode. Press the
      letter key(s) indicated, then hold down the {shift} key and press
      the letter key following the word SHIFT.


KEYWORD                         ABBREVIATION

ABS                                A SHIFT B
AND                                A SHIFT N
APPEND                             A SHIFT P
ASC                                A SHIFT S
ATN                                A SHIFT T
AUTO                               A SHIFT U
BACKUP                            BA SHIFT C
BANK                               B SHIFT A
BEGIN                              B SHIFT E
BEND                              BE SHIFT N
BLOAD                              B SHIFT L
BOOT                               B SHIFT O
BOX                                  none
BSAVE                              B SHIFT S
BUMP                               B SHIFT U
CATALOG                            C SHIFT A
CHAR                              CH SHIFT A
CHR$                               C SHIFT H
CIRCLE                             C SHIFT I
CLOSE                             CL SHIFT O
CLR                                C SHIFT L
CMD                                C SHIFT M
COLLECT                         COLL SHIFT E
COLINT                               none
COLLISION                        COL SHIFT L
COLOR                            COL SHIFT O
CONCAT                             C SHIFT O
CONT                                 none
COPY                              CO SHIFT P
COS                                  none
DATA                               D SHIFT A
DEC                                  none
DCLEAR                           DCL SHIFT E
DCLOSE                             D SHIFT C
DEF FN                               none
DELETE                            DE SHIFT L
DIM                                D SHIFT I
DIRECTORY                         DI SHIFT R
DLOAD                              D SHIFT L
DO                                   none
DOPEN                              D SHIFT O
DRAW                               D SHIFT R
DS                                   none
DS$                                  none
DSAVE                              D SHIFT S
DVERIFY                            D SHIFT V
EL                                   none
ELSE                               E SHIFT L
END                                  none
ENVELOPE                           E SHIFT N
ER                                   none
ERR$                               E SHIFT R
EXIT                              EX SHIFT I
EXP                                E SHIFT X
FAST                                 none
FETCH                              F SHIFT E
FILTER                             F SHIFT I
FN                                   none
FOR                                F SHIFT O
FRE                                F SHIFT R
GET                                G SHIFT E
GETKEY                          GETK SHIFT E
GET#                                 none
GO64                                 none
GOSUB                             GO SHIFT S
GOTO                               G SHIFT O
GRAPHIC                            G SHIFT R
GSHAPE                             G SHIFT S
HEADER                            HE SHIFT A
HELP                              HE SHIFT L
HEX$                               H SHIFT E
IF                                   none
INPUT                                none
INPUT#                             I SHIFT N
INSTR                             IN SHIFT S
INT                                  none
JOY                                J SHIFT O
KEY                                K SHIFT E
LEFT$                             LE SHIFT F
LEN                                  none
LET                                L SHIFT E
LIST                               L SHIFT I
LOAD                               L SHIFT O
LOCATE                            LO SHIFT C
LOG                                  none
LOOP                              LO SHIFT O
MID$                               M SHIFT I
MONITOR                           MO SHIFT N
MOVSPR                               none
NEW                                  none
NEXT                               N SHIFT E
NOT                                N SHIFT O
ON                                   none
OPEN                               O SHIFT P
OR                                   none
PAINT                              P SHIFT A
PEEK                              PE SHIFT E
PEN                                P SHIFT E
 (PI)                                none
PLAY                               P SHIFT L
POINTER                           PO SHIFT I
POKE                              PO SHIFT K
POS                                  none
POT                                P SHIFT O
PRINT                                    ?
PRINT#                             P SHIFT R
PRINT USING                      ?US SHIFT I
PUDEF                              P SHIFT U
RCLR                               R SHIFT C
RDOT                               R SHIFT D
READ                              RE SHIFT A
RECORD                             R SHIFT E
REM                                  none
RENAME                            RE SHIFT N
RENUMBER                         REN SHIFT U                                    KEYWORD                  ABBREVIATION
RESTORE                           RE SHIFT S
RESUME                           RES SHIFT U
RETURN                            RE SHIFT T
RGR                                R SHIFT G
RIGHT$                             R SHIFT I
RND                                R SHIFT N
RREG                               R SHIFT R
RSPCOLOR                         RSP SHIFT C
RSPPOS                             R SHIFT S
RSPRITE                          RSP SHIFT R
RUN                                R SHIFT U
RWINDOW                            R SHIFT W
SAVE                               S SHIFT A
SCALE                             SC SHIFT A
SCNCLR                             S SHIFT C
SCRATCH                           SC SHIFT R
SGN                                S SHIFT G
SIN                                S SHIFT I
SLEEP                              S SHIFT L
SLOW                                 none
SOUND                              S SHIFT O
SPC(                                 none
SPRCOLOR                         SPR SHIFT C
SPRDEF                           SPR SHIFT D
SPRITE                             S SHIFT P
SPRSAV                           SPR SHIFT S
SQR                                S SHIFT Q
SSHAPE                             S SHIFT S
STASH                              S SHIFT T
ST                                   none
STEP                              ST SHIFT E
STOP                              ST SHIFT O
STR$                              ST SHIFT R
SWAP                               S SHIFT W
SYS                                  none
TAB(                               T SHIFT A
TAN                                  none
TEMPO                              T SHIFT E
THEN                               T SHIFT H
TI                                   none
TI$                                  none
TO                                   none
TRAP                               T SHIFT R
TROFF                            TRO SHIFT F
TRON                              TR SHIFT O
USR                                U SHIFT S
VAL                                  none
VERIFY                             V SHIFT E
VOL                                V SHIFT O
WAIT                               W SHIFT A
WHILE                             WH SHIFT I
WIDTH                              W SHIFT I
XOR                                X SHIFT O




APPENDIX L

L. DISK COMMAND SUMMARY


This appendix lists the commands used for disk operation in C128 and C64
modes on the Commodore 128. For detailed information on any of these com-
mands, see Chapter V, BASIC 7.0 Encyclopaedia. Your disk drive manual also
has information on disk commands.

The new BASIC 7.0 commands can be used only in C128 mode. All BASIC 2.0
commands can be used in both C128 and C64 modes.



Command         Use                                 Basic 2.0     Basic 7.0

APPEND          Append data to file *                                 X

BLOAD           Load a binary file starting at
                the specified memory location                         X

BOOT            Load and execute program                              X

BSAVE           Save a binary file from the
                specified memory location                             X

CATALOG         Display directory contents of disk
                on screen *                                           X

CLOSE           Close logical disk file                 X             X

CMD             Redirect screen output to disk file     X             X

COLLECT         Free inaccessible disk space *                        X

CONCAT          Concatenates two data files *                         X

COPY            Copy files between drives *                           X

DCLEAR          Resets and initializes disk
                drives *                                              X

DCLOSE          Close logical disk files *                            X

DIRECTORY       Display directory of contents of
                disk on screen *                                      X

DLOAD           Load a BASIC program from disk *                      X

DOPEN           Open a disk file for a read and/or
                write operation *                                     X

DSAVE           Save a BASIC program to disk *                        X

DVERIFY         Verify program in memory against
                program on disk *                                     X

GET#            Receive input from open disk file       X             X

HEADER          Format a disk *                                       X

LOAD            Load a file from disk                   X             X

OPEN            Open a file for input or output         X             X

PRINT#          Output data to file                     X             X

RECORD          Position relative file pointers *                     X

RENAME          Change name of a file on disk *                       X

RUN filename    Execute BASIC program from disk                       X

SAVE            Store program in memory to disk         X             X

VERIFY          Verify program in memory against
                program on disk                         X             X

* Although there is no single equivalent command in BASIC 2.0, there is an
  equivalent multi-command instruction. See your drive manual for these
  BASIC 2.0 conventions.




GLOSSARY


This glossary provides brief definitions of frequently used computing
terms.

Acoustic Coupler or Acoustic Modem: A device that converts digital signals
     to audible tones for transmission over telephone lines. Speed is
     limited to about 1,200 baud, or bits per second (bps). Compare direct-
     connect modem.

Address: The label or number identifying the register or memory location
     where a unit of information is stored.

Alphanumeric: Letters, numbers and special symbols found on the keyboard,
     excluding graphic characters.

ALU: Arithmetic Logic Unit. The part of a Central Processing Unit (CPU)
     where binary data is acted upon.

Animation: The use of computer instructions to simulate motion of an object
     on the screen through gradual, progressive movements.

Array: A data-storage structure in which a series of related constants or
     variables are stored in consecutive memory locations. Each constant or
     variable contained in an array is referred to as an element. An ele-
     ment is accessed using a subscript. See subscript.

ASCII: Acronym for American Standard Code for Information Interchange. A
     seven-bit code used to represent alphanumeric characters. It is useful
     for such things as sending information from a keyboard to the com-
     puter, and from one computer to another. See Character String Code.

Assembler: A program that translates assembly-language instructions into
     machine-language instructions.

Assembly Language: A machine-orientated language in which mnemonics are
     used to represent each machine-language instruction. Each CPU has its
     own specific assembly language. See CPU and machine language.

Asynchronous Transmission: A scheme in which data characters are sent at
     random time intervals. Limits phone-line transmission to about 2,400
     baud (bps). See Synchronous Transmission.

Attack: The rate at which the volume of a musical note rises from zero to
     peak volume.

Background Color: The color of the portion of the screen that the charac-
     ters are placed upon.

BASIC: Acronym for Beginner's All-purpose Symbolic Instruction Code.

Baud: Serial-data transmission speed. Originally a telegraph term, 300 baud
     is approximately equal to a transmission speed of 30 characters per
     second.

Binary: A base-2 number system. All numbers are represented as a sequence
     of zeros and ones.

Bit: The abbreviation for Binary digIT. A bit is the smallest unit in a
     computer. Each binary digit can have one of two values, zero or one.
     A bit is referred to as enabled or "on" if it equals one. A bit is
     disabled or "off" if it equals zero.

Bit Control: A means of transmitting serial data in which each bit has a
     significant meaning and a single character is surrounded with start
     and stop bits.

Bit Map Mode: An advanced graphic mode in the Commodore 128 in which you
     can control every dot on the screen.

Border Color: The color of the edges around the screen.

Branch: To jump to a section of a program and execute it. GOTO and GOSUB
     are examples of BASIC branch instructions.

Bubble Memory: A relatively new type of computer memory; it uses tiny
     magnetic "pockets" or "bubbles" to store data.

Burst Mode: A special high speed mode of communication between a disk drive
     and a computer, in which information is transmitted at many times
     normal speed.

Bus: Parallel or serial lines used to transfer signals between devices.
     Computers are often described by their bus structure (i.e. S-100-bus
     computers, etc.).

Bus Network: A system in which all stations or computer devices communicate
     by using a common distribution channel or bus.

Byte: A group of eight bits that make up the smallest unit of addressable
     storage in a computer. Each memory location in the Commodore 128 con-
     tains one byte of information. One byte is the unit of storage needed
     to represent one character in memory. See Bit.

Carrier Frequency: A constant signal transmitted between communicating
     devices that is modulated to encode binary information.

Character: Any symbol on the computer keyboard that is printed on the
     screen. Characters include numbers, letters, punctuation and graphic
     symbols.

Character Memory: The area in Commodore 128's memory which stores the en-
     coded character patterns that are displayed on the screen.

Character Set: A group of related characters. The Commodore 128 character
     set consists of: upper-case letters, lower-case letters and graphic
     characters.

Character String Code: The numeric value assigned to represent a Commodore
     128 character in the computer's memory.

Chip: A miniature electronic circuit that performs a computer operation
     such as graphics, sound and input/output.

Clock: The timing circuit for a microprocessor.

Clocking: A technique used to synchronize a sending and a receiving data-
     communications device that is modulated to encode binary information.

Collision Detection: The recognition of the collision of sprites with other
     sprites or display data.

Color Memory: The area in the Commodore 128's memory that controls the
     color of each location in screen memory.

Command: A BASIC instruction used in direct mode to perform an action. See
     Direct Mode.

Compiler: A program that translates a high-level language, such as BASIC,
     into machine language.

Composite Monitor: A device used to provide a 40-column video display.

Computer: An electronic, digital device that stores and processes infor-
     mation.

Condition: Expression(s) between the words IF and THEN, evaluated as either
     true or false in an IF...THEN statement. The condition in the
     IF...THEN statement gives the computer the ability to make decissions.

Coordinate: A single point on a grid having vertical (Y) and horizontal (X)
     values.

Counter: A variable used to keep track of the number of times an event has
     occurred in a program.

CPU: Acronym for Central Processing Unit. The part of the computer con-
     taining the circuits that control and perform the execution of com-
     puter instructions.

Crunch: To minimize the amount of computer memory used to store a program.

Cursor: The flashing square that marks the current location on the screen.

Data: Numbers, letters or symbols that are input into the computer to be
     processed.

Data Base: A large amount of data stored in a well-organized manner. A
     database management system is a program that allows access to the
     information.

Data Link Layer: A logical portion of data communication control that
     mainly ensures that communication between adjacent devices is error
     free.

Data Packet: A means of transmitting serial data in an efficient package
     that includes an error-checking sequence.

Data Rate or Data Transfer Rate: The speed at which data is sent to a
     receiving computer - given in baud, or bits per second (bps).

Datassette: A device used to store programs and data files sequentially on
     tape.

Debug: To correct errors in a program.

Decay: The rate at which the volume of a musical note decreases from its
     peak value to a mid-range volume called the sustain level. See
     Sustain.

Decrement: To decrease an index variable or counter by a specific value.

Dedicated Line or Leased Line: A special telephone line arrangement sup-
     plied by the telephone company, and required by certain computers or
     terminals, whereby the connection is always established (an exclusive,
     rented line).

Delay Loop: An empty FOR...NEXT loop that slows the execution of a program.

Dial-Up Line: The normal switched telephone line that can be used as a
     transmission medium for data communications.

Digital: Of or relating to the technology of computers and data communica-
     tions where all information is encoded as bits of 1s and 0s that re-
     present on or off states.

Dimension: The property of an array that specifies the direction along an
     axis in which the array elements are stored. For example, a two-
     dimensional array has an X-axis for columns and a Y-axis for rows. See
     Array.

Direct Mode: The mode of operation that executes BASIC commands immediately
     after the {return} key is pressed. Also called Immediate Mode. See
     Command.

Direct Connect Modem: A digital non-acoustic modem.

Disable: To turn off a bit, byte or specific operation of the computer.

Disk Drive: A random access, mass-storage devices that saves and loads
     files to and from a floppy diskette.

Disk Operating System: Program used to transfer information to and from a
     disk. Often referred to as DOS.

Duration: The length of time a musical note is played.

Electronic Mail or E-Mail: A communications service for computer users
     where textual messages are sent to a central computer, or electronic
     "mail box", and later retreive by the addressee.

Enable: To turn on a bit, byte or specific operation of the computer.

Envelope Generator: Portion of the Commodore 128 that produces specific
     envelopes (attack, decay, sustain, release) for musical notes. See
     Waveform.

EPROM: A PROM that can be erased by the user, usually by exposing it to
     ultraviolet light. See PROM.

Error Checking or Error Detection: Software routines that identify, and
     often correct, erroneous data.

Execute: To perform the specified instructions in a command or program
     statement.

Expression: A combination of constants, variables or array elements acted
     upon by logical, mathematical or relational operators that return a
     numeric value.

File: A program or collection of data treated as a unit and stored on disk
     or tape.

Firmware: Computer instructions stored in ROM, as in a game cartridge.

Frequency: The number of sound waves per second of a tone. The frequency
     corresponds to the pitch of the audible tone.

Full-Duplex Mode: Allows two computers on the same line to transmit and
     receive data at the same time.

Function: A predefined operation that returns a single value.

Function Keys: The four keys on the far right of the Commodore 128 key-
     board. Each key can be programmed to execute a series of instructions.
     Since the keys can be SHIFTed, you can create eight different sets of
     instructions.

Graphics: Visual screen images representing computer data in memory (i.e.
     characters, symbols and pictures).

Graphic Characters: Non-alphanumeric characters on the computer's keyboard.

Grid: A two-dimensional matrix divided into rows and columns. Grids are
     used to design sprites and programmable characters.

Half-Duplex Mode: Allows transmission in only one direction at a time; if
     one device is sending, the other must simply receive data until it's
     time for it to transmit.

Hardware: Physical components in a computer system such as keyboard, disk
     drive and printer.

Hexadecimal: Refers to the base-16 number system. Machine language programs
     are often written in hexadecimal notation.

Home: The upper-left corner of the screen.

IC: Integrated Circuit. A silicon chip containing an electic circuit made
     up of components such as transistors, diodes, resistors and capaci-
     tors. Integrated circuits are smaller, faster and more efficient that
     the individual circuits used in older computers.

Increment: To increase an index variable or counter with a specified value.

Index: The variable counter within a FOR...NEXT loop.

Input: Data fed into the computer to be processed. Input sources include
     the keyboard, disk drive, Datassette or modem.

Integer: A whole number (i.e. a number containing no fractional part), such
     as 0, 1, 2, etc.

Interface: The point of meeting between a computer and an external entity,
     whether an operator, a peripheral device or a communications medium.
     An interface may be physical, involving a connector, or logical, in-
     volving software.

I/O: Input/Output. Refers to the process ot entering data into the com-
     puter, or transferring data from the computer to a disk drive, printer
     or storage medium.

Keyboard: Input component of a computer system.

Kilobyte (K): 1,024 bytes.

Local Network: One of several short-distance data communications schemes
     typified by common use of a transmission medium by many devices and
     high-data speeds. Also called a Local Area Network, or LAN.

Loop: A program segment executed repitively a specified number of times.

Machine Language: The lowest level language the computer understands. The
     computer converts all high-level languages, such as BASIC, into
     machine language before executing any statements. Machine language is
     written in binary form that a computer can execute directly. Also
     called machine code or object code.

Matrix: A two-dimensional rectangle with row and column values.

Memory: Storage locations inside the computer. ROM and RAM are two dif-
     ferent types of memory.

Memory location: A specific storage address in the computer. There are
     131,072 memory locations in the Commodore 128.

Microprocessor: A CPU that is contained on a single integrated circuit
     (IC). Microprocessors used in Commodore personal computers include the
     6510, the 8502 and the Z80.

Mode: A state of operation.

Modem: Acronym for MODulator/DEModulator. A device that transforms digital
     signals from the computer into electrical impulses for transmission
     over telephone lines, and does the reverse in reception.

Monitor: A display device resembling a television set but with a higher-
     resolution (sharper) image on the video screen.

Motherboard: In a bus-oriented system, the board that contains the bus
     lines and edge connectors to accommodate the other boards in the
     system.

Multi-Color Character Mode: A graphic mode that allows you to display four
     different colors within an 8 X 8 character grid.

Multi-Color Bit Map Mode: A graphic mode that allows you to display one of
     four colors for each pixel within an 8 X 8 character grid. See Pixel.

Multi-Access Network: A flexible system by which every station can have
     access to the network at all times; provisions are made for times when
     two computers decide to transmit at the same time.

Null String: An empty character (""). A character that is not yet assigned
     a character string code.

Octave: One full series of eight notes on the musical scale.

Operating System: A built-in program that controls everything your computer
     does.

Operator: A symbol that tells the computer to perform a mathematical,
     logical or relational operation on the specified variables, constants
     or array elements in the expression. The mathematical operators are
     +, -, *, / and ^. The relational operators are <, =, >, <=, >= and <>.
     The logical operators are AND, OR, NOT, and XOR.

Order of Operations: Sequence in which computations are performed in a
     mathematical expression. Also called Hierarchy of Operations.

Parallel Port: A port used for simultaneous transmission of data, one byte
     at a time over multiple wires, one bit per wire.

Parity Bit: A 1 or 0 added to a group of bits that identifies the sum of
     the bits as odd or even.

Peripheral: Any accessory device attached to the computer such as a disk
     drive, printer, modem or joystick.

Pitch: The pitch of a note is determined by the frequency of the sound
     wave. The higher the frequency of a note, the higher its pitch. See
     Frequency.

Pixel: Computer term for picture element. Each dot on the screen that makes
     up an image is called a pixel. Each character on the screen is dis-
     played within a 8 X 8 grid of pixels. The entire screen is composed of
     a 320 X 200 pixel grid. In bit-map mode, each pixel corresponds to one
     bit in the computer's memory.

Polling: A communications control method used by some computer/terminal
     systems whereby a "master" station asks many devices attached to a
     common transmission medium, in turn, whether they have information to
     send.

Pointer: A register used to indicate the address of a location in memory.

Port: A channel through which data is transferred to and from the CPU. An
     8-bit CPU can address 256 ports.

Printer: Peripheral device that outputs onto a sheet of paper. This paper
     is referred to as a hard copy.

Program: A series of instructions that direct the computer to perform a
     specific task. Programs can be stored on diskette or cassette, reside
     in the computer's memory, or be listed on a printer.

Programmable: Capable of being processed with computer instructions.

Program Line: A statement or series of statements preceded by a line number
     in a program. The maximum length of a program line on the Commodore
     128 is 160 characters.

PROM: Acronym for Programmable Read Only Memory. A semiconductor memory
     whose contents can only be written to once, after which the contents
     is permanent. See also EPROM and Read Only Memory (ROM).

Protocol: The rules under which computers exchange information, including
     the organization of the units of data to be transferred.

Random Access Memory (RAM): The programmable area of the computer's memory
     that can be read from and written to (changed). All RAM locations are
     equally accessible at any time in any order. The components of RAM are
     erased when the computer is turned off.

Random Number: A nine-digit decimal number from 0.000000001 to 0.999999999
     generated by the RaNDom (RND) function.

Read Only Memory (ROM): The permanent portion of the computer's memory. The
     contents of ROM locations can be read, but not changed. The ROM in the
     Commodore 128 contains the BASIC language interpreter, character-image
     patterns and portions of the operating system.

Register: Any memory location in RAM. Each register stores one byte. A
     register can store any value between 0 and 255 in binary form.

Release: The rate at which the volume of a musical note decreases from the
     sustain level to zero.

Remark: Comment used to document a program. Remarks are not executed by the
     computer, but are displayed in the program listing.

Resolution: The density of pixels on the screen that determines the fine-
     ness of detail of a displayed image.

RGBI Monitor: Red/Green/Blue/Intensity. A high-resolution display device
     necessary to produce an 80-column screen format.

Ribbon Cable: A group of attached parallel wires. Also called flat cable.

Ring Network: A system in which all stations are linked to form a conti-
     nuous loop or circle.

RS-232: A recommended standard for electronic and mechanical specifications
     or serial transmission ports. The Commodore 128 parallel user port can
     be treated as a serial port if accessed through software, sometimes
     with the addition of an interface device.

Screen: Video display unit which can be either a television or video
     monitor.

Screen code: The number assigned to represent a character in screen memory.
     When you type a key on the keyboard, the screen code for that charac-
     ter is entered into screen memory automatically. You can also display
     a character by storing its screen code directly into screen memory
     with the POKE command.

Screen Memory: The area of the Commodore 128's memory that contains the
     information displayed on the video screen.

Serial Port: A port used for serial transmission of data; bits are trans-
     mitted one bit after the other over a single wire.

Serial Transmission: The sending of sequentially ordered data bits.

Software: Computer programs (sets of instructions) stored on disk, tape or
     cartridge that can be loaded into random access memory (RAM). Soft-
     ware, in essence, tells the computer what to do.

Sound Interface Device (SID): The MOS 6581 sound synthesizer chip respon-
     sible for all the audio features of the Commodore 128.

Source Code: A non-executable program written in a high-level language. A
     compiler or assembler must translate the source code into an object
     code (machine language) that the computer can understand.

Sprite: A programmable, movable, high-resolution graphic image. Also
     called a Movable Object Block (MOB).

Standard Character Mode: The mode the Commodore 128 operates in when you
     turn it on and when you write programs.

Start Bit: A bit or group of bits that identifies the beginning of a data
     word.

Statement: A BASIC instruction contained in a program line.

Stop Bit: A bit or group of bits that identifies the end of a data word and
     defines the space between data words.

String: An alphanumeric character or series of characters surrounded by
     quotation marks.

Subroutine: An independent program segment separate from the main program
     that performs a specific task. Subroutines are called from the main
     program with the GOSUB statement and must end with a RETURN statement.

Subscript: A variable or constant that refers to a specific element in an
     array by its position within the array.

Sustain: The midranged volume of a musical note.

Synchronous Transmission: Data communications using a synchronizing, or
     clocking, signal between sending and receiving devices.

Syntax: The grammatical rules of a programming language.

Tone: An audible sound of specific pitch and waveform.

Transparent: Describes a computer operation that does not require user
     intervention, i.e. the user is unaware that it is taking place.

Variable: A unit of storage respresenting a character string or numeric
     value. Variable names can be any length, but only the first two
     characters are stored by the Commodore 128. The first character must
     be a letter.

Video Interface Controller (VIC): The MOS 6566 chip responsible for the
     40-column graphic features of the Commodore 128.

Voice: A sound-producing component inside the SID chip. There are three
     voices within the SID chip, so the Commodore 128 can produce three
     different sounds simultaneously. Each voice consists of a tone oscil-
     lator/waveform generator, an envelope generator and an amplitude
     modulator.

Waveform: A graphic representation of the shape of a sound wave. The wave-
     form determines some of the physical characteristics of the sound.

Word: Number of bits treated as a single unit by the CPU. In an eight-bit
     machine, the word length is eight bits; in a 16-bit machine, the word
     length is 16 bits.




INDEX

A
Abbreviations - BASIC, 3.3.2, K
ABS function, 4.6.7, 18.1
Addition, 3.6.1
ADM, 15.2
ADSR, 7.1, 7.3.2.1
Alt key, 5.9.3.5
Alt mode, 15.2
Animation, 6.3, 6.3.11
APPEND, 17.1
Arrays, 4.3.6, 19.1
ASC function, 4.6.4, 18.2
ASCII character codes, 4.6.4, E
ASM, 12.3.7
Asterisk key {*}, 3.6.2
Attack, 7.3.2.1
ATN function, 18.3
AUTO, 5.6.1.1, 17.2
AUXIN, 14.5
AUXOUT, 14.5



B
Bach, 7.4
BACKUP, 17.3
Bandpass, 7.3.2.4
BANK, 17.4
Bank table, 17.4
BAS, 12.3.7
BASIC
 abbreviations, 3.3.2
 commands, 17
 functions, 4.6, 18
 mathematics, 3.6
 operators, 3.6.1
 statements, 17
 variables, 19.1
BASIC 2.0, 2.1.2, 16.1
BASIC 7.0, 2.1.1, 16.1
BEGIN/BEND, 17.5
Binary files, 6.3.12
Bit Map mode, 6.2.2
BLOAD, 6.3.10, 6.3.12.2, 17.6
BOOT, 17.7
Booting, 11.4.3
BOX, 6.1.2, 6.2.4.2, 17.8
BSAVE, 6.3.10, 6.3.12, 6.3.12.1, 17.9
BUMP, 18.4



C
C128 Mode, 2.1.1
C64 Mode, 2.1.2
Caps Lock key, 5.9.3.3
Cartridge Port, C.2
Cassette Port, C.2
CATALOG, 17.10
CHAR, 6.1.2, 6.2.4.5, 17.11
Character sets, 3.2.1
Character string code, 4.6.4
CHR$ codes, 9.6, E, I
CHR$ function, 4.6.4, 18.5
CIRCLE, 6.1.2, 6.2.4.1, 17.12
Clock, 19.1
CLOSE, 10.1, 17.13
CLR, 3.7.3, 6.2.3, 17.14
CLR/HOME key, 3.2.2.9
CMD, 17.15, 17.28
COLLECT, 17.16
COLLISION, 17.17
Colon {:}, 4.1.1
COLOR, 6.1.2, 6.2.1, 17.18
Color
 code display chart, 3.3.4, 6.2.1, 17.18
 control, 3.2.2.6, 3.4.6, 15.2
 CHR$ codes, E
 keys, 3.3.4
 memory map, F.2
 screen and border, 6.2.2
 source code, 6.2.1
COM, 11.5.1, 12.3.7
Comma {,}, 3.3.1
Command, 3.1.1
Command keys, 3.2.2
Command keyword, 11.5
Command line, 11.5
Command tail, 11.5
Commodore key, 3.2.2.6, 3.2.2.10
Composite monitor, 2.1.1, 8.5
CONCAT, 17.19
CONIN, 14.5
Connections, C
CONOUT, 14.5
Constants, 3.7.1
CONTinue command, 4.7, 17.20
Control characters table, 7.3.2.3
Control key, 3.2.2.6, 11.2
Coordinate grid, 6.2.4.1
COPY, 17.21
Copying music, 7.4
Copying programs, 11.6.2
COSine function, 18.6
CP/M characters, 12.3.6
CP/M mode, 11
CP/M Plus User's Guide, 15.2
CP/M Plus 3.0, 2.1.3, 11
CTRL-, 11.5, 13.4
CuRSoR keys, 3.2.2.4.2, 9.5
Cursor, 3.2.2.4
Cutoff frequency, 7.3.2.4



D
Datassette, 3.9
DATA, 4.3.4, 17.22
Data file, 12.1
DATE, 14.3
DCLEAR, 17.23
DCLOSE, 17.24
Debug, 4.7, 5.6.2.3
DEC, 18.7
Decay, 7.1, 7.3.2.1
DEF FN, 17.25
Delay loops, 4.2.1
DELETE, 5.6.1.3, 17.26
DELete key, 3.2.2.5
DEVICE, 14.3
Dice, 4.6.3
DIMension statement, 4.3.6.2, 17.27
DIR command, 11.5, 14.3
Direct mode, 3.1.1
DIRECTORY, 3.6.9.2, 17.28
DIRSYS, 14.3
Disk commands, 3.9, 10.4, L
Disk directory, 3.6.9.2, 10.4
Disk Parameters, 3.9, 11.4.2
Division, 3.6.2
DLOAD", 3.1.2, 3.9.4, 17.29
Dollar sign {$}, 3.7.3, 7.3.2.3, 10.4.2
DO/LOOP, 17.30
DOPEN, 17.31
DRAW, 6.1.2, 6.2.4.3, 17.32
Drive Specifier, 12.3.1.1
DS/DS$ variables, 19.1
DSAVE", 3.1.2, 3.9.2, 17.33
Dual screens, 8.5
DUMP, 14.3
Duration, 7.2, 7.3.2.3
DVERIFY", 3.9.6.1, 17.34



E
Echo, 13.2
ED, 12.2, 14.3
Editing, 3.5, 13.3
EL variable, 19.1
ELSE clause, 5.2.2, 17.50
END statement, 4.1, 17.35
Envelope generator, 7.3.2.1
ENVELOPE, 7.3.2.1, 17.36
Equals {=}, 3.7.2, 4.1
ERASE, 14.2 14.3
ER/ERR$ variables, 5.6.2.3, 18.8, 19.1
Error functions, 5.6.2.3
Error messages, A, B
Escape codes, I.1
ESCape key, 6.2.3, 15.2
EXIT, 5.2.1.3, 17.30
Exponentiation, 3.6.3
EXPonent function, 18.9



F
40/80 Display key, 5.9.3.4, 8.2
FAST command, 5.8, 17.37
FETCH, 17.38
File, 12.2
Filename, 12.3.1.3
File specifications, 12.3.1
File type, 12.3.1.3
FILE NOT FOUND, 3.9.4
FILTER, 7.3.2.5, 17.39
Filter - SID, 7.3.2.4
Flat {$}, 7.3.2.3
FN function, 18.10
FOR...NEXT statement, 4.2, 17.40
FORMAT, 14.3
Formatting disks, 3.9.1, 10.1
FRE function, 18.11
Frequency, 7.2, 7.3.1
Function, 3.1
Function keys, 3.2.3, 5.9.1, 9.6



G
Game control and ports, C.1
GENCOM, 14.3
GET, 4.3.2, 14.3, 14.4, 17.41
GETKEY, 5.5, 17.42
GET# statement, 17.43
GO64, 17.44
GOSUB, 4.4.2, 17.45
GOTO, 3.4.4, 17.46
GRAPHIC, 6.1.2, 6.2.3, 17.47
Graphic characters, 3.2.4
Graphic modes, 5.8.1, 6.2.3
GSHAPE, 17.91



H
Harmonics, 7.3.1
Hash mark {#}, 5.3.1, 6.3.6, 17.24, 17.68
HEADER, 3.9.1, 17.48
HELP key, 5.6.2.1, 5.9.3.1
HEX, 12.3.7
HEX$, 18.12
HLP, 12.3.7
HOME key, 3.2.2.9
Hyperbolic functions, G



I
IF...THEN statement, 4.1, 17.50
INITDIR, 14.3
Initializing, 10.4.3
INPUT, 4.3.1, 17.51
INPUT#, 17.52
Input Prompt, 4.3.1.2
INSerT key, 3.2.2.5
INSTR, 18.13
INTeger function, 4.6.2, 18.14



J
JOY, 18.15
Joystick ports, C.1




K
KEY command, 5.9.2, 17.53
KEYFIG, 14.3
Keyboard, 3.2.0.1
Key assignment - CP/M, 15.1.1



L
LEFT$ function, 18.16
LENgth function, 18.17
LET statement, 17.54
Line Feed key, 5.9.3.7
Line numbers, 3.4.2
LOAD command, 3.9.4, 10.3.1, 17.56
LOADing cassette software, 10.3.2
LOADing CP/M software, 11.4.1
LOADing disk software, 10.3.1
LOCATE, 17.57
LOGarithm function, 18.18
Loops, 4.2
LST, 14.5



M
Machine language, J
Mathematics, 3.6, G
Memory maps, F, H
MID$ function, 18.19
Mode switching chart, 2.2.1
MONITOR, 17.58
Monitor - dual, 8.5
Monitor - machine language, 5.9.1, J
Monitor switching, 6.2.3, 8.5
MOVSPR, 6.3.7, 17.59
Multicolor bit mode, 6.2.2
Multiplication, 3.6.2
Music programs, 7.3.3, 7.4
Music videos, 7.3.4
Musical notes, 7.3.2.3
Musical instruments, 7.3.2.1
Musical staff, 7.4



N
Nested loops, 4.2.1
NEW, 3.4.6, 17.60
NEXT statement, 4.2, 17.40
Noise, 7.3.1
No Scroll key, 5.9.3.2, 13.1
Notch Reject Filter, 7.3.4
Notes, 7.3.2.3
Numeric functions, 4.6.1



O
Object code file, 6.3.12
ON GOTO/GOSUB, 4.4.2
OPEN statement, 10.1, 17.62
Operating System, 11.1
Operators,
 arithmetic, 3.6, 19.2
 logical, 19.2
 order of, 3.6.4
 relational, 4.1, 19.2



P
PAINT, 6.1.2, 6.2.4.4, 17.63
Parentheses, 3.6.4, 12.3.6
Password, 12.3.1.4
PATCH, 14.3
PEEK function, 4.5.1.1, 18.20
PEN, 18.21
Period {.}, 7.3.2.3
PI, 18.22
PIP, 11.6, 14.3
Pixel, 6.2.2, 6.3.4
PLAY, 7.3.2.3, 17.64
POINTER, 18.23
POKE, 4.5.1.2, 17.65
POS function, 18.24
POT, 18.25
PRINT, 3.3.1, 17.66
PRINT#, 10.1, 17.67
PRINT USING, 5.3.1, 17.68
Printer control - CP/M, 13.2
PRN, 12.3.7
Program file, 11.2
Program mode, 3.1.2
Programmable keys, 5.9.1, 9.6
Programming aids, 5.6
PUDEF, 5.3.2, 17.69
Pulse width, 7.2.1, 7.3.2.1
PUT, 14.3



Q
Question mark {?}, 3.3.2, 12.3.5
Quotation marks {"}, 3.3.3
Quote mode, 3.3.5



R
RAM, 4.5.1, 11.3
Random sounds, 7.2.2
RCLR, 18.26
RDOT, 18.27
READ, 4.3.4, 17.70
RECORD, 17.71
Relational operators, 4.1
REL, 12.3.7
Release, 7.1, 7.3.2.1
REMark statement, 3.2.5, 17.72
RENAME, 14.2, 14.3, 17.73
RENUMBER, 5.6.1.2, 17.74
Reset button, 8.2
Reserved variables, 19.1
Rest, 7.3.2.3
Restore key, 3.2.2.8
RESTORE statement, 4.3.5, 17.75
RESUME command, 5.6.2.2, 17.76
Return key, 3.2.2.1
RETURN statement, 4.4.1, 17.77
RGR, 18.28
RIGHT$ function, 18.29
RREG, 17.78
RSPCOLOR, 18.31
RSPPOS, 18.32
RSPRITE, 18.33
RUN command, 3.4.2, 17.79
RUN/STOP key, 3.2.2.7, 6.2.3, 7.2.1, 7.3.2.3, 8.2
RWINDOW, 18.34



S
SAVE command, 3.9.2, 10.2.1, 14.3, 17.80
Saving programs on tape, 3.9.3, 10.2.2
Saving progams on disk, 3.9.2, 10.2.1
Sawtooth waveform, 7.3.1
SCALE, 6.1.2, 6.2.4.7, 17.81
SCNCLR command, 17.82
SCRATCH command, 17.83
Screen display codes, D
Screen display, 6.2.2, 8.1
Screen memory map, F
Scrolling, 5.7.2
Sector, 3.9.1
Semicolon {;}, 3.3.1
Serial port, C.2
SET, 14.3
SETDEF, 13.1
SGN function, 18.35
Sharp {#}, 7.3.2.3
Sheet music, 7.4
Shift key, 3.2.2.2
SHOW, 14.3
SID chip, 7.1
SINe function, 18.36
Slash key {/}, 3.6.2
SLEEP, 5.2.4, 17.84
SLOW command, 5.8.1, 17.85
Software - 80 column, 8.3
SOUND, 7.2, 17.86
Sound Interface Device, 7.1
Sound Player Program, 7.2.1
Sound reset, 7.2.1, 7.3.2.3
SPC function, 18.37
Split screen display, 6.2.2
SPRCOLOR, 17.87
SPRDEF, 6.1.2, 6.3.9, 17.88
SPRITE, 6.1.2, 6.3.6, 17.89
Sprite Combinations, 6.3.11
Sprite Control, 6.3.6
Sprite Editor, 6.3.9
Sprite Programming, 6.3, 6.3.8
Sprite memory map, 6.3.12
Sprite movement, 6.3.7
Sprite viewing area, 6.3.7
Sprites, 6.3
SPRSAV, 6.1.2, 6.3.5, 17.90
SQR function, 4.6.2, 4.6.6, 18.38
SSHAPE, 6.1.2, 6.3.4, 17.91
ST variable, 19.1
STASH, 17.92
Statement, 3.1, 3.4.1
STEP, 4.2.2, 17.40
STOP, 4.7, 17.93
STOP key, 3.2.2.7
Storing programs, 3.9, 10.2
String functions, 4.6.4
Strings, 3.3.3, 3.7.3
STR$ function, 4.6.5.2, 18.39
SUB, 12.3.5.1
SUBMIT, Table 14-2
Subroutine, 4.4
Subscripts, 4.3.6.1
Subtraction, 3.6.1
Sustain, 7.1, 7.3.2.1
SWAP, 17.94
Sweep, 7.2
Syntax, 3.1
Syntax error, 3.2.2.1
Synthesizer, 7.1, 7.3.2.3
SYM, 12.3.5.1
SYS,  12.3.5.1, 17.95
System prompt, 11.5



T
Tab key, 5.9.3.6
TAB function, 18.40
TAB stops, 5.7.2
TANgent function, 18.41
TEMPO, 7.3.2.2, 17.96
Terminating CP/M, 14.8
THEN, 4.1, 17.50
Timbre, 7.3.1
Time delay, 4.2.1
TI/TI$ variables, 19.1
TO, 4.2, 17.40
Track, 3.9.1
Transient Utility Commands, 11.5.1, 14.1, 14.3
TRAP, 5.6.2.2, 17.97
Triangle waveform, 7.3.1.3
Trigonometric functions, G
TRON/TROFF, 5.6.2.3, 17.98, 17.99
TYPE, Table 14-1, Table 14-2
Typing rules, 3.2.5



U
UNTIL statement, 5.2.1.1, 17.30
Up arrow key {^}, 3.6.3
Upper case/graphics set, 3.2.1, 9.2
Upper/Lower case set, 3.2.1, 9.2
USER, 12.3.4, 14.2
User Number, 12.3.4
User port, C.2
USR function, 18.42



V
VALue function, 4.6.5.1, 18.43
Variables, 3.7.2, 4.3.6.1, 19.1
VERIFY command, 3.9.6.1, 10.4.1, 17.100
VIC chip, 6.1
Video ports, C.2
Voice, 7.1
VOLume, 7.2.1, 7.3.2.1, 17.101



W
WAIT command, 17.102
Waveform, 7.1, 7.3.1, 7.3.2.1
WHILE statement, 5.2.1.2, 17.30
WIDTH, 17.103
Wildcard, 12.3.5
WINDOW command, 5.7.1, 17.104
Windowing, 5.7



X
XOR, 18.44



Z
Z80 Microprocessor, 11.2




Commodore               Commodore Buromaschinen  Commodore Buromaschinen
Business Machines (UK)  GmbH                     GmbH
Ltd.                    Lyoner Str. 38           Kinskygasse 40-44
1, Hunters Road         6000 Frankfurt/Main 71   1232 Vienna
Weldon, Corby           West Germany             Austria
Northamptonshire,
NN 17 1QX
Great Britain

Commodore AG            Commodore France S.R.L.  Commodore Italiana S.R.L.
Aeschenvorstadt 57      8 Rue Copernic           Via Fratelli Gracchi 48
4010 Basel              75116 Paris              20092 Cinisello Balsamo
Switzerland             France                   Italy

Commodore Computers     Commodore Data AS        COE Computer Products AB
Norge A/S               Bjerrevej 67             Fagerstagatan 9
Brobekkveien 38         8700 Horsens             163 53 Spanga
0509 Oslo 5             Denmark                  Sweden
Norway

Commodore Computer      Commodore Computer BV    Commodore Business
NV-SA                   Kabelweg 88              Machines (Pty.) Ltd.
Leuvensesteenweg 43     1014 Amsterdam BC        5, Mars Road
1940 St. Stevens-       Netherlands              Lane Cove
Woluse                                           N.S.W. 2066
Belgium                                          Australia
