	TITLE Lab 4: File I/O

	.model	small		;start all programs you will write 
	.stack	100h		;for CS2011 with these directives

	.data			;the program's variables go here
filename	db	'LAB4FILE.TXT', 0
inhandle  	dw	?
insize	dw	?

outhandle   dw    ?

bufferSize = 100
filebuf	db	bufferSize dup(?)

prompt	db	"Enter filename: $"

;here is the data area for the buffered input
dataArea	label byte
maxlen	db	20
reallen	db	?
buffer	db	20 dup(0)


	.code					;the code starts here
	.startup				;TASM directive that sets up stack
						;segment and data segment

	;open your file
	mov	ah, **			;add the open function here (p. 450, Irvine)
	mov	al, 0			;file mode
	mov	dx, offset filename	;set up the file name
	int	21h
	mov	inhandle, **		;save the register containing the file handle
	

	;read the data into the buffer
	mov	ah, 3fh			;read from file or device
	mov	bx, **			;what goes in BX? (p. 451, Irvine)
	mov	cx, bufferSize		;size of the buffer
	mov	dx, **			;get the address of filebuf
	int 	21h				
	mov	insize, ax		;save the number of bytes stored

	;ask the user to enter a file name
	mov	ah, 09h			;output string
	mov	dx, offset prompt	;your prompt
	int 21h

	;read the filename using BUFFERED INPUT
	mov	ah, 0Ah			;selecting buffered input
	mov	dx, offset dataArea	;our data 
	int	21h

	;now the tricky part - how to put it in file name format
	;there are a number of ways to do this, here is one that will work
	mov	bx, offset buffer	;set BX to point to the last char in the
	mov	al, reallen
	mov	ah, 0
	add	bx, ax			;data buffer (start of the buffer area + count)
	mov	byte ptr [bx], 0	;put a zero in that spot

	mov	ah, 3ch			;create a new file
	mov	dx, offset buffer	;your file name
	mov	cx, 0			;what does this mean?
	int	21h
	mov	outhandle, ax		;save the output file handle

	;now, lets copy the data we read from the first file into our new file
	mov	ah, 40h
	mov	bx, outhandle		;the handle of the file we opened
	mov	**, insize		;where do we put the size? (Irvine, p. 452)
	mov	dx, offset filebuf	;point to our data
	int  	21h

	;don't forget to close your files!!!!
	mov	ah, 3eh
	mov	bx, inhandle		;our file handle
	int	21h
	
	;close the second file (you write the code - look at the code just above!)
   	**
	**
	**

	.exit				;a TASM directive that returns 
					;control to the calling program.
					;Meant to be used in conjunction
					;with .startup
	end				;end of source code
