Analysis model: gpt-5.5 xhigh, sol high

Last edited: 2026-08-25

# Mental Surgery by Future Crew - Technical Dissection

## Scope

This is a source-to-binary and direct-runtime pass over **Mental Surgery** by
Future Crew, released in 1991 for MS-DOS. The production is one real-mode
executable plus one data file, and the STMIK020 package preserves the demo's
assembly source as its example program. The important result is not merely a
list of effects: the source and restored release agree through every visible
demo routine, so the complete frame hand-off can be followed from retrace and
CRTC panning through strip generation, text lifetime, equalizer repair, star
erase/update, and final plotting.

Public references:

- Pouet production: https://www.pouet.net/prod.php?which=1280
- Demozoo production: https://demozoo.org/productions/68757/
- Scene.org executable archive: https://files.scene.org/view/demos/groups/future_crew/demos/mental_s.zip
- Scene.org STMIK020/source package: https://files.scene.org/view/demos/groups/future_crew/code/stmik020.zip
- Hornet mirror archive used for this binary pass: https://files.scene.org/get/mirrors/hornet/demos/1991/mental_s.zip

Demozoo lists the release date as 2 July 1991 and Pouet lists July 1991. The
demo source and runtime text say it uses the Scream Tracker Music Interface Kit
V0.2 (`STMIK020`) and targets an AT-class PC with VGA and optional Sound
Blaster output. Historical contact details present in the scrolltext and STMIK
documentation are intentionally not reproduced here.

## Examined Files

The Hornet mirror archive used for the executable/resource inspection was:

```text
44a9d94caf44ced04b2ddad206b0d7031f3ab0ec9f434144e797266c190a3f4f  mental_s.zip
```

It contains:

| File | Size | SHA-256 | Role |
| --- | ---: | --- | --- |
| `MENTAL.EXE` | 22,450 | `93b8339f839c970e9227f6980c1793875a5e2181f295794759911d4bbbd9a26c` | packed real-mode MZ executable |
| `MENTAL.FC` | 315,926 | `e3a3135b2deffcaa9c3886dd7366fd6a034648bf1d7f4c4ca1ddc622ee831811` | bitmaps, module, and UFF font data |
| `DEMOSITE.COM` | 1,104 | `ae4377ea5ad7ace3149992f111f8384a81a71b1d658cd2fe453291ab14b26d6f` | distribution text screen |

The source package used for source-level cross-checking was:

```text
d43b1ad830bdf502a4947b26a04bf2577b3c142981a24c15673bbaccf033704a  stmik020.zip
```

Relevant source files:

| Source | Role |
| --- | --- |
| `main.asm` | program variables, setup prompts, file split, STMIK calls, top-level loop |
| `init.asm` | VGA setup, CRTC/attribute-controller programming, timer/keyboard interrupts, bitmap upload |
| `demo.asm` | per-frame order, upper scroller, palette rotation, lower writer, logo fade, equalizer, starfield |
| `grap.asm` | Mode X pixel plot/read, starfield-aware wrappers, UFF compositor, and an unused line drawer |
| `misc.asm` | random generator, vblank wait, palette fades, raster-line estimate, file loader |
| `text.asm` | upper/lower text streams and text-control byte conventions |

The `MENTAL.FC` file in the STMIK source package is byte-identical to the one
in the Hornet archive. Its packaged `MENTAL.EXE` is a 22,354-byte sibling build
(`f960e02d1aaae74b4464de93a5d8a817f08faea991d3087d9a6725a6331fb2ca`).
UNP restores that sibling to 50,896 bytes. More importantly, its load image and
the restored public release are byte-identical from `0000h` through `4B23h`.
The first difference is at `4B24h`, inside the separately linked STMIK body;
all demo code, data labels, setup, and visible-effect routines end before that
boundary. The source is therefore exact evidence for the released visual path,
while STMIK implementation details remain build-specific.

## Direct Muted Runtime And Pixel Ownership

![Mental Surgery frame machinery](images/mental-surgery-runtime-frame-machinery.gif)

This three-second direct DOSBox-X capture shows the live machinery discussed
below: the upper glyph strip moves through CRTC start-address and pel-panning
changes, the blue points are records updated by `starfield2`, and the center
bottom bars are the delayed STMIK values drawn by `equs`. These are not three
screens from different parts and the title is not a static illustration; all
three loops own pixels in the same steady-state frame.

![Mental Surgery scroller, stars, and bars](images/mental-surgery-runtime-scroller-stars-bars.png)

The still is capture-stream time `00:30.000` from that same run, where time zero
is the first recorded tweaked-VGA frame after the setup screen changed modes.
The public release ran in DOSBox-X 2024.03.01, `svga_s3`, fixed 12,000 cycles,
16 MiB, emulated Sound Blaster 2 at `220h`/IRQ 7/DMA 1, with the mixer set to
`nosound=true` and MIDI disabled. Setup answers were fast machine `Y`, alternate
scroll workaround `N`, Sound Blaster `Y`, default `220h`, IRQ `7`. The hardware
music/equalizer route therefore executed, but no host playback was produced or
auditioned; every published derivative used `-an` and contains no audio. The
GIF covers stream times `00:29.000` to
`00:32.000`; the GIF and still are video-only derivatives.

## Packed Executable

The distributed `MENTAL.EXE` is an MZ executable with a small packed image:

```text
packed file size:       22,450 bytes
MZ header size:            512 bytes
declared load image:    21,938 bytes
entry point:           0545:0010
relocations:                 0
```

The entry stub is a familiar early-DOS executable compressor shape. It first
copies its own packed image upward with the direction flag set, then far-returns
into the moved decompressor. The stream format is only two block types:

```text
command B0/B1: read one byte and repeat it CX times
command B2/B3: copy CX literal bytes
low command bit set: this was the last block
```

After the stream ends, the stub applies a relocation-like table, rebuilds the
original stack, and jumps into the unpacked program. If an unknown token is
seen, it prints a short corrupt-file message and exits through DOS. Restoring
with UNP produced a normal MZ image:

```text
restored file size:     50,976 bytes
header size:                64 bytes
load image:             50,912 bytes
relocations:                 8
entry point:           0000:0000
```

The restored file hashes as
`e45ae168aff7d9c17f6176a64892f4f37c05952d2ae5e51add3977038a2a2691`.
Its eight relocation records and 64-byte header are part of that file; all
restored offsets below are offsets in the 50,912-byte load image after the
header.

The restored load image begins with a near jump to the real startup code. The
source package makes the labels clear: the entry is `main`, and the included
files are assembled into one code segment.

## Resource Layout

The demo does not carry separate asset filenames after startup. It loads
`MENTAL.FC` as one contiguous memory block, skips its first four paragraphs
(the 64-byte `Data file for MENTAL SURGERY from the Future Crew!` header), then
treats fixed offsets as segments:

```text
loaded_segment + 4      -> bm1seg
+ 4000 paragraphs       -> bm2seg
+ 4000 paragraphs       -> bm3seg
+ 4000 paragraphs       -> moduleseg
+ 6828 paragraphs       -> fontseg
```

The source literals `4000` and `6828` are decimal paragraph counts. Against
the authenticated 315,926-byte file, the half-open ranges are:

| Resource | File offset | Length |
| --- | ---: | ---: |
| ASCII prefix | `00000h` | 64 bytes |
| bitmap 1 | `00040h` | 64,000 bytes |
| bitmap 2 | `0FA40h` | 64,000 bytes |
| bitmap 3 | `1F440h` | 64,000 bytes |
| STX/module allocation | `2EE40h` | 109,248 bytes |
| UFF font | `49900h` | 14,614 bytes |

Those numbers are in paragraphs, so each bitmap segment is 64,000 bytes. This
matches the graphics mode: each source bitmap is stored as 320 bytes per row,
then uploaded into a planar virtual screen with a 1280-pixel pitch. The module
starts at a segment boundary because STMIK's play call requires a segment-only
far pointer to an STX module. The UFF font starts after the module block and is
consumed by the font routines in `grap.asm`.

The loader in `misc.asm` is a segment-aware DOS file loader:

1. Open the file with `int 21h AH=3Dh`.
2. Seek to end with `AH=42h` to get the length.
3. Convert bytes to paragraphs by shifting the 32-bit `DX:AX` size right four
   times.
4. Allocate DOS memory with `AH=48h`, respecting a caller-supplied minimum.
5. Seek back to the beginning.
6. Read in 32 KB chunks, advancing `DS` by `0800h` paragraphs after each full
   chunk.
7. Close the handle and return the segment in `DX`.

The inner chunk loop is exactly the old real-mode trick:

```text
DS = allocated_segment
repeat:
    read 32768 bytes to DS:0000
    DS += 0800h
until fewer than 32768 bytes were returned
```

No offset arithmetic is needed while reading. Every full transfer lands at the
start of the next 32 KB window.

## Startup And Setup

`main` starts by resizing the program memory block to 128 KB, then asks three
runtime questions:

| Question | Stored effect |
| --- | --- |
| Is the machine 12 MHz or faster? | if no: reduce `stars` from 32 to 16 and disable the equalizer |
| Have smooth-scroll demos caused problems? | if yes: set `alternatescroll`, which advances the scroller by four pixels on every frame |
| Use Sound Blaster? | if no: set `nosbc` and keep 32 stars because no mixer work is needed |

If sound is enabled, setup accepts a Sound Blaster base address from `210h` to
`260h` in 16-byte steps:

```text
io = 0200h + typed_digit * 0010h
```

The IRQ prompt text says 2, 3, 5, or 7, but the code path accepts characters
`1`, `3`, `5`, and `7`. The same convention appears in the included STMIK
player example, so this is not a disassembler error; it is how this package
expects the low IRQ option to be typed.

The top-level runtime order is:

```text
resize PSP block
ask setup questions
load MENTAL.FC
split data into bitmap/module/font segments
initialize STMIK if sound is enabled
ask STMIK for the equalizer-info pointer
fade off the default palette
hook keyboard interrupt
set tweaked VGA mode
copy bitmap data to planar VRAM
hook timer interrupt
run one frame to initialize windows
fade on the demo palette
enable STMIK polling mode
start the STX module
poll STMIK once explicitly
loop:
    run one demo frame
    process +, -, ESC
stop module, restore interrupts/video, print end page
```

The `+` and `-` keys adjust `drunkenstars`, the multiplier used by the moving
starfield origin. ESC exits.

Two apparent paths do no visual work. `demobackground` at restored `3187h`
returns immediately before its old latch-copy body, and every `setborder`
annotation in `demo.asm` expands to nothing because the active macro body is
commented out. Neither should be counted as a background compositor or a live
border profiler.

## STMIK Use

The demo owns the timer interrupt, so it does not let the music player steal
timer time automatically. Instead it switches STMIK into polling mode and calls
the poll function once per frame:

| AX | Demo use |
| ---: | --- |
| `0` | initialize Sound Blaster mode with `BL=1`, `BH=irq`, `CX=io`, `DX=mix_speed` |
| `5` | get far pointer to note/equalizer data |
| `3` | set polling mode, with `BX=1` |
| `1` | start the module at `moduleseg:0000` |
| `4` | poll/mix audio during every frame |
| `2` | stop the module on exit |

The mix speed variable is `musicq = 16384`, close to the 16 kHz example in the
STMIK documentation. The equalizer routine later reads the far pointer returned
by function 5, copies delayed note-level bytes into a local ring, decays the
player's values by two, and draws bars from the delayed copy.

## Tweaked VGA Mode

`initvideo` starts from BIOS mode 13h, but only as a convenient VGA reset. It
then reprograms VGA into a planar/tweaked 256-color mode:

```text
Sequencer 04h = 06h       unchain / disable normal chain-4 layout
Attribute 10h = 61h       graphics/256-color style mode bits
Attribute 11h = 00h       border/overscan
CRTC table               custom timings and 1280-pixel virtual pitch
Sequencer 02h = 0Fh       enable all four planes for clearing
```

The source comment describes the target as a `1280x200x256` virtual screen
with a `320x200` visible window and a `320x64` subwindow. The practical layout
is:

- One byte in a plane covers four horizontal pixels.
- One virtual scanline is `1280 / 4 = 320` bytes per plane.
- The row table stores `rows[y] = y * 320`.
- CRTC register `13h=A0h` selects that 320-byte pitch.
- CRTC register `09h=80h` enables double-scan, while line compare register
  `18h=7Fh` splits after physical scanline 127, hence after logical row 63.

At that split the VGA resets the display address to zero and clears horizontal
pel panning. The visible ownership is exact:

| Visible logical rows | Address source | Storage rows |
| --- | --- | --- |
| `0..63` | `AA00h + (winxpos >> 2)`, pel-panned | `136..199` |
| `64..199` | fixed address zero after line compare | `0..135` |

The old article called this a natural VRAM wrap. It is an explicit hardware
split: only the upper 64 logical rows move, while the lower 136 remain fixed.
The scroller's software work updates the hidden ring behind the moving upper
window rather than redrawing a 320x64 viewport.

`copybitmaps` uploads three 320-byte-per-row source bitmaps into planar VRAM:

| Source | Destination byte offset | Rows |
| --- | ---: | ---: |
| `bm1seg` | `320/4` | 136 |
| `bm2seg` | `640/4` | 136 |
| `bm3seg` | `960/4` | 200 |

Those byte offsets are chunky x positions 320, 640, and 960. Thus storage
x=0..319/rows 0..135 is the fixed lower display and its dynamic overlays;
hidden x=320, 640, and 960 retain source imagery. The upper scroll ring uses
storage rows 136..199 across x=320..959, with its seam copy reaching x=0..319.

The upload loop writes four planes separately. Each plane does 80 bytes per
row, uses the sequencer map mask (`1`, `2`, `4`, `8`), and skips source bytes
`>= FEh` as transparent holes:

```text
for each row:
    for plane in 1,2,4,8:
        set VGA map mask to plane
        repeat 80 times:
            al = *source
            if al < FEh: *vram = al
            else:        advance vram only
            source += 4
    source += 320
    dest   += 320
```

`LODSB` supplies the first increment and `ADD SI,3` supplies the other three;
the old version of this article incorrectly summarized that as a three-byte
stride. The four plane passes restore the row-start pointer and then begin one
byte apart, so they consume source positions `0,4,8...`, `1,5,9...`,
`2,6,10...`, and `3,7,11...`. This is a 320-byte chunky row being transposed
into four 80-byte planar rows, with `FEh` and `FFh` leaving the cleared
destination unchanged.

## Pixel Ownership And The Unused Line Kernel

`grap.asm` contains a general `line` / `lineto` rasterizer, but no production
routine calls it. Its only `psetc` calls are inside the line routine itself.
Consequently no visible line, large title, bar, or star in the runtime media is
evidence for Bresenham rendering. The live callers use the pixel wrappers and
UFF compositors described here; the line code is reusable library material
shipped beside the demo.

The core pixel writer in `grap.asm` is the standard Mode X formula:

```text
byte_offset = rows[y] + (x >> 2)
plane_mask  = 1 << (x & 3)
Sequencer index 2 = plane_mask
ES:[byte_offset] = color
```

The read path is the same address math, but it programs Graphics Controller
index 4 to select the read plane:

```text
read_plane = x & 3
GC index 4 = read_plane
color = ES:[rows[y] + (x >> 2)]
```

The starfield uses four wrappers around those routines. They remap the complete
200-line logical starfield around the hardware split:

```text
if y < 64:
    y += 136
    x += current_or_previous_winxpos
else:
    y -= 64
```

There are current-window and previous-window variants. The previous-window
variants erase stars at the position where they were drawn before the hardware
window moved; the current-window variants read and plot in the new frame.
In the public restore the chain is `pset=2651h`, `pget=2672h`,
`spset=2690h`, `spget=26A4h`, `ospset=26B8h`, and `ospget=26CCh`.

The retained, unreachable line routine is a compact fixed-point Bresenham
variant. It stores the current endpoint as `gcurx/gcury`, computes signed
deltas and absolute values,
chooses the dominant axis, and uses a 16-bit fractional accumulator initialized
to `32767`. For an x-major line:

```text
low_add = (yabs << 16) / xabs, low word only
for xabs + 1 pixels:
    plot(x, y)
    x += xsgn
    accumulator += low_add
    if carry: y += ysgn
```

For a y-major line, x and y swap roles. The division gives the fractional
increment, while carry from `add ax,si` decides when the minor axis steps.

## Per-Frame Order

The demo frame is deliberately ordered around display timing:

```text
wait until vertical retrace is active
scrollborder       ; hardware pel panning
canner             ; DAC upload + palette rotation
STMIK poll         ; mix one audio slice
scroll             ; draw new scroller strip and set CRTC start
enable keyboard IRQ
logofader          ; optional center logo wipe
writer             ; lower text compositor
equs               ; Sound Blaster note/equalizer bars, if enabled
starfield          ; two-pass moving starfield
disable keyboard IRQ
```

The restored public load image makes this more than a source-only schedule:

| Restored offset | Source label | Frame ownership |
| ---: | --- | --- |
| `3152h` | `demoframe` | retrace gate and complete call order |
| `3650h` | `scrollborder` | Attribute Controller pel pan |
| `3815h` | `canner` | 64-entry DAC upload and periodic rotation |
| `3669h` | `scroll` | new 64-row strip plus CRTC start address |
| `3FDEh` | `logofader` | paired latch-copy columns |
| `3E7Ch` | `writer` | lower-text parser, draw queue, and erase queue |
| `44C1h` | `equs` | 16-slot note-delay ring and bar repair |
| `3330h` | `starfield` | moving center and raster-split dispatcher |
| `33C8h` | `starfield2` | respawn, old-window erase, movement, occupancy test, plot |

At `3152h` the actual release instructions call those same offsets in that
same order. The only invisible call in the middle is STMIK's far entry at
`04A0:000F`; source function 4 is the per-frame poll. The frame is therefore a
single shared-VRAM schedule, not independent effect pages later composited by
an unseen backbuffer.

```asm
demoframe:
dwait:  mov  dx,3DAh
        in   al,dx
        test al,8
        jz   dwait
        call scrollborder
        call canner
        mov  ax,4
        call stmik_asm
        call scroll
        call enablekeyboard
        call logofader
        call writer
        cmp  cs:equson,0
        je   noequs
        call equs
noequs: call starfield
        call disablekeyboard
        ret
```

The keyboard is only briefly enabled around the part of the frame where the
program wants BIOS key handling to proceed. The custom IRQ1 handler consumes
all keys except ESC and the keypad plus/minus scancodes, and the frame code also
masks/unmasks PIC IRQ1 directly through port `21h`. The source comment says the
point is to prevent overactive keyboard input from disturbing the demo.

## Steady-Frame Work Ledger

The call order also gives a useful accounting boundary. The figures below are
CPU-visible byte accesses or explicit loop iterations, not guesses at VGA bus
cycles. A write-mode-1 byte transfer moves four latched plane pixels, while an
equalizer byte write has only planes 0..2 enabled. Counts are for the fast,
Sound-Blaster-enabled configuration used in the direct run: 32 stars and an
active equalizer.

| Stage | Exact fixed work | Conditional or periodic work |
| --- | --- | --- |
| upper hardware scroll | one pel-pan update and two CRTC start-address register writes every frame | none |
| upper strip producer, normal mode | over its exact 640-frame ring: 480 strips, 30,720 VRAM source reads, and 30,720 primary VRAM writes | 240 seam strips add 15,360 companion writes; averages are 48 reads and 72 writes per frame |
| upper strip producer, alternate mode | over its 160-frame ring: 160 strips, 10,240 reads, and 10,240 primary writes | 80 seam strips add 5,120 writes; averages are 64 reads and 96 writes per frame |
| palette pump | 192 palette-table reads and 192 DAC data-port writes every frame | every eighth frame, the table rotation adds 192 RAM reads and 192 RAM writes |
| lower writer | called every frame but returns immediately on alternating calls | an active call advances both history cursors, may parse one stream byte, may draw one glyph, and may erase the glyph 208 active calls behind it |
| logo wipe | no VRAM traffic while dormant | each active column does 32 latch reads and 32 writes; a complete repeating sweep does 2,528 of each |
| equalizer | 60 player reads, 60 delay-ring writes, 60 player decay writes, 40 delayed reads, and 40 previous-height reads | zero to 2,520 direct VRAM byte writes, plus up to 40 previous-height writes |
| starfield | 64 record visits, 32 complete star updates, 32 old-pixel reads, 64 movement multiplies, and two center multiplies | up to 32 current-pixel reads, 32 ownership clears, 32 plots, and five PRNG calls per respawn |

The scroller totals are full state cycles starting from the source initializer
`winxpos=16`, `srcount=0`. Normal movement is relatively prime to the 640-pixel
ring, so all 640 positions occur once; exactly half of the generated strips
land in the wrapped half and need the companion write. Alternate movement steps
by four, returning after 160 frames, with the same half-ring proportion. This
is why the high-level phrase "three strips every four frames" understates the
implementation: it is a deterministic producer/consumer cycle with a precisely
bounded seam cost.

STMIK's function-4 poll remains outside this ledger because its mixer body is
the one build-specific region after the source/release concordance boundary.
The table therefore measures the visible demo-owned work without pretending
that the linked audio implementation is identical between the two executables.

## Timer And Raster Estimate

`setints` hooks IRQ0, saves the old vector, then calibrates the timer by
programming PIT channel 0 and measuring the count over one vblank interval. The
computed values are stored as `frametime` and `frametimeb`. The new timer
interrupt does very little:

```text
raw_elapsed = -latched_counter
frametime   = raw_elapsed >> 1
frametimeb  = 2 * (frametime - high_byte(frametime))
```

```text
push AX
enable interrupts
call demointti        ; currently only preserves/restores ES
disable interrupts
send PIC EOI
wait for border/vblank edge
reload PIT from frametimeb
pop AX
iret
```

`getrasterline` then estimates the current scanline from the current PIT count:

```text
latch PIT counter 0
remaining = counter >> 1
elapsed = frametime - remaining
scanline = elapsed * 400 / frametime
```

The starfield uses this estimate to split its drawing work. It runs one pass,
waits until the estimated scanline is at least 160, then runs the second pass.

`waitborder` waits for a complete inactive-to-active retrace edge; the start of
`demoframe` merely waits until bit 3 is active. IRQ0 never chains the saved BIOS
timer handler, so BIOS/DOS clock ticks are lost while the demo owns the timer
and are not compensated on exit. The interrupt's `demointti` call is also an
effective no-op (`push es; pop es; ret`); the useful IRQ work is EOI, retrace
edge synchronization, and PIT reload.

## Upper Smooth Scroller

The upper scroller is the most important VGA trick in the demo. It combines
three movements:

1. Attribute Controller horizontal pel panning for the low two bits of `winxpos`.
2. CRTC start-address movement for the byte part of `winxpos`.
3. A one-strip software update when enough fractional movement has accumulated.

`scrollborder` runs during the border/retrace window and writes Attribute
Controller index `13h`:

```text
pel_pan = (winxpos & 3) << 1
AC[13h] = pel_pan
```

`scroll` advances the logical position:

```text
owinxpos = winxpos
winxpos += 3
if alternatescroll:
    srcount += 1
    winxpos += 1
srcount += 3
if winxpos >= 640:
    winxpos -= 640
```

The wrap constant is `1280 - 640`, because the virtual row is 1280 pixels and
the visible panning range uses a 640-pixel span. In normal mode the scroller
advances three pixels per frame. In alternate mode it advances four pixels per
frame and changes `srcount` accordingly.

Only when `srcount >= 4` does the demo generate a new vertical strip:

```text
if srcount >= 4:
    srcount -= 4
    enter VGA latch-transfer mode
    enable all four planes
    draw one new 64-row strip from the font sheet
    leave latch-transfer mode
```

The strip generator is a macro over a single source/destination operation. It
maintains:

| Variable | Meaning |
| --- | --- |
| `chartpos` | index into the upper scroll text |
| `charbodypos` | byte offset of the active glyph body inside the bitmap sheet |
| `charpos` | current four-pixel source column inside that glyph |
| `charwidth` | glyph width divided by four |

When `charpos` reaches `charwidth`, the macro fetches the next character. The
font table maps characters to `(source_offset, width)`. For every generated
strip it copies one byte per row for 64 rows:

```text
for y in 0..63:
    read ES:[source_column + y * 320]       ; load all four VGA latches
    write ES:[dest_column + y * 320]       ; copy four pixels in write mode 1
    optional duplicate to the wrapped companion column
```

The width words in `fontpos` are source-pixel widths such as 48 or 64, but the
macro shifts them right twice before comparing with `charpos`; each software
update therefore publishes one four-pixel strip. In normal mode `srcount`
produces the repeating update cadence `0,1,1,1` over four frames: three
four-pixel strips exactly match twelve pixels of hardware movement. Alternate
mode generates one strip every frame for four-pixel movement.

The longer cycles expose the exact cost. Starting from `winxpos=16` and
`srcount=0`, normal mode returns after 640 frames and has generated 480 strips.
Those strips perform 30,720 latch-loading reads and 30,720 primary writes. Of
them, exactly 240 occur with `winxpos>=320`, adding 15,360 companion writes.
Alternate mode returns after 160 frames: 160 strips, 10,240 reads, 10,240
primary writes, and 5,120 companion writes on its 80 seam-side strips. Each
number counts CPU byte accesses; all four VGA planes participate in every
latch transfer.

The optional duplicate is selected when `winxpos >= 320`. It writes the same
latched four-pixel strip 160 bytes earlier, the planar-byte distance for the
other side of the 640-pixel ring. Thus the CRTC/pel-panned window can cross the
seam without exposing an uninitialized column. Finally the routine positions
the visible display:

```text
start = 136 * (1280 / 4) + (winxpos >> 2)
CRTC[0Ch] = high(start)
CRTC[0Dh] = low(start)
```

That is why the scroller is smooth: most frames are hardware movement; the CPU
only renders the newly exposed strip.

## Palette Animation

`canner` updates DAC entries 128 through 191 every frame. It sets DAC write
index `80h`, then writes 64 RGB triples from the in-memory `palette` table.
The loop is manually unrolled to output six bytes per iteration:

```text
DAC index = 128
repeat 32 times:
    out R; out G; out B
    out R; out G; out B
```

Every eighth frame it rotates the 64-color range by one RGB triple:

```text
save palette[128]
move palette[129..191] down one slot
store saved triple at palette[191]
printcadd = (printcadd - 1) & 63
```

The rotation's `REP MOVSW` copies 94 words and the following `MOVSB` copies the
189th byte. Including the saved first triple and its final restore, that
eighth-frame branch reads 192 RAM bytes and writes 192 RAM bytes. Across eight
frames, `canner` consequently performs 1,728 palette-table reads, 192
palette-table writes, and 1,536 DAC data writes. The DAC pump itself never
pauses while the in-memory ring is being rotated.

`printcadd` is the color phase used by the lower writer's colored font path.
So the DAC rotation and the text color cycling are tied together: the palette
physically moves, and newly drawn text also shifts its palette index.

The fade routines in `misc.asm` are separate. They build a temporary palette
by subtracting a fade offset from each component, clamp underflow to zero, and
upload the 768 DAC bytes in two vblank-synchronized halves. `fadeoffpalette`
walks the offset upward; `fadeonpalette` walks it downward.

## Lower Writer

The current clean runtime capture ends before this scripted layer begins, so no
scroller or logo frame is presented here as visual evidence for it. This
section is bounded to the authenticated source and identical restored code.

The lower text stream is not just a byte string. `text.asm` defines control
bytes:

| Byte | Meaning |
| ---: | --- |
| `0` | restart from the initialized lower-text position |
| `1` | reset text position and wait for old characters to clear |
| `2` | center the following line up to carriage return |
| `3` | wait until the upper scroller has set the marker |
| `10` | move one line upward |
| `13` | move one line downward and reset x |

`writer` runs only every other frame. On each active call it may consume one
text/control byte, then it advances both history cursors and may erase one old
character. The storage is three parallel 512-byte arrays: 256 words for x, 256
words for y, and a byte array addressed only at even offsets for character
codes:

```text
wrcx[write_index] = x
wrcy[write_index] = y
wrcc[write_index] = character
draw character
write_index = (write_index + 2) & 511

old = read_index
erase wrcx/wrcy/wrcc[old] if present
read_index = (read_index + 2) & 511
```

The write index starts at zero and the erase index at 96 bytes. Because both
advance by two modulo 512, a glyph written at slot zero is revisited by the
erase cursor after `(512 - 96) / 2 = 208` active writer calls, or 416 normal
demo frames. `printclr` then walks that glyph's own non-`FFh` mask, so cleanup
is glyph-shaped rather than a rectangle or whole-page clear. Control bytes
still advance the two cursors, preserving elapsed-time spacing even when no
new glyph was drawn.

The waits are also temporal state rather than blocking loops. Control byte 1
loads `wrwait=256`, which is decremented only on active writer calls. Control
byte 3 alternates the sentinel values 30001 and 30000 until the upper scroller
sets `wrmark`; the next active call clears that marker and resumes consumption.
The lower script and upper strip generator therefore rendezvous through one
byte without stopping the rest of the frame.

Centering uses the font metrics directly. When byte `2` is seen, the routine
walks forward until carriage return, sums `getfontwidth` for each character,
then sets:

```text
wrx = (314 - summed_width) / 2
```

The value 314 leaves side margins inside the 320-pixel visible width.

## UFF Font Compositor

The font begins at `MENTAL.FC+49900h`, identifies itself as `UFF100`, and has an
18-pixel height. The UFF routines draw variable-width glyphs directly to planar
VRAM. The font segment has:

- a height word at offset `12`,
- a table of glyph segment offsets at `16 + char * 2`,
- a width table at `16 + 512 + char`,
- glyph byte streams in separate paragraph-relative chunks.

The compositor computes the starting byte and starting plane from x:

```text
screen_byte = rows[y] + (x >> 2)
start_plane = x & 3
```

Then each row cycles plane masks `1,2,4,8`, loading one glyph byte per pixel.
Byte `FFh` means transparent. After plane 8, it increments the screen byte:

```text
for each glyph row:
    plane = start_plane
    for each pixel column:
        set map mask for plane
        al = next glyph byte
        if al != FFh:
            write transformed al to ES:[screen_byte]
        advance plane
        if plane wrapped after 8:
            screen_byte += 1
```

There are three variants:

| Routine | Use |
| --- | --- |
| `printc2` | copy glyph byte as-is, transparent on `FFh` |
| `printc` | `(source + printcadd) & BFh`, transparent on `FFh` |
| `printclr` | write zero wherever the glyph byte is not `FFh` |

They are present unchanged in the public restore at `printc2=27F0h`,
`printc=289Ch`, and `printclr=2966h`.

The lower writer chooses `printc2` for lowercase-or-above character codes and
`printc` for the rest. Uppercase source pixels are in the `80h..8Ah` family and
therefore participate in the 64-phase palette range. Lowercase `b`, `w`, and
`y` are special solid-color glyphs used by `text.asm` to build the Finnish-flag
sequences; they carry source indices 6, 112, and 250 through `printc2` without
palette-phase addition.

`printclr` does not restore saved background pixels. It writes color zero
through the same opaque glyph mask. This is safe because the lower writer owns
a black fixed-display region and the starfield refuses to draw on nonzero
pixels; there is no hidden background-save buffer behind the text.

## Logo Fader

![Mental Surgery center-logo latch wipe](images/mental-surgery-runtime-logo-wipe.gif)

At capture-stream `00:54.100..00:55.250`, the center band reveals the authored
`MENTAL SURGERY` bitmap. The metallic text crossing the top is still the
independent upper scroller; it is not part of the logo source.

![Future Crew center-logo latch wipe](images/mental-surgery-runtime-future-crew-wipe.gif)

At `01:10.600..01:11.750`, the same destination is replaced by the authored
script `Future Crew` bitmap. These video-only GIFs come from the same muted
Sound Blaster run as the main frame capture.

`logofader` is dormant until the upper scroller encounters marker byte 1 and
sets `oktofade`. Its nominal cycle is 1,076 idle frames followed by 79 active
column positions. In VGA write mode 1, the read loads all four plane latches
and the following write transfers those four pixels without a per-plane CPU
loop.

Each active frame copies 16 bytes downward with a stride of 640 bytes:

```text
bp = fadecount - 1076                 ; 1..79
for 16 even destination rows:
    latch-copy source[fadeyadd + bp + row*640]
             to destination[bp + row*640]
for 16 odd destination rows:
    latch-copy source[fadeyadd + 320 + 79 - bp + row*640]
             to destination[399 - bp + row*640]
```

The 640-byte step is two 320-byte planar scanlines. One loop therefore fills
even rows left-to-right while the other fills odd rows right-to-left. Because
line compare resets the lower display to storage row zero, destination rows
0..31 appear in the middle visible band at y=64..95. After the 79-position sweep the
routine swaps source bases `320*40+80` and `320*8+80`, resets the long delay,
and eventually reveals the other preloaded logo. This is a two-direction
latched column wipe over static bitmap sources, not generated logo geometry or
a general fader.

Each active frame therefore executes exactly 32 VRAM reads and 32 VRAM writes,
or 128 four-plane pixels in each direction. A repeating 79-column sweep totals
2,528 reads and 2,528 writes, representing 10,112 latched pixels. One reset-only
frame follows the active range, making the repeating period 1,156 frames:
1,076 dormant, 79 copying, and one source-swap/reset frame. There is one
cold-start exception. `fadecount` is initialized to 1,077, so the first sweep
begins at column 2 and performs 78 active frames (2,496 reads and writes);
subsequent sweeps begin at column 1 and use the complete count above.

## Equalizer Bars

The equalizer is disabled on slow-machine setup and when no Sound Blaster is in
use. When active, `equs` reads the STMIK note/equalizer structure:

1. Selects VGA planes with map mask `07h`.
2. Reads 60 bytes from the STMIK pointer.
3. Stores them in a 1024-byte delay ring.
4. Subtracts two from the player-side byte, clamping at zero.
5. Advances the delay pointer by 64 bytes.
6. Draws 40 vertical bars from delayed values.

The 1,024-byte ring is sixteen 64-byte blocks. A frame writes 60 bytes in the
current block, skips its four padding bytes, advances to the next block, and
reads entries 20..59 there. That next block was last written 15 frames ago, so
the on-screen values are exactly 15 frames old even though the source comment
rounds the player's lead to approximately 16 frames.

The draw loop compares the new delayed value to `equlast` for that bar. It
draws upward with increasing colors for the new height, then clears any old
excess above it:

```text
new = delayed_value >> 2
old = previous_value >> 2
draw new colored cells upward from baseline
clear old - new cells if the bar shrank
previous_value = delayed_value
```

The repair traffic is exactly `max(new_height, old_height)` writes per bar:
the loop redraws all `new_height` colored cells even when a bar grew, then adds
`old_height-new_height` zero writes only when it shrank. Both heights are bytes
shifted right by two, so each lies in `0..63`; across 40 bars the frame bound is
therefore 0..2,520 CPU VRAM byte writes. Map mask `07h` turns that upper bound
into 7,560 plane-pixel stores. Outside VRAM, every active call always performs
60 player-structure reads, 60 delay-ring writes, 60 writes that apply the
two-unit player-side decay, 40 delayed-ring reads, and 40 `equlast` reads. It
writes up to 40 new `equlast` bytes, skipping that store only when both raw
values are zero.

The comments note that the player data arrives early relative to the audible
music, so this routine deliberately delays it before drawing.

The baseline address is `20 + 133*320`. After the line-compare remap this is
visible y=197 and x=80. Forty consecutive planar byte positions cover x=80..239.
Map mask `07h` enables planes 0, 1, and 2 but not plane 3, so each position is a
three-pixel bar followed by a one-pixel gap. Growth writes colors beginning at
32 upward; shrinkage writes zero only over the old excess. Like the writer,
the bars repair their owned black region rather than restore saved pixels.

## Starfield

The starfield is the other important inner loop. The source calls the user
adjustable parameter `drunkenstars`, which is accurate: the star origin moves
on a sine/cosine path, so the stars expand from a wobbling center rather than a
fixed point.

The star records are split across arrays:

| Array | Meaning |
| --- | --- |
| `stx` | 16.16-style x fixed point, low word then integer word |
| `sty` | 16.16-style y fixed point, low word then integer word |
| `stm[0]` | current displayed color |
| `stm[1]` | target color / speed source |
| `stm[2]` | processed flag for this frame |
| `stm[3]` | unused padding |

At the start of each frame:

```text
center_x = 160 + high_word(sin(srot) * drunkenstars)
center_y = 100 + high_word(cos(srot) * drunkenstars)
wrapped_center_x = center_x - 32
wrapped_center_y = center_y - 36
srot = (srot + 1) & 255
clear processed flags for all stars
```

The source also stores `stox2=center_x-32` and `stoy2=center_y-36`, but no
instruction reads either value. They are dead leftovers, not an alternate
origin used by the split display.

New stars are generated only when the integer x word is `FFFFh`:

```text
x = (rand() & 127) + (rand() & 127) + 32
y = (rand() &  63) + (rand() &  63) + 36
target_color = C0h + (rand() & 0Fh)
current_color = DFh
```

Summing two random values biases spawn positions toward the center instead of a
flat rectangular distribution. Respawn replaces the integer x/y words and
colors but does not clear the low fractional words, so a recycled record keeps
its previous subpixel phase.

Before moving a live star, the routine reads through `ospget`, using the
previous upper-window x position. It clears to zero only when the old pixel is
in the star-owned `C0h..DFh` range. This matters because the hardware window
may have moved since the star was drawn, and it prevents star cleanup from
erasing title, logo, writer, or bar pixels.

The movement is fixed point and outward from the moving center:

```text
factor = (((BFh - target_color + 20h) & FFh) << 8) >> 2
x_fixed += (x_integer - center_x) * factor
y_fixed += (y_integer - center_y) * factor
```

Because `target_color` is `C0h..CFh`, the byte arithmetic wraps and produces
factors from `07C0h` down to `0400h`, approximately 0.0303 down to 0.0156 in
16.16 units. Lower target-color values therefore move faster. Each signed
integer distance is multiplied by that factor; `ADD` updates the fractional
word and `ADC` carries the signed high product into the integer word.

If a moved star leaves `0 <= x < 320` or `0 <= y <= 199`, its integer x is set
back to `FFFFh` and it will respawn on a later frame. If the target pixel in
the current scrolling window is not zero, the star is skipped for this frame.
Otherwise its current color decays by one until it reaches the target color,
and `spset` plots it in the current window:

```text
if current_color > target_color:
    current_color -= 1
plot current_color
```

The pass split is exact. With `bp=0`, `starfield2` handles only logical
`y>=70`. The dispatcher then waits until `getrasterline()>=160`; with `bp=1`,
the same loop handles only `y<70`. A processed byte in every star record is
cleared before pass 0 and set by the selected pass, preventing duplicate work.
After moving, `spget` reads through the current upper-window position and the
star is plotted only when that destination is zero. Erase and collision policy
therefore form a complete ownership loop: previous-window conditional clear,
fixed-point update, current-window occupancy test, then plot.

The default and observed configuration has 32 records; the slow-machine setup
changes the mutable `stars` word to 16. With 32, each frame first performs 32
processed-flag clears. Pass 0 visits all 32 records. Pass 1 visits all 32 again,
but immediately skips those claimed by pass 0 and fully updates the remainder.
The invariant is thus 64 record visits, 32 processed-flag sets, and exactly 32
complete ownership/update paths—not 64 star movements.

Every complete path does one previous-window `pget` and two signed movement
multiplications. In addition to the two multiplies used to move the center,
that is 66 signed multiplies per frame. An in-bounds result adds one
current-window `pget`; an owned old pixel adds one `pset` clear; an empty new
pixel adds one `pset` plot. The VGA-facing bound is consequently 32..64 byte
reads and 0..64 byte writes per frame. Each get also selects one Graphics
Controller read plane, and each set selects one Sequencer map mask. Respawn is
not free or uniformly distributed: every invalid record makes five calls to
`rand`—two for x, two for y, and one for color—before it rejoins the same
ownership path.

## Why It Feels Advanced For 1991

The effect set is not large by later PC demo standards, but the architecture is
careful:

- The screen is not treated as a flat mode-13h framebuffer. It is a tweaked
  planar VGA surface with a 1280-pixel virtual pitch.
- The main scroll is mostly hardware movement; the CPU only draws newly exposed
  columns.
- The big font renderer writes variable-width transparent glyphs directly into
  VGA planes.
- The starfield has correct old-window erasure, so it coexists with hardware
  scrolling.
- The music player is polled inside the frame loop because the demo has its
  own timer/raster timing.
- Palette rotation is integrated with the lower writer's color phase.
- Equalizer bars use STMIK's internal note data, delayed and decayed to look
  synchronized on screen.

In other words, the visual design is mostly scrollers, stars, text, logo wipes,
and bars, but the inner loops are already the vocabulary of later DOS demo
engines: virtual screens, CRTC address changes, pel panning, plane masks,
latched copies, timer hooks, and careful scheduling around retrace.
