; Code to see if a value in SRAM can be
; the new Max or Min value, also
; stored in SRAM.
; Only work with positive values.
; By PEK  '2000


.include "8515def.inc"


; ************************************
; * Register and Constant Definitions             
; ************************************
.def	temp	=R16
.def	status	=R17

.equ	MM_MASK	=0x02			; To mask if Max & Min values available
.equ	MM_BIT	=1			; Bit 1 : Max & Min values available


; ************************************
; * SRAM Allocations
; ************************************
.dseg
value:	.BYTE	2			; Value to compare with
max:	.BYTE	2			; Max value
min:	.BYTE	2			; Min value


; ************************************
; * Start of Code                    
; ************************************
.cseg
.org 0

Start:
	ldi	temp,low(RAMEND)
	out	SPL,temp		; Set stack pointer to last internal RAM location
	ldi	temp,high(RAMEND)
	out	SPH,temp

	clr	status			; No Max & Min value available

MM_Main_Loop:
	lds	XL,value		; X = new value to compare with
	lds	XH,value+1

	sbrc	status,MM_BIT		; Check if Max & Min values are available
	rjmp	MM_Check_Value_Low	; Yes they are...

	sts	max,XL			; Store Max-value
	sts	max+1,XH
	sts	min,XL			; Store Min-value
	sts	min+1,XH
	ori	status,MM_MASK		; The Max & Min values are now available
	rjmp	MM_Main_Loop

MM_Check_Value_Low:
	lds	YL,min			; Y = the lowest value
	lds	YH,min+1

	cp	XL,YL
	cpc	XH,YH			; Check if value is lower than the lowest one
	brsh	MM_Check_Value_High	; No...

	sts	min,XL			; Store new Min-value
	sts	min+1,XH
	rjmp	MM_Main_Loop

MM_Check_Value_High:
	lds	YL,max			; Y = the highest value
	lds	YH,max+1

	cp	XL,YL
	cpc	XH,YH			; Check if value is higher than the highest one
	brlo	MM_Main_Loop		; No...

	sts	max,XL			; Store new Max-value
	sts	max+1,XH
	rjmp	MM_Main_Loop
