;--------------------------------------------------------------------------------------
; CREATEMP.COM
;
; Create a temporary file, lseek, write
; 
; CAUTION: On an actual DOS install involving the FAT filesystem, the lseek+write will
;          reveal contents from previously deleted clusters. Unlike Windows NT or
;          Linux, DOS makes no attempt to zero clusters when it allocates them to
;          satisfy the lseek() request.
;--------------------------------------------------------------------------------------
		bits 16			; 16-bit real mode
		org 0x100		; DOS .COM executable starts at 0x100 in memory

		segment .text

		push	cs
		pop	ds

; form the temporary name "base": the path + \ + 13 zeros
		cld
		mov	di,filename
		mov	cx,16/2
		xor	ax,ax
		rep	stosw
		mov	byte [filename],0x2E	; <- form '.\' + 13 zeros to make temp file in current directory
		mov	byte [filename+1],0x5C

; do the file creation
do_mkdir:	mov	dx,filename	; DS:DX = name of dir to make
		mov	ah,0x5A		; AH=0x5A create temporary file
		mov	cx,0		; CX=file attributes
		int	21h
		jnc	mkdir_ok	; CF=1 if error

		mov	dx,str_fail
		jmp	short exit_err

mkdir_ok:	mov	[filehandle],ax	; save the file handle returned by DOS

		; show the file name
		mov	si,filename
		call	putsz
		mov	dx,crlf
		call	puts

		mov	ah,0x40		; AH=0x40 write to handle
		mov	bx,[filehandle]
		mov	cx,str_msg_len
		mov	dx,str_msg
		int	21h

		mov	ax,0x4201	; AH=0x42 lseek AL=0x02 SEEK_END
		mov	bx,[filehandle]
		xor	cx,cx
		mov	dx,0x1000	; CX:DX = offset 0x1000
		int	21h		; result = 0x1000 + 13

		mov	ah,0x40		; AH=0x40 write to handle
		mov	bx,[filehandle]
		mov	cx,str_msg_len
		mov	dx,str_msg
		int	21h

		mov	ah,0x3E		; AH=0x3E close the file handle
		mov	bx,[filehandle]
		int	21h

; EXIT to DOS
exit:		ret
exit_err:	mov	ah,0x09
		int	21h
		mov	dx,crlf
		call	puts
		jmp	short exit

;------------------------------------
puts:		mov	ah,0x09
		int	21h
		ret

;------------------------------------
putsz:		push	si
		push	ax
		push	dx
		cld
putsz1:		lodsb
		or	al,al
		jz	putsz1e
		mov	dl,al
		mov	ah,0x02
		int	21h
		jmp	short putsz1
putsz1e:	pop	dx
		pop	ax
		pop	si
		ret

		segment .data

str_ok:		db	'Created$'
str_fail:	db	'Failed$'
crlf:		db	13,10,'$'
str_msg:	db	'Hello world',13,10
str_msg_len	equ	13

		segment .bss

filehandle:	resw	1
filename:	resb	16

