%include "exebin.mac"
%include "util.mac"
%include "icedump.inc"
%include "vxdn.inc"


%define CRLF$ 13,10,'$'


bits 16


EXE_begin

section .text
	mov	dx,msgLoad
	mov	ah,9
	int	0x21

; locate VXDLDR V86 API
	xor	di,di
	mov	es,di
	mov	bx,VXDLDR_Device_ID
	mov	ax,0x1684
	int	0x2F

	push	es
	push	di
	pop	dword [vxdldr]

	mov	dx,msgNoVXDLDR
;	cmp	dword [vxdldr],byte 0
	mov	ax,es
	or	ax,di
	jz	.exit

; call VXDLDR_UnloadDevice
	mov	dx,icedump
	mov	bx,0xFFFF
	mov	ax,VXDLDR_APIFUNC_UNLOADDEVICE
	call	far [cs:vxdldr]

	mov	dx,msgNotLoaded
	jc	@F

	mov	dx,msgUnloadOK

@@

; exit if user requested unload only with 'u' on the command line
	cmp	byte [0x80],0
	jz	@F

	cmp	byte [0x82],'u'
	jz	.exit

	cmp	byte [0x82],'U'
	jz	.exit

@@
	mov	ah,9
	int	0x21

; find out our own file name
	mov	es,[0x2C]		; PSP:env
	cld
	xor	di,di
	xor	al,al
	mov	cx,0xFFFF

@@
	repnz	scasb
	scasb
	jne	@B

; call VXDLDR_LoadDevice
	mov	ds,[0x2C]		; PSP:env
	lea	dx,[di+2]
	mov	ax,VXDLDR_APIFUNC_LOADDEVICE
	call	far [cs:vxdldr]

	mov	ax,cs
	mov	ds,ax
	mov	dx,msgLoadFailed
	jc	.exit

	mov	dx,msgLoadOK

.exit:
	mov	ah,9
	int	0x21

	mov	ax,0x4C00
	int	0x21

section .data
msgLoad:		db 'icedump v',ICEDUMP_VERSION_ASCII,' for winice v',WINICE_VERSION_ASCII,' loader',CRLF$
msgNoVXDLDR:		db 'no VXDLDR services',CRLF$
msgUnloadOK:		db 'icedump unloaded',CRLF$
msgNotLoaded:		db 'icedump was not loaded yet',CRLF$
msgLoadFailed:		db 'VXDLDR failed to load icedump',CRLF$
msgLoadOK:		db 'icedump loaded',CRLF$
icedump:		db ICEDUMP_DEVICE_NAME,0

	align 4, db 0
vxdldr:	dd 0

EXE_end
