; sch.asm
bits 16
org 0x0100

start:
jmp install
oldofs dw 0
oldseg dw 0
currstack dw 0x0180

switch:
; push everything
push es
push ds
push ax
push bx
push cx
push dx
push si
push di
push bp

xor ax, ax
mov es, ax

; store current program
mov bx, [cs:currstack]
mov [es:bx], sp
mov [es:bx+2], ss

; find valid program
.loop:
; add and loop around
add bx, 4
cmp bx, 0x0194
jle .temp
mov bx, 0x0180

; check if valid
.temp:
mov sp, [es:bx]
test sp, sp
jnz .done
jmp .loop


; found valid program
.done:
mov [cs:currstack], bx
mov ss, [es:bx+2]

; pop everything
pop bp
pop di
pop si
pop dx
pop cx
pop bx
pop ax
pop ds
pop es

; jump to the program
jmp far [cs:oldofs]



install:
mov ax, 0x3508
int 0x21
mov [cs:oldofs], bx
mov [cs:oldseg], es

cli
xor ax, ax
mov es, ax

; setup main program
mov word [es:0x0180], sp
mov word [es:0x0182], cs

; remove garbage tsrs
mov bx, 0x0184
mov cx, 5
.loop:
mov word [es:bx], 0
add bx, 4
loop .loop

; set timer interrupt
mov word [es:0x20], switch
mov word [es:0x22], cs

; tsr
mov dx, (install - start + 0x0100 + 15) >> 4
mov ax, 0x3100

sti
int 0x21