;++
;
; Filter to add CRs before LFs.
;
; 05/31/94	JMBW	Created.
;
;--
	.radix	8
;
lf=	12
cr=	15
;
bufsiz=	30000d			;buffer size
;
code	segment
	assume	cs:code
	org	100h
;
start:	cld			;DF=0
lp1:	; load input buf
	mov	dx,offset ibuf	;pt at buf
	mov	cx,bufsiz	;size
	xor	bx,bx		;stdin
	mov	ah,3Fh		;func=read
	int	21h
	jc	sk2
	mov	di,dx		;pt at buf
	mov	cx,ax		;copy # bytes actually read
	jcxz	sk2		;none, eof
	mov	si,di		;save ptr
lp2:	; si=first byte to write on next flush, di=next byte to check,
	; cx=# bytes left at [di]
	mov	al,lf		;search for LFs
	repne	scasb		;find one?
	jne	sk1		;flush and refill if not
	mov	byte ptr [di-1],cr ;change lf to cr
	call	write		;write preceding stuff
	lea	si,[di-1]	;point at preceding byte
	mov	byte ptr [si],lf ;change back to lf
	or	cx,cx		;anything left?
	jnz	lp2		;loop if so
sk1:	call	write		;flush everything
	jmp	short lp1	;go reload
sk2:	; end of file
	call	flush		;flush output
	int	20h
;+
;
; Write data to output buf.
;
; si	ptr to data to write
; di	ptr to byte after last byte to write
;
; Preserves di, cx.
;
;-
write:	push	cx		;save
	push	di
	mov	cx,di		;find length
	sub	cx,si
write1:	mov	di,ds:optr	;get pointer
	mov	bx,ds:octr	;get # free bytes
	mov	dx,cx		;save
	cmp	cx,bx		;will our stuff fit?
	jb	write2
	 mov	cx,bx		;no, stop at end of buf
write2:	sub	dx,cx		;# bytes that will be left to do
	sub	bx,cx		;# bytes that will be free in buf
	rep	movsb		;copy them
	mov	ds:optr,di	;update
	mov	ds:octr,bx
	or	bx,bx		;any space left?
	jnz	write3		;yes, then we must have copied all of it
	push	dx		;save # left to copy
	call	flush		;flush buf
	pop	cx		;restore
	or	cx,cx		;anything?
	jnz	write1		;loop if so
write3:	pop	di		;restore
	pop	cx
	ret
;+
;
; Flush output buffer.
;
;-
flush:	mov	dx,offset obuf	;pt at buffer
	mov	ds:optr,dx	;update
	mov	cx,bufsiz	;get # bytes in a full buf
	mov	bx,cx		;copy
	xchg	bx,ds:octr	;reset ctr, get value
	sub	cx,bx		;find # to write
	mov	bx,1		;stdout
	mov	ah,40h		;func=write
	int	21h
	ret
;
optr	dw	obuf		;ptr into output buf
octr	dw	bufsiz		;# free bytes in output buf
;
ibuf	db	bufsiz dup(?)	;input buffer
obuf	db	bufsiz dup(?)	;output buffer
;
code	ends
	end	start

