;*****************************************************************************
;Fibonacci_SRs
;This program rewrites the Full Fibonacci program to illustrate the use of 
;subroutines.
;Program intended for simulation only, hence no input/output.
;TJW 17.11.08					Tested by simulation 18.3.05
;****************************************************************************

;no i/o ports used
status  equ 03
c		equ 0
z		equ 2
;these memory locations hold the Fibonacci series
fib0	equ  10	;lowest number (oldest when going up; newest when reversing down)
fib1    equ  11 ;middle number
fib2    equ  12 ;highest number
fibtemp equ  13 ;temporary location for newest number
counter equ  14 ;indicates which value we have reached, opening value is 2 

		org 00
;preload initial values
		movlw 0
		movwf fib0
		movlw 1
		movwf fib1
		movwf fib2
		movlw 3	
		movwf counter	;have preloaded the first three numbers, so start at 3
;
forward movf  fib1,0
		addwf fib2,0
		btfsc status,c	;test if we have overflowed 8-bit range
		goto  reverse	;here if we have overflowed, hence reverse down the series
		movwf fibtemp	;latest number now placed in fibtemp
		incf  counter,1
;now shuffle numbers held, discarding the oldest
	    	goto shuffle_up
		goto  forward
;when reversing down, we will subtract fib0 from fib1 to form new fib0
reverse 	movf  fib0,0
		subwf fib1,0
		movwf fibtemp		;latest number now placed in fibtemp
		decf  counter,1
;now shuffle numbers held, discarding the oldest
		call shuffle_down
;test if counter has reached 3, in which case return to forward
		movf  counter,0 
		sublw 3
		btfsc status,z
		goto  forward
		goto  reverse
;**********************************
;Subroutines
;**********************************
;Shuffles numbers in series, moving fib1 to fib0, fib2 to fib1, fibtemp to fib2
shuffle_up 	movf  fib1,0 	;first move middle number, to overwrite oldest
		movwf fib0
		movf  fib2,0
		movwf fib1
		movf  fibtemp,0
		movwf fib2
		return
;Shuffles numbers in series, moving fib1 to fib2, fib0 to fib1, fibtemp to fib0
shuffle_down 	movf fib1,0 	;first move middle number, to overwrite oldest
		movwf fib2
		movf fib0,0
		movwf fib1
		movf fibtemp,0
		movwf fib0
		return
		end
		

