; CDPUSH.ASM--
;
; [Tools]
; 00=&Save current directory,cdpush
; 01=&Restore directory,%TEMP%\cdpop.bat
;
; Make: JWasm -mz cdpush.asm
;
	.model	small
	.stack
	.code
start:	jmp	around
_psp	dw	0
envlen	dw	0
cdpop	db	'cdpop.bat',0
@echo	db	'@echo off',13,10
drive	db	'A:'
crlf	db	13,10
	db	'CD\'
cd	db	80 dup(0)
temp	db	80 dup(0)

exit:	pop	dx
	push	ax
	mov	ah,9
	int	21h
	pop	ax
terminate:
	mov     ah,4Ch
	int     21h
abort:	mov	al,3
	call	exit
	db	'Abnormal program termination',13,10,'$'
getcwd:	push	si
	mov	si,offset cd
	xor	dx,dx
	mov	ah,47h
	int	21h
	mov	ax,0
	jc	getcwd_end
	mov	ax,si
    getcwd_end:
	or	ax,ax
	pop	si
	ret
write:	mov	bx,si
	mov	ax,4000h
	int	21h
	ret
strlen:	push	di
	push	ds
	pop	es
	mov	di,ax
	or	ax,ax
	jz	strlen_00
	xor	ax,ax
	cld
	mov	cx,-1
	repnz	scasb
	mov	ax,cx
	not	ax
	dec	ax
    strlen_00:
	pop	di
	ret
around:	mov	ax,offset abort
	push	ax
	xor	si,si
	mov	dx,ds
	mov	cs:_psp,dx
	mov	bp,[si+02h]
	sub	bp,dx
	mov	dx,cs
	mov	es,[si+2Ch]
	xor	ax,ax
	mov	bx,ax
	mov	di,ax
	mov	cx,7FFFh
	cld
    startup_envloop:
	cmp	word ptr es:[di],'ET'
	jne	startup_nextenv
	cmp	word ptr es:[di+2],'PM'
	jne	startup_nextenv
	cmp	byte ptr es:[di+4],'='
	je	startup_found
    startup_nextenv:
	repne	scasb
	inc	bx
	cmp	es:[di],al
	je	startup_fail
	or	cx,cx
	jnz	startup_envloop
    startup_fail:
	mov	ds,dx
	ret
    startup_found:
	push	es
	pop	ds
	mov	es,dx
	mov	si,di
	add	si,5
	mov	di,offset cd
    startup_loop:
	lodsb
	or	al,al
	jz	startup_break
	stosb
	jmp	startup_loop
    startup_break:
	mov	ds,dx
	mov	si,offset cdpop
	mov	al,'\'
	stosb
    startup_loop2:
	lodsb
	stosb
	or	al,al
	jnz	startup_loop2
	mov	dx,offset cd
	mov	ah,3Ch
	xor	cx,cx
	int	21h
	mov	si,ax
	jc	startup_fail
	mov	ah,19h
	int	21h
	add     drive,al
	mov	dx,offset @echo
	mov	cx,18
	call	write
	jc	oswrite_error
	call	getcwd
	mov	ax,offset cd
	call	strlen
	mov	cx,ax
	mov	dx,offset cd
	call	write
	jc	oswrite_error
	mov	dx,offset crlf
	mov	cx,2
	call	write
	jc	oswrite_error
	mov	bx,si
	mov	ah,3Eh
	int	21h
	xor	ax,ax
	jmp	terminate
    oswrite_error:
	mov	bx,si
	mov	ah,3Eh
	int	21h
	mov	al,1
	jmp	terminate
	end	start
