home *** CD-ROM | disk | FTP | other *** search
/ Emulator Universe CD / emulatoruniversecd1998.iso / Speccy / Emulators / z80 / TECHINFO.DOC < prev    next >
Encoding:
Text File  |  1996-08-09  |  79.9 KB  |  1,618 lines

  1. Sinclair ZX Spectrum Emulator 'Z80' v3.04  -  10/8/96  -  by G.A. Lunter
  2.  
  3.  
  4.  
  5.  
  6.  
  7. 5.  TECHNICAL INFORMATION
  8.  
  9.  
  10. Contents:
  11.  
  12.     5.1   The Spectrum 48K
  13.     5.2   The Spectrum 128K
  14.     5.3   The AY-3-8912 sound chip
  15.     5.4   The ZX Printer
  16.     5.5   The Interface I
  17.     5.6   The SamRam
  18.     5.7   The Multiface 128
  19.     5.8   The Z80 microprocessor
  20.     5.9   File formats
  21.  
  22.  
  23.  
  24.  
  25.  
  26. 5.1  The Spectrum 48K
  27.  
  28.  
  29.     In this section, the hardware of the 48K Spectrum is discussed. In this
  30.     section, 'Spectrum' by itself refers to the 48K machine only.
  31.  
  32.     The Spectrum is at the hardware level a very simple machine.  There's
  33.     the 16K ROM which occupies the lowest part of the address space, and
  34.     48K of RAM which fills up the rest.  An ULA which reads the lowest 6912
  35.     bytes of RAM to display the screen, and contains the logic for just one
  36.     I/O port completes the machine, from a software point of view at least.
  37.  
  38.     Every even I/O address will address the ULA, but to avoid problems with
  39.     other I/O devices only port FE should be used.  If this port is written
  40.     to, bits have the following meaning:
  41.  
  42.  
  43.         Bit   7   6   5   4   3   2   1   0
  44.             ┌───┬───┬───┬───┬───┬───┬───┬───┐
  45.             │   │   │   │ E │ M │   Border  │
  46.             └───┴───┴───┴───┴───┴───┴───┴───┘
  47.  
  48.  
  49.     The lowest three bits specify the border colour; a zero in bit 3
  50.     activates the MIC output, and a one in bit 4 activates the EAR output
  51.     (which sounds the internal speaker).  The real Spectrum also activates
  52.     the MIC when the ear is written to; the emulator doesn't.  This is no
  53.     problem; MIC is only used for saving, and when saving the Spectrum
  54.     never sounds the internal speaker.  The upper three bits are unused.
  55.  
  56.     If port FE is read from, the highest eight address lines are important
  57.     too.  A zero on one of these lines selects a particular half-row of
  58.     five keys:
  59.  
  60.       IN:    Reads keys (bit 0 to bit 4 inclusive, in that order)
  61.  
  62.       #FEFE  SHIFT, Z, X, C, V            #EFFE  0, 9, 8, 7, 6
  63.       #FDFE  A, S, D, F, G                #DFFE  P, O, I, U, Y
  64.       #FBFE  Q, W, E, R, T                #BFFE  ENTER, L, K, J, H
  65.       #F7FE  1, 2, 3, 4, 5                #7FFE  SPACE, SYM SHFT, M, N,
  66.  
  67.     A zero in one of the five lowest bits means that the corresponding key
  68.     is being pressed.  If more than one address line is made low, the
  69.     result is the logical AND of all single inputs, so a zero in a bit
  70.     means that at least one of the corresponding keys are pressed.  For
  71.     example, only if each of the five lowest bits of the result from
  72.     reading from port 00FE (for instance by XOR A/IN A,(FE)) is one, no key
  73.     is pressed.
  74.  
  75.     A final remark about the keyboard.  It is connected in a matrix-like
  76.     fashion, with 8 rows of 5 columns, as is obvious from the above
  77.     remarks.  Any two keys pressed simultaneously can be uniquely decoded
  78.     by reading from the IN ports; however, if more than two keys are
  79.     pressed decoding may not be uniquely possible.  For instance, if you
  80.     press Caps shift, B and V, the Spectrum will think also the Space key
  81.     is pressed, and reacts by giving the 'Break into Program' report.  This
  82.     matrix behaviour is also emulated - without it, Zynaps for instance
  83.     won't pause when you press 5,6,7,8 and 0 simultaneously.
  84.  
  85.     Bit 5 (value 64) of IN-port FE is the ear input bit.  When the line is
  86.     silent, its value is zero, except in the early Model 2 of the Spectrum,
  87.     where it was one.  When there is a signal, this bit toggles.  The
  88.     Spectrum loading software is not sensitive to the polarity of this bit
  89.     (which it definitely should not be, not only because of this model
  90.     difference, but also because one cannot be sure the tape recorder
  91.     does not change the polarity of the recorded signal!)  Some old
  92.     programs rely on the fact that bit 5 is always one (for instance
  93.     Spinads); for these programs the emulator can mimic a Model 2 Spectrum.
  94.  
  95.     Bits 6 and 7 are always one.
  96.  
  97.     The ULA with the lower 16K of RAM, and the processor with the upper 32K
  98.     RAM and 16K ROM are working independently of each other.  The data and
  99.     address buses of the Z80 and the ULA are connected by small resistors;
  100.     normally, these effectively decouple the buses.  However, if the Z80
  101.     wants to read of write the lower 16K, the ULA halts the processor if it
  102.     is busy reading, and after it's finished it lets the processor access
  103.     lower memory through the resistors.  A very fast, cheap and neat design
  104.     indeed!
  105.  
  106.     If you run a program in the lower 16K of RAM, or read or write in that
  107.     memory, the processor is halted sometimes.  This part of memory is
  108.     therefore somewhat slower than the upper 32K block.  This is also the
  109.     reason that you cannot write a sound- or save-routine in lower memory;
  110.     the timing won't be exact, and the music will sound harsh.  Also,
  111.     INning from port FE will halt the processor, because the ULA has to
  112.     supply the result.  Therefore, INning from port FE is a tiny bit slower
  113.     on average than INning from other ports; whilst normally an IN A,(nn)
  114.     instruction would take 11 T states, it takes 12.15 T states on average
  115.     if nn=FE. See below for more exact information.
  116.  
  117.     If the processor reads from a non-existing IN port, for instance FF,
  118.     the ULA won't stop, but nothing will put anything on the data bus.
  119.     Therefore, you'll read a mixture of FF's (idle bus), and screen and
  120.     ATTR data bytes (the latter being very scarce, by the way).  This will
  121.     only happen when the ULA is reading the screen memory, 61.5% (192/312)
  122.     of the 1/50th second time slice in which a frame is generated.  The
  123.     other 38.5% of the time the ULA is building the border or generating a
  124.     vertical retrace.  This behaviour is actually used in some programs,
  125.     for instance by Arkanoid, and Z80 also emulates this.
  126.  
  127.     Finally, there is an interesting bug in the ULA which also has to do
  128.     with this split bus.  After each instruction fetch cycle of the
  129.     processor, the processor puts the I-R register 'pair' (not the 8 bit
  130.     internal Instruction Register, but the Interrupt and R registers) on
  131.     the address bus.  The lowest 7 bits, the R register, are used for
  132.     memory refresh.  However, the ULA gets confused if I is in the range
  133.     64-127, because it thinks the processor wants to read from lower 16K
  134.     ram very, very often.  The ULA can't cope with this read-frequency, and
  135.     regularly misses a screen byte.  Instead of the actual byte, the byte
  136.     previously read is used to build up the video signal.  The screen seems
  137.     to be filled with 'snow'; however, the Spectrum won't crash, and
  138.     program will continue to run normally.  There's one program I know of
  139.     that uses this to generate a nice effect: Vectron.  (which has very
  140.     nice music too by the way).  This effect has not been implemented
  141.     however - it's a bit useless (but maybe I'll include it in the future).
  142.  
  143.     The processor has three interrupt modes, selected by the instructions
  144.     IM 0, IM 1 and IM 2.  In mode 1, the processor simply executes a RST
  145.     #38 instruction if an interrupt is requested.  This is the mode the
  146.     Spectrum is normally in.  The other mode that is commonly used is IM 2.
  147.     If an interrupt is requested, the processor first builds a 16 bit
  148.     address by combining the I register (as the high byte) with whatever
  149.     the interrupting device places on the data bus.  The processor then
  150.     fetches the 16-bit address at this interrupt table entry, and finally
  151.     CALLs the subroutine at that address.  Rodnay Zaks in his book
  152.     'Programming the Z80' states that only even bytes are allowed as low
  153.     index byte, but that isn't true.  The normal Spectrum contains no
  154.     hardware to place a byte on the bus, and the bus will therefore always
  155.     read FF (because the ULA also doesn't read the screen if it generates
  156.     an interrupt), so the resulting index address is 256*I+0FF.  However,
  157.     some not-so-neat hardware devices put things on the data bus when they
  158.     shouldn't, so later programs didn't assume the low index byte was 0FF.
  159.     These programs contain a 257 byte table of equal bytes starting at
  160.     256*I, and the interrupt routine is placed at an address that is a
  161.     multiple of 257.  A useful but not so much used trick is to make the
  162.     table contain FF's (or use the ROM for this) and put a byte 18 hex, the
  163.     opcode for JR, at FFFF.  The first byte of the ROM is a DI, F3 hex, so
  164.     the JR will jump to FFF4, where a long JP to the actual interrupt
  165.     routine is put.
  166.  
  167.     In interrupt mode 0, the processor executes the instruction that the
  168.     interrupting device places on the data bus.  On a standard Spectrum
  169.     this will be the byte FF, coincidentally (...) the opcode for RST #38.
  170.     But for the same reasons as above, this is not really reliable.
  171.  
  172.     The 50 Hz interrupt is synchronized with the video signal generation by
  173.     the ULA; both the interrupt and the video signal are generated by it.
  174.     Many programs use the interrupt to synchronize with the frame cycle.
  175.     Some use it to generate fantastic effects, such as full-screen
  176.     characters, full-screen horizon (Aquaplane) or pixel colour (Uridium
  177.     for instance).  Many modern programs use the fact that the screen is
  178.     'written' (or 'fired') to the CRT in a finite time to do as much
  179.     time-consuming screen calculations as possible without causing
  180.     character flickering:  although the ULA has started displaying the
  181.     screen for this frame already, the electron beam will for a moment not
  182.     'pass' this-or-that part of the screen so it's safe to change something
  183.     there. So the exact time in the 1/50 second time-slice at which the
  184.     screen is updated is very important.  Normally the emulator updates the
  185.     entire screen at once (50 times a second), and no best solution can be
  186.     given as to when exactly the screen should be updated.  The user can
  187.     select one of three possibilities (low, normal and high video
  188.     synchronisation, corresponding to a screen update after 1/200, 2/200 or
  189.     3/200 of a (relative) second after a Z80 interrupt) to try to get the
  190.     best results.  Try for instance Zynaps; with normal video
  191.     synchronisation the top four or five lines of the background move
  192.     out-of-phase with the rest, and your space-ship flickers in that
  193.     region.  With low video synchronisation the background moves smoothly
  194.     but the sprites flicker in all parts of the screen.  Only with high
  195.     video sync everything moves smoothly and doesn't flicker.
  196.  
  197.     In Hi-resolution colour emulation mode, however, the emulator makes a
  198.     copy of every screen- and attribute-line in a buffer at the exact time
  199.     the ULA would display it.  Also, the exact times the border colour is
  200.     changed is stored.  Using this information the emulator builds the
  201.     screen; in this way, what you see on your PC monitor is exactly what a
  202.     real Spectrum would display on a television.  Remember Aquaplane, with
  203.     its full-width horizon?
  204.  
  205.     Each line takes exactly 224 T states.  After an interrupt occurs, 64
  206.     line times pass before the byte 16384 is displayed.  At least the last
  207.     48 of these are actual border-lines.  I could not determine whether my
  208.     monitor didn't display the others or whether it was in vertical
  209.     retrace, but luckily that's not really important.  Then the 192
  210.     screen+border lines are displayed, followed by 56 border lines again.
  211.     This makes a total of 312 lines of 224 T states, or 69888 T states,
  212.     which is, at 3.5 MHz, very nearly 1/50th of a second.
  213.  
  214.     Now for the timings of each line itself.  I define a screen line to
  215.     start with 256 screen pixels, then border, then horizontal retrace, and
  216.     then border again.  All this takes 224 T states.  Every half T state a
  217.     pixel is written to the CRT, so if the ULA is reading bytes it does so
  218.     each 4 T states (and then it reads two: a screen and an ATTR byte). The
  219.     border is 48 pixels wide at each side.  A video screen line is
  220.     therefore timed as follows: 128 T states of screen, 24 T states of
  221.     right border, 48 T states of horizontal retrace and 24 T states of left
  222.     border.
  223.  
  224.     When an interrupt occurs, the running instruction has to be completed
  225.     first.  The Z80 samples the state of its interrupt request line at the
  226.     start of the last T state of each instruction.  The Z80 starts to act
  227.     upon an interrupt request at least 1, and at most 1+23 T states after
  228.     it is made active, as the slowest instructions (e.g. INC (IX+d), RL
  229.     (IX+d), EX (SP),IX) take 23 T states).  This difference, which may be
  230.     hard to control, is sometimes significant in practice for hi-resolution
  231.     colour effects.  When the Z80 is executing a HALT instruction, it is
  232.     effectively executing NOPs and not incrementing the PC until an
  233.     interrupt is received (and interrupts are enabled).  As a NOP takes 4
  234.     clocks to execute, in this case the start of the interrupt is fixed up
  235.     to 4 T states.
  236.  
  237.     In all interrupt modes, the interrupt acknowledge cycle is basically an
  238.     ordinary M1 instruction fetch cycle with two wait states added, taking
  239.     up 5 T states.  Then, in mode 0, any instruction that is placed on the
  240.     bus in the acknowledge cycle is executed, whereas in mode 1 this is
  241.     always RST #38.  The Spectrum ordinarily leaves the bus floating at
  242.     interrupt time, so that in mode 0 also a RST #38 (opcode #FF) is
  243.     executed.  A RST #38 normally takes 11 T states, so that the complete
  244.     mode 0 or 1 (or 0/1) interrupt takes 13 T states.  (Thanks to Ian
  245.     Collier for correcting this in the FAQ version)
  246.  
  247.     A mode 2 interrupt starts off with a 7 T state M1 cycle in which the
  248.     interrupt vector is read, followed by two stack-write cycles of 3 T
  249.     states each in which the program counter is pushed, and two memory-read
  250.     cycles of 3 T's each that read the interrupt address.  That is 19 T's.
  251.  
  252.     Ian Collier states that an NMI cycle takes 15 T states.  My reference
  253.     (Mostek Technical Manual of the Z80) breaks it down as follows: a 5 T
  254.     M1 cycle in which the opcode is ignored, then two 3-T stack-write
  255.     cycles to push the program counter, which adds up to 11 T states.  I
  256.     haven't done any testing, so I cannot say anything definite here.
  257.  
  258.     The ZX81 hardware generates a WAIT only 16 T states before it generates
  259.     an NMI, which, by some combined hardware and software wizardry,
  260.     generates one scanline on the television screen.  It seems therefore
  261.     that by executing a whole lot of slow instructions in a block, it is
  262.     possible to jam the horizontal synchonisation of the ZX81 video signal.
  263.     Has this ever been tried?
  264.  
  265.     Now when to OUT to the border to change it at the place you want?
  266.     First of all, you cannot change the border within a 'byte', an 8-pixel
  267.     chunk. If we forget about the screen for a moment, if you OUT to port
  268.     FE after 14326 to 14329 T states (including the OUT) from the start of
  269.     the IM 2 interrupt routine, the border will change at exactly the
  270.     position of byte 16384 of the screen.  The other positions can be
  271.     computed by remembering that 8 pixels take 4 T states, and a line takes
  272.     224 T states.  You would think that OUTing after 14322 to 14325 T
  273.     states, the border would change at 8 pixels left of the upper left
  274.     corner of the screen.  This is right for 14322, 14323 and 14324 T
  275.     states, but if you wait 14325 T states the ULA happens to be reading
  276.     byte 16384 (or 22528, or both) and will halt the processor for a while,
  277.     thereby making you miss the 8 pixels.  This exception happens again
  278.     after 224 T states, and again after 448, an so forth.  These 192
  279.     exceptions left of the actual screen rectangle are the only ones;
  280.     similar things don't happen at the right edge because the ULA don't
  281.     need to read things there - it has just finished!
  282.  
  283.     As noted above, reading or writing in low ram (or OUTing to the ULA!)
  284.     causes the ULA to halt the processor.  When and how much?  The
  285.     processor is halted each time you want to access the ULA or low memory
  286.     and the ULA is busy reading.  Of the 312 'lines' the ULA generates,
  287.     only 192 contain actual screen pixels, and the ULA will only read bytes
  288.     during 128 of the 224 T states of each screen line.  But if it does,
  289.     the processor seems to be halted for 64 T states.  It is not clear to
  290.     me when, and for how long exactly, the ULA halts the processor.
  291.     Sometimes the ULA even stops the processor when it is not interfering
  292.     with it (when it is busy making the border left or right of the screen
  293.     rectangle).
  294.  
  295.     For 128K timings, which are slightly different, see the next section.
  296.  
  297.  
  298.  
  299.  
  300. 5.2  The Spectrum 128K
  301.  
  302.  
  303.     In comparison to the Spectrum 48K, and on the hardware side, the
  304.     Spectrum 128 offers more RAM (128K, you guessed it), more ROM (32K
  305.     instead of 16K), a soundchip, and a serial printer port.  Nothing
  306.     really spectacular.
  307.  
  308.     Another difference with the 48K Spectrum is in the timing of the video
  309.     signals.  You can see this if you save something: the bars in the
  310.     border move differently.  The really important difference of the 128K
  311.     with respect to the video is that the 128K ULA is more relaxed in
  312.     giving the Z80 access to (screen) memory.  This allows programs to make
  313.     hi-resolution colour effects not only in the border, but also on the
  314.     screen itself.  Many 128K programs use this effect.  Note however that,
  315.     although the 128K ULA is more relaxed towards memory access, it does
  316.     still halt the Z80 occasionally.  Partly for this reason it is
  317.     impossible to have hi-res colour effect over the entire screen; there is
  318.     only time to change approximately half of it.  (This does not seem to
  319.     be true; the Shock Megademo manages to move 1-pixel thick lines up on
  320.     the screen one pixel per frame on the whole screen.  Very well done
  321.     indeed!  This is the only program I know to feature hi-res colour effect
  322.     over the entire width of the screen.  It might be, however, that this
  323.     program only changes the entire ATTR line every two scan line times.)
  324.  
  325.     The basic video timings, with the Z80 out of the way, are as follows.
  326.     Each video line takes 228 T states, 4 T states more than on the 48K
  327.     Spectrum.  It starts with 128 T states of screen pixels (or border).
  328.     Then there's border, horizontal retrace and border again, of 100 T
  329.     states.  A complete '50 Hz' frame consists of 311 video lines (of which
  330.     a few are vertical retraces), that is, 1 less than for 48K models.  A
  331.     complete frame is 311 x 228 = 70908 T states long.
  332.  
  333.     I don't know whether the 128K model uses a different crystal.  If not,
  334.     one frame on the Spectrum 128K is 1.5% longer than a 48K frame.
  335.  
  336.     A quote from the +2 manual, page 279; Cliff Lawson writes: "For the
  337.     contended RAM [pages 4-7] (which shares time between the video
  338.     circuitry and the processor), during 128 out of every 228 CPU T states
  339.     (1 TV line), and during 192 out of every 311 TV lines (1 frame) the CPU
  340.     is allowed only 1 access to contended RAM in every 8 T states.  The CPU
  341.     is controlled by introducing wait states".  My guess is this holds true
  342.     for the 128K too.
  343.  
  344.     Directly after an interrupt is generated by the ULA (so slightly before
  345.     the Z80 acts upon it), 63 video lines are written to the CRT.  A first
  346.     few may be verical retraces; this is difficult to find out without an
  347.     oscilloscope, but luckily we don't need this information.  Then 192
  348.     screen lines are written, and then 56 border lines and (possibly)
  349.     vertical retrace lines.  The first screen byte is written to the screen
  350.     14364 T states after the interrupt was generated.
  351.  
  352.     Then the other things.  Memory is arranged in banks of 16K.  The bank
  353.     at 0000-3FFF contains either the original 48K ROM or the new 128K ROM.
  354.     The latter is active at reset.  The bank at 4000-7FFF always contains
  355.     RAM page 5.  The bank at 8000-BFFF is always page 2.  The bank at
  356.     C000-FFFF contains any page from 0-7, including page 2 and 5.  If page
  357.     2 or 5 is enabled in the high bank, every byte written in this bank is
  358.     mirrored in the other bank at 4000 or at 8000, and vice versa.  The
  359.     screen information is read, by the ULA, from the first 6912 bytes of
  360.     either page 5 or page 7.
  361.  
  362.     All this is controlled by writing to port 7FFD (or, in fact, by writing
  363.     to any address with bit 15 and 1 zero; don't use this fact, though; it
  364.     does not work on the +3, where there's another port 1FFD, and neither
  365.     will this work in full generality on the emulator.)
  366.  
  367.  
  368.        Port #7FFD:
  369.  
  370.        Bit    7   6   5   4   3   2   1   0
  371.             ┌───┬───┬───┬───┬───┬───┬───┬───┐
  372.        WRITE│   │   │ P │ R │ S │  page no  │
  373.             └───┴───┴───┴───┴───┴───┴───┴───┘
  374.  
  375.  
  376.     Bits 0-2 determine which page is to appear in bank C000-FFFF.  If S=0,
  377.     the ULA reads the screen from page 5, otherwise it reads page 7.  If
  378.     R=0, the 128K Rom is selected in bank 0000-3FFF; otherwise the 48K Rom.
  379.     If P=1, port #7FFD will be disabled and keep its value until the
  380.     computer is reset.  This bit is set if you select 48K Spectrum in the
  381.     128K startup menu, so that no 48K program is able to (accidentally)
  382.     swap itself into oblivion.
  383.  
  384.     The sound chip of the Spectrum 128 is described in the next section.
  385.  
  386.  
  387.  
  388.  
  389. 5.3  The AY-3-8912 sound chip.
  390.  
  391.  
  392.     The following section was put together using information collected from
  393.     comp.sys.sinclair.  Thanks, and large parts of the information below,
  394.     are due to Alastair Booker, who put a detailed description on the net
  395.     in April '95, and to Ian Collier who recently carried out some thorough
  396.     investigations on the AY chip.
  397.  
  398.     This chip is used in for instance the Sinclair ZX Spectrum 128/+2/+3,
  399.     Amstrad CPC 464/664/6128, Mattel Intellivision, Atari ST, Sega Master
  400.     System and the MSX.
  401.  
  402.     The AY has 16 internal registers.  A register is selected by OUTing the
  403.     register number in bits 0-3 to port #FFFD (only A15, A14 and A1 are
  404.     decoded).  Then write to a register by OUTing to #BFFD, read it by
  405.     INning from #FFFD.  When reading from a register, unused bits are
  406.     always 0.  Reading always yields the value last written to the
  407.     register, except for R14 and R15 when bit 6 or 7 of R7 are reset (R14 /
  408.     R15 used for input).  On the AY-3-8912, when R7 bit 7 is reset, R15
  409.     always reads 255.  Writing to R14 or R15 when they are selected for
  410.     input does load the output register.
  411.  
  412.     Here are the names of the AY registers:
  413.  
  414.         Register        Name                                Bits used:
  415.  
  416.         R0              Fine tone control (FTC) channel A      0-7
  417.         R1              Coarse tone control (CTC) channel A    0-3
  418.         R2              FTC channel B                          0-7
  419.         R3              CTC channel B                          0-3
  420.         R4              FTC channel C                          0-7
  421.         R5              CTC channel C                          0-3
  422.         R6              Noise generator pitch control          0-4
  423.         R7              Mixer and I/O control                  0-7
  424.         R8              Amplitude channel A                    0-4
  425.         R9              Amplitude channel B                    0-4
  426.         R10             Amplitude channel C                    0-4
  427.         R11             Envelope fine period control           0-7
  428.         R12             Envelope coarse period control         0-7
  429.         R13             Envelope control                       0-3
  430.         R14             RS232 i/o                              0-7
  431.         R15             I/O port 2                             0-7
  432.  
  433.     The AY chip consists of three tone generators, one noise generator, an
  434.     envelope generator, three mixers, and three volume generators.
  435.  
  436.     Tone generator A is controlled by R0 and R1.  It contains a 12 bit up
  437.     counter which is reset to 0 whenever it is larger than or equal to the
  438.     value of R1R0 (most significant bits are in R1), and is counted up at a
  439.     frequency of 221660 Hz (which is the driving frequency of the chip
  440.     divided by 8). Loading R0 or R1 takes effect directly.  If the internal
  441.     counter is below the new value, it simply continues; if it is above, it
  442.     immediately resets to 0.  Every time the internal counter is reset, the
  443.     tone generator changes it output from 0 to 1 or vice versa, so the
  444.     frequency of the tone generated is 110830/R1R0 Hz (one period consists
  445.     of two transitions). If R1R0 contains 0, the counter behaves as if R1R0
  446.     contained 1.
  447.  
  448.     The noise generator contains a 5 bit up counter, which is reset to 0
  449.     whenever it is >= R6.  It is counted up at a frequency of 110830 Hz
  450.     (driving frequency divided by 16) [1].  Every time it reaches zero, it
  451.     randomly chooses 0 or 1 as its new output [2].  When R6 is zero, the
  452.     noise generated is the same as when R6 is 1.  Changes to R6 take effect
  453.     only when the internal counter reaches 0.
  454.  
  455.  
  456.        Bit      7    6    5    4    3    2    1    0
  457.              ┌────┬────┬────┬────┬────┬────┬────┬────┐
  458.        R7    │ D2 │ D1 │ Nc │ Nb │ Na │ Tc │ Tb │ Ta │
  459.              └────┴────┴────┴────┴────┴────┴────┴────┘
  460.  
  461.  
  462.     If D1 is 1, R14 acts as output register (RS232 output: bit 2 is CTS,
  463.     bit 3 is data output); when it is 0 R14 acts as input register (bit 6
  464.     is DTR [3]).  D2 is ignored as the AY chip has only one I/O register;
  465.     the bit and its corresponding register are present however.  Reading
  466.     R15 in input mode always yields 255.  Changes made to R7 take effect
  467.     immediately.
  468.  
  469.     The noise and tone output of a channel is combined in the mixer in the
  470.     following way:
  471.  
  472.         Output_A = (Tone_A OR Ta) AND (Noise OR Na)
  473.  
  474.     Here Tone_A is the binary output of tone generator A, and Noise is the
  475.     binary output of the noise generator.  Note that setting both Ta and Na
  476.     to 1 produces a constant 1 as output.  Also note that setting both Ta
  477.     and Na to 0 produces bursts of noise and half-periods of constant
  478.     output 0.
  479.  
  480.     Each binary tone channel output is fed to a separate volume generator.
  481.     Each volume generator is controlled by its amplitude register (R8 for
  482.     channel A) and the 4-bit output of the envelope controller.
  483.  
  484.  
  485.        Bit      7    6    5    4    3    2    1    0
  486.              ┌────┬────┬────┬────┬────┬────┬────┬────┐
  487.        R8    │    │    │    │ Ev │ V3 │ V2 │ V1 │ V0 │
  488.              └────┴────┴────┴────┴────┴────┴────┴────┘
  489.  
  490.  
  491.     If Ev=0, the current volume is given by V3V2V1V0.  If Ev=1, the current
  492.     volume is given by the output of the envelope generator.  The volume
  493.     controller produces an output voltage proportional to its channel's
  494.     binary output value times the current volume.  These analogue outputs
  495.     are then added together to give the final output (this is done outside
  496.     the chip actually).  Note that even when a channel is disabled (say Ta
  497.     = Na = 1), changing the volume level changes the final output, as the
  498.     binary tone channel output is constant and equal to 1, not 0.  Changes
  499.     to the amplitude registers take effect immediately.
  500.  
  501.     The envelope generator is controlled by R11, R12 and R13.
  502.  
  503.  
  504.        Bit     7  6  5  4      3         2         1        0
  505.              ┌──┬──┬──┬──┬──────────┬────────┬───────────┬──────┐
  506.        R13   │  │  │  │  │ Continue │ Attack │ Alternate │ Hold │
  507.              └──┴──┴──┴──┴──────────┴────────┴───────────┴──────┘
  508.  
  509.  
  510.     The envelope generator contains a 16-bit up counter, operated at a
  511.     frequency of 110830 Hz.  The lowest frequency attainable by the
  512.     envelope clock is therefore 1.7 Hz.  If R12R11 contains 0, the clock
  513.     runs at 110830 Hz; otherwise it runs at 110830/R12R11 Hz.  The envelope
  514.     generator is reset by writing to R13 (but not by writing to R11 or
  515.     R12); otherwise it works just as the other counters.
  516.  
  517.     Each time the envelope generator up counter is reset, it produces a
  518.     envelope clock tick.  A 'period' is the time taken by 16 clock ticks.
  519.     The output of the envelope generator during the first period is as
  520.     follows.  If Attack = 1, the output starts off at 0 and at each clock
  521.     tick is increased by 1 until it reaches 15.  If Attack = 0, the output
  522.     starts off at 15 and is falls to 0.
  523.  
  524.     The output in the subsequent periods is 0 if Continue = 0.  Otherwise,
  525.     first the (internal) 'Attack' bit is toggled if Alternate is set,
  526.     otherwise it doesn't change.  How if Hold = 1, the output is a constant
  527.     15 in this and subsequent periods if Attack = 1, otherwise it is a
  528.     constant 0.  If Hold = 0, the envelope generator behaves just as in the
  529.     first period (except that Attack has possibly changed).  To sum it up:
  530.  
  531.  
  532.         0,1,2,3  \__________     single decay then off
  533.  
  534.         4,5,6,7  /|_________     single attack then off
  535.  
  536.         8        \|\|\|\|\|\     repeated decay
  537.  
  538.         9        \__________     single decay then off
  539.  
  540.         10       \/\/\/\/\/\     repeated decay-attack
  541.                    _________
  542.         11       \|              single decay then hold
  543.  
  544.         12       /|/|/|/|/|/     repeated attack
  545.                   __________
  546.         13       /               single attack then hold
  547.  
  548.         14       /\/\/\/\/\/     repeated attack-decay
  549.  
  550.         15       /|_________     single attack then off
  551.  
  552.  
  553.     If the envelope generator is used to generate a tone, its frequency is
  554.     either 110830/(16*R12R11) Hz (R13 = 8 or 12) or 110830/(32*R12R11) Hz
  555.     (R13 = 10 or 14).
  556.  
  557.  
  558.     [1] This has been checked by Pierre Guerrier using an oscilloscope.
  559.     [2] The algorithm used for the pseudo random output is not known.  It
  560.         seems not to be too good, as sounds vaguely similar to tape loading
  561.         sounds are audible if you set R6 to 31.
  562.     [3] I don't know which bit is data input; it is probably not bit 3.
  563.  
  564.  
  565.  
  566.  
  567. 5.4  The ZX Printer
  568.  
  569.  
  570.     As always, very Sinclair, this is a simple but ingenious piece of
  571.     equipment.  The ZX Printer is controlled through one I/O port, namely
  572.     #FB.  It is decoded using A2 only.  Port #FB:
  573.  
  574.  
  575.        Bit      7    6    5    4    3    2    1    0
  576.              ┌────┬────┬────┬────┬────┬────┬────┬────┐
  577.        READ  │styl│  0 │    │    │    │    │    │ enc│
  578.              └────┴────┴────┴────┴────┴────┴────┴────┘
  579.  
  580.              ┌────┬────┬────┬────┬────┬────┬────┬────┐
  581.        WRITE │Data│    │    │    │    │ Mot│Slow│    │
  582.              └────┴────┴────┴────┴────┴────┴────┴────┘
  583.  
  584.  
  585.     To print, first read port #FB and check that bit 6 is 0 to make sure
  586.     that the printer is attached.  The printer motor is started by writing
  587.     a byte 0 to #FB (Mot=0).  Then check bit 7 until it goes high; this
  588.     means that the printer head is in the starting position.  A line is
  589.     printed as follows.  Wait for bit 0 (encoder) to go high, and write a
  590.     bit of data (1=black dot), and do this 256 times.  The Spectrum ROM
  591.     makes the 'Slow' bit 1 in the last two lines; this ensures that the
  592.     printer head stops at the start of the new line, instead of halfway
  593.     into it.  Stop the printer by writing a byte 4.  See #0EF4 in the ROM
  594.     for the relevant routine.
  595.  
  596.     The emulator returns #FF on a port #FB IN if there is no printer
  597.     attached to the LPT port selected for ZX Printer output.  If the
  598.     printer is off-line, busy, or out of paper, the emulator will usually
  599.     return #FF too, so that the Spectrum program will not even consider to
  600.     print, unless you set option -xj, as then the emulator will return 1 so
  601.     that the program will try to print, and will wait for the printer to go
  602.     on line.  The reason for including the -xj switch is that usually the
  603.     status lines of the printer are not too reliable, so that a Spectrum
  604.     program may halt on a COPY statement even if there's no printer
  605.     attached (e.g. with SuperSpy, which makes screendumps on the ZX Printer
  606.     without asking).  In the inner printing loop, the ROM does not check
  607.     for BREAKs, so that the encoder bit is always high to prevent locking
  608.     the emulated Spectrum.  If the printer is happy to accept data, the
  609.     emulator returns #81.
  610.  
  611.  
  612.  
  613.  
  614. 5.5  The Interface I
  615.  
  616.  
  617.     The Interface I is quite complicated.  It uses three different I/O
  618.     ports, and contains logic to page and unpage an 8K ROM if new commands
  619.     are used.  I won't be very detailed here; you could refer to the source
  620.     code of the emulator if you want to know some details, or read the
  621.     'Spectrum Shadow ROM Disassembly' by Gianlura Carri, published by
  622.     Melbourne House - but don't expect the same level of detail as of Ian
  623.     Logan and Frank O'Hara in their Rom disassembly book.
  624.  
  625.     The ROM is paged if the processor executes the instruction at ROM
  626.     address 0008 or 1708 hexadecimal, the error and close# routines.  It is
  627.     inactivated when the Z80 executes the RET at address 0700.
  628.  
  629.     I/O Port E7 is used to send or receive data to and from the microdrive.
  630.     Accessing this port will halt the Z80 until the Interface I has
  631.     collected 8 bits from the microdrive head; therefore, it the microdrive
  632.     motor isn't running, or there is no formatted cartridge in the
  633.     microdrive, the Spectrum hangs.  This is the famous 'IN 0 crash'.
  634.  
  635.     Port EF is used for several things:
  636.  
  637.  
  638.        Bit    7   6    5    4    3    2    1     0
  639.             ┌───┬───┬────┬────┬─────┬───┬─────┬─────┐
  640.         READ│   │   │    │busy│ dtr │gap│ sync│write│
  641.             │   │   │    │    │     │   │     │prot.│
  642.             ├───┼───┼────┼────┼─────┼───┼─────┼─────┤
  643.        WRITE│   │   │wait│ cts│erase│r/w│comms│comms│
  644.             │   │   │    │    │     │   │ clk │ data│
  645.             └───┴───┴────┴────┴─────┴───┴─────┴─────┘
  646.  
  647.  
  648.     Bits DTR and CTS are used by the RS232 interface.  The WAIT bit is used
  649.     by the Network to synchronise, GAP, SYNC, WR_PROT, ERASE, R/_W, COMMS
  650.     CLK and COMMS DATA are used by the microdrive system.  If the
  651.     microdrive is not being used, the COMMS DATA output selects the
  652.     function of bit 0 of out-port F7:
  653.  
  654.  
  655.        Bit      7    6   5   4   3   2   1       0
  656.             ┌──────┬───┬───┬───┬───┬───┬───┬───────────┐
  657.         READ│txdata│   │   │   │   │   │   │    net    │
  658.             │      │   │   │   │   │   │   │   input   │
  659.             ├──────┼───┼───┼───┼───┼───┼───┼───────────┤
  660.        WRITE│      │   │   │   │   │   │   │net output/│
  661.             │      │   │   │   │   │   │   │   rxdata  │
  662.             └──────┴───┴───┴───┴───┴───┴───┴───────────┘
  663.  
  664.  
  665.     TXDATA and RXDATA are the input and output of the RS232 port.  COMMS
  666.     DATA determines whether bit 0 of F7 is output for the RS232 or the
  667.     network.
  668.  
  669.  
  670.  
  671.  
  672. 5.6  The SamRam
  673.  
  674.  
  675.     The SamRam contains a 32K static CMOS Ram chip, and some I/O logic for
  676.     port 31.  If this port is read, it returns the position of the
  677.     joystick, as a normal Kempston joystickinterface would.  If written to,
  678.     the port controls a programmable latch chip (the 74LS259) which
  679.     contains 8 latches:
  680.  
  681.  
  682.        Bit    7   6   5   4   3   2   1   0
  683.             ┌───┬───┬───┬───┬───┬───┬───┬───┐
  684.        WRITE│   │   │   │   │  address  │bit│
  685.             └───┴───┴───┴───┴───┴───┴───┴───┘
  686.  
  687.  
  688.     The address selects on of the eight latches; bit 0 is the new state of
  689.     the latch.  The 16 different possibilities are collected in the diagram
  690.     below:
  691.  
  692.         OUT 31,   │  Latch  │ Result
  693.         ──────────┼─────────┼────────────────────────────────────────
  694.             0     │    0    │ Switch on write protect of CMOS RAM
  695.             1     │    "    │ Writes to CMOS RAM allowed
  696.             2     │    1    │ turn on CMOS RAM (see also 6/7)
  697.             3     │    "    │ turn off CMOS RAM (standard Spec.  ROM)
  698.             4     │    2    │ -
  699.             5     │    "    │ Ignore all OUT's to 31 hereafter
  700.             6     │    3    │ Select CMOS bank 0 (Basic ROM)
  701.             7     │    "    │ Select CMOS bank 1 (Monitor,...)
  702.             8     │    4    │ Select interface 1
  703.             9     │    "    │ Turn off IF 1 (IF1 rom won't be paged)
  704.            10     │    5    │ Select 32K ram bank 0 (32768-65535)
  705.            11     │    "    │ Select 32K ram bank 1 (32768-65535)
  706.            12     │    6    │ Turn off beeper
  707.            13     │    "    │ Turn on beeper
  708.            14     │    7    │ -
  709.            15     │    "    │ -
  710.  
  711.     At reset, all latches are 0.  If an OUT 31,5 is issued, only a reset
  712.     will give you control over the latches again.  The write protect latch
  713.     is not emulated; you're never able to write the emulated CMOS ram in
  714.     the emulator.  Latch 4 pulls up the M1 output at the expansion port of
  715.     the Spectrum.  The Interface I won't page its ROM anymore then.
  716.  
  717.  
  718.  
  719.  
  720. 5.7  The Multiface 128
  721.  
  722.  
  723.     This device consists of an 8K rom, paged into the area 0-8191, and 8K
  724.     of ram, paged into 8192-16383, and a latch storing the screen select
  725.     bit of the Spectrum 128K (bit 3 of OUT-port #7FFD), which would
  726.     otherwise be impossible to know (the Disciple requires the user to
  727.     press Y or N according to whether the screen changed at some point of
  728.     the snapshot procedure, in order to get hold of this bit.)
  729.  
  730.     The Multiface rom and ram pages have highest priority, higher than both
  731.     the ordinary rom (48K or 128K) or the Interface 1, Disciple or Plus D
  732.     roms.
  733.  
  734.     The Multiface memory is paged in when an NMI occurs, or when the
  735.     processor reads from IN address #BF.  Bit 7 of the returned byte is the
  736.     screen select bit (or, on 48K machines, the value of bit 3 of the byte
  737.     last written to port #7FFD - unlikely to be useful.)  Other bits follow
  738.     the floating bus.
  739.  
  740.     The Multiface memory is paged out by reading from port #3F.  The
  741.     Multiface does not put bits on the bus.
  742.  
  743.  
  744.  
  745.  
  746. 5.8  The Z80 microprocessor
  747.  
  748.  
  749.     The Z80 processor is quite straightforward, and contains to my
  750.     knowledge no interesting bugs or quirks.  However, it has some
  751.     undocumented features.  Some of these are quite useful, and some are
  752.     not, but since many programs use the useful ones, and a few programs
  753.     use the weird ones, I tried to figure them out and emulate them as best
  754.     as I could.  There is a Z80 emulator around, intended as a CP/M
  755.     emulator, which halts the program if an undocumented opcode is
  756.     encountered.  I don't think this makes sense.  ZiLOG doesn't dictate
  757.     the law, the programs which use the processor's features do!
  758.  
  759.     In section 5.1 there is some information on Z80 interrupt timings in
  760.     different modes.
  761.  
  762.     Most Z80 opcodes are one byte long, not counting a possible byte or
  763.     word operand.  The four opcodes CB, DD, ED and FD are 'shift' opcodes:
  764.     they change the meaning of the opcode following them.
  765.  
  766.     There are 248 different CB opcodes.  The block CB 30 to CB 37 is
  767.     missing from the official list.  These instructions, usually denoted by
  768.     the mnemonic SLL, Shift Left Logical, shift left the operand and make
  769.     bit 0 always one.  Bounder and Enduro Racer use them, to name just two.
  770.     The SamRam monitor can disassemble these and uses the mnemonic SLL.
  771.     These instructions are quite commonly used.
  772.  
  773.     The DD and FD opcodes precede instructions using the IX and IY
  774.     registers.  If you look at the instructions carefully, you see how they
  775.     work:
  776.  
  777.         2A nn           LD HL,(nn)
  778.         DD 2A nn        LD IX,(nn)
  779.         7E              LD A,(HL)
  780.         DD 7E d         LD A,(IX+d)
  781.  
  782.     A DD opcode simply changes the meaning of HL in the next instruction.
  783.     If a memory byte is addressed indirectly via HL, as in the second
  784.     example, a displacement byte is added.  Otherwise the instruction
  785.     simply acts on IX instead of HL.  (A notational awkwardness, that will
  786.     only bother assembler and disassembler writers: JP (HL) is not
  787.     indirect; it should have been denoted by JP HL.)  If a DD opcode
  788.     precedes an instruction that doesn't use the HL register pair at all,
  789.     the instruction is executed as usual.  However, if the instruction uses
  790.     the H or L register, it will now use the high or low halves of the IX
  791.     register!  Example:
  792.  
  793.         44              LD B,H
  794.         FD 44           LD B,IYh
  795.  
  796.     These types of inofficial instructions are used in many programs.  By
  797.     the way, many DD or FD opcodes after each other will effectively be
  798.     NOPs, doing nothing except repeatedly setting the flag 'treat HL as IX'
  799.     (or IY) and taking up 4 T states.  Note that the FD or DD 'opcode' is
  800.     treated as part of an instruction, so that the Z80 cannot be interrupted
  801.     during execution of such a block.  (This last remark was not checked;
  802.     it was remarked by someone on comp.sys.sinclair)
  803.  
  804.     When (parts of) HL are used both as source and target, above rule is
  805.     ambiguous.  The special cases are: LD H,(IX+d) and LD L,(IX+d), and
  806.     LD IXl,IXl / LD IXl,IXh / LD IXh,IXl / LD IXh,IXh.  Things like
  807.     LD IXh,(IX+d) or LD H,IXh do not exist.
  808.  
  809.     Two instructions do not obey the DD/FD rule.  They are EX DE,HL and
  810.     EXX.  These instructions take 4 T states to execute, and are therefore
  811.     most probably implemented by toggling a flag that changes the reference
  812.     to the registers; no data is actually being moved, which explains why
  813.     they cannot operate on IX or IY.
  814.  
  815.     The doubly-shifted opcodes that start with DD CB and DD ED also do not
  816.     follow the standard rule.  If a DD or FD precedes an ED instruction,
  817.     it is ignored.  ED instructions never operate on the IX or IY register.
  818.     With CB instructions, the situation is more interesting.  Every DD CB
  819.     instruction operates on (IX+nn), but also copies the result to the
  820.     specified register, except when it is (HL).  For example,
  821.  
  822.         CB CE           SET 0,(HL)
  823.         CB C0           SET 0,B
  824.         DD CB nn CE     SET 0,(IX+nn)
  825.         DD CB nn C0     SET 0,(IX+nn) ; copy result to B
  826.  
  827.     (The information about the inofficial CB instructions was given to me
  828.     by Arnt Gulbrandsen, and originated from David Librik.)
  829.  
  830.     There are a number of inofficial ED instructions, but none of them are
  831.     very useful.  The ED opcodes in the range 00-3F and 80-FF (except for
  832.     the block instructions of course) do nothing at all but taking up 8 T
  833.     states and incrementing the R register by 2.  Most of the unlisted
  834.     opcodes in the range 40-7F do have an effect, however.  The complete
  835.     list: (* = not official)
  836.  
  837.         ED40   IN B,(C)                 ED60   IN H,(C)
  838.         ED41   OUT (C),B                ED61   OUT (C),H
  839.         ED42   SBC HL,BC                ED62   SBC HL,HL
  840.         ED43   LD (nn),BC               ED63 # LD (nn),HL
  841.         ED44   NEG                      ED64 * NEG
  842.         ED45   RETN                     ED65 * RET
  843.         ED46   IM 0                     ED66 * IM 0
  844.         ED47   LD I,A                   ED67   RRD
  845.         ED48   IN C,(C)                 ED68   IN L,(C)
  846.         ED49   OUT (C),C                ED69   OUT (C),L
  847.         ED4A   ADC HL,BC                ED6A   ADC HL,HL
  848.         ED4B   LD BC,(nn)               ED6B # LD HL,(nn)
  849.         ED4C * NEG                      ED6C * NEG
  850.         ED4D   RETI                     ED6D * RET
  851.         ED4E * IM 0                     ED6E * IM 0
  852.         ED4F   LD R,A                   ED6F   RLD
  853.         ED50   IN D,(C)                 ED70 # IN (C)
  854.         ED51   OUT (C),D                ED71 * OUT (C),0
  855.         ED52   SBC HL,DE                ED72   SBC HL,SP
  856.         ED53   LD (nn),DE               ED73   LD (nn),SP
  857.         ED54 * NEG                      ED74 * NEG
  858.         ED55 * RET                      ED75 * RET
  859.         ED56   IM 1                     ED76 * IM 1
  860.         ED57   LD A,I                   ED77 * NOP
  861.         ED58   IN E,(C)                 ED78   IN A,(C)
  862.         ED59   OUT (C),E                ED79   OUT (C),A
  863.         ED5A   ADC HL,DE                ED7A   ADC HL,SP
  864.         ED5B   LD DE,(nn)               ED7B   LD SP,(nn)
  865.         ED5C * NEG                      ED7C * NEG
  866.         ED5D * RET                      ED7D * RET
  867.         ED5E   IM 2                     ED7E * IM 2
  868.         ED5F   LD A,R                   ED7F * NOP
  869.  
  870.     Guenter Woigk remarked that the three instructions marked # (which were
  871.     previously marked *) are documented by ZiLog, though not normally used.
  872.     The ED63 and ED6B instructions have shorter and faster equivalents.
  873.  
  874.     The ED70 instruction reads from port (C), just like the other
  875.     instructions, but throws away the result.  It does change the flags in
  876.     the same way as the other IN instructions, however.  The ED71
  877.     instruction OUTs a byte zero to port (C), interestingly.  These
  878.     instructions 'should', by regularity of the instruction set, use (HL)
  879.     as operand, but since from the processor's point of view accessing
  880.     memory or accessing I/O devices is the same thing except for activation
  881.     of the /IORQ line instead of the /MREQ line, and since the Z80 does not
  882.     access memory twice in one instruction (disregarding instruction fetch
  883.     of course) it can't fetch or store the data byte.  (A hint in this
  884.     direction is that, even though the NOP-synonyms LD B,B, LD C,C etcetera
  885.     do exist, LD (HL),(HL) is absent and replaced by the HALT instruction.)
  886.  
  887.     The instructions ED 4E and ED 6E are IM 0 equivalents: when FF was put
  888.     on the bus (physically) at interrupt time, the Spectrum continued to
  889.     execute normally, whereas when an EF (RST #28) was put on the bus it
  890.     crashed, just as it does in that case when the Z80 is in the official
  891.     interrupt mode 0.  In IM 1 the Z80 just executes a RST #38 (opcode FF)
  892.     no matter what is on the bus.
  893.  
  894.     The RETI instruction is functionally exactly equivalent to the RET
  895.     instruction.  It is used only to signify the end of an interrupt
  896.     routine to an external hardware device (read: the Z80 PIO).  The RETN
  897.     however is different from RET in that it resets IFF1 to the current
  898.     value of IFF2.  Now IFF1 and IFF2 are usually equal (and become equal
  899.     after DI and EI and after a maskable interrupt has been accepted).
  900.     They're different only if an NMI occurs when interrupts are enabled;
  901.     then IFF1 is off, and IFF2, holding the previous state of the interrupt
  902.     flip flop, is on, signifying that interrupts were enabled before the
  903.     non-maskable interrupt.  Since the state of IFF2 can be read by using
  904.     LD A,R and LD A,I, the RETN instruction is not used much in Spectrum
  905.     ROM software, and it is utterly useless in normal software.  In other
  906.     words, I have not tried to figure out whether the unofficial RET's are
  907.     RETI's or RETN's.  One can make an educated guess though.
  908.  
  909.     About the R register.  This is not really an undocumented feature,
  910.     although precise explanations were hard to find.  The R register is a
  911.     counter that is updated every instruction, where DD, FD, ED and CB are
  912.     to be regarded as separate instructions.  So shifted instructions will
  913.     increase R by two.  There's an exception: doubly-shifted opcodes, the
  914.     DDCB and FDCB ones, increase R by two too.  LDI increases R by two,
  915.     LDIR increases it by 2 times BC, as does LDDR etcetera.  The sequence
  916.     LD R,A / LD A,R increases A by two. The highest bit of the R register
  917.     is never changed (except possibly by LD R,A of course).  This is
  918.     because in the old days everyone used 16 Kbit chips.  Inside the chip
  919.     the bits were arranged in a 128x128 matrix, and needed a 7 bit refresh
  920.     cycle.  Probably for this reason ZiLOG decided to count only the lowest
  921.     7 bits.  If the R register emulation is switched on the R register will
  922.     behave as is does on a real Spectrum; if it is off it will (except for
  923.     the upper bit) act as a random generator.
  924.  
  925.     You can easily check that the R register is really crucial to memory
  926.     refresh.  Assemble this program:
  927.  
  928.         ORG 32768
  929.         DI
  930.         LD B,0
  931.     L1  XOR A
  932.         LD R,A
  933.         DEC HL
  934.         LD A,H
  935.         OR L
  936.         JR NZ,L1
  937.         DJNZ L1
  938.         EI
  939.         RET
  940.  
  941.     It will take about three minutes to run.  Look at the upper 32K of
  942.     memory, for instance the UDG graphics.  It will have faded.  Only the
  943.     first few bytes of each 256 byte block will still contain zeros,
  944.     because they were refreshed during the execution of the loop.  The ULA
  945.     took care of the refreshing of the lower 16K.  (This example won't work
  946.     on the emulator of course!)
  947.  
  948.     Then there's one other dark corner of the Z80 which has its effect on
  949.     programs like Sabre Wulf, Ghosts'n Goblins and Speedlock.  The Mystery
  950.     of the Undocumented Flags!
  951.  
  952.     Bit 3 and 5 of the F register are not used.  They can contain
  953.     information, as you can readily figure out by using PUSH AF and POP AF.
  954.     Furthermore, sometimes their values change.  I found the following
  955.     empirical rule:
  956.  
  957.         The values of bit 7, 5 and 3 follow the values of the
  958.         corresponding bits of the last 8 bit result of an instruction
  959.         that changed the usual flags.
  960.  
  961.     For instance, after an ADD A,B those bits will be identical to the bits
  962.     of the A register.  (Bit 7 of F is the sign flag, and fits the rule
  963.     exactly).  An exception is the CP x instruction (x=register, (HL) or
  964.     direct argument).  In that case the bits are copied from the argument.
  965.  
  966.     If the instruction is one that operates on a 16 bit word, the 8 bits of
  967.     the rule are the highest 8 bits of the 16 bit result - that was to be
  968.     expected since the S flag is extracted from bit 15.
  969.  
  970.     Ghosts'n Goblins use the undocumented flag due to a programming error.
  971.     The rhino in Sabre Wulf walks backward or keeps running in little
  972.     circles in a corner, if the (in this case undocumented) behaviour of
  973.     the sign flag in the BIT instruction isn't right.  I quote:
  974.  
  975.         AD86    DD CB 06 7E        BIT 7,(IX+6)
  976.         AD8A    F2 8F AD           JP P,#AD8F
  977.  
  978.     An amazing piece of code!  Speedlock does so many weird things that
  979.     everything must be exactly right for it to run.  Finally, the '128 rom
  980.     uses the AF register to hold the return address of a subroutine for a
  981.     while.  To keep all programs happy, and still have a fast emulator, I
  982.     had to make a compromise.  The undocumented flags are not always
  983.     emulated right, but they are most of the time.  Not telling you when
  984.     not.
  985.  
  986.     Now for the emulated Z80.  I have added eight instructions, to speed up
  987.     the RS232 input and output of the Interface I and several things of the
  988.     SamRam.  These opcodes, ED F8 to ED FE are of little use to any other
  989.     program.  ED FF is a nice one: it returns you to DOS immediately.  I
  990.     used it for debugging purposes, and it is also used in TAP2TAPE and
  991.     SAMLIST.
  992.  
  993.     The opcode ED FB, which is used by the SamRam, is now also used to use
  994.     multi-load games on the emulator.  If the emulator encounters the
  995.     opcode ED FB in RAM (above 16384), it loads a block of code into memory
  996.     at address HL.  The data is first looked for in the .Z80 or .SLT
  997.     snapshot file last loaded (see description of the .Z80 file format); if
  998.     it is not found there, the emulator looks for a .DAT file with the same
  999.     name as the snapshot last loaded, and the decimal value of the A
  1000.     register appended to it (dropping letters from the snapshot name if
  1001.     required to make it at most 8 characters long).  If this file is not
  1002.     found either, a window is popped up to inform the user of the value of
  1003.     the A register, and allow him to supply a .DAT file (or .Z80/.SLT file)
  1004.     himself.
  1005.  
  1006.     When the emulator fails to load a block, it complements the carry flag,
  1007.     so that the running Spectrum program can decide what to do.  Note that
  1008.     versions of Z80 prior to v3.04 did not change the flags, so that on old
  1009.     versions (and on other emulators) loading will always seem to succeed.
  1010.  
  1011.  
  1012.  
  1013.  
  1014. 5.9  File formats
  1015.  
  1016.  
  1017.     This section describes the format of the files used by the emulator.
  1018.  
  1019.  
  1020.  
  1021.     ROMS.BIN:
  1022.     ---------
  1023.  
  1024.         00000-03fff     Ordinary Spectrum rom
  1025.         04000-05fff     Interface I rom (8K)
  1026.         06000-09fff     First SamRam rom (contains BASIC)
  1027.         0a000-0dfff     Second SamRam rom (contains monitor,...)
  1028.         0e000-11fff     First Spectrum 128K rom (active at RESET)
  1029.         12000-15fff     Second Spectrum 128K rom (contains BASIC)
  1030.         16000-19fff     Disciple rom, system file 3b, Epson printer code
  1031.         1a000-1dfff     Disciple rom, system file 3b, HP printer code
  1032.         1e000-1ffff     Multiface rom (8K)
  1033.  
  1034.     The ordinary rom has not been modified.  The Interface I rom has
  1035.     undergone some modifications, to speed up the RS232 input/output
  1036.     routines.  If you don't like this, or want to use another version of
  1037.     the Interface I, you could put that code at the right place in the
  1038.     ROMS.BIN file.  The interface I should work properly, although the
  1039.     RS232 will be slower (always FORMAT the "b" or "t" channel at 19200
  1040.     baud, by the way, if you replace the rom code, there's no point in
  1041.     waiting for nothing.)  The microdrive routines have not been modified
  1042.     in any way.  Here are the changes of the Interface I rom:
  1043.  
  1044.         Address: Old: New:           Address: Old: New:
  1045.  
  1046.         0B9E     ED   ED             0D20     FB   00
  1047.         0B9F     5B   FC             0D2A     37   ED
  1048.         0BA0     C3   F5             0D2B     F3   FD
  1049.         0BA1     5C   C3             0D2C     CE   18
  1050.         0BA2     21   34             0D2D     00   10
  1051.         0BA3     20   0C             0D4C     FB   00
  1052.  
  1053.     These changes are not likely to cause problems; there are several
  1054.     versions of the Interface I rom around, and program developers know
  1055.     this.  It is also a bit pointless to check whether the Interface I rom
  1056.     hasn't been modified; who would put his snapshot software in there
  1057.     anyway, and that's what those people are afraid of.
  1058.  
  1059.     The first and second SamRam rom have been modified more extensively.
  1060.     The biggest problem was that switching the upper 32K ram bank is very
  1061.     fast in reality, but on the PC two blocks of 32K bytes had to be REP
  1062.     MOVSWded (or the EMS emulator be called).  But since no programs know
  1063.     of the SamRam code anyway, this won't cause any more problems it
  1064.     wouldn't already cause either.
  1065.  
  1066.     The two Spectrum 128 roms have not been modified, and neither have the
  1067.     Disciple roms or the Multiface rom.  The Disciple roms, as they appear
  1068.     in the ROMS.BIN file, do have system files pre-loaded however.
  1069.  
  1070.  
  1071.  
  1072.     .TAP FILES:
  1073.     -----------
  1074.  
  1075.     The .TAP files contain blocks of tape-saved data.  All blocks start
  1076.     with two bytes specifying how many bytes will follow (not counting the
  1077.     two length bytes).  Then raw tape data follows, including the flag and
  1078.     checksum bytes.  The checksum is the bitwise XOR of all bytes including
  1079.     the flag byte.  For example, when you execute the line SAVE "ROM" CODE
  1080.     0,2 this will result:
  1081.  
  1082.  
  1083.              |------ Spectrum-generated data -------|       |---------|
  1084.  
  1085.        13 00 00 03 52 4f 4d 7x20 02 00 00 00 00 80 f1 04 00 ff f3 af a3
  1086.  
  1087.        ^^^^^...... first block is 19 bytes (17 bytes+flag+checksum)
  1088.              ^^... flag byte (A reg, 00 for headers, ff for data blocks)
  1089.                 ^^ first byte of header, indicating a code block
  1090.  
  1091.        file name ..^^^^^^^^^^^^^
  1092.        header info ..............^^^^^^^^^^^^^^^^^
  1093.        checksum of header .........................^^
  1094.        length of second block ........................^^^^^
  1095.        flag byte ............................................^^
  1096.        first two bytes of rom .................................^^^^^
  1097.        checksum (checkbittoggle would be a better name!).............^^
  1098.  
  1099.  
  1100.     The emulator will always start reading bytes at the beginning of a
  1101.     block.  If less bytes are loaded than are available, the other bytes
  1102.     are skipped, and the last byte loaded is used as checksum.  If more
  1103.     bytes are asked for than exist in the block, the loading routine will
  1104.     terminate with the usual tape-loading-error flags set, leaving the
  1105.     error handling to the calling Z80 program.
  1106.  
  1107.     Note that it is possible to join .TAP files by simply stringing them
  1108.     together, for example COPY /B FILE1.TAP + FILE2.TAP ALL.TAP
  1109.  
  1110.     For completeness, I'll include the structure of a tape header.  A
  1111.     header always consists of 17 bytes:
  1112.  
  1113.         Byte    Length  Description
  1114.         0       1       Type (0,1,2 or 3)
  1115.         1       10      Filename (padded with blanks)
  1116.         11      2       Length of data block
  1117.         13      2       Parameter 1
  1118.         15      2       Parameter 2
  1119.  
  1120.     The type is 0,1,2 or 3 for a Program, Number array, Character array or
  1121.     Code file.  A screen$ file is regarded as a Code file with start
  1122.     address 16384 and length 6912 decimal.  If the file is a Program file,
  1123.     parameter 1 holds the autostart line number (or a number >=32768 if no
  1124.     LINE parameter was given) and parameter 2 holds the start of the
  1125.     variable area relative to the start of the program.  If it's a Code
  1126.     file, parameter 1 holds the start of the code block when saved, and
  1127.     parameter 2 holds 32768.  For data files finally, the byte at position
  1128.     14 decimal holds the variable name.
  1129.  
  1130.  
  1131.  
  1132.     .MDR FILES:
  1133.     -----------
  1134.  
  1135.     The emulator uses a cartridge file format identical to the 'Microdrive
  1136.     File' format of Carlo Delhez' Spectrum emulator Spectator for the QL,
  1137.     who devised the format.  This format is now also supported by XZX of
  1138.     Des Harriot.  The following information is adapted from Carlo's
  1139.     documentation.  It can also be found in the 'Spectrum Microdrive Book',
  1140.     by Ian Logan (co-writer of the excellent 'Complete Spectrum ROM
  1141.     Disassembly').
  1142.  
  1143.     A cartridge file contains 254 'sectors' of 543 bytes each, and a final
  1144.     byte flag which is non-zero is the cartridge is write protected, so the
  1145.     total length is 137923 bytes.  On the cartridge tape, after a GAP of
  1146.     some time the Interface I writes 10 zeros and 2 FF bytes (the
  1147.     preamble), and then a fifteen byte header-block-with-checksum.  After
  1148.     another GAP, it writes a preamble again, with a 15-byte record-
  1149.     descriptor-with-checksum (which has a structure very much like the
  1150.     header block), immediately followed by the data block of 512 bytes, and
  1151.     a final checksum of those 512 bytes.  The preamble is used by the
  1152.     Interface I hardware to synchronise, and is not explicitly used by the
  1153.     software.  The preamble is not saved to the microdrive file:
  1154.  
  1155.     offset length name    contents
  1156.  
  1157.       0      1   HDFLAG   Value 1, to indicate header block
  1158.       1      1   HDNUMB   sector number (values 254 down to 1)
  1159.       2      2            not used
  1160.       4     10   HDNAME   microdrive cartridge name (blank padded)
  1161.      14      1   HDCHK    header checksum (of first 14 bytes)
  1162.  
  1163.      15      1   RECFLG   - bit 0: always 0 to indicate record block
  1164.                           - bit 1: set for the EOF block
  1165.                           - bit 2: reset for a PRINT file
  1166.                           - bits 3-7: not used (value 0)
  1167.      16      1   RECNUM   data block sequence number (value starts at 0)
  1168.      17      2   RECLEN   data block length (<=512, LSB first)
  1169.      19     10   RECNAM   filename (blank padded)
  1170.      29      1   DESCHK   record descriptor checksum (of previous 14 bytes)
  1171.      30    512            data block
  1172.     542      1   DCHK     data block checksum (of all 512 bytes of data
  1173.                            block, even when not all bytes are used)
  1174.     ---------
  1175.     254 times
  1176.  
  1177.  
  1178.     (Actually, this information is 'transparent' to the emulator.  All it
  1179.     does is store 2 times 254 blocks in the .MDR file as it is OUTed,
  1180.     alternatingly of length 15 and 528 bytes.  The emulator does check
  1181.     checksums, see below; the other fields are dealt with by the emulated
  1182.     Interface I software.)
  1183.  
  1184.     A used record block is either an EOF block (bit 1 of RECFLG is 1) or
  1185.     contains 512 bytes of data (RECLEN=512, i.e.  bit 1 of MSB is 1).  An
  1186.     empty record block has a zero in bit 1 of RECFLG and also RECLEN=0.  An
  1187.     unusable block (as determined by the FORMAT command) is an EOF block
  1188.     with RECLEN=0.
  1189.  
  1190.     The three checksums are calculated by adding all the bytes together
  1191.     modulo 255; this will never produce a checksum of 255.  Possibly, this
  1192.     is the value that is read by the Interface I if there's no or bad data
  1193.     on the tape.
  1194.  
  1195.     In normal operation, all first-fifteen-byte blocks of each header or
  1196.     record block will have the right checksum.  If the checksum is not
  1197.     right, the block will be treated as a GAP.  For instance, if you type
  1198.     OUT 239,0 on a normal Spectrum with interface I, the microdrive motor
  1199.     starts running and the cartridge will be erased completely in 7
  1200.     seconds. CAT 1 will respond with 'microdrive not ready'.  Try it on the
  1201.     emulator...
  1202.  
  1203.  
  1204.  
  1205.  
  1206.     .OUT FILES:
  1207.     -----------
  1208.  
  1209.     These files are produced when logging OUTs; see menu option O in the
  1210.     Extra Functions menu.  For the specified I/O ports, all OUTs to these
  1211.     ports are recorded in the .OUT file, together with the exact time at
  1212.     which the OUTs were executed.
  1213.  
  1214.     An .OUT file consists of a string of 5-byte blocks.  The first word is
  1215.     the timing word; it has a value between 0 and 17471 inclusive (or
  1216.     between 0 and 17726 inclusive when a 128K Spectrum is emulated), and a
  1217.     unit value corresponds to 1 T state (=1/3494400 s).  After this, the
  1218.     OUT port that was written to follows, then the value OUTed itself:
  1219.  
  1220.         Offset  Length  Description
  1221.  
  1222.         0       2       Time (0-17471 or 0-17726)
  1223.         2       2       Port address
  1224.         4       1       Value
  1225.  
  1226.     Every 1/200th of an emulated second, that is, every 69888/4=17472 T
  1227.     states (or 70908/4=17727 T states on 128K Spectrums), a time-wraparound
  1228.     block is written to the .OUT file:
  1229.  
  1230.         Offset  Length  Description
  1231.  
  1232.         0       2       Flag word #FFFF indicating wraparound-block
  1233.         2       2       Length of preceding block (17472 or 17727 T)
  1234.         4       1       Not used
  1235.  
  1236.     So even when the Spectrum does not OUT to the logged ports at all, 1000
  1237.     bytes get written to the log file every second.
  1238.  
  1239.     By default, an OUT to an even I/O address which does not change the
  1240.     state of the MIC and EAR outputs is not written to the .OUT file, to
  1241.     save disk space when recording music.  If you want all OUTs, specify
  1242.     -xg on the command line.
  1243.  
  1244.     The .OUT files are also used to make a simple trace of a running
  1245.     Spectrum program.  Specify -xy on the command line; as soon as you
  1246.     activate OUT logging, a trace is dumped also.  For each instruction
  1247.     encountered during emulation, the following block is written to the
  1248.     .OUT file:
  1249.  
  1250.         Offset  Length  Description
  1251.  
  1252.         0       2       Flag word (#FFFE)
  1253.         2       2       Program counter
  1254.         5       1       A register
  1255.  
  1256.     Furthermore, no time-wraparound blocks are written to the .OUT file
  1257.     when tracing.  HALT instructions (118 decimal) are special in that they
  1258.     do not generate a block in the log file; this is to make comparisons
  1259.     between different logs of the same program easier.  Admittedly, this is
  1260.     a very crude way of tracing a program, but it's better than nothing,
  1261.     and very useful very occasionally.
  1262.  
  1263.  
  1264.  
  1265.  
  1266.     Map files
  1267.     ---------
  1268.  
  1269.     Map files are those that are produced via option -0m; see section 2.19
  1270.     in Z80.DOC.  These files have no default extension; .MAP seems a natural
  1271.     suggestion.  These files are meant to be used with a future version of
  1272.     Leslie Styles' DSNA (a snapshot disassembler; you can find it on
  1273.     ftp.nvg.unit.no).
  1274.  
  1275.     Map files are 8192 bytes long.  Each byte represents 8 addresses in
  1276.     Spectrum memory, from #0000 to #FFFF.  Note that the rom is also
  1277.     mapped.  A one at bit-position k in byte n means that at least once
  1278.     during the time the emulator emulated, it emulated the opcode it found
  1279.     at address 8n+k.  The shifted opcodes will only have the shift code
  1280.     marked (though the Z80 chip is, I think, in machine cycle 1, M1, during
  1281.     both the shift fetch and the secondary opcode fetch).  Due to the way
  1282.     inofficial DD and FD instructions are implemented, a sequence of DD's
  1283.     is considered as one very long instruction, and will result in only the
  1284.     address of the first DD that was executed being tagged.
  1285.  
  1286.     You should not use Hi-res color emulation during opcode mapping; they
  1287.     use the same buffer area.  HRC emulation still works, but destroys the
  1288.     mapping buffer.  Also, option -xu (disable HCR emulation to use less
  1289.     memory) will disable opcode mapping.  Finally, the mapping procedure
  1290.     does not take memory paging into account, and it is therefore not very
  1291.     practical in 128K modes, in SamRam mode, and for mapping the execution
  1292.     of the shadow roms (128K, SamRam, Interface I, Multiface).  It works
  1293.     best for mapping the ordinary rom and ordinary 48K Spectrum programs.
  1294.     Also note that the map is never cleared, not even when another snapshot
  1295.     is loaded.
  1296.  
  1297.     The best way to use this feature is the following.  Load the program
  1298.     you want to disassemble, and let it run to the main starting point, so
  1299.     that all decoding, decompressing, and moving around has probably been
  1300.     done.  Then save the snapshot ('program.z80'), and start the emulator
  1301.     with 'z80 -0m program.map program.z80'.  Run it for a while, but be
  1302.     sure never to reset the Spectrum, or to enter the SamRam or Multiface,
  1303.     or load another snapshot.  After a while, quit the emulator
  1304.     (Ctrl-Break), and you'll find the file 'program.map' contain the
  1305.     locations of the opcodes executed.  By tracing the code blocks found,
  1306.     and also taking the conditional branches that were left alone during
  1307.     execution, most of the code can probably be found.
  1308.  
  1309.     This option has been added after reading a remark of Leslie Styles
  1310.     (lsm@soton.ac.uk), who had been trying to make his disassembler figure
  1311.     out which parts of memory were actual code, and which were data.  It
  1312.     seemed to me that the only reliable way was to actually emulate the
  1313.     code.  For almost all programs this will be sufficient.  It however
  1314.     still does not take into account the possibility of self-modifying
  1315.     code.  For completely general programs, the approach that Arnt
  1316.     Gulbrandsen followed in his JPP (also keeping a map of executed opcode
  1317.     locations, but invalidating these if necessary when data is written to
  1318.     memory)  is the only right solution.  The current approach however was
  1319.     so simple to implement that I thought it to be worthwhile.
  1320.  
  1321.  
  1322.  
  1323.  
  1324.     .SCR FILES:
  1325.     -----------
  1326.  
  1327.     .SCR files are memory dumps of the first 6912 bytes of the Spectrum
  1328.     memory.  A coordinate (x,y), x between 0 and 255 and y between 0 and
  1329.     192, (0,0) being the upper left corner of the screen, corresponds to
  1330.     the pixel address
  1331.  
  1332.         16384+INT (x/8)+1792*INT (y/64)-2016*INT (y/8)+256*y
  1333.  
  1334.     I admit this is not quite the clearest way to explain the organization
  1335.     of Spectrum's video memory, but with a bit or (hard) thinking you can
  1336.     extract from above formula all information you need...  The lowest
  1337.     three bits of x determine which bit of this address corresponds to the
  1338.     pixel (x,y).  This bit-map constitutes the larger part of the screen
  1339.     memory, 256*192/8=6144 bytes.  The final 768 bytes are attribute bytes.
  1340.     The address of the attribute byte corresponding to pixel (x,y) is
  1341.  
  1342.         22528+INT (x/8)+32*INT (y/8)
  1343.  
  1344.     The lowest three bits of the attribute byte control the foreground
  1345.     colour (the colour of the pixel if the corresponding bit in the bitmap is
  1346.     set), bits 3-5 control the background colour, bit 6 is the bright bit
  1347.     and bit 7 is the flash bit - if it is set, every 16/50th of a second
  1348.     the ULA effectively flips the foreground and background colours.
  1349.  
  1350.  
  1351.  
  1352.     .DAT files:
  1353.     -----------
  1354.  
  1355.     These files are used to store level data; blocks of memory that are
  1356.     loaded when the opcode ED FB is executed.  The block is loaded at the
  1357.     address pointed to by the HL register.  The level number is in the A
  1358.     register.  If the emulator fails to load a level data block, it
  1359.     complements the carry flag.  Versions of the emulator prior to v3.04
  1360.     did not do this.
  1361.  
  1362.     When an ED FB opcode is encountered, the emulator first looks for the
  1363.     snapshot file last loaded, and checks whether it contains the level
  1364.     requested (see the description of the .Z80 format below).  If this
  1365.     fails, it looks for a .DAT file of the level; the name of this file is
  1366.     derived from the name of the last snapshot loaded by appending the
  1367.     (decimal) value of the A register to the name of the snapshot file,
  1368.     dropping characters from the original snapshot name to make the total
  1369.     length 8 characters if necessary.  .DAT files simply contain the plain
  1370.     level data (in contrast to the level data in .Z80 files, which are
  1371.     compressed).
  1372.  
  1373.  
  1374.  
  1375.     .Z80 and .SLT files:
  1376.     --------------------
  1377.  
  1378.     The old .Z80 snapshot format (for version 1.45 and below) looks like
  1379.     this:
  1380.  
  1381.         Offset  Length  Description
  1382.  
  1383.         0       1       A register
  1384.         1       1       F register
  1385.         2       2       BC register pair (LSB, i.e. C, first)
  1386.         4       2       HL register pair
  1387.         6       2       Program counter
  1388.         8       2       Stack pointer
  1389.         10      1       Interrupt register
  1390.         11      1       Refresh register (Bit 7 is not significant!)
  1391.         12      1       Bit 0  : Bit 7 of the R-register
  1392.                         Bit 1-3: Border colour
  1393.                         Bit 4  : 1=Basic SamRom switched in
  1394.                         Bit 5  : 1=Block of data is compressed
  1395.                         Bit 6-7: No meaning
  1396.         13      2       DE register pair
  1397.         15      2       BC' register pair
  1398.         17      2       DE' register pair
  1399.         19      2       HL' register pair
  1400.         21      1       A' register
  1401.         22      1       F' register
  1402.         23      2       IY register (Again LSB first)
  1403.         25      2       IX register
  1404.         27      1       Interrupt flipflop, 0=DI, otherwise EI
  1405.         28      1       IFF2 (not particularly important...)
  1406.         29      1       Bit 0-1: Interrupt mode (0, 1 or 2)
  1407.                         Bit 2  : 1=Issue 2 emulation
  1408.                         Bit 3  : 1=Double interrupt frequency
  1409.                         Bit 4-5: 1=High video synchronisation
  1410.                                  3=Low video synchronisation
  1411.                                  0,2=Normal
  1412.                         Bit 6-7: 0=Cursor/Protek/AGF joystick
  1413.                                  1=Kempston joystick
  1414.                                  2=Sinclair 2 Left joystick (or user
  1415.                                    defined, for version 3 .Z80 files)
  1416.                                  3=Sinclair 2 Right joystick
  1417.  
  1418.     Because of compatibility, if byte 12 is 255, it has to be regarded as
  1419.     being 1.  Following this header block of 30 bytes the 48K bytes of
  1420.     Spectrum memory are stored, in a compressed format (if bit 5 of byte 12
  1421.     is set).
  1422.  
  1423.     The compression method is this.  Repetitions of at least five equal
  1424.     bytes are replaced by the four-byte code ED ED xx yy, which stands for
  1425.     "byte yy repeated xx times".  Only sequences of length at least 5 are
  1426.     coded. The exception is sequences consisting of ED's; if they are
  1427.     encountered, even two ED's are encoded into ED ED 02 ED.  Finally,
  1428.     every byte directly following a single ED is not taken into a block,
  1429.     for example ED 6*00 is not encoded into ED ED ED 06 00 but into ED 00
  1430.     ED ED 05 00.  The block is terminated by an end marker, 00 ED ED 00.
  1431.  
  1432.     That's the format of .Z80 files as used by versions up to 1.45.
  1433.     Starting from version 2.0, a different format is used, since from then
  1434.     on also 128K snapshots had to be supported.  This new format is used
  1435.     for all snapshots (48K or 128K).
  1436.  
  1437.     Version 2.01 and 3.0x .Z80 files start with the same 30 byte header
  1438.     that old .Z80 files used.  Bit 4 and 5 of the flag byte (offset 12)
  1439.     have no meaning anymore, and the program counter (offset 6 and 7) are
  1440.     zero to signal a version 2.01 (or later) snapshot file.
  1441.  
  1442.     After the first 30 bytes, the additional header follows:
  1443.  
  1444.  
  1445.         Offset  Length  Description
  1446.  
  1447.       * 30      2       Length of additional header block (see below)
  1448.       * 32      2       Program counter
  1449.       * 34      1       Hardware mode (see below)
  1450.       * 35      1       If in SamRam mode, bitwise state of 74ls259.
  1451.                         For example, bit 6=1 after an OUT 31,13 (=2*6+1)
  1452.                         If in 128 mode, contains last OUT to 7ffd
  1453.       * 36      1       Contains 0FF if Interface I rom paged
  1454.       * 37      1       Bit 0: 1 if R register emulation on
  1455.                         Bit 1: 1 if LDIR emulation on
  1456.       * 38      1       Last OUT to fffd (soundchip register number)
  1457.       * 39      16      Contents of the sound chip registers
  1458.         55      2       Low T state counter
  1459.         57      1       Hi T state counter
  1460.         58      1       Flag byte used by Spectator (QL spec. emulator)
  1461.                         Ignored by Z80 when loading, zero when saving
  1462.         59      1       0FF if MGT Rom paged
  1463.         60      1       0FF if Multiface Rom paged. Should always be 0.
  1464.         61      1       0FF if 0-8191 is RAM
  1465.         62      1       0FF if 8192-16383 is RAM
  1466.         63      10      5x keyboard mappings for user defined joystick
  1467.                         (Default values: 0x0103,0x0203,0x0403,0x0803,0x1003)
  1468.         73      10      5x ascii word: keys corresponding to mappings above
  1469.                         (Default values: 0x0031,0x0032,0x0033,0x0034,0x0035)
  1470.         83      1       MGT type: 0=Disciple+Epson,1=Discipls+HP,16=Plus D
  1471.         84      1       Disciple inhibit button status: 0=out, 0ff=in
  1472.         85      1       Disciple inhibit flag: 0=rom pageable, 0ff=not
  1473.  
  1474.  
  1475.     The value of the word at position 30 is 23 for version 2.01 files, and
  1476.     54 for version 3.0x files.  The starred fields are the ones that
  1477.     constitute the version 2.01 header, and their interpretation has
  1478.     remained unchanged except for offset 34 (Hardware mode):
  1479.  
  1480.         Value:          Meaning in v2.01        Meaning in v3.0x
  1481.  
  1482.         0               48k                     48k
  1483.         1               48k + If.1              48k + If.1
  1484.         2               SamRam                  SamRam
  1485.         3               128k                    48k + M.G.T.
  1486.         4               128k + If.1             128k
  1487.         5               -                       128k + If.1
  1488.         6               -                       128k + M.G.T.
  1489.  
  1490.     The hi T state counter counts up modulo 4.  Just after the ULA
  1491.     generates its once-in-every-20-ms interrupt, it is 3, and is increased
  1492.     by one every 5 emulated milliseconds to take the values 0,1,2 and 3
  1493.     again respectively.  In these 1/200s intervals, the low T state counter
  1494.     counts down from 17471 to 0 inclusive (or 17726 to 0 in 128K modes),
  1495.     which make a total of 69888 T states (70908 T states) per frame.
  1496.  
  1497.     The 5 ascii words (high byte always 0) at 73-82 are the keys
  1498.     corresponding to the joystick directions left, right, down, up, fire
  1499.     respectively.  Shift, Symbol Shift, Enter and Space are denoted by
  1500.     [,],/,\ respectively.  The ascii values are used only to display the
  1501.     joystick keys; the information in the 5 keyboard mapping words
  1502.     determine which key is actually pressed (and should correspond to the
  1503.     ascii values).  The low byte is in the range 0-7 and determines the
  1504.     keyboard row.  The high byte is a mask byte and determines the column.
  1505.     Enter for example is stored as 0x0106 (row 6 and column 1) and 'g' as
  1506.     0x1001 (row 1 and column 4).  The default values correspond to the Left
  1507.     Sinclair Interface 2 joystick.
  1508.  
  1509.     Byte 60 must be zero, because the contents of the Multiface RAM is not
  1510.     saved in the snapshot file.  If the Multiface was paged when the
  1511.     snapshot was saved, the emulated program will most probably crash when
  1512.     loaded back.
  1513.  
  1514.     Bytes 61 and 62 are a function of the other flags, such as byte 34, 59,
  1515.     60 and 83.
  1516.  
  1517.     Hereafter a number of memory blocks follow, each containing the
  1518.     compressed data of a 16K block.  The compression is according to the
  1519.     old scheme, except for the end-marker, which is now absent.  The
  1520.     structure of a memory block is:
  1521.  
  1522.  
  1523.         Offset  Length  Description
  1524.  
  1525.         0       2       Length of data (without this 3-byte header)
  1526.         2       1       Page number of block
  1527.         3       [0]     Compressed data
  1528.  
  1529.  
  1530.     The pages are numbered, depending on the hardware mode, in the
  1531.     following way:
  1532.  
  1533.  
  1534.         Page    In '48 mode     In '128 mode    In SamRam mode
  1535.  
  1536.          0      48K rom         rom (basic)     48K rom
  1537.          1      Interface I, Disciple or Plus D rom, according to setting
  1538.          2      -               rom (reset)     samram rom (basic)
  1539.          3      -               page 0          samram rom (monitor,..)
  1540.          4      8000-bfff       page 1          Normal 8000-bfff
  1541.          5      c000-ffff       page 2          Normal c000-ffff
  1542.          6      -               page 3          Shadow 8000-bfff
  1543.          7      -               page 4          Shadow c000-ffff
  1544.          8      4000-7fff       page 5          4000-7fff
  1545.          9      -               page 6          -
  1546.         10      -               page 7          -
  1547.         11      Multiface rom   Multiface rom   -
  1548.  
  1549.  
  1550.     In 48K mode, pages 4,5 and 8 are saved.  In SamRam mode, pages 4 to 8
  1551.     are saved.  In '128 mode, all pages from 3 to 10 are saved.  This
  1552.     version saves the pages in numerical order.  There is no end marker.
  1553.  
  1554.     This concludes the specification of .Z80 files.  .SLT files (which
  1555.     stands for 'super level loader trap files') are like .Z80 files except
  1556.     that after the ordinary data another section follows, containing things
  1557.     like level data (previously stored in .DAT files, and giving .SLT files
  1558.     their name) or loading screens.  The ".Z80"-file preceding the SLT must
  1559.     conform the format of v2.01 or v3.0x files (long header).
  1560.  
  1561.     Though it is agreed that .Z80 files will not contain SLT data, and
  1562.     files with SLT data will always have extension .SLT, Z80 does in fact
  1563.     not distinguish between the extensions.
  1564.  
  1565.     The SLT format was cooked up by Damien Burke, James McKay and yours
  1566.     truly.  It starts as an ordinary >= v2.01 .Z80 file.  Directly
  1567.     following this comes a
  1568.  
  1569.  
  1570.         Offset  Length  Description
  1571.  
  1572.         0       6       Separator (0,0,0,'S','L','T')
  1573.  
  1574.  
  1575.     Then a table follows, each entry describing a piece of data.  The
  1576.     format of a single table entry is:
  1577.  
  1578.  
  1579.         Offset  Length  Description
  1580.  
  1581.         0       2       Data type: 1=level data, 3=loading screen
  1582.         2       2       Id word: Level number (between 0 and 255 inclusive)
  1583.                          for type 1, border colour (between 0 and 7) for
  1584.                          type 3.
  1585.         4       4       Length of data block in bytes (Note: long word)
  1586.  
  1587.  
  1588.     Data types other than type 1 and 3 are not supported by Z80 v3.04, and
  1589.     are ignored.  The table ends with an all-zero end marker:
  1590.  
  1591.  
  1592.         Offset  Length  Description
  1593.  
  1594.         0       8       End marker (all zeroes)
  1595.  
  1596.  
  1597.     Finally, the data blocks follow.  The blocks are stored in the order in
  1598.     which they appear in the table,  i.e. the offset of a particular data
  1599.     block is the sum of the lengths of the blocks that precede it.  The
  1600.     internal format of these blocks depend on the data type:
  1601.  
  1602.  
  1603.         Type:   Format:
  1604.  
  1605.         0       (no data)
  1606.         1       Compressed data (ED ED xx yy scheme, see above) expanding
  1607.                  to anything up to 48K
  1608.         3       Compressed data expanding to exactly 6912 bytes of data
  1609.  
  1610.  
  1611.     See the end of section 5.8 for an explanation how to load these blocks
  1612.     using the ED FB opcode, and error handling.
  1613.  
  1614.     All words in the format have the least significant byte first.
  1615.  
  1616.  
  1617.  
  1618.