home *** CD-ROM | disk | FTP | other *** search
/ Chip 1998 March / Chip_1998-03_cd.bin / hry / Sinclair / SimDOS2 / TECHINFO.DOC < prev    next >
Text File  |  1996-11-10  |  87KB  |  1,716 lines

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