include	clib.inc
include	stdio.inc
include	stdlib.inc
include	string.inc

	public	assert_out
	public	assert_exit

_DATA	SEGMENT

reg_ax	dw ?
reg_dx	dw ?
reg_bx	dw ?
reg_cx	dw ?
reg_cs	dw ?
reg_ip	dw ?
reg_ds	dw ?
reg_si	dw ?
reg_es	dw ?
reg_di	dw ?
reg_ss	dw ?
reg_sp	dw ?
reg_bp	dw ?
flags	dw ?

fbuf	db 256 dup(?)

failed	db "assert failed:",9,0
regs	db 13,10,13,10
	db '         regs:  AX: %04X DX: %04X',13,10
	db 9,9,	'BX: %04X CX: %04X',13,10
	db 9,9,	'CS: %04X IP: %04X',13,10
	db 9,9,	'DS: %04X SI: %04X',13,10
	db 9,9,	'ES: %04X DI: %04X',13,10
	db 9,9,	'SS: %04X SP: %04X',13,10
	db 9,9,	'BP: %04X ST: %04X',13,10
	db 13,10
	db 9,'flags:  %016lb',13,10
	db 9,'        r n oditsz a p c',0

format	db 13,10
	db 'Debug error',13,10
	db 'File: %s, line %2d, expression: (%s)',13,10
	db 0

_DATA	ENDS

_TEXT	SEGMENT

assert_out PROC FAR
	mov	[reg_ax],ax
	mov	[reg_dx],dx
	mov	[reg_bx],bx
	mov	[reg_cx],cx
	mov	[reg_es],es
	pop	ax
	pop	dx
	pop	cx
	mov	[reg_cs],dx
	mov	[reg_ip],cx
	push	ds
	push	offset fbuf
	push	dx
	push	ax
	call	strcpy
	mov	ax,offset fbuf
	call	@printf
	mov	ax,[reg_ax]
	mov	dx,[reg_dx]
	mov	bx,[reg_bx]
	mov	cx,[reg_cx]
	mov	es,[reg_es]
	push	[reg_cs]
	push	[reg_ip]
	ret
assert_out ENDP

assert_exit PROC DIST
	mov	ss:[reg_ds],ds
	push	ss
	pop	ds
	mov	[reg_ax],ax
	pushf
	pop	ax
	mov	[flags],ax
	mov	[reg_dx],dx
	mov	[reg_bx],bx
	mov	[reg_cx],cx
	mov	[reg_si],si
	mov	[reg_es],es
	mov	[reg_di],di
	mov	[reg_ss],ss
	mov	[reg_bp],bp
	pop	ax
	mov	[reg_ip],ax
  ifdef LPROG
	pop	dx
  else
	mov	dx,cs
  endif
	mov	[reg_cs],dx
	mov	[reg_sp],sp
	push	ds
	push	offset fbuf
	push	dx
	push	ax
	call	strcpy
	cld
	mov	ax,0B800h
	mov	es,ax
	mov     bh,0
	mov     ah,3
	int     10h
	mov	al,80*2
	mul	dh
	mov	di,ax
	mov	ax,0720h
	mov	cx,2*80
	rep	stosw
	mov	ax,offset failed
	call	@printf
	mov	ax,offset fbuf
	call	@printf
	push    [flags]
	push	offset _dsstack
	push	[reg_bp]
	push	[reg_sp]
	push	[reg_ss]
	push	[reg_di]
	push	[reg_es]
	push	[reg_si]
	push	[reg_ds]
	push	[reg_ip]
	push	[reg_cs]
	push	[reg_cx]
	push	[reg_bx]
	push	[reg_dx]
	push	[reg_ax]
	mov	ax,offset regs
	call	@printf
	push	1
	call	exit
	ret
assert_exit ENDP

_TEXT	ENDS

PPROC	debugmsg, file:DPTR, line:word, expression:DPTR, doexit:word
	MPUSH	word ptr expression+2
	push	word ptr expression
	push	line
	MPUSH	word ptr file+2
	push	word ptr file
	mov	ax,offset format
	call	@printf
	add	sp,2+DPTRZ+DPTRZ
	mov	ax,doexit
	test	ax,ax
	jz	DEBUGMSG_00
	push	ax
	call	exit
DEBUGMSG_00:
	ret
PEND	debugmsg

	END
