				Tunesmith: Da Manual
				--------------------

A major undertaking by a minor composer.

Last revised: 7/28/98

This is Tunesmith, version B (the B is for Bach).

-----
	Please send any comments or questions to 

		sjudd@nwu.edu

The latest versions of the binaries, not to mention the source code,
can be found in the Fridge at

		http://stratus.esam.nwu.edu/~judd/fridge/

Note that the above address will be changing sometime in early 1999!

If you find this program useful and write some example songs, macros,
or programs, please send them to me!  I'd love to hear them, and I'd
love to put them on my web page to share with the world.

-----

Table of Contents:

Section 1	Introduction
	1.1 	  History, Anecdotes, General Narcissism
	1.2 	  Writing your first song
	1.3 	  Other files
	1.4 	  Compatibility
Section 2	Overview
	2.1 	  The top level
	2.2 	  Music editor
	2.3 	  Instrument editor
	2.4 	  Macro manager
Section 3	The Music Editor
	3.1	  Editor
	3.2	  Editor commands
	3.3	  Other commands
	3.4	  Recovering data
Section 4	The Instrument Editor
Section 5	The Macro Manager
Section 6	The Player
Section 7	Macros
	7.1	  Arguments
	7.2	  Flags
	7.3	  Keywords
	7.4	  Player routines
	7.5	  Variables
	7.6	  The Compiler
Section 8	Some Elementary Music Theory
	8.1 	  Rhythm and Meter
	8.2 	  Notes and intervals
	8.3 	  Scales and keys
	8.4 	  Chords and chord progressions
	8.5 	  Dynamics and music performance
	8.6	  Acoustics
	8.7	  Conclusion
References



Section 1: Introduction
---------

	Tunesmith is a powerful system for composing music on the
Commodore 64.  My goal was to write a program which was very flexible and
unconstraining, so that I could explore both musical possibilities and
hardware possibilities.
	It is quite different from other music composition systems, very
flexible, and very powerful.  Abject novices can begin writing music
in no time and expert users can take advantage of the advanced features
to push the C-64 to its hardware limits.  It features an easy to use 
instrument editor, an extensive and configurable music editor, and
its most novel feature is an actual, compiled, little computer language
which can interact with the player while the music is playing.
	The program is aimed at composers first and foremost, but I
have put a lot of work into it to make it comfortable for demo and
game music programming.


1.1 History, Anecdotes, General Narcissism

	Tunesmith is "The Program Formerly Known As Blahtune".  It has a 
number of new features, and tons of little details and bugs have been 
fixed up.  All in all, it took a month or two to add all the new stuff.  
As you can see, the main program is huge -- 101 blocks -- but it now 
includes several features that make the original program quite a lot 
nicer, more powerful and more comfortable.  I hope you enjoy it.

	At this point I would like to give a very special thanks to
Attilla Szoke, a.k.a. da Blondie/WiSH, the only known person to have
used Blahtune (besides me).  He has offered encouragement and 
innumerable suggestions and criticisms, and if you see a feature
in this program that is useful and original, it was probably his idea.
He also wrote one of the sample tunes (the cool one).  A simple 
"Thanks d00d" doesn't quite cut it, but will have to do.

Apparently, here was my motivation to write blahtune, from the old manual:

	I have listened to music since conception and I have played
violin since I was five.  At some point I became interested in
composition, and for some time now I've wanted to do some more
serious composing, explore various aspects of music, and really sit 
down and learn some stuff.
	I've also been interested in exporing various aspects of the C64!
In particular I've wanted to experiment with SID.  I was also curious
about how one might write a compiler, and a few other things.
	The various composition programs already out there are very good
for what they do; the problem is that they aren't capable of many
things that I want to do!  What do you do when music composers don't
meet your needs?  Write your own of course!

	So, after years of dreaming, I started planning.  A year ago, after
Polygonamy, I started working on it in the back of my mind.  I also wrote
a little SID lab program which is actually the instrument editor.  In
the summer I used dim4 to get some practice at writing a music player.
Around August I began work more seriously, by writing a crappy text
editor.  A few months later I designed the macro language and wrote
the player; by December the compiler was finished.  Finally, at the
end of March, after some marathon coding sessions the music editor was
finally finished, and all the underlying structural code (like the
macro manager) was written.  A few months more of work, and here we
are.
	One of the really great things about the 64 is that a guy
like me, with zero experience writing languages, compilers, editors,
interacting with SID, etc. etc. etc., can write something like this on
it.  It is very thrilling to and satisfying to have so many months
of planning and effort finally come to fruition (and actually work!).
I love it when a plan comes together!

	There are about 700 blocks of source code.  The mighty Merlin 128
is used to compile and link about 620 of those blocks into the single
executable, which is around 20k.  (The Merlin 128 linker is a thing of 
pure beauty).  The player source is around 73 blocks of code, and 2k of
binary.  The source code will undoubtably make it to my web site
eventually, but some of it is pretty nasty.  SPED is a truly stinky
piece of code and is going to get an enormous rewrite fairly soon,
possibly from scratch.  This was all developed on my (stock) 128D,
using a single, thoroughly fragmented, HD disk on an FD-2000 for data
storage.
	There are many people who have helped with this project either
directly or indirectly, answering questions or providing insights into
the workings of the 64, so thanks to all my friends in the C= community!
	Special thanks to my beta testers: Roman Chlebec, Cameron Kaiser
Mark Seelye, and Bob Stoner.  Cliff Anderson saved my butt by
sending me this documentation file after I had deleted it.  And my
especial thanks to Bob Stoner for innumerable suggestions, criticisms,
and witticisms which considerably shaped the system during its development.


1.2 Writing your first song

	Please see the additional "Getting Started" document for
an introduction to the system.  You might want to read through it,
and play around with the program for a bit, before continuing into
this, the main reference manual.
	It is mighty handy to have a copy of the quick reference sitting
nearby, too.


1.3 Other files

	There are a number of documentation files which come in handy:

	- getstart	-- Easy introduction
	- manual	-- This document: the reference manual
	- playvars	-- Description of player variables and memory
			   usage, which is mighty handy for those wanting
			   to use these tunes in/with outside programs.
	- quickref	-- A short summary of all system commands/keystrokes.

	The binary files are:

	- loader	-- What you would expect
	- player	-- The music player (can be any saved file)
	- editor	-- The main program
	- quickref.petscii -- quickref, above

Two sample tunes (with accompanying macros) are also included, one
by myself, and another by dB.  Additional sample tunes are available
in the Fridge, above.

1.4 Compatibility

	This program is compatible with almost all devices -- SuperCPU,
hard drives, etc.  For some reason, fastload cartridges may not get
along with it -- the Action Replay fastloader in particular acts funny
from time to time.  That is, it works, but sometimes it gets confused,
and will e.g. jump into the freeze routine.  I think it gets confused
because my disk i/o routines are in the $7000 area, which is where
its own routines are; perhaps it tries to do some stack manipulation.
Also, note that the AR interrupt routine resets the CIA for some reason,
so the speed probably won't be right when playing tunes from BASIC.
Caveat emptor!


Section 2: Overview
---------

2.1 The top level

	The very top level of the system consists of three parts: the
music editor, the instrument editor, and the macro manager.  These are
accessed by pressing F1, F3, and F5, respectively. A disk access menu 
is available to the music editor and macro manager by pressing F7.
	Each does what you would expect: the actual song is written
in the music editor, and songs are also loaded and saved from here.
The instrument editor is similar, except that instruments are not
saved to disk, but instead saved to the music -- saving the music
will then save any instruments to disk.  The macro manger is used to --
surprise, surprise! -- manage the editing and compilation of macros.
	With power comes responsibility: some really spectacular
crashes are possible with the program.  Luckily there is an error handler
however which can recover from many situations, and if something like
an infinite loop occurs Run/Stop-RESTORE may be used to reset the
program (while preserving music and macros) -- unless the processor
is physically locked up it is generally possible to recover, often
without even a hiccup.
	If all else fails, it may still be possible to recover the
data -- see Section 3.4, below.


2.2 Music editor

	There are a total of 24 notes, plus their octaves, allowed by the
music player.  Each note is assigned a key from a-y, an octave from 0-7,
and a duration.  A total of 24 durations are allowed, and these are
assigned to keys 0-9,a-n.
	Both the notes and the durations are completely definable by
the user: the user simply assigns a numerical value, be it a duration or
a frequency, to each key.  Each user may thus customize both the keyboard
layout and the allowed frequencies to whatever is desired.
	In addition to notes the music player understands a few
special instructions, so the editor can place these into the music too.
Examples of these instructions are to load a new instrument, to repeat a
section of music, and to restart the song.
	It wouldn't be much of an editor if it didn't have any editing
commands.  In fact it has a huge number of useful editing commands, including
a home (bookmarking) capability, the ability to go to a specific line
in the music, to single-step through a piece, to fast-forward through
the music, cut and paste, and so on.
	The editor is also very configurable: you can change whether
numbers are entered in base 10 or base 16, what is displayed on the
screen, and so on.

2.3 Instrument editor

	A total of 14 different instruments may be defined (macros
may be used for infinite variety).  The instrument editor is used to
experiement with SID.  When a satisfying combination is found it
may be saved as an instrument, to be recalled by the player at any
time.  In addition the instrument editor may be used to change
SID while a song is being played, in real-time, or just to experiment
around with SID.

2.4 Macro manager

	The macro manager is used to mange macros.  Individual macros
may be named, edited, and deleted.  Entire macro bundles are compiled,
loaded, and saved from here as well.  Note that macros are not necessary
to write music with, but all advanced features are done via macros.
Note also that you don't have to be able to write macros in order to
use them!


Section 3: Music Editor
---------

3.1 The music editor

	The editor screen is divided into a number of parts:

+-------------------------------------------+
| Field 1 | Field 2 | Field 3 |             |
|         |         |         |             |
|         |         |         |             |
|         |         |         |  Status     |
|         |         |         |     Box     |
|         |         |         |             |
|         |         |         |             |
|         |         |         |             |
|         |         |         |             |
+------+--+---------+---------+-------------+
| Act  | Message Box                        |
+------+------------------------------------+

The three large boxes in the upper left are where most of the editing
occurs, and display the actual music data.  The status box on the
right displays important information on the physical status of the
music and the editor.  The Message Box displays important messages
to the user, and provides a more elucidating display of the music
data.  The Action Box describes what action the editor is expecting,
and is also used for input.  For instance, it normally says "?Note",
which of course means that the player is waiting for a note or
player instruction to be entered.

	The music is organized in terms of "fields".  Each field may
be assigned to a particular SID voice, and consists of a series of
instructions for the music player to process.  For more information
on the player and the types of instructions allowed, see the section
on the player below.  A single keystroke is used to access these
functions; for a list of the keystrokes, see the quick reference.
	Many instructions require an additional parameter to be
entered.  The message box will usually indicate what parameter
needs to be read, and the action box will contain a flashing cursor.
Values may be entered in decimal (base 10) or hex, selectable by
the user.  Press return or the cursor keys to accept the default value.
	To enter a note, press one of the keys a-y.  These keys
are defined by the user to correspond to a particular note and
frequency.  To edit this note table, press CTRL-n...
	Pressing CTRL-n enters the note editor.  From here the
frequency may be changed as well as the two-character text which
is printed by the editor.  The cursor keys are used to move
through the various values; press return to edit.  The note text
can be any two characters of text.  The lo and hi frequency values may
be any number between 0 and 255.  The number may be entered in decimal
(default) or in hex, by specifying a '$' as the first character.
Entering an empty string will retain the old value.
	You can also assign where notes lie in the note table.  Consider
that a normal piano keyboard has 12 keys -- 12 notes -- which span
an octave.  This program is like a piano keyboard with 24 keys per
octave: starting from some key on the keyboard, the next octave will
always be 24 keys away.  You can of course tune these keys to
be any frequency, but certain tuning schemes make more sense.
In particular, like on a normal piano, each note ought to increase
in pitch as the keys move to the right.  Now imagine that you can
swap the _physical positions_ of keys on the piano keyboard: they keep
the same pitch you've tuned them to, but now they appear in a different
_order_ on the piano keyboard.
	That's the problem to be addressed: we are on a computer and not
a piano, thus the _computer_ keyboard must be mapped to the _piano_ keyboard
in some way.  The goal is to make the _computer_ key pitches appear in a
particular order in the frequency table -- to place keys on the piano
keyboard in some logical order.
	So, the _position_ of notes in the frequency table may be
specified.  The frequency table has 24 'slots' in it, and each
key -- each note -- may be assigned to a slot in the table.  Why is
this important?  For instance, it is very convenient to have increasing
pitches sit on top of each other in the frequency table.  On a piano,
a scale or chord is played by taking the current note, and moving
a few notes down on the piano keyboard to get the next note.  On the computer,
a macro might want to do the same thing: take the current position in
the frequency table and add a little bit to it to get another position
in the table; for instance, to play an arpeggio.  
	Thus, if you change the key mappings -- perhaps to make the
computer keyboard mimic a piano keyboard layout -- you also ought to
update their position in the note frequency table.
	If you are completely confused at this point, you are probably
in good company.  Just make sure each note occupies a different
slot in the table and you will be fine (but some macros might not work).
	Press 'e' or run/stop to exit the note edit screen.  At this
point all of the octaves are computed automatically, no matter what
octave frequencies were entered for a particular note.  For example,
whether the specified value for a note is in octave 2 or octave 6 does not 
matter -- the computer automatically deduces which octave the note is in 
and computes all of the other octaves.  For accuracy purposes however it
is best to use the largest possible frequency value (i.e. octave 7
values).
	One key is not definable by the user: 'x'.  'x' is a special
"hold" note: it simply continues the last note for a specified
duration.  It is most commonly used to extend the duration of
a note for long times, but can also be used to make more intuitive
musical constructions (i.e. a dotted quarter note).
	After pressing a key to enter a note, the octave needs to
be specified.  A default octave is provided; press space to accept
the default octave, otherwise enter in the desired octave 0-7.  The
'#' key may also be pressed, as an altenate way of accessing notes m-w,y.
(Pressing # adds twelve to the current keypress, so pressing 'a#' is the
same as pressing 'm', 'b#' is the same as 'n', etc.)  You can also
press '#' beforehand: #a-#l is the same as a#-l#.
	Finally, the duration needs to be specified.  The duration
is a key 0-9 or a-n.  Space or return accepts the default value.
CTRL-d enters the duration editor, which is very similar to the note
editor.  Finer adjustments in tempo may be made by changing the
interrupt value: see CTRL-i, below.
	Uh-oh, you entered the wrong octave!  Do you have to go
through the whole 3-key sequence again?  Nope: pressing the back arrow
key <- will "back up" a step in the 3-key sequence.  Not terribly
useful, but it comes in handy sometimes.
	The entire 3-key sequence does not need to be performed for
every note.  In addition to using space to accept the default value,
the normal editing keys (such as the cursor keys, or RETURN) may also
be used during the process.  The default data will be entered
and the key pressed will be processed normally, so pressing (for
instance) cursor down will enter the data specified and move the
cursor down!
	To enter notes in quickly, press the note and then press
RETURN -- the default octave and duration will be assumed.  The
'+' and '-' keys may be used to change the default octave.
	The editor also features a single-keypress mode: shift-1
toggles this mode.  As you might expect, only one keypress is used
for notes and player commands.  The octave and duration are taken
from the detault octave and duration: '+' and '-' are used to change
the octave, and will change the duration when shifted.  The square
brackets [ and ] may be used to change the default macro; when shifted,
they will change the default macro by large amounts.

	In addition to entering notes and player directives there are
a number of editing commands, and still other special commands.  Most
of the commands are self-explanatory and may be found in the quick
reference; a few however deserve further explanation.

3.2 Editing commands

	The editor is customizable, via a series of "flags".  The status
of the flags is printed in the status box.  Shift-1 toggles singlekey
mode.  Shift-2 toggles how macros and subroutines are displayed in
the fields: either a raw instruction like LOL 04 may be displayed,
or else the full name may be displayed, e.g. +Vibrato.  The macro names
are taken from the macro manager list; if no macros have been loaded,
these names will be empty.  Shift-4 toggles whether base 10 or base 16
is used for number entry.  Shift-6 toggles the display in the status
box: either system variables or macro names may be displayed.  Shift-7
toggles "auto-insert" mode, which toggles whether a new line will be 
inserted after every new player instruction.  Finally, Transpose mode
(CTRL-T) and Audible mode (CTRL-A) are indicated with T and A,
respectively.

	Meta-keys: Some things require many keypresses.  For example, 
let's say the tune you're working on does a lot of switching between two
instruments.  Moreover, each instrument might have some special
macro associated with it, so the total keyboard activity would
be: disable macro, enter macro number, load instrument, instrument
number, activate macro, macro number.  What pain.  To help out this
kind of situation, the editor features four "meta-keys", otherwise
known as keyboard macros.  The idea is that you can assign a whole
series of keypresses to a single key.  Use CTRL-m to assign a meta-key,
and choose the key number (1 through 4).  Then enter in the series
of keypresses -- which can be anything, including RETURN -- and press
the back-arrow key when finished.  The meta-keys are then accessed
simply by pressing C=-1 through C=-4.

	Cutting and pasting is accomplished via a clipboard technique:
a block of data is selected and is either clipped or cut to the clipboard.
This data may then be pasted into the fields with reckless abandon.  
To select a block to be clipped press either C=-x or C=-c, which will 
initiate block selection.  Move the cursor down to whatever line is 
desired -- the editor will indicate which data are selected.  The cursor 
may be moved back up as well, but if the cursor moves behind the first 
line the clip will be cancelled.  Cursor left/right may also be used to 
abort block selection.
	Once a block is selected, use C=-x to cut the data from the 
field and place it into the clipboard, or C=-c to simply place a copy
of the data into the clipboard.  C=-p may then be used to paste the
clipboard contents elsewhere in the field data.
	Subsequent block selections will clobber the clipboard, as
will any macro edit or compile.  Note, however, that load/save operations
do not affect the clipboard in general, so that sections of data may
be cut and pasted between different files.

	As you might imagine, any reasonably sized piece of music
is going to get fairly large, involving many lines of data.  Several
features exist to make navigating and working with the data much
simpler.
	The page up/page down commands will quickly move through
the data; related to these are the top/bottom keys, which place
the cursor at either the top or bottom of the current field.
Pressing '@' will move the cursor to a specified line, and
Shift-@ is used to go to a specified marker.
	The HOME key may be used to select a home position for the
cursor -- a bookmark.  Pressing C=-HOME will then place the cursor at
the last home position specified.  For instance, let's say you're
working in a certain area, and want to check something that is
many lines away.  You can set the home position, go to whatever
line, and then when finished can just press C=-HOME to instantly
transport back to whatever you were originally working on.  Pressing
HOME sets the home position for the current field, and does not
affect the home positions of other fields.
	A special feature called a fold is also available.  Folds are 
a purely _cosmetic_ feature -- they do not affect the actual music data
in any way, only the way it is displayed on the screen.  Folds allow a
block of data to be represented by a single name.
	Let's say you've just written the bridge section of some tune.
It's not much fun paging through all those notes, so you could just
fold them up under a single name, say "bridge1".  The editor will
then display "bridge1" on the screen instead of the big block of notes.
	Folds are created in the same way as clipping operations.  C=-f is
used to begin/end the fold block.  When the block has been marked off, you
are prompted for the fold name.  
	Folds may be open or closed.  To toggle the open/closed state use 
'%' (shift-5).  An open fold displays all the notes inside of the fold;
when closed, only the fold name appears.  To dissolve a fold, use C=-5 
(i.e. C=-%).  This does _not_ affect the data in any way -- ONLY what is
displayed on the screen.
	There are a few restrictions involving folds: 1) Folds cannot
contain another fold, and 2) clip/cut operations are not allowed inside a
fold.  Pasting, however, is allowed, as are other normal editing functions.
Up to 256 folds are allowed, and no attempt is made to make sure you don't
create more!  When jumping to markers within folds, the fold name is 
printed along with the marker number, which gives an intuitive visual
picture of the flow of the music.

	Just what is a marker?  A marker is a special kind of label which
may be set from the editor using Shift-m (use C=-m to clear).  A total
of 32 markers are available.  The marker is 'attached' to the field position 
it is stuck on.  If data is inserted or deleted the marker moves along with 
it -- it always points to the same note (unless you actually change that 
note :).  There are two speical player instructions which involve markers: 
JMP and JSR.  JMP M13 is like saying "GOTO M13", and JSR M3 is like saying 
"GOSUB M3".  Markers may be accessed by macros as well -- in particular,
macros may set the current field pointer to a marker, and thus perform 
another type of flow control.

3.3 Other commands

	The disk menu is accessed by pressing F7.  F8 accesses the
"Old" disk menu -- this is used to load files which were created
with an older version of the editor, or to re-load the music data
from a current tune (which is useful if, for example, the player
gets screwed up somehow).

	To quit the program, type CTRL-e (the e is for exit).  This
actually just exits to BASIC, which gives a way of doing some
calculations, setting up tables, etc.  To re-enter the editor,
press RS/RESTORE.

	Sometimes it is useful to completely clear SID -- the 'pi'
key (shift-^) does just that.  Sometimes it is also useful to look
at all instruments that are defined, so it's a good thing that CTRL-z
just happens to be defined for that purpose.

	Note the status box.  It contains the pointers in
memory to the beginning of macros, the beginnings (and hence
ends) of each field, and the end of all fields.  FRETOP represents
the highest free memory location available; FREBOT represents
the lowest free memory location.  "End" represents the end of all
field data.  Folds sit on top of End, and the clipboard sits right
underneath FRETOP.  If macros have not yet been compiled, the macro
value will be highlighted.
	There are also two possible displays in the status box:
in the first, there are visual indicators for the "Audible" and 
"Transpose" modes, as well as the actual transpose values which
will be used when this mode is in effect.  In the second mode,
macro names are displayed.  These names are taken from the macro
manager, so obviously it will be blank if no macro names are defined.
The default macro number is indicated by an asterisk.

	Like any music program this one is driven by interrupts.
However, the CIA is used to generate the interrupt instead of VIC.
The user can then choose whatever interrupt speed is desired: use
CTRL-i to set the interrupt timer count.  The default value is once
per screen refresh.  Want a double-speed tune?  How about a x5
tune?  With a SuperCPU ridiculous things like x40 tunes can be
realized.  The more important utility is for fine adjustments in
tempo; demo coders may hate you for it, but there's no need to
limit yourself to double or half speed.
	The number entered is simply the number of cycles which
are counted down between interrupts (plus one, since the counter
moves through zero).  In terms of rasters, this is simply

	(number of cycles/line)*(number of lines between interrupts)-1

One is subtracted because the counter counts down to zero.
On a typical NTSC machine there are 65 cycles/line and 263 lines,
giving the default value of 17094=$42C6.

	To play a song using the given interrupt value, use CTRL-p,
which will start a song from the beginning.  To play a song from
the current spot in the editor, use Shift-CTRL-p -- use caution
though!  Sometimes things may not be set up quite the way you
want them to be.
  	The border will change color through the duration of the
player call, to indicate the number of raster lines (and hence the
number of cycles) which the player is eating up. (Yummy!)  Pressing
'=' toggles this feature.
	Sometimes it is desirable to fast-forward through sections
of a song while it is playing; other times it is useful to slow down!
Pressing C=+ will double the current tune speed, and C=- will halve
it.  The effects are cumulative, so doubling it three times will
produce a tune which blazes past at eight times the normal speed.
The effects are also temporary -- they only affect the speed a tune
is currently being played at.  The value set by CTRL-i is unchanged,
and is still the value used when the tune is restarted.
	Often it is handy to be able to turn voices on and off while
the music is playing (or during audible mode, etc.).  Pressing the
asterisk ('*') key will toggle the gate bit for the current voice,
which will turn off the voice (unless something else turns the gate
bit back on!).
	Just about everything except compiling macros may be done
while a song is playing; attempting some things is to really tempt
fate, though!  One useful thing is to enter the instrument editor
while a song is playing -- not only may SID be viewed but it may be
changed, to try out different instruments and such.  Be warned
however that the player is constantly modifying SID (either through
macros or by executing a Load Instrument directive), and may
just uncaringly stomp on your edits.

	Another feature is single stepping, accessed via CTRL-s.
Single stepping will step through the music, one player call at a time.
It is also possible to skip forwards by up to 256 calls at a time.
Upon exiting single stepping, the editor points to the current spot
in the fields, thus problems may be located exactly.  Shift-CTRL-s
will single step starting from the current editor positions, instead
of from the very beginning.

	CTRL-t is used to toggle transpose mode; when active, pressing 
'.' will add the transposition values to the current note/duration pair.
Note that the note/duration data is actually an index into the note
and duration tables, so transposition affects this index.  Shift-CTRL-t
allows you to specify the transposition values.  Negative values may
be entered.

	Finally, CTRL-a is used to toggle notes as audible.  That is,
notes will be played as they are entered.  This can get annoying
after a while though -- more useful perhaps is the '.' key.  When
audible it will play the note under the cursor and advance the
cursor.  In this way pieces of the song may be stepped through very
quickly, in total disregard of durations and such.

	Whew!

3.4 Recovering data

	If, after all else has failed, and the computer locks up
after three hours of work, just as you were saying to yourself "I really
ought to save this" -- there is still a shred of hope.  If you have
a reset button which won't trash memory, you can reset the machine
and type "SYS 26624" -- this performs a soft-reset of the composer,
and you may (or may not!) be able to save whatever work is still in
memory.  (Note that the current device will often be reset to zero,
and will need to be changed from F7, the disk menu).
	Finally, if even that doesn't work and you have a machine
language monitor handy: enter the monitor, write down the value
contained at location $0FE4-$0FE5, and save the data from $0EFA to
the value contined in $0FE4 to disk ($0FE4/$0FE5 should contain
a value like 04 21, so you would save $0EFA-$2104 to disk).
Then reload the editor, and try loading in this file using F8 -- the
"Load old version" disk menu.  Even if the player becomes corrupted
this can extract the data.  ("Load old file" just looks for an ID byte,
which tells it where the start and data in the old file is located).
	Unless the data itself has been completely trashed, it is
possible to recover it!


Section 4: The Instrument Editor
---------

	Pressing F3 enters the instrument editor, which is very
simple to use.  See the quick reference for a list of commands.
Information on SID may be found in various books and on the web;
I have written an introductory article on SID in disC=overy magazine,
issue #2, which may also provide insight.  If nothing else, know
that setting the gate bit begins the attack/decay phase, and
clearing it intiates the release phase -- if the gate ain't on
the note won't play!
	The instrument editor simply lets one play around with SID.  
Once some settings are found that are suitably nifty, they may be saved 
as an instrument by pressing Shift-s, at which point the program prompts 
for the instrument number to be saved as -- press RETURN to abort.  
Once an instrument number is entered, and instrument name must also be 
entered -- press RETURN to accept the current name, as displayed in
the lower-right portion of the screen.  Instruments are loaded using
shift-l.
	A number of key shortcuts are also provided to toggle
various bits, or to quickly move to key values.  To test octaves of
a given frequency, use the doubling keys '<' and '>'.  Shift-'+'
and Shift-'-' are also useful for quickly incrementing and decrementing
values.  See the quick reference for a complete list of commands.
	Note that the instrument editor gets its values not from SID,
but from the Shadow SID.  Thus if macros modify SID directly, the
changes won't appear in the instrument editor.


Section 5: The macro manager
---------

	The macro manager is used to, well, manage macros.  Macros
may be assigned a name and edited from here.  Press return or 'e'
to edit a macro.
	The name of the old text editor was SPED, and it was really,
really crappy.  Downright embarassing.  The new editor, however, is 
NED: Nifty Editor.  And it is pretty nifty.  Lines can be 240-columns
wide.  It has cut and paste, and a "goto line" feature.  It is pretty
zippy and comfortable to use, and is to SPED what an alpine meadow in
bloom is to a fresh pile of dog turds.  NED commands are listed in
the quick reference.  Note that the NED clipboard is at $E000; this
means that clipped text may be copied between macros.  Note further
that CTRL-z from NED compiles the macro to $E000, and hence will
clobber the clipboard.  (Compiling from the macro manager doesn't
affect this).
	The macro manager operates on the entire 24 macro bundle.
Loading and saving loads and saves all macros, along with their
names and addresses.  Compiling from here compiles all of the
macros into the music player; empty macros and macros which did not
successfully compile are compiled as a dead macro -- they are
callable but do nothing (and hence won't crash the player!).
	The 'a' key toggles auto-compiling: all macros are compiled
every time you exit NED.
	Individual macros may be deleted with the 'd' key, and
the entire lot may be layed waste using Shift-CLR.
	Note that once a macro is compiled, that's it -- the
text does not need to be in memory, in fact the entire macro
manager does not need to be in memory!  Compiled macros become
a part of the player at this point.  When using shift-CLR to clear
all macros, you are given the option of keeping the macro names
around -- remember that the editor uses these names in various
displays.
	Macro bundles cannot be compiled while a song is playing.
On the plus side, CTRL-p works from the macro manager more or less
the same way as from the music editor -- it either stops playing a
tune, or restarts it.  Thus a macro may be compiled and tried
out without too much hassle.


Section 6: The player
---------

	The player is in essence the operating system for the music.  It
processes music data and handles macros in a sort of cooperative-multitasking
environment.  In the note-duration model, each note has an associated
duration which counts down each time the player is called.  When it
hits zero, the next note+duration (and any other data) is read in, and
the process continues.
	The later players (starting with version C) actually peek ahead
a few instructions at a time, to keep the processing time down.  That is,
instead of waiting until the current note is finished and then reading
ten instructions all at once, it instead will read a couple of instructions
at a time while the current note is counting down.  Thus is spreads
the processing time over several player calls.  The "lookahead" value
is stored in locations $0FFD-$0FFF, and may be changed to try and
optimize the player; the default value is 2.
	The operation of the player is straightforward.  When called, it
first processes global macros, by calling each in turn, if active.  It then
proceeds to voice 1, where the duration counter for the current note is
decremented.  If it is not zero, then the active macros for this voice are
processed.  If zero, data is read in from the current field and processed,
and active macros are restarted.  In summary, when the player is called:

	- Process global macros
	- If voice 1 is 
	   - Stopped, then go to voice 2
 	   - Waiting for a sync, then process local macros and go to voice 2
	   - Active, then decrement duration counter
	     If nonzero, then 
		Read in and process some player data (the lookahead)
		Process active local macros
	     Else
	        Read in and process music data until note/duration
		  pair is encountered.
		Process any instructions read in during the lookahead
		Update note/duration data in player and SID
		If slur mode is activated, then process active local
		  macros,
		else restart active local macros
	- Process voices 2 and 3 similarly

	"Fields" are simply sets of commands and music data for the
player to chew on.  When you see "field", just think "the music data
for this voice".  But a field is really more than that.  Each field is
a sort of module for the player -- they have their own set of data,
their own set of local variables, they may each call their choice of
macros, and they are all more or less independent from one another.
Global macros "belong" to a field which doesn't have any music data.
	The player data is either a note+duration or else a command
for the player to process.  Currently the following commands are
implemented:

	- Activate/Deactivate Global Marco
		If a macro is not activated, it will not be called.  Global
		macros act before any voices are called, and are thus
		very useful for manipulating the other voices, for instance
		changing pointers and such.  A global macro is restarted
		only when activated.

	- Activate/Deactivate Local Macro

	- Load Global Variable with value
		Unlike local variables, there is only one set of global
		variables.  They provide a means of communication between
		different fields, and even the outside world.  When macros
		access global variables, they all access the same variables.
		Note that global variables do not "belong" to global macros.
		There are 16 global variables available.

	- Load Local Variable with value
		Each field has its own set of 8 local variables.  When
		macros access a local variable, they actually access the
		local variable for the current field.  Thus two different
		fields (i.e. two different voices) may use the same
		macros without conflict.  Of course, macros in the same
		field use the same set of variables, and thus may conflict
		with each other (or communicate with each other).

		Loading local and global variables gives the player a
		means of passing variables to macros.

	- Load instrument
		Load instrument grabs the appropriate information from
		the instrument table, and copies the information into
		the Shadow SID.

	- Set volume

	- Repeat the next section of data n times

	- End of repeat section (go back to Repeat begin)

	- Jump to marker
		This is the first of two flow-control instructions for the
	 	player.  Like it suggests, it will immediately transfer
		the data pointer to the specified marker and continue
		processing without looking back.

	- Jump to subroutine at marker
		This is like Jump, above, but the current field location
		is saved.  RTS, below, may be then used to return to this 
		location.  This allows for musical subroutines.  Subroutines
		may be nested up to a depth of four -- subroutines can
		call other subroutines, but only up to four times!

	- Return from subroutine
		Exits a subroutine and sets the field pointer back to
		wherever the subroutine was called from.

	- Stop
		Deactivates this field/voice.

	- Gate off
		Turns off the gate bit for the current voice, which
		will start the release phase of the current SID
		envelope.

	- Gate on
		Turns on the gate bit for the current voice, starting the
		attack phase and re-enabling the voice.  Loading a new
		instrument will always turn the gate bit on; this command
		is to fix up a gate bit which has been turned off by the
		above directive.

	- Cycle test bit
		The test bit resets the current SID voice.  This will
		fix up a locked SID, and will also reset the current
		voice settings, in particular the ASDR sequence.
		Sometimes this is referred to as a hard SID reset.

	- Wait for sync
		This instruction makes the current voice sit idling
		until a different voices issues a SYNC.  Macros are
		still processed while it is waiting.  Two WAITs
		should not follow one after the other -- there must
		always be a real note (not a hold note) in-between
		the WAITs.

	- Sync
		Sends out a sync signal to any waiting voices, which
		will then resume processing.  Note that the sync is
		'simultaneous' -- that is, even though voice 1 is
		processed before voice 2, voice 2 can send out a
		sync signal to voice 1 with no problems.  This is because
		the sync is handled during the "look-ahead" phase of
		the player.  Because of this, if a bunch of instructions
		are occuring at the same time as the SYNC (gate on,
		load macros, etc.), the SYNC should be performed BEFORE
		the other instructions.

	- Slur mode on
		Normally, the player resets macros on every note; each
		macro is restarted, from the beginning.  With slur mode, 
		macros will continue uninterrupted.  There is an
		important downside: never activate a new macro during
		slur mode, because it won't start that macro from
		the beginning!  In fact, if the "continue" address for
		that macro is set to garbage, then it may even lock
		up the computer.

	- Slur mode off
		Turns off slur mode.

	- Restart
		Restart the whole player

	The note/duration data is actually an index into a frequency and
duration table.  When a note is read in, the corresponding frequency is
read in from the frequency table and copied into the Shadow SID.  There
is one special "note":

	- Hold
		Holds (slurs) the current note.  This allows durations
		greater than 255 without restarting macros.

	The current versions of the player copy values into SID as well 
as the Shadow SID.  SID registers (with minor exception) are read-only; 
the shadow gives a way of reading the current SID values.  Macros
should modify the Shadow values directly, and then copy them into SID
via the & extension.  Otherwise the Shadow SID is not used by the
player.
	There is also a small Kernal jump table at the beginning of the
code.  There are several reasons for this, among them that different
players may be written without having to recompile/write a new compiler.
Indeed, the current player is the "Lite" version -- won't fill up your
memory and won't slow you down.  The Kernal routines are:

$1000	MAINPLAY	- The main player routine
$1003	PLAYINIT	- Initialize the player
$1006	SETIRQ		- Wedge player into current IRQ routine
$1009	LOADINST	- Load instrument (X)
$100C	GETP		- Get field pointer for current voice (A,X = lo,hi)
$100F	SETP		- Set field pointer for current voice
$1012	V1GETP		- Get field pointer for voice 1 (A,X)
$1015	V2GETP
$1018	V3GETP
$101B	V1SETP		- Set field pointer for voice 1
$101E	V2SETP
$1021	V3SETP
$1024	RETURN		- Macro exit

	Wait a minute... Macros?  Compilers?  What the...?


Section 7: Macros
---------

	Just what the dickens is a macro, anyways?  This player differs
from most other players in that it doesn't know how to do much of
anything -- no effects, no nothing.  This is where macros come in.
Macros are programs written by the user and compiled, and which may be
then called by the player routine.  Thus effects like vibrato, portamento,
arpeggios, all the usual guys are implemented via macros --  but they
can do much more.  Macros allow a control over the music while it is
being executed.  Macros can interact with the outside world, so a macro
may for instance signal a program once a particular note is reached, or
a program may signal a macro to take some action.  In short, macros provide
a total flexibility over the music and SID.
	Macros are called in a sort of cooperative multitasking
environment -- that is, they must explicitly pass control back to the 
player.  When they are called again, execution will resume at the point 
where they passed control to the player routine.  Specifically, they are 
returned to the place they left off when they were last called by the 
current field (that is, each field knows where it last left each macro).  
This allows, for example, two fields to use the same macro (say an arpeggio 
macro) on different notes, of different lengths.
	Only one copy of a macro exists.  It might reference different
local variables, and it might have different exit points for different
fields, but there is only one physical piece of code.  There is not
one macro for each field.
	Here is an example macro:

; Vibrato SLJ 11/96

ENTRY

BMOVE #3 > L1 ;Local variable L1=3
LOOP
  LOOP
    WAIT
    WADD #200 > FREQ & $D400,COFFSET  ;Add 200 to frequency of current voice
    BINC L1		;L1=L1+1
    BTEST L1<#6		;Compare L1 to #6
  UNTIL EQUAL	;Continue until L1=6

  LOOP
    WAIT
    WSUB #200 > FREQ & $D400,COFFSET  ;FREQ = FREQ-200
    BDEC L1	 ;L1=L1-1
    BTEST L1<#0  ;Actually not necessary
  UNTIL EQUAL	 ;Loop until L1=0
FOREVER		;UNTIL NEQUAL would also work


7.1 Arguments

	Note the arguments given to WADD BADD etc.  Arguments may take
on several forms:

	- (Immediate) Number.  The # prefix denotes a number is to follow.
	  Numbers may be specified in decimal, hex, or binary:

		#32	 - The number 32
		#$20	 - The same number in hex
		#%100000 - ...and in binary

	- An address.  Addresses are specified in hex, thus the $ prefix
	  denotes an address.

		#$D020	- The number 53280
		$D020	- The address 53280

	Both addresses and numbers may be 16 bits large.  The compiler will
	give an error if numbers larger than 16 bits are specified.

	- A variable.  If it isn't a number or an address, then it is
	  a variable or a syntax error.  Defined variables are detailed
	  later on.

In addition, there are several extensions allowed:

	- Uninvolved Operand.  It's a silly name but a useful feature,
	  and works as follows:

                COMMAND (ARG1 > ARG2) > ARG3
          or
                COMMAND (ARG1 < ARG2) > ARG3

          The idea is to perform the operation on ARG1 and ARG2 and then
          store the result in ARG3, e.g.

                BSUB (#4 > L1) > $C000   $C000 = L1 - 4

          Previously, the results were always stored in the argument being
          operated on, i.e. L1 = L1 - 4.
          Common sense applies -- you can't use & extensions within the
          parenthesis, although ARG3 & ARG4 & ... is fine.  Also, the ()'s
          may not be nested: BADD ((L1 > L2) > L3) > L4 is not allowed.

	- Indexed.  A "," denotes indexed mode.  The argument following
	  the comma is read in, and its contents are added to the ADDRESS
	  specified by the first argument.  That is,

		$D400,$FF is like PEEK(54272+PEEK(255)), not
				  PEEK(54272)+PEEK(255)

	  This is implemented by reading the index into X, and then
	  using LDA ARG1,X.  However, some variables (such as local
	  variables) are already indexed, and cannot have an additional
	  index, e.g.

		BMOVE  L1,#2

	  is illegal, because local varibles are already indexed, but

		BMOVE SHADOW,L1

	  is allowed.  Also, an index cannot be itself indexed :).

	- Offsets.  A "+" or "-" sign denotes an offset to be added to the
	  current address.  It is similar to indexed mode, but only immediate
	  numbers ( "#" ) are allowed.  This number is then added to or 
	  subtracted from the address of the preceding argument.  This mode
	  is intended to be used with certain variables, for instance

		SHADOW+#$18 is like PEEK(SHADOW+24)

	  This is faster than using indexed mode, and also allows access
	  to variables which are already indexed.  For instance,

		FREQ,#1

	  would be illegal, but

		FREQ+#1

	  is fine, and will access the high byte of the freqeuncy of the
	  current voice.  Multiple offsets are allowed e.g.

		SID+#24-#$0A	;(SID+14)

	- Additionals.  The "&" denotes an additional destination.  The results
	  of the current operation are stored to the following arguments
	  as well as the destination argument.  That is,
	
		BADD #6 > $FA & $D020&$D021

	  is compiled as

		LDA #06
		CLC
		ADC $FA
		STA $FA
		STA $D020
		STA $D021

	  Only the first argument of DEST is used for purposes of any
	  operation performed on SRC and DEST -- above, $FA is used in the
	  addition, not $D020 or $D021.

The wahkas ("<" and ">") are used as direction indicators -- read them
as "from" and "to".  All commands which use directions are bidirectional,
so

	BMOVE #02 > $D020

is the same as

	BMOVE $D020 < #02

The "from" or source part is denoted by SRC.  The "to" part is the destination
and is denoted by DEST.  Arguments and their extensions will be designated
by ARG.  Naturally, a number (# prefix) is not a legal DEST.
	Comments are specified by using a semi-colon.  When a ";" is
seen, all text is skipped up to the end of the line.


7.2 Flags

	There are four flags which are set by various commands, depending
on the result of the command: EQUAL (EQU) NEQUAL (NEQ) POSITIVE (POS)
and NEGATIVE (NEG).  For the programmers out there, EQU and NEQ correspond
to the zero flag, and POS/NEG correspond to the carry flag (they do *not* 
correspond to the N flag).  These flags are used as branch conditionals by
two other statements: UNTIL and WHEN.


7.3 Keywords

	All of the "operator" commands have two forms, binary and word.
The binary form will act upon a single byte, the word will perform the
command on a word (2-bytes, lo hi).  Thus

	BMOVE #256 > $D020

will move the low byte of 256 (0) to $D020, but

	WMOVE #256 > $D020

will move 0 into $D020 and 1 (the high byte of 256) into $D021.  Similarly,

	WADD $C000 > $C100 & $C200

will add ($C000 $C001 = lo hi) to ($C100 $C101 = lo hi) and store the
result in ($C100 $C101 = lo hi) and ($C200 $C201 = lo hi).  That is, the
above compiles to

	LDA $C000
	CLC
	ADC $C100
	STA $C100
	STA $C200
 	LDA $C001
	ADC $C101
	STA $C101
 	STA $C201

Neat, huh?

There are currently 43 keywords:

BADD/WADD
BAND/WAND 
BDEC/WDEC
BEOR/WEOR
BINC/WINC
BMOVE/WMOVE
BOR/WOR
BSUB/WSUB
BTEST/WTEST
COMMENT
DATA
DONE
EMBED
ENTRY
ILOAD
LOOP
UNTIL
FOREVER
GETP
SETP
V1GETP
V2GETP
V3GETP
V1SETP
V2SETP
V3SETP
WAIT
WHEN/LWHEN
ELSE
WEND


BMOVE/WMOVE  SRC > DEST  (DEST < SRC)
	SRC -> DEST (& DEST2 ...)

	Copies the contents of source into dest.
	Example: WMOVE FREQ > $D400,COFFSET

BADD/WADD  SRC > DEST
	DEST + SRC -> DEST (& DEST2 ...)

	Adds the source to the destination, storing the result in the
	destination.
	Example: BADD #3 > FREQ+#1

BSUB/WSUB  SRC > DEST
	DEST - SRC -> DEST

	Subtracts the source from the destination, and stores the result
	in dest.
	Example: WSUB #600 > FREQ	;FREQ = FREQ-600

BAND/WAND  SRC > DEST
	DEST AND SRC -> DEST

	Logically ANDs the source and destination, result in dest.
	Example: BAND $C000 < #$EE

BOR/WOR  SRC > DEST
	DEST OR SRC -> DEST

	Logically ORs the source and destination, result in dest.

BEOR/WEOR  SRC > DEST
	DEST EOR SRC -> DEST

	Performs an exclusive-OR on src and dest, result in dest.

BTEST/WTEST  SRC > DEST
	DEST - SRC

	Like BSUB/WSUB, TEST subtracts dest from source but the result is 
	not stored anywhere -- only the flags are set appropriately.
	TEST is used to form conditional statements, i.e. to check when
	something reaches zero, etc.  If the result of the subtraction is
	zero, then the EQUAL flag will be set.  Otherwise, the NEQUAL
	flag will be set.  (Note that WSUB will not set EQU/NEQ correctly).
  	If SRC is larger than or equal to DEST, then the POS flag will be set,
	otherwise NEG will be set.
	Example: BTEST L1<#10

BDEC/WDEC ARG
	ARG=ARG-1

	BDEC and WDEC subtract one from the current argument.  They are
	equivalent to BSUB #1 > ARG but use DEC instead of SBC, so they
	are faster as well as more compact.
	Example: BDEC FREQ

BINC/WINC ARG
	ARG=ARG+1

	BINC/WINC adds one to the current argument.  They are equivalent to
	BADD #1 > ARG but use INC instead of ADC, and so are faster and
	more compact.
	Example: WINC $FA

BDIV/WDIV ARG
	ARG = ARG/2

	MUL just halves the current argument.  Think LSR.  Note that
	octaves are just factors of two, so this is useful for generating
	octaves, among other things.
	Example: WDIV $C000

BMUL/WMUL ARG
	ARG = ARG*2

	MUL just doubles the current argument.  Think ASL.  
	Example: BMUL L1

COMMENT string
	Places string directly into the code

	This places the following string, up to the end of the line,
	directly into the code.  It may only be used at the very
	beginning of any macro, before any actual statements take
	place.  This is useful for identification purposes, and also
	for debugging/altering compiled macros (it is easy to search
	for the string).  If you use a COMMENT, be sure to use ENTRY.

DELAY ARG
	Generate a short delay.

	DELAY generates a simple busy-loop, i.e. it assembles to

		LDA ARG
		TAX
		DEX
		BNE -3

	Example: DELAY #10

DONE
	End macro

	DONE effectively halts macro execution.  It does not deactivate
	the macro, but no further statements will be executed.  If
	DONE is not used to end a macro, and the macro does not
	loop infinitely, execution will proceed right into whatever
	follows the macro, be it code, data, or garbage.
	So, use DONE at the end of every macro!

EMBED number (number number ...)
	Places data directly into the code
	
	EMBED takes byte numbers and places them directly into the code.
	EMBED is used to create data tables, or to place machine language
	instructions directly into the code.  Arguments may be in
	decimal, hex, or binary, and are assumed to be immediate numbers
	(so don't use # on them).
	Example: EMBED $20 0 $C0   (Places a JSR $C000 into the code)

ENTRY
	Set the beginning of the program

	ENTRY sets the current line to be the line at which a macro
	is entered.  That is, when a macro is first run, execution
	begins at this point.  This is why COMMENTs and DATA tables
	may appear at the beginning of the code, and not be executed.
	If ENTRY is omitted, the first line marks the entry point.  If
	for some reason multiple ENTRY statements appear in a program,
	the last one will be the entry point used by the player.

DEF label string
	Define new variable

	DEF assigns the text in "string" to the variable "label".  This
	text is then substituted for "label" anywhere this variable is
	referenced in the program (C programmers can compare with #define).
	Example:
	        DEFINE S1 FREQ & SID,COFFSET
       		DEFINE FLASH BINC $D020

        	WADD #32 > S1
        	FLASH

        DEFines may NOT be nested.  If you go too crazy on the DEFines,
        and make a line longer than 256 characters, the compiler will be
        sure to let you know.  Unlike VAR, no bytes are embedded in the
        code.

        Note that DEFines can supersede keyword commands, e.g.
        DEF BIN BINC $D020 is a valid command, even though "BIN" is
        a keyword! (DEF DEF DEF would also be valid).

	There are a few restrictions on new variables; see Section 7.5,
	below.

VAR, VAR*n label
	Create new variable

	VAR creates an n-byte variable at the current address, with
	name "label".  Compare with DATA EMBED above -- n bytes are
	embedded into the code, with a label assigned to the first
	address.  All variables must be defined before being used;
	be sure to place ENTRY points after all variables.  VAR is
	identical to VAR*1.
	Examples:

        	VAR BLAH        $E000 00
        	BINC BLAH       $E001 INC $E000

        	VAR*3 ZOT       $E000 00 00 00
        	WMUL ZOT+#1     $E003 ASL $E001
               		              ROL $E002

	See Section 7.5 for the rules regarding new variables.

DATA
	User defined label

	DATA has been made pretty obsolete by VAR, above.

	Data is a special command, in that it is not really a command
	but a label which the macro may reference as a normal variable.
	References are always backwards, that is, to the last place DATA
	was placed.  Multiple DATA statements may appear in a macro, and
	each placement will redefine DATA.

	Example: DATA 
		   EMBED 1 2 4 8 16 32 64 128
		 BMOVE DATA > $D020	;Stores #1 in $D020
		 DATA EMBED $20 0 $C0 $EA
		 WMOVE DATA+#2 > $FA  ;Stores #$C0 in $FA and #$EA in $FB

	If for some reason you were thinking of it, DATA should be used
	with caution inside of subroutines.

	See Section 7.5 for the rules regarding new variables.

SUB/SEND/JSUB 
	Subroutine commands.  Example:

        SUB BLARG
          WADD #32 > S1
          BINC L1        ;Case insensitive!
        SEND

        ENTRY
        JSUB BLARG

        SUB creates a new label "BLARG" and assigns it to the current
        address.  Subroutines must end with a SEND.  And of course JSUB
        calls the subroutine.  All commands are available within a
        subroutine except three: ENTRY, which would be really bad; SUB,
        which would be pretty useless anyways; and VAR, which is equally
	useless.  Obviously it is very important to have the ENTRY point 
	somewhere in the macro!

	Also note that subroutines containing a JSUB, WAIT, or DONE are
	larger and more time consuming, since extra code is needed to pull 
	the subroutine's return address from the stack and save it.

	See Section 7.5 for the rules regarding new variables.

LOOP ... UNTIL FLAG  /  FOREVER
	Executes the block of instructions until the FLAG condition is met.

	LOOP ... UNTIL is remarkably similar to every other loop construct
	in every other computer language.  LOOPs may be nested, but each
	must have a matching UNTIL.  If FOREVER is used instead of
	UNTIL the loop will always repeat.
	Example: LOOP
		   ...
		   BTEST ARG1<ARG2	;ARG1-ARG2
		 UNTIL EQUAL	  ;Continue looping until ARG1=ARG2

WHEN/LWHEN FLAG ... [ELSE] ... WEND
	If the conditional is met then execute the block of instructions.

	WHEN is remarkably similar to every other IF/THEN construct in
	every other computer language.  ELSE may be used to execute
	a block of commands if the condition is not met, but is
	optional.  All WHEN/ELSE blocks must end with a WEND.  WHEN
	statements may be nested, but each must have a corresponding WEND.

	WHEN and LOOP statements may be nested together, but if one
	ends ahead of another they become tangled.  i.e.
		LOOP  
		  WHEN POS
		    BTEST L1<$FE	;L1-$FE
		    UNTIL NEG
 		  WEND
	is a (contrived) LOOP/WHEN tangle -- the WHEN is inside of the
	LOOP, but the LOOP is terminated first.

	Only one ELSE statement may follow a WHEN statement.

	WHEN uses a branch statement to skip statements.  Occasionally
	there will be a substantial number of statements contained
	inside of a WHEN statement, which will force a bad branch.
	In this case, use LWHEN (Long WHEN) instead, which uses a
	JMP.  The compiler will print a message if this situation
	arises.

WAIT
	Returns control to player routine

	WAIT suspends macro execution until the next player cycle, at
	which point the macro will resume execution at the next
	statement.  (The exception is if a new note is read in, in
	which case the macro will start again from the beginning, assuming
	it is still active.)


7.4 Player routines:

GETP ARG
	Place the current field data pointer into ARG

	GETP uses the kernal GETP routine to fetch the data pointer
	of the current voice; this pointer is then placed in ARG
	(lo byte) and ARG+1 (hi byte).  SETP may then be used at
	a later time to return to this point, so repeat constructs
	may be formed.

ILOAD ARG
	Load instrument number ARG

	ILOAD uses the Kernal LOADINST routine to load instrument
	number ARG from the index table into the shadow SID.

SETP ARG
	Set the current field pointer to ARG,ARG+1 (lo,hi)

	SETP sets the field pointer to ARG,ARG+1.  When the current
	note duration reaches zero, field data will be read in
	starting from this point.  In this way repeat constructs
	may be formed.

V1GETP/V2GETP/V3GETP ARG
	Load a specific field pointer into ARG,ARG+1

	These commands are like GETP, but load the pointer corresponding
	to a specific voice (1 2 or 3), as opposed to the the current voice.

V1SETP/V2SETP/V3SETP ARG
	Load ARG,ARG+1 into a specific field pointer

	These commands are to SETP as V1GETP etc. are to GETP.

7.5 Variables

	A number of variables are defined for use by macros.  Some of
them are "relative", i.e. to the current voice, to the current field,
etc.  For instance, FREQ gives the frequency of the current voice.
Any relative variable may not be used with indexed mode, because these
variables are already accessed using indexed mode.  The "+" extension
may be used with them, however.
	New variables may also be created by DEF, VAR, and SUB.  There
are are four basic types of variable: normal variables, the old DATA 
variable, DEFined variables, and SUBroutines.
        There are just two rules for creating new variables:

        1. The first character must be a colon : or greater -- names
           such as 1234 and $D020 are invalid.

        2. The variable can't have the same name as another variable.

Variables may be defined anywhere in the program, so you could, for example,
have all VARs and subroutines after the main program.

In addition to global variables, local variables, and markers, there
are 17 pre-defined system variables which may be used as ARGs:

ATDK
COFFSET
CREG
CURFIELD
CURVOICE
DATA
DUR
FLOTAB
FHITAB
FREQ
INST
NOTE
PWIDTH
SHADOW
SID
SUREL
V1STOP
V2STOP
V3STOP

G0, G1, ... G15
	Global variables.

	These are variables for general use by macro routines.  All
	macros see these variables at the same location, i.e. they
	are shared between all macros.  They are stored sequentially,
	so that G0+#1 gives G1.

L0, L1, ..., L7
	Local variables.

	These variables are local to the current field.  They are visible
	only to active macros within that field.

	There are 8 local variables for each field, i.e. each voice has its
	own set of local variables.  Thus if a macro uses these variables, the
	variable it "sees" will depend on the current field.  Each variable is
	a single byte, and they are stored squentially in memory, so for
	instance L3+#1 is the same location as L4.

M0, M1, ..., M31
	Markers.

	These are variables, visible to all macros, which are generally
	set up by the editor routine to point to specific field locations.
	They are used as labels for branching to different parts of the
	music.

ATDK
	Attack/Decay register for the current voice.

	SID register offset 5 is the attack/decay register.  The upper
	four bits give the attack value and the lower four give the
	decay value.  This variable is defined as SHADOW+#5,COFFSET.

COFFSET
	SID offset (0 7 14) for current voice.

	Each voice has 7 SID registers.  COFFSET gives the correct offset
	for the current voice; thus something like
		WMOVE FREQ > SID,COFFSET
	will move the current freqeuncy to the correct SID location.

CREG
	Control register for the current voice.

	SID regster offset 4 is the control register.  It contains the waveform
	bits, sync and ring modulation bits, the gate on/off bit, and the
	test bit.  This variable is defined as SHADOW+#4,COFFSET.

CURFIELD
	Current field.

	CURFIELD contains the current field being processed, 0-6.  In
	the Lite version of the player, this is identical to CURVOICE.
	Global macros are field 0.

CURVOICE
	Current voice (1 2 3)

DATA
	User-defined variable.

	DATA is defined by the user, and has different values for
	different macros.  See the keywords listing for more details.

DUR
	(Remaining) duration of the current note for the current field

	DUR is the actual duration value which is being counted down by
	the player routine, for the current field.

FREQ
	Frequency of the current voice

	FREQ is defined as SHADOW,COFFSET, where SHADOW is the shadow SID
	maintained by the player, and COFFSET is the offset (0 7 or 14)
	of the current voice.  Thus, FREQ gives the current SID frequency
	settings for the current voice.
	The frequency is a two byte value; FREQ itself points to the low
	byte of the frequency.  Thus, word operations (WADD etc.) are
	generally used for this variable.  To access the high byte,
	use FREQ+#1.

FLOTAB, FHITAB
	Frequency tables.

	There are 24 notes available, and there are eight octaves for
	each note.  Thus, a total of 192 frequencies are used by the
	player.  Each frequency is two bytes, so there are two tables
	used by the player, each of which is 192 bytes large, one of
	which contains the low byte of the frequency, the other contains
	the high byte of the frequency.  NOTE, below, is an index into
	these tables.

	See the Arpeggio macro for a use of FLOTAB, FHITAB, and NOTE.

INST
	Instrument for the current field

	INST gives the index into the instrument table of the
	current instrument (i.e. the last one read in by the player for
	the current field).

NOTE
	Note value for the current field

	NOTE gives the index into the note table for the current note
	being played for the current field.

PWIDTH
	Pulse width of the current voice.

	SID registers offset 2 and 3 are the low byte and high nybble of the
	pulse width.  PWIDTH points to the low byte of the pulse width
	for the current voice.  PWIDTH is defined as SHADOW+#2,COFFSET.

SHADOW
	Shadow SID maintained by the system.

	Because SID registers are read-only, a second set of registers is
	maintained by the system which shadows the actual values.  In this
	way SID may be modified based on its current values.  Manipulations
	should be made directly to the SHADOW registers, and if these
	are not copied into SID by the player routine they should be
	stored there via the & command.  That is, use something like
		WADD #300 > FREQ & SID,COFFSET
	which will store the result in FREQ and the correct SID register.

SID
	The real SID, $D400

	SID is defined as a convenience, and is simply $D400, the location
	of SID.

SUREL
	Sustain/Release register for the current voice.

	SID register offset 6 is the sustain/release register.  The
	upper four bits give the sustain value and the lower four give
	the release value.  SUREL is defined as SHADOW+#6,COFFSET.

V1STOP/V2STOP/V3STOP
	Halt processing for this voice

	These are player variables; if any one has a zero value, then
	that voice is processed normally.  If they are set to a nonzero
	value, the corresponding voice will not be processed at all -- no
	macros, no duration countdown, no nothing.


7.6 The Compiler

	The compiler is case-insensitive.

	Because of the way the compiler works, only the first three letters
of each keyword are actually relevant, and at least one space must follow the
keyword (otherwise the compiler doesn't much care about spaces).  Thus

	BMOVE #32 > $D401

is equivalent to

	BMO #32 > $D401
	BMOHAHAIAMTHEGREATESTCOMPOSEREVER $D401 < #32
	BMOV    #32>$D401

as far as the compiler is concerned, but

	BMO#32 > $D401

will generate an error.  Flags are similar, so that NEQ is equivalent to 
NEQUAL, etc.  Variables do not have this restriction -- all letters matter 
and spaces don't.  The two modifiers "+" and "," must follow an argument 
without any spaces: SID,COFFSET is legal but SID , COFFSET will generate an 
error.  SID,    COFFSET is perfectly valid however.

	In general, the compiler is not picky about putting multiple
commands on the same line, but it will complain if a command is split
across a line.  The special character '<-' (back-arrow) may be used to
continue to the next line; this is a hold-over from the old version,
because SPED could not handle lines longer than 40 columns.  Since
NED can handle 240-column lines, this command is obsolete.

	The compiler is reasonably smart.  It is not perfect but it does
a good job of eliminating redundant code, it knows about zero page, etc.
Branches are used when possible with LOOP..UNTIL, and WHEN defaults to
a branch instruction.  It is possible to fake the compiler out, but it
takes a pretty strange construct to do it, so I didn't bother to cover
these cases.  I did not want a picky compiler, rather something that
will catch errors and generate good code, leaving style considerations up
to the programmer.  Some things, like ENTRY, EMBED, and DATA, must be used
carefully.  Extra code is generated when a subroutine has a WAIT, DONE, or
JSUB inside of it, to save the subroutine return address (otherwise the
stack would be all screwed up for the player).

	LOOPs and WHENs may be nested pretty deeply... about 85 deep
in fact.  In principle, around 40 & extensions may be specified.  I
felt this was quite adequate for most applications :).


Section 8 Elementary Music Theory
---------

	It should be pretty obvious that music is much more than a bunch
of notes merely plopped down.  There is an overal structure and logic
inherent to any piece of music, and part of the enjoyment of music is
"figuring out" what a piece of music is doing.  And it is exactly that
with which this section is concerned.
	Note that practice almost always precedes theory: these concepts
do not *define* music, but are defined *by* music.  In other words, music
theory doesn't say "This is how to write music", but instead "This is
how music has been written."  Innovative new composers are always pushing
back the boundaries.  Music theory also gives a language for talking
about music -- you can move beyond "I liked it" to "I really like the
way he uses those descending diminished sevenths to modulate into the
major section."

	Everyone has at least an intuitive feel for music; we can all
"hear" something and "feel" something.  This section explains some of
the underlying structure and foundations of music theory and composition.
Only the very basics are covered here; see the references for some
more advanced and complete sources of information, and to learn more
about the devices and techniques available to composers.
	Most of these things are very logical and easy to understand 
(and easy to hear).  If you aren't already familiar with some of the
concepts below, just listen for them the next time you're listening
to the radio -- with a little practice you'll soon follow the beats and
chords and different instruments in a song without even trying (and then
be an actual participant in the music, instead of a passive listener).
Like anything else worthwhile it just takes a little practice; I think
you will find the rewards to be well worth any effort.

	With few exceptions I have taken my examples from popular and folk
music, i.e. I tried to take songs everyone is familiar with.

8.1 Rhythm and Meter
8.2 Notes and intervals
8.3 Scales and Keys
8.4 Chords and chord progressions
8.5 Dynamics
8.6 Acoustics	

8.1 Rhythm and Meter

	Why not just start with a song:

		Old Mac-Dok-ken had a farm,
		 '       '       '     '    

 		e-i-e-i-o
		'   '   '   '
		

Like most popular songs, there is a steady rhythm, an underlying pulse,
to this song.  It falls on the words marked with a ' above.  If you tap 
your foot or hand while singing this song, it will coincide with these 
words; when spoken aloud, each of these words receives a little
accent.  Each one of these accents is called a "beat".
	After four of these beats an "idea" is completed.  This completes
a measure of music; this music thus has four beats to the measure.
After the first set of four beats is completed, the second set of
beats -- the second measure -- begins (e-i-e-i-o).  Note that
the beats are equally spaced, that is, they are equally divided in 
time across the measure.  In almost all music rhythm is "metrical":
its values are multiples or divisions of the steady beat.
	The speed at which the beats occur is called the "tempo".
One might use a tempo of one beat=one second, above, which means there
would be one second between beats!
	In the song above there are two syllables -- two notes -- per
beat, thus each note requires half of a beat, with one exception...

		Old Mac-Dok-ken had  a  farm,
		 '       '       '       '
		 1  and  2  and  3  and  4  and

...the last note, "farm", which lasts a full beat.  Each of the other words
lasts half of a beat, and there are four beats per measure.  Easy.  Here's
another song with four beats to the measure:

		Hick-or-y Dick-or-y Dok
		 '         '         '      '
		 1         2         3      4

A-ha!  This one is a little trickier.  Hickory and Dickory each require
_three_ notes to the beat.  This is called a "triplet": each note
lasts 1/3 of a beat.  But the strong accent falls only on the first 
syllable -- there are still just four steady beats to the measure.
This song also features something new: a rest.  Nothing is actually
said or sung on the fourth beat, but the beat is most definitely there!
	Although it is what the vast majority of music uses there is
certainly more to life than four beats per measure...

		Pic-ture your-self in a 
	  	 '   '    '    '   '  '
	 	 1   2    3    1   2  3  

		boat on a   river
		 '   '  '    ' . '  '
		 1   2  3    1   2  3

Incidentally, this song does something sneaky, called metrical modulation:
We might have called it two beats per measure (duple meter), with a
set of triplets on each beat:

		1  2  3  1  2  3	Triple meter
		1        2		Duple meter

Without changing the tempo it takes those two beats, doubles them, and makes
the time four beats per measure.  The song changes from "threes" (triple meter)
to "fours" (quadruple meter):

		Lu-cy in the sky-y    with
		'  '  '   '  '   '  '  '
		1     2      3      4		New time
		1            2
		1   2    3   1    2   3		Old time, same tempo
		
 		di-a-a-monds
		'      '     '     '
		1      2     3     4   

At this point you might be wondering if everything has to plod ahead,
landing strictly on the beats -- far from it!  In fact, most music
dodges around the beat, gravitating around the steady beat but
painting a picture instead of drawing a line.  Jazz in particular
goes to great lengths to try and hide the underlying beat -- try
finding the beats in the song "Ten Per Cent For Nothing" on the
Yes album "Fragile" sometime (it's eight beats per measure).
	The above song demonstrates another type of rhythmical
technique: syncopation.  The word "sky" is extended half of a beat, so 
that the next few notes are off of the (strong) beat, but rather on the
weak "and" beats between 3-4 and 4-1.  Syncopation can be used to "blur"
the underlying beat, highlight different beats and notes, to break up the
time, or just to sound neat.
	Fours and threes are the easiest to work with and generally
pleasing, but other times are of course possible.  Consider the opening
of "Money", by Pink Floyd (forgive the dums):

	(Money...                  get away...)
	dum dee-da-dum dum dum dum dum dum
	 1   2      3   4   5   6   7 | 1
              12 3                    |
				 end of measure

So, seven beats per measure.  The "dee-da" is roughly a triplet, with the 
"dee" holding for 2/3 of a beat, and the "da" the remaining third.  The 
"Impossible Mission" TV show theme uses five beats per measure.  The song 
in Roy Batty's 4k demo is an example of a twelve-beat song.  The
song "Tubular Bells" (the Exorcist theme) is something wacky like
seven beats followed by nine beats.

	Notationally, the beat is usually assigned to a "quarter note",
sometimes to an eighth note, and occasionally to a half note.  A quarter
note is a note which lasts 1/4 as long as a whole note!  An eighth note
lasts half as long (is twice as fast) as a quarter note, etc.  The
meter of a song is the basic grouping of beats per measure, as
indicated by the "time signature".  A time signature of 3/4 means
that there are three beats per measure, and a quarter note represents
each beat.  12/8 means there are twelve beats per measure, and
each eighth note is one beat.  And so on.
	The three simple meters are duple (2/2, 2/4, 2/8), triple 
(3/2, 3/4, 3/8), and quadruple meter (4/2, 4/4, 4/8) -- 4/4 is
generally called common meter, for obvious reasons.  Compound meters,
on the other hand, are the above meters multiplied by three: 6/4, 9/8,
12/8, and so on.  Usually (but not always in my opinion) fancy times, 
i.e. five beats per measure, are represented as a combination of the
above meters (3/4 + 2/4).  I say not always because there are certainly
some 5-beat songs where I sure don't hear a 3+2 beat division.

	How rigorous is the rhythm?  It is of course "allowed" to
change times in the middle of a song.  Usually, via syncopation
or other techniques, the composer will try to obscure, blur, or
otherwise wander around the underlying beat.  For instance in
rap the singer will jump around against the steady, 4/4 beat
underneath.
	Sometimes two different meters will be placed on top of
each other, e.g. threes against twos, which is called polymeter.  The 
example song, the Adagio by Mozart, does this in the middle sections:
one voice plays six notes for every four of another.  The band "Yes" 
does this often, sometimes with even more than two simultaneous meters.
	Another trick is to place an accent at regular intervals
which aren't a simple divisor of the meter.  For instance, in the song
"Long Distance Runaround" again on the "Fragile" album, although the
song is in eight, the drum and keyboard play a note every five beats.
Jazz uses all of these rhythmic techniques quite often.  
	The band "Dream Theater" is fond of using a little trick
in nine beats per measure, of grouping the first eight notes into two
groups of four, so it sounds like an extra beat is added (4+4+1).
This is a little different than multimeter, when the entire meter
of the piece changes frequently (e.g. Stravinsky).
	Sometimes a Jazz musician, especially when improvising, will
abandon the steady rhythm altogether.  The normal rhythm is
also abandoned for e.g. ritards (a gradual slowing down of the
music, for instance towards the end of the piece), accelerando
(speeding up), rubato (speeding up and slowing down around the
beat, although the meter itself usually remains constant), and so on.
	The important thing is to distinguish _meter_, which is just
a measure of time -- the number of beats/time per measure -- and
_rhythm_, which involves the actual beats, their arrangement and
placement within the meter.  Nine beats per measure is the meter;
4+4+1, 3+3+3, etc. is more indicative of the rhythm.
	So, although the rhythm can be broken up, superimposed,
regularly changed, and occasionally even abandoned altogether, there 
is almost always an underlying steady meter throughout any piece of
music (although it may also change in some more or less regular way).


8.2 Notes and intervals

	Western music is based on a series of twelve notes.  These twelve
pitches, or frequencies, form an octave.
	Consider a piano keyboard:

	|  | | | |  |  | | | | | |  |  |
	|  | | | |  |  | | | | | |  |  |
	|  | | | |  |  | | | | | |  |  |
	|  | | | |  |  | | | | | |  |  |
	|  | | | |  |  | | | | | |  |  |
	|  --- ---  |  --- --- ---  |  --
	|   |	|   |   |   |   |   |   |
	| C | D | E | F | G | A | B | C'|
	|___|___|___|___|___|___|___|___|

The keys labeled A-G are white keys; the rest are black keys.  The
"distance" between two adjacent pitches is called a "semitone" or half-step.
Two semitones form a whole tone or whole step.  The distance between two
pitches in general is called an interval.  On the keyboard above, the
number of semitones between two notes is exactly the number of
keys between the two notes.
	To raise or lower a note in semitone increments an "accidental"
is used: the sharp ('#') is used to raise the pitch by one semitone;
the flat ('b') lowers the pitch by a semitone.  Thus, the black key in
between the two white keys C and D is referred to as either C# or Db.
The black key between G and A is G# or Ab.  E# is the same note as F;
Fb is the same note as E.  Sometimes they are even doubled up: raise
G one half step to get G#.  Raise it again and you get "G##", written
as GX, which is the same as A.
	Why two or more symbols for the same note?  As we shall see
below, depending on the context -- what key we are in, what note
was just modified, etc. -- particular symbols are more approprite.


8.3 Scales

	Know this hymn?

	Joy to the world, the Lord is come.
	D   C#  B    A     G   F#  E   D

It's a descending D-major scale.  A scale is a sequence of notes, normally
a whole or half tone apart, arranged in ascending or descending order.
There are all sorts of different kinds of scales, but the most widespread
in western music are the major and minor scales, and it's easiest to start
examining them in the key of C (which has no sharps or flats).

	A C-major scale is simply played on the white keys: C D E F G A B C'
where the C' is one _octave_ (eight scale notes) above the first C played.
Although the C' sounds "higher" than the C, they still sound the "same".
You may know this scale in another form: do re me fa sol la si do (which
is called "solmization" in case you're curious).

Looking at the keyboard above, the intervals between notes are

	C   D   E   F   G   A   B   C' 
	  w   w   h   w   w   w   h	  w=whole step h=half step

In fact, any major scale has this interval relationship of wwhwwwh:
two whole steps, one half-step, three more whole steps, and one half-step.
So, for instance, an A#-major scale would be: A# B# D D# F G A A#

A C-minor scale, on the other hand, looks like

	C   D   Eb  F   G   Ab  Bb  C'
	  w   h   w   w   h   w   w

It's pretty amazing that such a simple change -- moving the positions of
just two whole/semi-tone intervals -- can have such a dramatic effect!
The above is actually the "natural" minor scale.  The _harmonic_
minor scale is

	C   D   Eb  F   G   Ab  B   C'
	  w   h   w   w   h   wh  h

It is like the natural minor scale, but with a raised 7th (Bb->B).
The large 1 1/2 steps gap can be detrimental to melodic flow.  To
fix this up, the _melodic_ minor scale raises the 6th (Ab->A) as well:

	C   D   Eb  F   G   A   B   C'
	  w   h   w   w   w   w   h

but only when ascending (if starting at C' and moving downwards to C,
the natural minor scale is used).

Finally, the _chromatic_ scale should be mentioned.  It is just a scale
in half steps: C C# D D# E F F# etc.  Now that you have mastered minor
and chromatic scales, you can write heavy metal music and make big $$$.

	As you probably figured out, the term "C-major" scale means
a scale with major semi/whole-tone intervals, starting on the
note C (called the "tonic").  When a piece of music is said to be
in the key of C, it means that the tones in that piece of music
all relate to that one central tone C, and that the functions of other
notes in the piece result from how they relate to that central tone.
The central tone is also referred to as the "tonic".  For example:

	When you know the notes to sing
	 So  do   la  fa   me   do  re

	You can sing most an- y- thing
	 So  do  la   si  do  re  do

All of the notes revolve around the note "do" -- they are all attracted
towards it in some way.  It's as if the notes all want to head towards
the central tone as a goal.  The music doesn't always reach that goal
when we expect it, in fact by not ending on the tonic a state of
suspense gets created.  For instance, try ending the above song on
the last "re" of the first bar -- somehow there's a feeling of
incompleteness.  Try ending it on the last "re" of the second bar --
now that feeling is very strong!  The music demands a resolution;
once the notes resolve back to the tonic (the last "do"), there is
a sense of completion, and the song can end.  (One of the mysterious
properties of music is this ability to give a sense of motion -- not
by rhythmic properties, but purely by melodic and harmonic properties).

	The above song is in the key of C because C is the tonic
for the song; it is in C-major because all of the notes lie in the
C-major scale, i.e. the intervals of the notes, as they relate to
the tonic C, are all major intervals.  (Actually, it's in the key
of "do", so assuming the note "do" is the note C...).  If the
note intervals were minor, then the piece would be in C-minor.

	The notes (or "degrees") of a scale are assigned numbers,
usually roman numerals, but sometimes decimal as well:

	C   D   E   F   G   A   B   C'
	I  II  III IV   V  VI   VII VIII
	1   2   3   4   5   6   7   8

Each of these numbers is given a name as well (1=tonic, 3=mediant,
5=dominant, etc.) -- just so you know.  Usually the term "interval"
actually refers to the distance between scale degrees.  For
instance, the distance between C and E is a third -- three letter
names between the two.  C-G is a fifth, and so on.
	Let's take a closer look at a major scale, by letting the
scale span two octaves.  The whole/half tone relationship is then:

		wwhwwwhwwhwwwh

A natural minor scale, though, has the form whwwhww.  If we superimpose
these relationships:

		1 2 3 4 5 6 7 8
		 w w h w w w h w whwwwh		Major
		           w h w whww		Natural minor

Wow!  If we start on the sixth note of a major scale -- any major
scale -- and play the notes in that scale, we get a minor scale!
The sixth note of the C-major scale is A, thus notes in a C-major
scale are _exactly_ the same as notes in an A-minor scale; for
keys, this means that the key of C-major has a very similar structure
to the key of A-minor.
	Maybe we can use a similar trick to find other key
relationships.  What happens if we start on 5 instead of 6?  We
would get wwhwwhw:

	C  D  E  F  G  A  B  C'
		    G  A  B  C  D  E  F  G
		     w  w  h  w  w  h  w

This is very close to a major scale itself; the only problem is that
last half step, and that is very easy to fix by introducing a
single accidental:

	G  A  B  C  D  E  F# G
	 w  w  h  w  w  w  h 

Whereas a C-major scale has no sharps or flats, a G-major scale has
a single sharp.  Said another way, the key of G-major has one
sharp -- F is raised to F#.  By taking the sixth note we get the
relative minor key -- E minor and G major are relative minor/major keys.
	So we have a new rule: by taking the fifth of a major
key -- raising the tonic note by five scale steps -- we can get
a new key by introducing a sharp.  If we try the other way, and
count _backwards_ by five steps to get the tonic, we get
		
		F  G  A  B  C  D  E  F'
		 w  w  w  h  w  w  h

Again, this is very close to a major scale, except for the whole
step between 3 and 4 (A and B).  To fix it up, we just introduce
a _flat_:

		F  G  A  Bb C  D  E  F'
		 w  w  h  w  w  w  h

All of this can be encapsulated in the circle of fifths:

				C
				|
		    (1b) F	Am	 G (1#)
			  \		/
			  Dm          Em
	       (2b) Bb			      D (2#)
		      \Gm		   Bm/

	    (3b) Eb - Cm		   F#m - A (3#)

		      /Fm		  C#m\
	       (4b) Ab    		      E (4#)
			 Bbm+A#m    Abm+G#m
			  /		\
		    (5b) Db	D#m	 B (5#)
		    (7#) C#    	Ebm	 Cb (7b)
				 |
				F# (6#)
				Gb (6b)

Moving around the circle clockwise amounts to starting a new scale
on the fifth of the current scale.  The outer circle denotes the
major keys, the inner circle denotes the relative minor keys.
The numbers in parenthesis denote the number of sharps or flats
present.
			
8.4 Chords and chord progressions

	The very basic of basics.

	A chord is simply the combination of two or more intervals;
the simplest and most fundamental chords are triads: three tones 
consisting of two thirds.  For example

		C D E F G A B C'	Scale

		C E G			Triad

The triad has three notes: the root (in this case C), the third (E),
and the fifth (G).  These terms are derived from the scale, and not
from the position (or octave) of the notes in the chord.  For instance,
the chord can appear in different forms, or inversions:

	- A triad with its root as lowest tone is in root position: 

		C E G	 C G E' ...	Triads, root position

	- A triad with its third as the lowest tone is in the first inversion:

		E G C'   E C' G'	Some first inversion triads

	- A triad with its fifth as lowest tone is in the second inversion:

		G C' E'  ...		Second inversion triads

Now that you have mastered root triads you can write 90's popular
music and make big $$$.

	We can get a whole flock of triads by starting on different
notes of the scale.  Each of these is identified by its root:

		1  2  3  4  5  6  7   (I II III IV V VI VII)

		C  D  E  F  G  A  B
		E  F  G  A  B  C' D'
		G  A  B  C' D' E' F'
	
We can also write down the triads for the minor scale.
	Recall, however, that the interval is determined simply by
counting the letter names between the two notes in an interval.
Thus C-E is a third, but so is C-Eb, C-E#, C#-E#, etc.  Naturally
then C-Eb-G, C-E-G#, C-Eb-Gb etc. are all perfectly "legal" triads.
In fact, they are called minor, augmented, and diminished triads.
Rather than get involved in a bunch of definitions, at this point I
will suggest consulting the references for more information.
(There's nothing difficult about it; it's just a little detailed
for this "brief introduction" to music theory :).

	Now that you have mastered chords I IV and V you can write
rock and roll music, country western, and a variety of other songs.
Try it -- play chord I.  Then play chord IV, and play chord I
again.  Then play chord V, chord IV, and chord I -- voila!
	This brings up an important idea: chord progression.

	I used to do a lot of running in high school.  One day for
whatever reason I thought I'd try staying inside and running in
place for 30 minutes (I could listen to music, etc.).  I rank that
as one of the single most boring things I have ever done.
	A piece of music that plays one chord over and over may make
a lot of money in the 90's, but it sure is boring.

	Let's see a concrete example of a chord progression:

	Nobody knows where you are...  How near or how far
	  G-Bb-D                    F#-G#-A#            F-Bb-D
	  G-minor chord	      F# (or Gb)-major chord  (Inverted) Bb-major chord

	Shine     on     you   cra..          aaa.. zy    diamond
	Bb-Eb-G   Bb-D-F       Bb-C-Eb      F-Bb-D	 F-A-C
        Eb-major  Bb-major    C-minor 7th    Bb-major	  F-major
                              (inverted)

If you look at where the notes sit on a keyboard, the progression is not as
complicated as it looks above.  Also, note that "shine on..." progression
is a series of chords molded around the intervals in a Bb-major scale.
That is, a Bb-major scale is Bb C D Eb F G A.  In the chords above, the
top note is just a descending Bb-major scale: G F Eb D C, and they
are always combined with Bb, giving all the intervals in the key of Bb.
The last F-major chord (which is composed of notes all within the Bb-major
scale) makes the transition back to G-minor a breeze.

How about a more detailed example?  First the notes:

	Oh yeah I- I- I-    tell you so- om- thing	[guitar/bass]
	E   E   D  C  B      B    D  C   B    A		 D C# D D# E
	
	I think you'll un- der- stand
	B   B    B      B   B     F#

	When I- I- I-	    say that so- om- thing
	E    D  C  B         B    D  C   B    A		[D C# D D# E]

	I want to hold your haaaaaaaaaand
	B  B    B  B    B     F#'+B' (one octave up, interval=fourth)

Now the underlying chords:

	Oh yeah I- I- I-    tell you so- om- thing	[guitar/bass]
		G-B-D		     D-F#-A		[D C# D D# E]

	I think you'll un- der- stand
	E-G#-B			B-D#-F#

	When I- I- I-	    say that so- om- thing
	     G-B-D		     D-F#-A		[D C# D D# E]

	I want to hold your haaaaaaaaaand
	E-G#-B		    D#-F#-B

Now in words.  The song is in the key of G-major: G A B C D E F# G'.
We start with chord I:G-B-D.  Next is chord V (D-F#-A').  Remember, though,
that we can get to new keys by starting on the fifth.  Chord V in G-major
is exactly chord I in D-major: D E F# G A B C# D'.  Now look at chord
II in D-major (E-G-B) -- this chord is just a root triad in the
key of E-minor.  To get the E-G#-B in the song amounts to shifting
to E-major: E F# G# A B C# D# E'.  We have one chord left, B-D#-F#,
which we now see is just chord V in E-major.  But then again, chord V
in E-major is just chord I of B-major: B C# D# E F# G# A# B'.
	How in the world do we get back to G-major?  Take a look at
chord III of G-major: B-D-F#.  So, chord I of a B-minor scale is
chord III of a G-major scale.  We are back to where we started and
can repeat.  Note the inverted last chord.
	Note the smooth transitions between chords.  This is possible
because of the relationships of the chords to one another: because
they share certain intervals, and span different scales, it is
possible to seamlessly move between them.  It doesn't work to just
play random chords, one after the other, and quite a number of
songs have some very awkward or clumsy chord progressions in them
(ever hear of a band called "Extreme"?  Dream Theater qualifies as well).
	The above example also hints at an even broader possibility
of not just progressing between chords but modulating into completely
different keys.  Most pieces of music quickly return to their starting
point, so they haven't really modulated into a different key so much
as made a temporary excursion away from the key.  Others, however,
are practically modulating on every other note -- Wagner, for instance.
	I hope you notice the syncopation in the above song.  It
also somewhat demonstrates a technique called sequencing: repeating a
pattern of notes, for instance to descend a scale.  The "I- I- I-" and
"so- om- thing" are both a descending 3-note scale, with idential
rhythm and note intervals.  You could keep repeating the sequence
and end up on any note you wanted.  Usually sequences follow one after
the other:

	B A G  A G F  G F E  F E D  C

This is a sequence of triplets, which ends on a C in a nice way.
Sequencing is a useful tool for making all sorts of otherwise
awkward transitions.  Another example of a transition trick
(not to mention a 'hook') is the guitar riff D C# D D# E in the
above song.  Notice how it leads so smoothly -- practally falls --
into the E-major chords.
	This isn't the whole story for this song, of course, since there
are dissonant intervals and such being played on top of the chords (an
example of a dissonant interval is G-G#).  I leave the analysis of
the refrain, bridge, bass line, rhythm line, and 2-part vocal
harmonies (which are in unison on the above words) to you!

	There are many other kinds of chords besides triads, among
them are sevenths, ninths, elevenths, thirteenths, etc., but
one of them is so important that it must be mentioned: the
dominant, or major-minor, seventh.  Example:

		G B D F

Other 7th chords are

		D F A C		Minor
		C E G B		Major
		B D F Ab	Diminished
		B D F A		Half-diminished

Finally, there's one more interval worth mentioning (which is intimately
related to the 7th): the tritone, otherwise known as a diminished fifth
or (its inversion) an augmented fourth.  A tritone is just three whole
steps: F-B.  In medieval times the tritone was referred to as "Diabolus
in musica" -- the Devil in music -- and its use was strictly forbidden!
(It is a very awkward and distinctive sound, and difficult to harmonize).


8.5 Dynamics and music performance

	SID is really a musical instrument of sorts.  A C-64 composer
not only composes music but actually _performs_ that music on SID,
so it is worthwhile to mention some aspects of music performance.
	A piece of music is just a collection of notes.  It is up
to the composer to indicate how those notes should "sound", and it
is up to the performing musician(s) to determine how to play those
notes.  There are quite a lot of things left up to the performer.
This section doesn't deal with how music should be performed, but
rather covers a few of the related issues and terms.
	Something that is dynamic is something that is changing in time.
In music, there are two types of dynamics that a composer might
indicate: volume dynamics and tempo dynamics.  A crescendo is an
indication in music which means "gradually increase the volume"; a
decrescendo indicates a decrease in volume.  Just for completeness, 
"piano" means play quietly, "forte" means play loudly.  Sometimes a
composer will indicate accents on a note, which generally translates
to "attacking" the note a little more sharply -- a little more initial
pressure on the violin bow, or pressing the piano key a little
faster/harder.
	Tempo dynamics are obviously used to speed up or slow down
a piece.  Usually these happen at the end of a phrase, or near
a transition point.  A ritardando is a gradual slowing down of the
tempo, and an accelerando is a gradual speeding up of tempo.

	Some other musical terms relating to performance:

	Arpeggio: From the Italian word for harp, "Arpa".  It means,
		unsurprisingly, to play a chord "harp-like", that
		is, playing the notes of a chord in succession,
		instead of simultaneously.  This term applies to
		_ornaments_, which basically decorate a note, but
		also to written out figurations (that is, an arpeggio
		may take place across several measures of music --
		they don't have to happen all at once).

	Portamento: Portamento is a vocal effect, and means to smoothly
		slide from one note to the next.  Stringed instruments
		(violins etc.) and trombones can do this as well.

	Rubato: In Italian, it means "robbed".  In music, it means
		an elasticity of tempo, i.e. slight ritardandos and
		accelerandos which make the beats a little rubbery.

	Tremolo: Think "trembling".  On a violin, this is done by
		more or less shaking the bow -- it plays the same
		note in rapid succession, and makes a very dramatic
		effect (for example, the beginning of Tchaikovsky's
		"Swan Lake", which also begins with a sforzando, i.e.
		a very strong accent).

	Trill: A trill is a kind of musical ornament, performed by
		rapidly varying a note with the note just above it.
		The speed at which a note is trilled is up to the
		performer, and in many cases (e.g. baroque music)
		the speed changes during the trill (starts slow,
		becomes fast).

	Vibrato: On a violin, vibrato is done by rocking the finger
		back and forth.  It thus makes minute changes in
		pitch to a particular note.  There are two aspects
		to vibrato: the speed (how fast the finger is rocked)
		and the width (how far the finger is rocked).  The
		appropriate speed and witdh really depend on the
		music.
 

8.6 Acoustics

	This section will just talk a little about the scientific
and mathematical aspects of music.  You may have wondered what
makes the note A the note A, or how the notes A B C etc. are all
related, or what makes an octave an octave.  This section will
attempt to answer some of these questions.

	If you've ever played with a record player, you know that
the pitch of the notes can change by changing the speed of the
turntable -- speeding it up makes the pitches higher, and slowing
it down makes the pitches lower.  This is the idea behind frequency.
	An LP plays at 33rpm -- revolutions per minute, meaning that
in one minute the record makes 33 full 360 degree revolutions.
This is a measure of angular frequency -- you repeat something
(a revolution) at a certain rate (33 revs/min).
	With linear frequency, the unit is "Hertz", which means
"cycles per second".  If you've ever seen a tuning fork, you know
that it is just a piece of metal which wiggles back and forth
at a certain rate, i.e. a certain frequency.  A piano works by
hitting a metal string, which then vibrates at a certain frequency.
Things that vibrate faster generate a higher pitch; things that
vibrate slower generate a lower pitch.
	The note A (above middle C) is now generally defined as 440Hz --
440 cycles per second.  In the old days, of course, things were not
so standardized, and in fact the "standard" pitch varied widely
from locale to locale.  It has also been steadily rising since the
time of Bach, so that some compositions are today actually a half
tone higher than when they were written!  Beethoven's fifth symphony
is in C-minor, but was originally heard at today's B-minor level of
pitch.

	Octaves, as you may recall, sound very similar.  Playing the
next octave amounts to doubling the frequency -- concert A has
pitch 440Hz, so one octave above concert A has pitch 880Hz.  It
makes sense why the notes are so similar: it's like playing a
record at 66rpm instead of 33rpm.  The record at 66rpm turns _exactly_
twice for each time the record at 33rpm turns.  If you were to put
a white dot on two records, and play one at 33rpm, and the other
at 66rpm, what would happen?  If the needles start right on top of
the white dots, then every time the 33rpm dot is underneath the
needle, the 66rpm dot will _also_ be underneath the needle -- but it
will have gone around twice.  So the repetitions fall at _exactly_
the same place in time, but there are twice as many of them.  If
you were to blink your eyes at 33rpm, you would always see a dot
underneath the needle.
	Compare with turning one of the records at 45rpm.  If you
were to blink your eyes at 33rpm, you would have to wait a very
long time before the white spot appeared under the needle again.
The two are not synchronized in any simple way.
	Now, what was the point again?  That octaves sound very
similar, and correspond to doubling (or halving) the frequency.

	So far so good; we know how to get from a note to its octave,
but how do we know where to put all the in-between notes?  This is
called "temperament".  It turns out that there are a lot of different
ways to put the in-between notes!  It wasn't until nearly 1800
that the current system of _equal temprament_ was generally accepted.
J.S. Bach first brought it in to practical use -- showed the true
possibilities of the system -- in the early 18th century.  Although
this explanation will be mathematical, remember that musicians at that
time only had an analog device for working these things out: their ears!
	There are twelve semitones between octaves, and the equal tempered
system just distributes those tones equally.  To get from one semitone
to the next, we simply multiply the frequency by the twelfth root
of two, which is equal to 1.0594631.  If A is 440Hz, then the A#/Bb
above it is

		440Hz * 1.059... = 466.164 Hz

and so on.  To get to the next note (B) we simply multiply again
by the twelfth root of two.  After twelve steps, we get the
twelfth root of two to the twelfth power, which is just... two!
(Multiply 1.059... by itself twelve times and you get 2).  So,
after twelve steps we have just doubled the frequency: we are now
at the next octave.
	Equal temprament is used because it is very flexible: music
may be played in all keys, and it is possible to move between all
keys.  Bach's "Well-Tempered Klavier" was written to demonstrate
just this: there are two volumes, and each consists of 24 pieces,
one in each of the major and minor keys, in ascending chromatic order.
	Of course in the old days people didn't have the mathematics,
they had the music.  They had to discover note relationships using their
ears.  Only some of the relationships had been discovered, possibly
by Pythagoras.  The ratio of two tones in an octave is 2:1.  The
ratio of tones in a fifth (seven half steps) is 3:2, and the ratio
of tones in a major third is 5:4.  Using these relationships all
other intervals in the so-called just intonation system are deduced.
A Pythagorean scale is deduced purely from the interval of the fifth.
In these systems music is possible in certain keys, but is nearly
impossible in keys involving many sharps or flats.
	If you compute out the intervals using the twelfth root of
two system, you'll see that a fifth works out to multiplying the
frequency by 1.498 (3/2 = 1.5) and a major third works out to 1.26
(5/4 = 1.25).  Of course, piano tuners use their ears, not a calculator.
	Why only twelve tones?  Indeed.  In fact, some eastern
music (e.g. music in India) makes extensive use of quartertones.
If you can find an album called "Intuition" from the band TNT, you
can listen to what a quarter-toned electric guitar sounds like.
(_Great_ album, btw, and still available in stores).
 
8.7 Conclusion

	If you have found this interesting, you ought to look into
the subject further.  This introduction has BARELY even scratched
the surface of theory and composition.  Maybe the next version can
have a chapter on themes and theme development, who knows?
	Of course, only so much knowledge can be gained by just
reading books.  There's no substitute for listening carefully to
a wide variety of music, and figuring out what is going on.  Sometimes
it's handy to keep a notebook of interesting chord progressions or
rhythmic structures, which can then be referred to at a later time.
	As I think I stated I am just an amateur at all of this,
and part of my reason for writing this program (not to mention
this documentation) was to work out a lot of these ideas, and try
to gain a more fundamental understanding of how stuff fits together,
and perhaps to explore things on my own (for instance, quartertones).
	If nothing else, I hope I have conveyed a sense of the
breadth and wonder of music that exists out there, and that there
is so much more to music than the excruciatingly vapid "See Dick Run.
Run, Dick, Run." mentality of nearly all 90's music (and popular
culture as a whole, for that matter).
	There are lots of really exciting things out there in the world!
I hope you enjoy the program!
 
SLJ 6/26/97

 
References
----------

The Fridge: http://stratus.esam.nwu.edu/~judd/fridge/
	- Source code, index into C=Hacking and disC=overy, latest
	  binaries and documentation for this program.
 
"A SID Primer" -- disC=overy, Issue #2
	- An introduction to SID.  This issue also has an interview
	  with Bob Yannes, the designer of SID.
 
"The Harvard [Brief] Dictionary of Music"
	- The brief version is a very inexpensive paperback with
	  lots of information.

"Harmony", by Walter Piston
	- The classic.  Excellent.

"Elementary Harmony", by Robert W. Ottman
	- A good book, with accompanying tape available.

"Harmony and Voice Leading", by Edward Aldwell and Carl Schachter
	- Another good book.
