*
*
*               FACTORIAL PROGRAM
*               BSR : Brach to subroutine; Uses relative addressing
*               JSR : Jump to subrotine;  Uses direct, indexed, and extended addressing
*
RAMStart        EQU     $0040
RomStart        EQU     $E000
ResetVector     EQU     $FFFE

                ORG     ResetVector
                FDB     MAIN

                ORG     RAMStart


                ORG     RomStart

MAIN            RSP                   ; Reset stack pointer to FF
                LDA     #$04          ; Load A with $04
                JSR     FACTOR        ; Jump to subroutine FACTOR
                NOP                   ; Accumulator holds the factorial
                NOP
                NOP



FACTOR          PSHA                  ; PUSH A CALLING VALUE
                DBNZA    CONT         ; GO TO PUSH RETURN ADDRESS
                PULA                  ; PULL THE LAST VALUE FORM STACK
                BRA      RETURN       ; GO TO RETURN TO COMPUTE FACTORIAL

CONT            BSR      FACTOR       ; PUSH THE RETURN ADDRESS ONTO STACK

                                      ; COMPUTE FACT(N) * N+1 AT EACH STEP (RETURN)
                                      ; FACT (1) * 2 AT 1ST STEP
                                      ; FACT (2) * 3 AT 2ND STEP
                                      ; FACT (3) * 4 AT 3RD STEP
                                      ; AND SO ON

                PULX                  ; PULL N+1 FROM STACK
                MUL                   ; A <-- A * X ; A <-- FACT(N) + N+1
RETURN          RTS                   ; RETURN FROM SUBROUTINE

