;
; *** Listing 11-32 ***
;
; Compares two arrays of 16-bit signed values in order to
; find the first point at which the arrays cross, using
; non-string instructions.
;
	jmp	Skip
;
; The two arrays that we'll compare.
;
ARRAY_LENGTH	equ	200
;
Array1	label	byte
TEMP=-100
	rept	ARRAY_LENGTH
	dw	TEMP
TEMP=TEMP+1
	endm
;
Array2	label	byte
TEMP=100
	rept	ARRAY_LENGTH
	dw	TEMP
TEMP=TEMP-1
	endm
;
; Compares two buffers to find the first point at which they
; cross. Points at which the arrays become equal are
; considered to be crossing points.
;
; Input:
;	CX = length of arrays in words (they must be of
;		equal length)
;	DS:SI = start of first array
;	ES:DI = start of second array
;
; Output:
;	DS:SI = pointer to crossing point in first array,
;		or SI=0 if there is no crossing point
;	ES:DI = pointer to crossing point in second array,
;		or DI=0 if there is no crossing point
;
; Registers altered: BX, CX, DX, SI, DI
;
; Note: Does not handle arrays that are longer than 64K
;	bytes or cross segment boundaries.
;
FindCrossing:
	jcxz	FindCrossingNotFound
			;if there's nothing to compare, we
			; certainly can't find a crossing
	mov	dx,2	;amount we'll add to the pointer
			; registers after each comparison,
			; kept in a register for speed
	mov	bx,[si]	;compare the first two points to
	cmp	bx,es:[di] ; make sure that the first array
			; doesn't start out below the second
			; array
	pushf		;remember the original relationship
			; of the arrays, so we can put the
			; pointers back at the end (can't
			; use LAHF because it doesn't save
			; the Overflow flag)
	jnl	FindCrossingLoop ;the first array is above
				; the second array
	xchg	si,di	;swap the array pointers so that
			; SI points to the initially-
			; greater array
FindCrossingLoop:
	mov	bx,[si]		;compare the next element in
	cmp	bx,es:[di]	; each array
	jng	FindCrossingFound ;if SI doesn't point to a
				; greater value, we've found
				; the first crossing
	add	si,dx		;point to the next element
	add	di,dx		; in each array
	loop	FindCrossingLoop ;check the next element in
				; each array
FindCrossingNotFound:
	popf		;clear the flags we pushed earlier
	sub	si,si	;return 0 pointers to indicate that
	mov	di,si	; no crossing was found
	ret
FindCrossingFound:
	popf		;get back the original relationship
			; of the arrays
	jnl	FindCrossingDone
			;SI pointed to the initially-
			; greater array, so we're all set
	xchg	si,di	;SI pointed to the initially-
			; less array, so swap SI and DI to
			; undo our earlier swap
FindCrossingDone:
	ret
;
Skip:
	call	ZTimerOn
	mov	si,offset Array1 ;point to first array
	mov	di,seg Array2
	mov	es,di
	mov	di,offset Array2 ;point to second array
	mov	cx,ARRAY_LENGTH	;length to compare
	call	FindCrossing	;find the first crossing, if
				; any
	call	ZTimerOff
