
	TITLE	EVENT
	NAME	EVENT

	include	dos.mac
	.286p

X	equ	4		; for near calls
;X	equ	6		; for far calls

ebuf	STRUC
start_addr	dw	?
count		dw	?
ebuf	ENDS

mbuf	STRUC
dp	dw	?
next	dw	?
len	dw	?
mbuf	ENDS

	extrn	@ipinterpret:near
	extrn	@tcptick:near
	extrn	_mbfree:word
	extrn	_mbprocess:word
	extrn	_mbnext:word
	extrn	_eb:byte
	extrn	_send_pkt:near
	extrn	_arp:word
	extrn	_arp_queued:word

LIBTCP_TEXT	segment
	ASSUME	cs: LIBTCP_TEXT, ds: nothing

	public	_netsleep
_netsleep proc far
	push	ds
	push	si
	push	di

	mov	ax,seg LIBTCP_DATA_GROUP
	mov	ds,ax
	ASSUME ds: LIBTCP_DATA_GROUP

	mov	si,_mbprocess
	or	si,si
	jnz	$A12
	jmp	$A0
$A12:
	cli
	mov	bx,[si].next
	mov	_mbprocess,bx
	or	bx,bx
	jnz	$A4
	mov	_mbnext,offset _mbprocess
$A4:
	sti
	mov	bx,[si].dp
	mov	ax,[si].len
	call	@ipinterpret

	mov	ax,ds
	mov	es,ax
	ASSUME	es: LIBTCP_DATA_GROUP

	mov	bx,[si].dp		; bx = start of data
	mov	dx,[si].len
	add	dx,bx			; dx = byte past end of buffer
	mov	di,offset _eb
	cli
$A3:
	mov	cx,[di].count
	jcxz	$A6			; slot is not used
	mov	ax,[di].start_addr
	cmp	ax,dx
	je	$A6			; fix address and count
	ja	$A5			; move slot down
	add	ax,cx
	cmp	ax,bx
	je	$A7			; fix count only
	add	di,size ebuf		; point to next entry
	cmp	di,offset _eb + 32 * size ebuf
	jb	$A3			; are we done?
$AXX:
	sub	bx,bx			; joe code!!!
	mov	ax,0e13h
	int	10h
	jmp short $A9
$A5:
	push	di
	push	si
	mov	si,di			; si = current ebuf
$A30:
	add	di,size ebuf		; point to next ebuf
	mov	cx,[di].count		; get count
	jcxz	$A31
	cmp	di,offset _eb + 31 * size ebuf
					; are we at the last ebuf?
	jb	$A30
	jmp short $AXX			; joe code!!
$A31:
	mov	cx,di			; count = new ebuf - original ebuf
	sub	cx,si
	shr	cx,1			; make it words
	dec	di
	dec	di
	mov	si,di			; point to end of real data
	add	di,size ebuf
	std
	rep	movsw
	cld

	pop	si
	pop	di
	mov	[di].start_addr,bx
	mov	ax,[si].len
	mov	[di].count,ax
	jmp short $A9
$A6:
	mov	[di].start_addr,bx
	add	dx,cx
	mov	ax,dx
	sub	dx,bx
	mov	[di].count,dx
	cmp	di,offset _eb
	jbe	$A9
	sub	di,size ebuf
	jmp short $A8
$A7:
	mov	ax,dx
	add	dx,cx			; add in original ebuf count
	sub	dx,bx			; restore the count
	mov	[di].count,dx
$A8:					; check for continuous ebufs
	cmp	ax,[di + size ebuf].start_addr
	jne	$A9
	add	dx,[di + size ebuf].count
	mov	[di].count,dx		; add in next ebuf's count
	add	di,size ebuf
	cmp	di,offset _eb + 31 * size ebuf
	jae	$A9
	push	si
	mov	si,di
	add	si,size ebuf
$A81:
	movsw				; copy in start_addr
	lodsw				; get count
	stosw				; save it
	or 	ax,ax
	jnz	$A81
	pop	si
$A9:	
	mov	bx,_mbfree
	mov	[si].next,bx
	mov	_mbfree,si
	sti
$A0:
	pop	di
	pop	si

	mov	ax,_arp_queued
	or	ax,ax
	jz	$A10
	push	60
	push	ds
	mov	ax,offset _arp
	push	ax
	call	_send_pkt
	add	sp,6
	xor	ax,ax
	mov	_arp_queued,ax
$A10:

	mov	ax,_mbprocess
	or	ax,ax
	jnz	$A2
	call	@tcptick
$A2:
	pop	ds
	ASSUME	ds: nothing
	ret
_netsleep endp

LIBTCP_TEXT	ends
	end
