MINUETZ
-------
by R Hopkins & M Laverty
from Your Computer, March 1983


MOZART LIVES

Roll those dice and set Mozart spinning in his grave. Rod Hopkins applies the
power of a Spectrum to the Dice Waltz to compose millions of genuine Mozart
minuets that the maestro never heard.


YOU CAN COMPOSE instant Mozart with a little known opus called the Dice
Waltz. In effect, this was an automatic generator of minuets. This claim
holds true in spite of the fact that Wolfgang Amadeus never heard most of the
theoretically possible 4.6E16 variations!

It was constructed in this manner: Mozart assembled 176 musical bars of two
types, suitable for the two parts into which each "minuet" would be divided.
The two groups of 88 bars were arranged into tables of eight columns and 11
rows, each element of a column representing a single, three-eight bar. In
each column the bars were written or selected such that any bar in one column
could be played after any bar taken from the column to its left, and before
any bar taken from the column to its right.

In the first table, a sequence of bars selected in order from the first to
the eighth columns would combine to form a minuet beginning in the key of the
tonic, and modulating by the last bar to the dominant  for example C to G.
Providing the normal symmetry, though not that of the traditional AABA
minuet, the second table contributes bars opening on the dominant and working
their way back to the tonic. Each half would of course be repeated, giving a
total of 32 bars per minuet.

As the title of Mozarts work suggests, the bars to be played were chosen by
throwing a pair of dice. The range of numbers possible from a pair of dice is
two to 12, and so the rows of the two tables were labelled accordingly, 16
throws in all generating the required bars in a hopefully random fashion.
Loaded dice would definitely have been a disadvantage in this context.

In practice, Mozart compiled three tables. The first two were organised in
the manner just described, each cell containing a number from one to 176,
pointing to one of the bars written out on full double staves in the third
table. One cannot help feeling that he conceived the whole thing with
computers in mind; the manuscript table of thc bars was a serial table, and
so presumably, if a sequence was to be played through on the piano or
clavichord with any comfort, the bars would have to be transcribed in full on
to a separate sheet of manuscript.

Our program attempts to preserve the flavour of the original. The user
actually throws the dice, which tumble across the screen to reveal the
desired numbers on their top faces. And to complete the charade, appropriate
numbers appear on the other two visible faces. A count of the number of
throws made is displayed, and on completing 16 throws, a tabular record of
the dice numbers is provided. Next, the manuscript of the music generated by
the dice sequence may be printed on the screen in two sections, representing
parts one and two of the minuet. After each part is printed, like the
original, in three voices and on two staves, the option is given to SAVE the
manuscript. This will be as hard copy if a printer is connected, or on tape
as a named Screen if not. Then, after prompts for volume and tempo, and in
one of two keys, the music will be played through in three-part harmony, and
of course, may be repeated if desired. Other refinements are included such as
the ability to fix the dice, and so generate a predetermined sequence of bars.

By now the astute reader will have realised the raison d'etre of the
hardware. Valiant though it is, the Spectrum beeper cannot cope with more
than one voice at a time. A General Instruments chip, the AY-3-8910 provides
not only the three sound channels needed for our purpose, but also two
entirely independent and bi-directional I/O ports, each of eight bits.
Moreover, the chip is simplicity itself to program for most purposes, either
in machine code or BASIC, and equally convenient to drive in hardware terms.
The spare appearance of the PSGIO board  Programmable Sound Generator and
Input/Output  will bear the latter out.

Having said that the Spectrum beeper is not man enough to handle
full-blooded, three-part Mozart, some readers will no doubt be relieved to
hear that the software can be largely proved using the beeper before any
hardware is actually connected. In fact, the program will automatically
detect the lack of the interface and default to beeper. It must be stressed
however, that the beeper routine gives only a very crude foretaste of the
real thing.

The circuit of the PSGIO board is very straightforward, using only the
AY-3-8910, two cheap 14-pin LS TTL integrated circuits, a common eight-pin
audio amplifier chip and a small handful of discrete components.

It lays out naturally on 0.1in. pitch Vero board, with very little in the way
of track-cutting or wiring involved. A ZX-81 type connector should be used,
since this allows the simultaneous use of a ZX Printer. This connector has 23
pins per side, as opposed to the 28 boasted by the Spectrum; the shell of the
printer extender will only admit a 23-way connector. Taking this course also
has the advantage that the board might be used with a ZX-81.

It is recommended that the connector be mounted on the board itself, and the
whole plugged directly on to the Spectrum or printer connector without
intervening wiring. The Spectrum is frustratingly sensitive to the loading
caused by even the shortest of cables. All of the components used in the
circuit are readily available from the majority of suppliers advertising in
the electronics monthlies.

Communication with the PSG is register-orientated. In practice, this means
that the programmer first tells the chip which register he wishes to alter or
read, and then sends or retrieves the relevant data to or from the register
specified. All functions are controlled internally by the PSG, and may
persist thus while the controlling program is busy with other matters. To
perform these functions, the PSG makes use of the data programmed into its
register array, numbered 0-15. Table 1 summarises the signal requirements of
the two control pins of the 8910 that are used.

	Table 1.
	BDIR BC1
	 0    0  Inactive
	 0    1  Read from PSG
	 1    0  Write to PSG
	 1    1  Latch PSG Register Address

They are met by decoding two I/O addresses  that is, eight-bit addresses
combined with the CPU signal IORQ  to talk to the chip, namely 221 and 223.
The former address plays a dual role: OUT 221,X will prepare the PSG for a
data transfer involving register X. On the other hand, IN 221 will have as
its result the contents of the register last pointed to by an OUT 221
instruction; for example, PRINT IN 221 will print those contents. The other
I/O address used, 223, is the output data destination address, if you like.
OUT 223,Y writes the value Y into the register last referred to by an OUT 221
instruction.

All of the PSG registers are eight-bit registers, although some of them are
handled as pairs. Note that Bit 0 is the least significant bit  LSB  while
Bit 7 is the most significant  MSB. If two registers are combined, the
register with the higher address  number  constitutes the most significant
byte, the summed value of their contents being the low-register value plus
256 times the high-register value.

The value of each register bit, of course, can only be either a logic 1 or a
logic 0; but, in their proper positions, the bits collectively form a binary
number whose decimal equivalent can be calculated by adding together the
weighted values of any bits set to 1, thus:

	BIT BIT BIT BIT BIT BIT BIT BIT
	 7   6   5   4   3   2   1   0
	-------------------------------
	 1   1   1   1   1   1   1   1  = 255
	128 64  32  16   8   4   2   1
	-------------------------------
	 1   0   1   1   0   0   1   1  = 179
	128 64  32  16   8   4   2   1

If, for instance, a register contained zero, all bits would be reset, that is
logic zero. And, to set a particular bit to logic 1, simply write into the
register the decimal value of that bit, plus those of any other bits required
set. Conversely, if a register were to contain 255, that is, all bits set to
1, and the need were to reset to zero bits 0, 1 and 2, it would be necessary
to write into the register:
	(255-4-2-1) = 248

Now to move on to the PSG registers. Remember first of all that the chip has
three sound channels, referred to as A, B and C; and note further that the
two highest registers, 14 and 15, are used to transmit and receive data via
the two I/O ports available. The PSG registers are utilised as follows:

Register
   0 }  Set Channel A Tone Period
   1 }
   2 }  Set Channel B Tone Period
   3 }
   4 }  Set Channel C Tone Period
   5 }
   6    Set random noise period on all channels
   7    Enable noise and/or tone on all channels
        Control direction of I/O transfers for both ports
   8    Set Channel A amplitude
   9    Set Channel B amplitude
  10    Set Channel C amplitude
  11
  12 }  Set Envelope period and shape
  13 }  according to same pattern
  14    I/O Port A data
  15    I/O Port B data

Channel tones are set by writing values into registers 0-5, each voice using
two registers. Of each pair, the higher register only uses the four lowest
bits. This means that the highest combined value that can be programmed for
any channel is:
	255 + 256 * (8+4+2+1) = 4095

An external oscillator or clock frequency is applied to pin 22 of the PSG
chip. As a preliminary, this frequency is divided by 16 before being directed
to the three channels, where it is further divided down by the numbers stored
in the relevant tone period register pairs, producing the output frequency
for each channel:
	CLOCK frequency / 16 * Tone Period Value

Amplitude Control is set by ignoring envelope control and writing into
registers 8, 9 and 10 any value from 0 to 15, the resulting volume being
proportional to the number programmed.

To enable the channels and the I/O individual bits of register 7 are used for
this purpose as follows:

	1=O/P	0=Channel ON
	0=I/P	1=Channel OFF
	BIT BIT BIT BIT BIT BIT BIT BIT
	 7   6   5   4   3   2   1   0
	I/O I/O  C   B   A   C   B   A
	         ---------   ---------
	 B   A     NOISE       TONES

Writing (255421)=248 into register 7 would thus switch on the tone outputs
of all three channels, switch off noise on all three, and set both I/O ports
to output mode. These bit switches are active when zero.

When you have built or acquired a PSGIO board, try the following routine,
which simply demonstrates how to output a tone from channel A, and then
switch it off. It is as easy as that; and the most complicated sound programs
are little more than collections of similar instructions:
Program line    Rem
10 OUT 221,0    Point to channel A register 0
20 OUT 223,200  Set tone period to 200
                Leave register 1 at zero
30 OUT 221,8    Point to register 8
40 OUT 223,10   Set channel A volume to 10
50 OUT 221,7    Point to register 7
60 OUT 223,254  Switch on channel A only
                Bit 0 now equals 0
70 INPUT "Press ENTER to switch off",A$
80 OUT 223,255  PSG still pointing to register 7
                Writing 255 to it sets bit 0 to 1

Do not bother typing in the remarks; they are only included to make you feel
quite certain as to what the routine is doing. Try adding extra lines in
between lines 10 to 50 to program tones or noise for channels B and C.
Remember to set the volume for each voice used, and to change line 60 to
switch the required voices on.

First the BASIC program  see Figure 1. The only points to watch are that the
length of line 1 remains unaltered; music manuscript file names are POKEd
into the SAVE expression in the following line, so that any additions to line
1 could cause havoc. Also, be careful with the machine-code addresses set up
at the beginning of the program. SAVE the BASIC at the beginning of a tape by
typing:
	SAVE "MINUETZ" LINE 1
This allows it to AutoRun on loading, Line 1 fetching the tables and machine
code from their final position on the tape immediately following the BASIC.

Second, the bar table, Figure 2, embodies the main data bank of the program,
holding Mozarts 176 bars. 18 bytes of RAM are used to store the information
for one bar. Since all of them are in three-eight time, and since the
shortest note used was a semiquaver, the obvious time-slot of a sixth of a
bar was chosen as the building block of the music. There is, in fact, one
byte per channel per time slot. Figure 2 reveals something of the identity of
the data by grouping them in bar "dominoes", with one time slot occupying a
single domino row.

Using ASCII characters to represent the bytes has allowed a very compact
table with a meaningful appearance and easy points of entry. Use the routine
given at the end of Figure 2 to enter the data. It mimics the printed listing
on the screen as the bytes  in the form of strings  are entered, and allows
you to start at any row of dominoes. If you wish to save the code at some
stage prior to having entered it completely, type:
	SAVE "MINUETCODE" CODE 28930,3642
Before entering any code at all, always type CLEAR 28929. To continue with a
half-entered table, type CLEAR 28929, LOAD in the code from tape, and again
use the routine at the foot of Figure 2, returning the appropriate bar to the
prompt.

Third the machine-code routines and tables  Figure 3. Having completed the
bar table and Saved it on tape, type in the little loader at the end of
Figure 3. Type CLEAR 28929, and LOAD in the bar table, since the material in
Figure 3 will be part of the same 3,642-byte block of RAM. Run the Figure 3
loader, and enter each block in turn, making sure you get the start address
right, and of course, the number of bytes. The start address is the first
address given under each block and the number of bytes is clearly marked.

Follow the same procedure used for Figure 2 to save intermediate stages. Note
that the Figure 3 loader also mimics the layout of the printout on the screen
to make checking of entries easier.

In the BASIC program, lines 36-200 encompass the dice loop, generating the
random numbers for the dice and drawing the dice themselves in their first
two positions. But as you might imagine, there is a fair amount of work
involved in drawing the dice. This could be handled only with the aid of
machine code, which had the added advantage of economising on rapidly
shrinking text-space. It may be of interest to point out that the final dice
are drawn initially in "invisible" ink; this avoids flicker since the
operation of converting the ink colour is a lot quicker than that of
performing the calculations and drawing the dice with dots. Machine-code
routines used are Dicemain, Drawdice and Prtdots, with their associated
tables. Another subterfuge used for reasons of speed is that the monitor
CIRCLE routine is avoided.

Line 9890  this short subroutine is called after the dice have been thrown
to convert the dice numbers into equivalent bar numbers.

Lines 9916-9925 draw the blank manuscript, and lines 8530-8775  see Figure 6
 actually print out the music. Each voice is printed out in full before
moving on to the next voice. The appropriate data is fetched from the bar
table by the machine-code routine Notesort. Lines 8771-8775 actually print
the notes, U being a flag to determine the direction in which the tails are
drawn, Z being another flag indicating whether leger lines are required.

Line 9900 is a subroutine to print out the record of dice numbers.

Lines 9800-9835 play the music. The PSG is initialised in BASIC before
calling the machine code which actually outputs the music. The first entry
point to the subroutine is at line 9830, the routine re-entering itself from
line 9800 if a repeat is desired. Which machine-code routines are called
depends on whether a PSGIO board is connected. If it is then Playmain is
called, which in turn uses Playslot and Out. If no soundboard is detected
then Musicbox is called, which simulates a musical box playing through the
top voice only; even the clicks of the wards are included. Seriously though,
the Musicbox routines  including Part and Beepout  are really only intended
to verify the software as a whole if you have not yet got hold of a PSGIO
board, and though fun, is no substitute for the real, three-voice original.
On the PSGIO board, an output socket is provided to allow you to plug into
the AUX input of your amplifier: this arrangement really does justice to the
music.

Lines 207-253 call the manuscript drawing and play subroutines when required,
and handle saving of manuscript, as well as setting up volume and tempo
variables.

Line 253 changes key each cycle, according to the factor KY.

Finally, a note on I/O: the two registers, 14 and 15 in the PSG give 16 bits
of TTL-compatible I/O capability to the PSGIO circuit. As pointed out
earlier, the ports can be driven completely independently of the sound
generation; while sound is being output, I/O operations can be performed. The
ports are bidirectional. Bits 6 and 7 of register 7 are used to dictate which
direction is operational for each port; if either is set to one then the
corresponding port is in output mode, if a zero setting, then the port is in
input mode. The possibilities are endless.

There is nothing to stop anyone substituting his own bars for the Mozart
using the information given in the text, and with the limitations that with
the current arrangement only triple-time music can be accommodated.

Those familiar with machine code should find it relatively easy to cope with
duple times by changing the number of slots and the cycle counters which
handle them.

Some programmers will be unwilling or unable to deal with the effort of
punching in the whole of Minuetz, or building the programmable sound
generator and input/output board. If they wish, they may write to Rod Hopkins
at [Address Deleted] for a copy of the program at 3.25, or the fully-built
PSGIO board together with the program for 19.75. Both prices include postage
and packing.
