; 2026.1105 Mueck_f42.txt
; Program suite for all Mueck_f42 Free42 skins - mick.mueck@mac.com

; NOTE: After installing this suite, go into program mode and enter XEQ "LOCK". 
; It'll look like you're adding a line of code, but you're actually performing 
; a write protect function. That will avoid future grief if you accidentally 
; modify or delete any code. The program pointer turns "gray" to indicate the 
; LOCK was successful. The process can similarly be undone with XEQ "UNLOCK".

; To run this skin in Plus42, use the Mueck_p42 program suite instead.
; It's the same thing but without TVM (because Plus42 has its own TVM).

; Usage instructions for .CONST, .POLY and TVM are given in the 
; headers of each of those programs.

; My usage model for local labels (00-99, A-J, a-e) is:
;   NUMERIC 00-99: Can loop to be found.
;   PRIMARY   A-J: Can loop to be found.
;   SECONDARY a-e: Are heavily reused to ONLY work searching downwards. 
; LBLs 05-06 are currently the only remaining ones available!

;--------------------------------------------------------------
; FIX02 Toggles the current display state with FIX 02
; Flags 40-41 store FIX/SCI/ENG/ALL, flags 36-39 store #digits
; FIX 02 defined by: Flags 36-41 CLEAR except for 38 & 40 
;--------------------------------------------------------------
LBL ".FIX02"
FUNC 00
SF 25
FC? 41       ; See if the current display state is FIX 02
FC? 40
GTO a        ; Not FIX 02
FC? 39
FC? 38
GTO a        ; Not FIX 02
FC? 37
FS? 36
GTO a        ; Not FIX 02
RCL ".DISP"  ; Is FIX 02, recall saved display state
FC?C 25
GTO a        ; .DISP is uninitialized, the current state is FIX 02
36.41
STOFLAG      ; Set the previously saved display state 
RTN
LBL a        ; Not FIX 02. Save the display state and set FIX 02
RCLFLAG      ; In case .DISP hasn't been defined yet
STO ".DISP"  ; Save the current display state
FIX 02
RTN

;--------------------------------------------------------------
; X³ → X⁹   Hot-keys ⌥3 → ⌥9   Mimics a built-in function
;--------------------------------------------------------------
LBL ".X↑9"
FUNC 11
9
GTO a

LBL ".X↑8"
FUNC 11
8
GTO a

LBL ".X↑7"
FUNC 11
7
GTO a

LBL ".X↑6"
FUNC 11
6
GTO a

LBL ".X↑5"
FUNC 11
5
GTO a

LBL ".X↑4"
FUNC 11
4
GTO a

LBL ".X↑3"
FUNC 11
3
GTO a

LBL a
SF 25
Y↑X
FS?C 25
RTN
ERRNO
RTNERR IND ST X


;--------------------------------------------------------------
; ³√X → ⁹√X   Hot-keys ⇧⌥3 → ⇧⌥9   Mimics a built-in function
; Yields intuitive results e.g. ³√-27 = -3 vs 3 angle 60°
;--------------------------------------------------------------
LBL ".9√X"
FUNC 11
9
GTO a

LBL ".8√X"
FUNC 11
8
GTO a

LBL ".7√X"
FUNC 11
7
GTO a

LBL ".6√X"
FUNC 11
6
GTO a

LBL ".5√X"
FUNC 11
5
GTO a

LBL ".4√X"
FUNC 11
4
GTO a

LBL ".3√X"
FUNC 11
3 

LBL a
SF 25
X<>Y
SIGN            ; If complex, returns it's unit vector
LASTX
REAL?
ABS             ; Returns the magnitude of a complex number as a real
RCL ST Z
1/X
Y↑X
REAL?
*
FS?C 25
RTN
ERRNO
RTNERR IND ST X

;--------------------------------------------------------------
; E↑iX   Hot-key ⇧⌥e   Mimics a built-in function
;--------------------------------------------------------------
LBL ".E↑iX" 
FUNC 11
SF 25
-1
SQRT
×
E^X
FS?C 25
RTN
ERRNO
RTNERR IND ST X

;--------------------------------------------------------------
; √-1   Hot-keys i and j  (don't use FUNC because it will void LASTx)
;--------------------------------------------------------------
LBL ".i"
CSLD?
CLX
LASTX		; Preserve LASTx
LSTO "X"
CLX
-1		; This way you don't have to worry about the complex MODE setting 
SQRT
STO ST L	; Store answer in LASTX
CLX
RCL "X"
X<> ST L
RTN

;--------------------------------------------------------------
; RSSdB & RDSdB   i.e. dB(√((dB⁻¹Y)² ± (dB⁻¹X)²)
; Hot-keys ⌃⌥v and ⌃⇧⌥v   Mimics a built-in function
;--------------------------------------------------------------
LBL ".RDSdB"
FUNC 21
SF 25
20
/
10^X
X^2
X<>Y
20
/
10^X
X^2
X<>Y
-
SQRT
LOG
20
*
FS?C 25
RTN
ERRNO
RTNERR IND ST X

LBL ".RSSdB"
FUNC 21
SF 25
20
/
10^X
X^2
X<>Y
20
/
10^X
X^2
+
SQRT
LOG
20
*
FS?C 25
RTN
ERRNO
RTNERR IND ST X

;--------------------------------------------------------------
; RSS & RDS i.e. √(Y²±X²)   Hot-keys ⌥v and ⇧⌥v   Mimics a built-in function
;--------------------------------------------------------------
LBL ".RDS"
FUNC 21
SF 25
X^2
X<>Y
X^2
X<>Y
-
SQRT
FS?C 25
RTN
ERRNO
RTNERR IND ST X

LBL ".RSS"
FUNC 21
SF 25
X^2
X<>Y
X^2
+
SQRT
FS?C 25
RTN
ERRNO
RTNERR IND ST X

;--------------------------------------------------------------
; dB & dB⁻¹   Hot-keys ⌥d and ⇧⌥d    Mimics a built-in function
;--------------------------------------------------------------
LBL ".dB-1"
FUNC 11
SF 25
20
/
10^X
FS?C 25
RTN
ERRNO
RTNERR IND ST X

LBL ".dB" 
FUNC 11
SF 25
LOG
20
×
FS?C 25
RTN
ERRNO
RTNERR IND ST X

;--------------------------------------------------------------
; LOG₂ & 2↑X   Hot-keys ⌥b and ⇧⌥b   Mimics a built-in function
;--------------------------------------------------------------
LBL ".2↑X"
FUNC 11
SF 25
2
X<>Y
Y^X
FS?C 25
RTN
ERRNO
RTNERR IND ST X

LBL ".LOG2" 
FUNC 11
SF 25
LOG
2
LOG
/
FS?C 25
RTN
ERRNO
RTNERR IND ST X

;--------------------------------------------------------------
; .CONST 2026.1105 - 4STK and NSTK compliant
; If you're unsure what the symbol on the button is, do ⇧Button
;   to just reveal the description without entering any data.
;   Note: doing that voids any CSLD (Caller Stack Lift Disable)
; To tailor the CONSTANT menu to your own needs:
; - Edit the contents of each menu level as needed.
; - Maintain the systematic labeling used in each level. 
; - Add or delete levels as needed (8 at the most).
; - Edit "NUMBER OF MENU LEVELS USED" (in TWO places)
; Uses LBLs 00-01 and reserves LBLs 10→16 → 80→86
;--------------------------------------------------------------

LBL ".CONST"
XEQ a            ; Initialization
;--------------------------------------------------------------
LBL 00           ; RUN LOOP (ONLY modifies the Alpha-register)
;--------------------------------------------------------------
XASTO ".areg"    ; Save the Alpha-register (menu building will destroy it)
CLMENU
; It can be dangerous to use non-unique LBLs in KEY commands.
; If an error occurs the program pointer can be in a random 
; place and pressing the menu buttons could XEQ an unwanted 
; function. For CONST, there is no danger of errors, so it's OK.
; More free unique LBLs means more available CONST menu levels.
KEY 7 XEQ d      ; Menu UP
KEY 8 XEQ c      ; Menu DOWN
KEY 9 GTO b      ; EXIT
XEQ IND ".conl"  ; Build the currently selected menu level
CLA
ARCL ".areg"     ; Restore the Alpha-register
CLV ".areg"      ; Reduce clutter
MENU1            ; Won't be dismissed when exiting other menus
STOP             ; Menu functions start their XEQs from here
GTO 00
;--------------------------------------------------------------
LBL a            ; INITIALIZATION
FUNC 00
10               ; Menu level must be a multiple of 10
STO ".conl"      ; Set the initial menu level
SF 33            ; For Menu1 operation (not needed, but just in case)
RTN
;--------------------------------------------------------------
LBL b            ; EXIT
CLV ".areg"
CLV ".conl"
CLMENU
EXITALL
STOP
;--------------------------------------------------------------
LBL c            ; MENU DOWN
FUNC 00
10               ; Menu level must be a multiple of 10
STO/ ".conl"
3                ; <~~~~~~ "NUMBER OF MENU LEVELS USED" (Max=8)
X=? ".conl"
STO- ".conl"
ISG ".conl"
NOP
GTO a
;--------------------------------------------------------------
LBL d            ; MENU UP
FUNC 00
10               ; Menu level must be a multiple of 10
STO/ ".conl"
3                ; <~~~~~~ "NUMBER OF MENU LEVELS USED" (Max=8)
DSE ".conl"
GTO a
STO ".conl"
LBL a
DROP
STO* ".conl"
RTN
;--------------------------------------------------------------
LBL 01           ; Show the Alpha-register for a PSE delay time
SF 33            ; Allows menu buttons to be responsive during the delay.
AVIEW
PSE
CLD
CLA
ARCL ".areg"     ; Restore the Alpha-register
RTN
;--------------------------------------------------------------
LBL 10           ; LEVEL 1 menu
"g"
KEY 1 XEQ 11
"G"
KEY 2 XEQ 12
"c"
KEY 3 XEQ 13
"R"
KEY 4 XEQ 14
"Na"
KEY 5 XEQ 15
" "
KEY 6 XEQ 16
RTN

LBL 11           ; Button 1 <----------------------
XASTO ".areg"    ; Save the Alpha-register
"Earth Gravity"
├"[LF](m/s^2)"
FS? 64           ; See if shift was pressed
GTO 01           ; Yes, only VIEW the constant name
CSLD?            ; MUST use KEYX, not KEYG
CLX
9.80665
GTO 01           ; View the constant name
LBL 12           ; Button 2 <----------------------
XASTO ".areg"    ; Save the Alpha-register
"Gravitational"
├" Constant"
├"[LF](m^3/kg/s^2)"
FS? 64           ; See if shift was pressed
GTO 01           ; Yes, only VIEW the constant name
CSLD?            ; MUST use KEYX, not KEYG
CLX
6.6743E-11
GTO 01           ; View the constant name
LBL 13           ; Button 3 <----------------------
XASTO ".areg"    ; Save the Alpha-register
"Speed of Light"
├"[LF](m/s)"
FS? 64           ; See if shift was pressed
GTO 01           ; Yes, only VIEW the constant name
CSLD?            ; MUST use KEYX, not KEYG
CLX
299792458
GTO 01           ; View the constant name
LBL 14           ; Button 4 <----------------------
XASTO ".areg"    ; Save the Alpha-register
"Gas Constant"
├"[LF](J/mol/K)"
FS? 64           ; See if shift was pressed
GTO 01           ; Yes, only VIEW the constant name
CSLD?            ; MUST use KEYX, not KEYG
CLX
8.314462618
GTO 01           ; View the constant name
LBL 15           ; Button 5 <----------------------
XASTO ".areg"    ; Save the Alpha-register
"Avogadro Number"
├"[LF](/mol)"
FS? 64           ; See if shift was pressed
GTO 01           ; Yes, only VIEW the constant name
CSLD?            ; MUST use KEYX, not KEYG
CLX
6.02214076E23
GTO 01           ; View the constant name
LBL 16           ; Button 6 <----------------------
RTN              ; An unassigned menu button
;--------------------------------------------------------------
LBL 20           ; LEVEL 2 menu
"h"
KEY 1 XEQ 21
"k"
KEY 2 XEQ 22
"q"
KEY 3 XEQ 23
"e0"
KEY 4 XEQ 24
"μ0"
KEY 5 XEQ 25
"Z0"
KEY 6 XEQ 26
RTN

LBL 21           ; Button 1 <----------------------
XASTO ".areg"    ; Save the Alpha-register
"Planck Constant"
├"[LF](J/Hz)"
FS? 64           ; See if shift was pressed
GTO 01           ; Yes, only VIEW the constant name
CSLD?            ; MUST use KEYX, not KEYG
CLX
6.62607015E-34
GTO 01           ; View the constant name
LBL 22           ; Button 2 <----------------------
XASTO ".areg"    ; Save the Alpha-register
"Boltzmann "
├"Constant"
├"[LF](J/K)"
FS? 64           ; See if shift was pressed
GTO 01           ; Yes, only VIEW the constant name
CSLD?            ; MUST use KEYX, not KEYG
CLX
1.380649ᴇ-23
GTO 01           ; View the constant name
LBL 23           ; Button 3 <----------------------
XASTO ".areg"    ; Save the Alpha-register
"Electron Charge"
├"[LF](C)"
FS? 64           ; See if shift was pressed
GTO 01           ; Yes, only VIEW the constant name
CSLD?            ; MUST use KEYX, not KEYG
CLX
1.602176634ᴇ-19
GTO 01           ; View the constant name
LBL 24           ; Button 4 <----------------------
XASTO ".areg"    ; Save the Alpha-register
"Permittivity of"
├" Vacuum"
├"[LF](F/m)"
FS? 64           ; See if shift was pressed
GTO 01           ; Yes, only VIEW the constant name
CSLD?            ; MUST use KEYX, not KEYG
CLX
8.8541878128ᴇ-12
GTO 01           ; View the constant name
LBL 25           ; Button 5 <----------------------
XASTO ".areg"    ; Save the Alpha-register
"Permeability of"
├" Vacuum"
├"[LF](N/A^2)"
FS? 64           ; See if shift was pressed
GTO 01           ; Yes, only VIEW the constant name
CSLD?            ; MUST use KEYX, not KEYG
CLX
1.25663706212ᴇ-6
GTO 01           ; View the constant name
LBL 26           ; Button 6 <----------------------
XASTO ".areg"    ; Save the Alpha-register
"Impedance of"
├" Vacuum"
├"[LF](Ohms)"
FS? 64           ; See if shift was pressed
GTO 01           ; Yes, only VIEW the constant name
CSLD?            ; MUST use KEYX, not KEYG
CLX
376.730313668
GTO 01

;--------------------------------------------------------------
LBL 30           ; LEVEL 3 menu
"er_ox"
KEY 1 XEQ 31
"er_ni"
KEY 2 XEQ 32
"P_Al"
KEY 3 XEQ 33
"P_Cu"
KEY 4 XEQ 34
"µe"
KEY 5 XEQ 35
"µh"
KEY 6 XEQ 36
RTN

LBL 31           ; Button 1 <----------------------
XASTO ".areg"    ; Save the Alpha-register
"SiO2 Rel "
├"Permittivity"
FS? 64           ; See if shift was pressed
GTO 01           ; Yes, only VIEW the constant name
CSLD?            ; MUST use KEYX, not KEYG
CLX
3.9
GTO 01           ; View the constant name
LBL 32           ; Button 2 <----------------------
XASTO ".areg"    ; Save the Alpha-register
"Si3N4 Rel "
├"Permittivity"
FS? 64           ; See if shift was pressed
GTO 01           ; Yes, only VIEW the constant name
CSLD?            ; MUST use KEYX, not KEYG
CLX
7.5
GTO 01           ; View the constant name
LBL 33           ; Button 3 <----------------------
XASTO ".areg"    ; Save the Alpha-register
"Aluminum "
├"Resistivity"
├"[LF](Ohm.m)"
FS? 64           ; See if shift was pressed
GTO 01           ; Yes, only VIEW the constant name
CSLD?            ; MUST use KEYX, not KEYG
CLX
2.65E-8
GTO 01           ; View the constant name
LBL 34           ; Button 4 <----------------------
XASTO ".areg"    ; Save the Alpha-register
"Copper "
├"Resistivity"
├"[LF](Ohm.m)"
FS? 64           ; See if shift was pressed
GTO 01           ; Yes, only VIEW the constant name
CSLD?            ; MUST use KEYX, not KEYG
CLX
1.68E-8
GTO 01           ; View the constant name
LBL 35           ; Button 5 <----------------------
XASTO ".areg"    ; Save the Alpha-register
"Si Electron "
├"Mobility"
├"[LF](cm^2/V/s)"
FS? 64           ; See if shift was pressed
GTO 01           ; Yes, only VIEW the constant name
CSLD?            ; MUST use KEYX, not KEYG
CLX
1360
GTO 01           ; View the constant name
LBL 36           ; Button 6 <----------------------
XASTO ".areg"    ; Save the Alpha-register
"Si Hole "
├"Mobility"
├"[LF](cm^2/V/s)"
FS? 64           ; See if shift was pressed
GTO 01           ; Yes, only VIEW the constant name
CSLD?            ; MUST use KEYX, not KEYG
CLX
480
GTO 01

;----------------------------------------------------------------------------
; 2026.1105: ".POLY" - Mick Mueck mick.mueck@mac.com
;----------------------------------------------------------------------------
; With thanks to Thomas Sigrist.
; Formula solutions for quadratic, cubic & quartic polynomials
; 4STK and NSTK compliant, also works with complex coefficients.

; MENU Level 1:
; Coefficients entered via the menus are stored in registers named:
;       .X^4, .X^3, .X^2, .X^1, .X^0
;   Note that coefficients can be both real and complex.
; SOLV solves the polynomial implied by the highest order non-zero
;   coefficient. 
; ⇧SOLV resets all coefficients to zero.
; Roots are stored in registers named  ".√4"→".√1"
;   quadratic uses .√2→.√1, cubic uses .√3→.√1, quartic uses .√4→.√1
; Coefficients are NOT reset when you start .POLY in case you need to
;   leave .POLY to calculate the coefficients.
; Any variables not used by a polynomial solution are reset to zero.
; To VIEW a coefficient for ~1 sec without disrupting the stack, ⇧press
;   the coefficient's menu button. You can also do RCL (or STO or VIEW)
;   and select a coefficient from that menu.

; MENU Level 2:
; QUAD, CUBIC, QRTC: A coefficient entry GUI is nice, but I prefer
;   entering them on the stack and then press QUAD, CUBIC, QRTC.
; A program can populate the stack and do XEQ ".QUAD" etc.
;   Because of the 4 level stack limitation, when doing XEQ ".QRTC" you 
;   must modify the coefficients so .X^4=1. That does NOT apply for NSTK.
; When using this stack method, the coefficients are also stored in the
;   .X^n registers so that you can subsequently use the SOLV method on  
;   them if a typo was made with e.g. just one of the coefficients.
; EVAL evaluates the polynomial using the value in the X-register.
;   This can be also used to confirm the validity of a root.
; ⇧EVAL puts all coefficients on the stack. In 4STK, .X^4 is put in LASTX.

; Uses LBLs unused by .CONST & TVM: 02-04, 07-09,17-19,27-29,37-39,95-99


LBL ".POLY"
XEQ c            ; Initialization
;----------------------------------------------------------------------------
LBL 99           ; MAIN RUN LOOP (ONLY modifies the Alpha-register)
;----------------------------------------------------------------------------
XASTO ".areg"    ; Save the Alpha-register (menu building will destroy it)
XEQ d            ; Make RCL menu variable order match TVM's menu
CLMENU
0>? ".plyl"      ; Build the currently selected menu level
GTO a
"X^4"
XEQ e            ; Badge menu label with "." if zero, "!" if illegal
KEY 1 GTO 07     ; "X^4"
"X^3"
XEQ e            ; Badge menu label with "." if zero, "!" if illegal
KEY 2 GTO 08     ; "X^3"
"X^2"
XEQ e            ; Badge menu label with "." if zero, "!" if illegal
KEY 3 GTO 09     ; "X^2"
"X^1"
XEQ e            ; Badge menu label with "." if zero, "!" if illegal
KEY 4 GTO 17     ; "X^1"
"X^0"
XEQ e            ; Badge menu label with "." if zero, "!" if illegal
KEY 5 GTO 18     ; "X^0"
"SOLV"
KEY 6 GTO 19     ; "SOLV"
GTO b

LBL a            ; Create the 2nd Level menu
"QUAD"
KEY 1 GTO 27     ; Quadratic (Stack entry method)
"CUBIC"
KEY 2 GTO 28     ; Cubic     (Stack entry method)
"QRTC"
KEY 3 GTO 29     ; Quartic   (Stack entry method)
" "
KEY 4 GTO 99     ; NOP
" "
KEY 5 GTO 99     ; NOP
"EVAL"
KEY 6 GTO 95     ; Evaluate the polynomial
LBL b
KEY 7 GTO 96     ; Menu UP
KEY 8 GTO 96     ; Menu DOWN
KEY 9 GTO 97     ; EXIT
CLA
ARCL ".areg"     ; Restore the Alpha-register
CLV ".areg"      ; Reduce clutter
MENU1            ; Robust against being dismissed when exiting other menus
STOP             ; Menu functions start their XEQs from this location
GTO 99           ; Ideally this instruction never gets executed due to KEYG
;----------------------------------------------------------------------------
LBL 97           ; EXIT - restore affected original environment
CLV ".areg"
CLV ".mvar"
LCLV ".plyx"
CLV ".plyl"
CLMENU           ; From page 148 of the HP42S manual
EXITALL
;RTN             ; If execution stopped at some random place due to an
                 ; error, this will RTN there and likely yield an error.
STOP             ; May leave debris on the stack, but better than RTN
;----------------------------------------------------------------------------
LBL 96           ; Invert the menu level
XEQ a            ; FUNC will protect the stack & LASTX
GTO 99           ; Back to the Run Loop
LBL a
FUNC 00
-1
STO* ".plyl"
RTN
;----------------------------------------------------------------------------
LBL c            ; POLY INITIALIZATION (modifies X-register so use FUNC 00)
FUNC 00
XASTO ".areg"    ; Save the Alpha-register
1
STO ".plyl"      ; Set the POLY menu level (instead of using a global flag)
RTN
;----------------------------------------------------------------------------
LBL d            ; Delete/recreate X^4 → X^0 in reverse order to match what
;                  you see when you press RCL. Zero them if they don't exist.
FUNC 00
XSTR ".√4"
XEQ a
XSTR ".√3"
XEQ a
XSTR ".√2"
XEQ a
XSTR ".√1"
XEQ a
XSTR ".X^0"
XEQ a
XSTR ".X^1"
XEQ a
XSTR ".X^2"
XEQ a
XSTR ".X^3"
XEQ a
XSTR ".X^4"
XEQ a
CLV ".mvar"
RTN
; CLEAR and RECREATE the variable referenced by X. Default value is in Y.
LBL a
SF 25
RCL IND ST X     ; Make sure it exists
FC?C 25
0                ; default value, Y-register now still holds variable name
CLV IND ST Y
STO IND ST Y
RTN
;----------------------------------------------------------------------------
LBL e            ; Create MENU hints: "!" → Illegal, ":" → Complex, "." → =0
FUNC 00
ASTO ST X
REV
XSTR "."
APPEND
REV
RCL IND ST X     ; RCL variable prefixed by "."
CPX?             ; Ensure X is legal (REAL or COMPLEX)
SKIP
REAL?
GTO a
├" !"
RTN
LBL a
CPX?
├":"             ; Badge with ":" if complex
CPX?
ABS
X=0? 
├"."             ; Badge with "." if zero
RTN
;----------------------------------------------------------------------------
LBL 07           ; X^4
XASTO ".areg"    ; Save the Alpha-register
".X^4"
GTO a
;----------------------------------------------------------------------------
LBL 08           ; X^3
XASTO ".areg"    ; Save the Alpha-register
".X^3"
GTO a
;----------------------------------------------------------------------------
LBL 09           ; X^2
XASTO ".areg"    ; Save the Alpha-register
".X^2"
GTO a
;----------------------------------------------------------------------------
LBL 17           ; X^1
XASTO ".areg"    ; Save the Alpha-register
".X^1"
GTO a
;----------------------------------------------------------------------------
LBL 18           ; X^0
XASTO ".areg"    ; Save the Alpha-register
".X^0"
LBL a
XEQ 39
CLA
ARCL ".areg"     ; Restore the Alpha-register
GTO 99           ; Back to the Run Loop
;----------------------------------------------------------------------------
LBL 39           ; Manage STO & VIEW button actions for X^4 → X^0
;                  This routine does NOT modify the stack or LASTx 
ASTO ".mvar"     ; Store the coefficient name into ".mvar"
FS? 64           ; See if shift was pressed
GTO a            ; Yes, VIEW the variable for 1 sec if it exists
; STORE Result
SF 25            ; Check for trying a STO with an empty NSTK
STO ST X
FC?C 25
GTO b            ; Trying to STO an empty X-register :-/
CPX?             ; Ensure X is legal (REAL or COMPLEX)
SKIP
REAL?
GTO c
├": Invalid Type"
AVIEW            ; View an error message that you need to dismiss
RTN
LBL c            ; Number is either REAL or COMPLEX
STO IND ".mvar"  ; Store the error checked variable
├"= "            ; "=" signifies a STO operation 
ARCL ST X
GTO 01           ; View the Alpha-register during a PSE

LBL a            ; ⇧MENU: VIEW the variable for 1 sec if it exists 
XEQ e            ; Existence check of variable in the Alpha-register 
GTO b            ; Variable doesn't exist, show a stick error message
├": "            ; ":" signifies a VIEW operation
ARCL IND ".mvar"
AVIEW
PSE
CLD
RTN
LBL b
├": Nonexistent"
AVIEW            ; View an error message that you need to dismiss
RTN

LBL e            ; Alpha-register variable name existence test  
FUNC 00
ASTO ST X        ; Store the variable name into X
SF 25
RCL IND ST X 
FC?C 25
RTNYES           ; Does not exist
RTNNO            ; Does exist
;----------------------------------------------------------------------------
LBL 19           ; SOLV
XASTO ".areg"    ; Save the Alpha-register
FC? 64           ; See if shift was pressed
GTO b            ; No, Process the calculations 
XEQ a
GTO 99           ; Back to the Run Loop
LBL a
FUNC 00
0
STO ".X^0"
STO ".X^1"
STO ".X^2"
STO ".X^3"
STO ".X^4"
RTN

;----------------------------------------------------------------------------
LBL b            ; Solves the polynomial, maintains stack & Alpha-register
XEQ a
CLA
ARCL ".areg"     ; Restore the Alpha-register
GTO 99           ; Back to the Run Loop
LBL a
0≠? ".X^4"       ; If the coefficient of x⁴ ≠ 0 go to quartic solver
GTO b
0≠? ".X^3"       ; If the coefficient of x³ ≠ 0 go to cubic solver
GTO c
0≠? ".X^2"       ; If the coefficient of x² ≠ 0 go to quadratic solver
GTO d
0=? ".X^1"       ; If the coefficient of x¹ = 0 the equation is illegal
RTNERR 5         ; Error message Invalid Data
FUNC 01          ; Valid linear equation
RCL ".X^0"
RCL/ ".X^1"
+/-
STO ".√1"
RTN              ; Back to the Run Loop
LBL b            ; Get the stack in order for a .QRTC call
FUNC 04
RCL  ".X^3"
RCL/ ".X^4"
RCL  ".X^2"
RCL/ ".X^4"
RCL  ".X^1"
RCL/ ".X^4"
RCL  ".X^0"
RCL/ ".X^4"
XEQ 04           ; Don't XEQ "QRTC" - it sets ".X^4"=1
RTN              ; Back to the Run Loop
LBL c            ; Get the stack in order for a .CUBIC call
FUNC 03
RCL ".X^3"
RCL ".X^2"
RCL ".X^1"
RCL ".X^0"       ; All menu register coefficients now on the stack
XEQ ".CUBIC"
RTN              ; Back to the Run Loop
LBL d            ; Get the stack in order for a .QUAD call 
FUNC 02
RCL ".X^2"
RCL ".X^1"
RCL ".X^0"       ; All menu register coefficients now on the stack
XEQ ".QUAD"
RTN              ; Back to the Run Loop
;----------------------------------------------------------------------------
LBL 27           ; Quadratic: DROPs 2 elements, returns 2 roots
XASTO ".areg"    ; Save the Alpha-register
XEQ ".QUAD"
GTO a
;----------------------------------------------------------------------------
LBL 28           ; Cubic: DROPs 3 elements, returns 3 roots
XASTO ".areg"    ; Save the Alpha-register
XEQ ".CUBIC"
GTO a
;----------------------------------------------------------------------------
LBL 29           ; Quartic: DROPs 4 elements, returns 4 roots
FS? 64           ; See if shift was pressed
GTO b            ; Yes, fill the stack ready for a 4STK solve 
XASTO ".areg"    ; Save the Alpha-register
XEQ ".QRTC"
LBL a
CLA
ARCL ".areg"     ; Restore the Alpha-register
GTO 99           ; Back to the Run Loop
LBL b
RCL ".X^0"
STO ST L
DROP
RCL ".X^3"
RCL ".X^2"
RCL ".X^1"
RCL ".X^4"
STO/ ST Y
STO/ ST Z
STO/ ST T
STO/ ST L
X<> ST L
RTN
;----------------------------------------------------------------------------
LBL 95           ; Evaluate the polynomial
FS? 64           ; See if shift was pressed
GTO b            ; Yes, put all coefficients onto the stack 
XEQ a
GTO 99           ; Back to the Run Loop
LBL a            ; Plug X into the implied equation and solve
FUNC 11
ENTER
RCL* ST Y
ENTER
RCL* ST Z
ENTER
RCL* ST T        ; X→T: x⁴, x³, x², x
RCL* ".X^4"
X<>Y
RCL* ".X^3"
+
X<>Y
RCL* ".X^2"
+
X<>Y
RCL* ".X^1"
+
RCL+ ".X^0"
XEQ 98           ; Clean up tiny numerical precision errors, turns a+i0 → a
RTN
;-----------
LBL b            ; ⇧EVAL puts all coefficients on the stack
RCL ".X^4"
FC? 80           ; If in 4STK put ".X^4" in L
STO ST L
RCL ".X^3"
RCL ".X^2"
RCL ".X^1"
RCL ".X^0"
GTO 99

;-----------------------------------------------------------------------
; QUARTIC equation solver (can use complex coeffs, 4STK/NSTK compliant)
; 4STK: Solves ax⁴+bx³+cx²+dx+e = 0  via   a + b ↑ c ↑ d ↑ e XEQ ".QRTC" 
; NSTK: Solves ax⁴+bx³+cx²+dx+e = 0  via   a ↑ b ↑ c ↑ d ↑ e XEQ ".QRTC" 
; Note: For 4STK, "a" must be stored in LASTX (hence the "+", or whatever)
; Roots are stored in ".√4" → ".√1" (which can hold complex numbers)
; Coefficients are stored in ".X^4" → ".X^0"
;   This enables checking coefficients that would otherwise be lost and
;   subsequently using the SOLV menu button to repeat the calculation.
; Works with complex coefficients.
; A useful website: https://www.1728.org/quartic2.htm
; Some examples:
; 2x⁴-20x³+70x²-100x+48 = 0
;                    (2, -20, 70, -100, 48)  →  Roots: 1, 2, 3, 4
; x⁴-9x³+45x²-87x+50 = 0
;                         (-9, 45, -87, 50)  →  Roots: 1, 2, 3±i4
; -4x⁴+32x³-168x²+320x-500 = 0
;                 (-4, 32, -168, 320, -500)  →  Roots: 1±i2, 3±i4
; x⁴-2x³+x² = 0            (1, -2, 1, 0, 0)  →  Roots: 1, 1, 0, 0
; x⁴-x³ = 0                (1, -1, 0, 0, 0)  →  Roots: 1, 0, 0, 0
; x⁴+x² = 0                 (1, 0, 1, 0, 0)  →  Roots: 0, 0, 0±i
; x⁴+x = 0                  (1, 0, 0, 1, 0)  →  Roots: 0, -1, 0.5±i√3/2
; x⁴+1 = 0                  (1, 0, 0, 0, 1)  →  Roots: √2±i√2, -√2±i√2
; x⁴ = 0                    (1, 0, 0, 0, 0)  →  Roots: 0, 0, 0, 0
; x⁴-2x²+1 = 0             (1, 0, -2, 0, 1)  →  Roots: 1, 1, -1, -1
; x⁴+2x²+1 = 0              (1, 0, 2, 0, 1)  →  Roots: i, i, -i, -i
; x⁴-4x³+6x²-4x+1 = 0      (1, -4, 6, -4, 1) →  Roots: 1, 1, 1, 1
; x⁴-(7+i13)x³-(45-i67)x²+(191+i21)x-(60+i155) = 0
;   (1, -7-i13, -45+i67, 191+i21, -60-i155)  →  Roots: 1+i2, 3+i4, 2+i3, 1+i4
;-----------------------------------------------------------------------
LBL ".QRTC"
; Populates the ".X^0" → ".X^4" variables (sets ".X^4"=1 in 4STK mode)
; You get an NSTK error if you try to call this with too few arguments!
FC? 80           ; 4STK mode?
GTO a
R↑N 5
0≠? ST X         ; Legal Quartic equation? coefficient of x⁴ is non-zero.
GTO b
R↓N 5            ; Restore stack, LASTX untouched, bail out
RTNERR 5         ; Error message Invalid Data
LBL b
X<> ST L
R↓N 5            ; Save NSTK's LASTX in level 5
LBL a            ; X→T: e, d, c, b  L=a  for both 4STK and NSTK
0=? ST L         ; Illegal Quartic equation: coefficient of x⁴ is zero.
RTNERR 5         ; Error message Invalid Data
STO ".X^0"       ; X→T: e, d, c, b  L=a
R↓N 4
STO ".X^1"
R↓N 4
STO ".X^2"
R↓N 4
STO ".X^3"
R↓N 4
X<> ST L
STO ".X^4"       ; X→T: a, d, c, b  L=e, all coefficients stored
LSTO ".plya"
X<> ST L         ; 4STK stack/LASTX restored ready for FUNC
FC? 80           ; 4STK mode?
GTO c
R↑N 5
X<> ST L
R↓N 5
LBL c            ; Both 4STK and NSTK environments restored ready for FUNC
FUNC 44          ; Now prepare the stack assuming the coefficient of x⁴ is 1
X<> ".plya"      ; e is now in ".plya", LASTX=0 inside FUNC
STO/ ST T
STO/ ST Z
STO/ ST Y
STO/ ".plya"
X<> ".plya"
LCLV ".plya"
XEQ 04
RTN
;-----------------------------------------------------------------------
; BEWARE: This requires the coefficient of x⁴ be 1. DO NOT access ".X^n"
LBL 04           ; QRTC entry point (".X^0" → ".X^4" already populated)
0=? ".X^4"       ; Illegal Quartic equation: coefficient of x⁴ is zero.
RTNERR 5         ; Error message Invalid Data
FUNC 44          ; X→T: d, c, b, a
; Filter out the trivial case of 1 zero root leaving just a CUBIC to do
; This also avoids some significant accumulating numerical precision errors.
0≠? ST X         ; Note: If .X4=i and .X0=0 then .X0/.X4 = 0+i0 :-/ 
GTO a            ; X→T: d, c, b, a    Do the full quartic solve
RE               ; Turns 0+i0 → 0
STO ".√4"        ; X→T: 0, c, b, a
CLX
1
R↓N 4            ; X→T: c, b, a, 1
XEQ 03           ; Solve the CUBIC equation
RTN
LBL a            ; X→T: d, c, b, a   Do the full quartic solve
LSTO "d"
R↓N 4
LSTO "c"
R↓N 4
LSTO "b"
R↓N 4
LSTO "a"         ; X→T: a, d, c, b 
2
/
ENTER
X^2
-1.5
RCL* ST Y        ; X→T: -3/2*(a/2)², (a/2)², a/2
RCL+ "b"         ; X→T: b-3/2*(a/2)², (a/2)², a/2
STO ".√1"        ; Temporary storage for "f"
DROP
RCL- "b"
RCL* ST Y
RCL+ "c"         ; X→T: c+a/2*((a/2)²-b), a/2
STO ".√4"        ; Temporary storage for "g"
X<>Y
ENTER
X^2
ENTER
X^2
-0.1875          ; X→T: -3/16, (a/2)⁴, (a/2)², a/2
*
RCL+ "d"
RCL "c"
RCL* ST T        ; X→T: c*a/2, d-3/16*(a/2)⁴, (a/2)², a/2
2
/
-                ; X→T: d-3/16*(a/2)⁴-c*a/4, (a/2)², a/2
X<>Y
RCL* "b"
4
/
+                ; X→T: d-3/16*(a/2)⁴-c*a/4+b/4*(a/2)²   This is h
RCL ".√1"        ; Temporary storage for "f",  Build CUBIC coefficients
2
/
ENTER
X^2
RCL- ST Z        ; X→T: (f/2)²-h, f/2, h
4
/
RCL ".√4"        ; Temporary storage for "g"
X^2
-64
/                ; X→T: -g²/64, ((f/2)²-h)/4, f/2, h
1
R↓N 4            ; X→T: 1, f/2, ((f/2)²-h)/4, -g²/64
XEQ 03           ; Solve the CUBIC equation
; The order of the roots is now important!
; A zero root must be in Z (X & Y shouldn't be zero). Next,
; For one real and 2 complex roots, the real root must be in Z.
0=? ST X         ; If a root is 0 put it in Z
GTO a
X<> ST Z
0=? ST X
GTO a
X<>Y
0=? ST X
GTO a
REAL?            ; If a root is real put it in Z
GTO a
X<> ST Z
REAL?
GTO a
X<>Y
LBL a
R↓N 3
SQRT             ; p
X<>Y
SQRT             ; q
RCL ".√4"        ; Temporary storage for "g"
0=? ST X
GTO a            ; g=0 
-8
/                ; X→T: g/8, q, p
RCL ST Y
RCL* ST T        ; X→T: p*q, g/8, q, p
0≠? ST X
/
LBL a
-0.25
RCL* "a"         ; X→T: -s, r, q, p
STO ".√1"
STO ".√2"
STO ".√3"
STO ".√4"
DROP
STO+ ".√1"
STO- ".√2"
STO- ".√3"
STO+ ".√4"
DROP
STO+ ".√1"
STO- ".√2"
STO+ ".√3"
STO- ".√4"
DROP
STO+ ".√1"       ; root1 =  p + q + r - s
STO+ ".√2"       ; root1 =  p - q - r - s
STO- ".√3"       ; root1 = -p + q - r - s
STO- ".√4"       ; root1 = -p - q + r - s
RCL ".√4"
XEQ 98           ; Clean up tiny numerical precision errors, turns a+i0 → a
STO ".√4"
RCL ".√3"
XEQ 98           ; Clean up tiny numerical precision errors, turns a+i0 → a
STO ".√3"
RCL ".√2"
XEQ 98           ; Clean up tiny numerical precision errors, turns a+i0 → a
STO ".√2"
RCL ".√1"
XEQ 98           ; Clean up tiny numerical precision errors, turns a+i0 → a
STO ".√1"
RTN

;-----------------------------------------------------------------------
; CUBIC equation solver (can use complex coeffs, 4STK/NSTK compliant)
; Solves ax³+bx²+cx+d = 0   via   a ↑ b ↑ c ↑ d  XEQ ".CUBIC"
; Drops the stack 4 levels and then pushes the 3 roots onto the stack
; Roots are stored in ".√3" → ".√1" (which can hold complex numbers)
; 1st cubic root → X=".√3" and the quadratic roots → Y=".√2" & Z=".√1". 
; Coefficients are stored in ".X^3" → ".X^0"
;   This enables checking coefficients that would otherwise be lost and
;   subsequently using the SOLV menu button to repeat the calculation.
; A useful website: https://www.1728.org/cubic2.htm
; I used the following website to code up this formula:
; math.stackexchange.com/questions/15865/why-not-write-the-solutions-of-a-cubic-this-way/18873#18873
; Some examples:
;  2x³-12x²+22x-12 = 0       (2, -12, 22, -12)  →  Roots: 1, 2, 3
;   x³+6x²+12x+8 = 0         (1, 6, 12, 8)      →  Roots: -2, -2, -2
;   x³+2x²-x-2 = 0           (1, 2, -1, -2)     →  Roots: 1, -1, -2
; -2x³+10x²-22x+30 = 0       (-2, 10, -22, 30)  →  Roots: 1±i2, 3
; x³-(6+i9)x²-(15-i34)x+(40-i5) = 0
;                   (1, -6-i9, -15+i34, 40-i5)  →  Roots: 1+i2, 3+i4, 2+i3
;-----------------------------------------------------------------------
LBL ".CUBIC"
; Populates the ".X^0" → ".X^3" variables (sets ".X^4" = ".√4" = 0)
; You get an NSTK error if you try to call this with too few arguments!
0=? ST T         ; Illegal Cubic equation: coefficient of x³ is zero.
RTNERR 5         ; Error message Invalid Data
FUNC 43          ; X→T: d, c, b, a
STO ".X^0"
R↓N 4            ; X→T: c, b, a, d
STO ".X^1"
R↓N 4            ; X→T: b, a, d, c
STO ".X^2"
R↓N 4            ; X→T: a, d, c, b
STO ".X^3"
R↓N 4            ; X→T: d, c, b, a
CLX              ; Reset variables not pertaining to a cubic solution
0                ; It's an NSTK thing...
STO ".X^4"
STO ".√4"
CLX
RCL ".X^0"       ; End of coefficient storage, stack restored
XEQ 03
RTN
;-----------------------------------------------------------------------
LBL 03           ; CUBIC entry point (".X^0" → ".X^4" already populated)
0=? ST T         ; Illegal Cubic equation: coefficient of x³ is zero.
RTNERR 5         ; Error message Invalid Data
FUNC 43          ; X→T: d, c, b, a
RCL/ ST T        ; X→T: d/a, c, b, a
X<> ST Z
RCL/ ST T        ; X→T: b/a, c, d/a, a
X<>Y
RCL/ ST T        ; X→T: c/a, b/a, d/a, a
3
STO/ ST Y
STO/ ST Z        ; X→T: 3, c/3a, b/3a, d/a
R↓N 4
X<>Y
+/-              ; X→T: -b/3a, c/3a, d/a, 3
STO ".√1"        ; Temporary storage: -b/3a
X^2
RCL- ST Y
LSTO ".√2"       ; X→T: (b/3a)²-c/3a, c/3a, d/a, 3  (Temporary storage: B's numerator)
-0.5
RCL* ST Z
+                ; X→T: (b/3a)²-1.5c/3a, c/3a, d/a
RCL* ".√1"
+/-              ; X→T: b/3a*((b/3a)²-1.5*c/3a), c/3a, d/a
0.5
RCL* ST T
+                ; Final "g"   X→T: b/3a*((b/3a)²-1.5*c/3a)+d/2a, c/3a, d/a
XEQ 98           ; Clean up tiny numerical precision errors, turns a+i0 → a
LASTX
X^2
+/-              ; -(d/2)², g, c/3a, d/a
RCL ST T
RCL* ST Z
+                ; X→T: g*d/a-(d/2a)², g, c/3a
-0.75
RCL* ".√1"
RCL* ".√1"       ; X→T: -0.75*(b/3a)², g*d/a-(d/2a)², g, c/3a
RCL ST T
+
LASTX
X^2              ; X→T: (c/3a)², c/3a-0.75*(b/3a)², g*d/a-(d/2a)², g
*
+                ; X→T: (c/3a)²(c/3a-0.75*(b/3a)²)+g*d/a-(d/2a)², g
SQRT             ; This is the determinant - the cube root term can't = 0
XEQ 98           ; Clean up tiny numerical precision errors, turns a+i0 → a
X=Y?             ; Select the other root if A will become 0
+/-
RCL- ST Y
3
1/X
Y^X              ; A is now complete
0≠? ST X
STO/ ".√2"       ; B is now complete
0=? ST X
STO ".√2"
; X-register holds A, the value of B in ".√2" is now final
RCL ".√1"        ; X→T: -b/3a, A
STO ".√3"
X<> ".√2"        ; X→T: B, A   .√1→3 now hold -b/3a
STO+ ".√1"
X<>Y
STO+ ".√1"       ; X→T: A, B    ".√1" = -b/3a+A+B is the final value
-0.5
0.75
SQRT
RCOMPLX          ; X→T: (-1+i√3)/2, A, B
RCL* ST Y
STO+ ".√3"
LASTX
RCL* ST T
STO+ ".√2"
DROPN 2
LASTX
CONJ
RCL* ST Y
STO+ ".√2"       ; ".√2" = -b/3a+A*(-1-i√3)/2+B*(-1+i√3)/2 is the final value
LASTX
RCL* ST T
STO+ ".√3"       ; ".√3" = -b/3a+A*(-1+i√3)/2+B*(-1-i√3)/2 is the final value
RCL ".√1"
XEQ 98           ; Clean up tiny numerical precision errors, turns a+i0 → a
STO ".√1"
RCL ".√2"
XEQ 98           ; Clean up tiny numerical precision errors, turns a+i0 → a
STO ".√2"
RCL ".√3"
XEQ 98           ; Clean up tiny numerical precision errors, turns a+i0 → a
STO ".√3"
RTN

;-----------------------------------------------------------------------
; QUADRATIC equation solver (can use complex coeffs, 4STK/NSTK compliant)
; Solves ax²+bx+c = 0   via   a ↑ b ↑ c XEQ ".QUAD"
; Drops the stack 3 levels and then pushes the 2 roots onto the stack
; Roots are stored in ".√2" → ".√1" (which can hold complex numbers)
; Coefficients are stored in ".X^2" → ".X^0" with ".X^3"=0 
;   This enables checking coefficients that would otherwise be lost and
;   subsequently using the SOLV menu button to repeat the calculation.
; Works with complex coefficients.
; Some examples:
;  2x²-6x+4 = 0             (2, -6, 4)          →  Roots: 1, 2
; -2x²+4x-10 = 0            (-2, 4, -10)        →  Roots: 1±i2
; x²-(4+i6)x-(5-i10) = 0    (1, -4-i6, -5+i10)  →  Roots: 1+i2, 3+i4
;-----------------------------------------------------------------------
LBL ".QUAD"
0=? ST Z         ; Illegal Quadratic equation: coefficient of x² is zero.
RTNERR 5         ; Error message Invalid Data
FUNC 32 
; You get an NSTK error if you try to call this with too few arguments!
0                ; Reset variables not pertaining to a quadratic solution
STO ".X^4"
STO ".X^3"
STO ".√4"
STO ".√3"
DROP             ; X→T: c, b, a, ?
STO ".X^0"
R↓N 3            ; X→T: b, a, c, ?
STO ".X^1"
R↓N 3            ; X→T: a, c, b, ?
STO ".X^2"
R↓N 3            ; X→T: c, b, a, ?
                 ; End of coefficient storage, stack restored
XEQ 02
RTN
;-----------------------------------------------------------------------
LBL 02           ; QUAD entry point (".X^0" → ".X^4" already populated)
0=? ST Z         ; Illegal Quadratic equation: coefficient of x² is zero.
RTNERR 5         ; Error message Invalid Data
FUNC 32          ; X→T: c, b, a
X<> ST Z
STO/ ST Z
STO+ ST X
/
+/-
X^2
LASTX
X<> Z
-                ; X = (-b/2a)² - c/a, Y = -b/2a
SQRT             ; can be complex
ENTER
+/-
RCL ST Z
STO+ ST Z
+                ; The solve is complete, now just store the results
XEQ 98           ; Clean up tiny numerical precision errors, turns a+i0 → a
STO ".√2"        ; 2nd root (-b - √determinant)/2a
X<>Y
XEQ 98           ; Clean up tiny numerical precision errors, turns a+i0 → a
STO ".√1"        ; 1st root (-b + √determinant)/2a
RTN

;-----------------------------------------------------------------------
LBL 98           ; Zeros out numbers very close to zero. Turns N+i0 into N
LSTO ".plyx"     ; Holds the original X-register
X<> ST L         ; Preserves original LASTX 
FUNC 11          ; NOTE: This puts X into LASTX when it returns 
1E-30
X<> ".plyx"      ; Restores X, saves the clipping threshold
ENTER
IM               ; Imaginary part
XEQ a
X<>Y
RE               ; Real part
XEQ a
LCLV ".plyx"
0=? ST Y
RTN 
X<>Y
RCOMPLX
RTN
LBL a
ABS
X≤? ".plyx"
0
X>? ".plyx"
LASTX
X<>Y
DROP
RTN

;------------------------------------------------------------------------
; 2026.1105: TVM - Mick Mueck mick.mueck@mac.com
;------------------------------------------------------------------------
; With thanks to Thomas Okken's open source TVM code and Duncan Murray
; Don't even try to modify this code without reaching out to me first - it's
; too complex! I have a copy with tons more comments you'll want to have. 

; Mimics Plus42's TVM with the exception of AMRT (Amortization)
; This code will run both in 4STK and NSTK modes.
; Uses LBLs unused by .CONST & .POLY: A→J,47→49,57→59,67→69,77→79,87→94

; Terminology:
; N:    Number of Periods
; I%YR: Interest % per Year   ("I%YR"=i*100*"P/YR")
; PV:   Present Value 
; PMT:  Payment
; FV:   Future Value
; P/YR: Payments/Year (input only)

; •The "big-5" primary TVM variables are N, I%YR, PV, PMT, FV
; •They are internally stored in global registers of the same name.
; •They are entered and solved for in classic HP42S VARMENU style i.e. the
;    known variables are stored by doing num1→menu1, num2→menu2 etc. and a
;    successive click on an unknown variable's button i.e. num4→menu4→menu5
;    changes the data entry mode from STORE to SOLVE. I never liked VARMENU's 
;    behavior because if you want to store the same number into two different
;    variables the second variable's menu button press initiates SOLVE instead
;    of STORE. Also, if you leave the calculator for a while and come back to 
;    it later you might not remember which state you left it in.
; •CLEAR zeros all 5 primary TVM variables and sets the data entry mode to STO.
; •RESET performs:  P/YR = 12  and  BEGIN = 0 (i.e. END mode)
; •P/YR (Payments/Year) is write-only and must be an integer between 1 → 999.
; •BEGIN, END set the payment to the beginning or end of the payment period.
; •RESET, BEGIN, END & P/YR do NOT alter your data entry mode.
; •STO shows the current data entry mode and toggles it when pressed.
; •When you start TVM, no previous TVM state is lost, but you are put into 
;    STORE data entry mode for your next TVM variable button click.
; •⇧Press on any of the big-5 buttons to briefly reveal it's value.
; •You can also do RCL (or STO or VIEW) and select a variable from that menu.
; •The big-5 menu buttons show helpful hints by interpreting their variables
;    after each menu button press. A zero value is denoted by a trailing "." 
;    and an illegal value by a trailing "!". You can't enter an illegal value
;    via the menus, but you can externally write one directly into its variable.
; •TVM can be used by other programs. Write to the known variable TVM registers 
;    and the BEGIN variable (which can ONLY be 0 or 1) and then XEQ the variable
;    name to be solved. Ordinarily all my skin related program and variable  
;    names start with ".", but for Plus42 TVM compatibility these ones do not.

LBL "TVM"
XEQ e            ; Initialization
; Each big-5 menu routine should SF 33 to mimic VARMENU behavior.
;------------------------------------------------------------------------
LBL A            ; MAIN RUN LOOP (ONLY modifies the Alpha-register)
;------------------------------------------------------------------------
XASTO ".areg"    ; Save the Alpha-register (menu building will destroy it)
XEQ D            ; Make the RCL menu match the big-5 in the TVM menu.
CLMENU
0>? ".tvml"      ; Build the currently selected menu level
GTO a
"N"
XEQ c            ; Badge menu label with "." if zero, "!" if illegal
KEY 1 GTO 47     ; "N"
"I%YR"
XEQ c            ; Badge menu label with "." if zero, "!" if illegal
KEY 2 GTO 48     ; "I%YR"
"PV"
XEQ c            ; Badge menu label with "." if zero, "!" if illegal
KEY 3 GTO 49     ; "PV"
"PMT"
XEQ c            ; Badge menu label with "." if zero, "!" if illegal
KEY 4 GTO 57     ; "PMT"
"FV"
XEQ c            ; Badge menu label with "." if zero, "!" if illegal
KEY 5 GTO 58     ; "FV"
"CLEAR"
KEY 6 GTO 59     ; "CLEAR"
GTO b

LBL a            ; Create the 2nd Level menu
XEQ d            ; P/YR: Badge menu label with "." if zero, "!" if illegal
KEY 1 GTO 67     ; "P/YR"
"BEGIN"
0≠? "BEGIN"
"BEGI•"
KEY 2 GTO 68     ; "BEGIN"/BEGI•"
"END"
0=? "BEGIN"
├"•"
KEY 3 GTO 69     ; "END"/END•"
CLA
KEY 4 GTO A      ; NOP
"STO"
FC? 33
├"•"
KEY 5 GTO 77     ; STO/XEQ mode toggle for the next big-5 menu operation
"RESET"
KEY 6 GTO 78     ; "RESET"
LBL b
KEY 7 GTO 87     ; Menu UP
KEY 8 GTO 87     ; Menu DOWN
KEY 9 GTO 88     ; EXIT
CLA
ARCL ".areg"     ; Restore the Alpha-register
CLV ".areg"      ; Reduce clutter
MENU1
STOP             ; Menu functions start their XEQs from this location
GTO A            ; Ideally this never gets executed due to KEYG usage
;------------------------------------------------------------------------
LBL 88           ; EXIT - restore affected original environment
CLV ".tvml"      ; Remove TVM internal variables
CLV ".areg"
CLV ".mvar"
CLMENU           ; From page 148 of the HP42S manual
EXITALL
;RTN             ; If execution stopped at some random place due to an
                 ; error, this will RTN there and likely yield an error.
STOP             ; May leave debris on the stack, but better than RTN
;------------------------------------------------------------------------
LBL 87           ; Invert the menu level
XASTO ".areg"    ; Save the Alpha-register
XEQ a            ; FUNC 00 will protect the stack & LASTX
CLA
ARCL ".areg"     ; Restore the Alpha-register
GTO A            ; Back to the Run Loop
LBL a
FUNC 00
-1
STO* ".tvml"
0>? ".tvml"      ; menu level 2?
XEQ B            ; Yes, show the status line
RTN              ; Maintain exist data entry mode
;------------------------------------------------------------------------
LBL c            ; Make MENU hints "!" or "." for N, I%YR, PV, PMT, FV
FUNC 00
XASTO ST X
RCL IND ST X     ; Guaranteed to exist due to XEQ D
REAL?
GTO a
├" !"
RTN
LBL a
X=0?
├"."
RTN

LBL d            ; Make MENU hints "!" or "." ONLY for P/YR
FUNC 00
"P/YR"
RCL "P/YR"
XEQ J
SKIP
RTN
CLA
"P/YR!"          ; P/YR was illegal 
RTN
;------------------------------------------------------------------------
LBL e            ; TVM INITIALIZATION (modifies X, so use FUNC 00)
FUNC 00
CF 33            ; For STO operation on the big 5 (to mimic VARMENU)
1
STO ".tvml"      ; Set the TVM menu level
RTN
;------------------------------------------------------------------------
LBL D            ; Clear & recreate N I%YR PV PMT FV P/YR MODE in reverse
;                  order so the RCL menu matches TVM's. Sets them to the 
;                  default if since returning to TVM they were cleared.
;                  If MODE is illegal (i.e. not 0 or 1) it is set to 0.
FUNC 00
0                ; Default value
CF 25            ; Just in case some rogue function didn't clear it
XSTR "BEGIN"
XEQ a
REAL?            ; Only MODE is constantly forced to be legal
SKIP
0
X≠0?
1
STO "BEGIN"
12               ; Default value
XSTR "P/YR"
XEQ a
0                ; Default value
XSTR "FV"
XEQ a
0                ; Default value
XSTR "PMT"
XEQ a
0                ; Default value
XSTR "PV"
XEQ a
0                ; Default value
XSTR "I%YR"
XEQ a
0                ; Default value
XSTR "N"
XEQ a
CLV ".mvar"      ; to reduce clutter between menu commands
RTN
; CLEAR & RECREATE the variable in X. Default value in Y.
LBL a
SF 25
RCL IND ST X     ; Make sure it exists
FC?C 25
RCL ST Y         ; default value, Y holds the variable name
CLV IND ST Y
STO IND ST Y
RTN
;------------------------------------------------------------------------
LBL 47           ; N
XASTO ".areg"    ; Save the Alpha-register
"N"
GTO a
;------------------------------------------------------------------------
LBL 48           ; I%YR
XASTO ".areg"    ; Save the Alpha-register
"I%YR"
GTO a
;------------------------------------------------------------------------
LBL 49           ; PV
XASTO ".areg"    ; Save the Alpha-register
"PV"
GTO a
;------------------------------------------------------------------------
LBL 57           ; PMT
XASTO ".areg"    ; Save the Alpha-register
"PMT"
GTO a
;------------------------------------------------------------------------
LBL 58           ; FV
XASTO ".areg"    ; Save the Alpha-register
"FV"
LBL a
XEQ C
CLA
ARCL ".areg"     ; Restore the Alpha-register
GTO A            ; Back to the Run Loop
;------------------------------------------------------------------------
LBL 59           ; CLEAR
XEQ a            ; FUNC 00 will protect the stack & LASTX
GTO A            ; Back to the Run Loop
LBL a
FUNC 00
0
STO "FV" 
STO "PMT"
STO "PV"
STO "I%YR"
STO "N"
CF 33            ; After a CLEAR, setup the big-5 menu for STO
RTN              ; Back to the Run Loop
;------------------------------------------------------------------------
LBL 67           ; P/YR
XASTO ".areg"    ; Save the Alpha-register
"P/YR"
SF 25
LSTO "X"         ; Pass X into a FUNC 00 without disturbing LASTX 
FC?C 25
GTO b            ; "Nonexistent" error message, and GTO A
XEQ a
GTO c            ; Back to Run Loop, data entry mode Flag 33 untouched
LBL b
├": Nonexistent"
AVIEW
CF 33            ; Setup big-5 menus for STO after an error
LBL c
CLA
ARCL ".areg"     ; Restore the Alpha-register
GTO A            ; Back to the Run Loop

LBL a
FUNC 00          ; Now preserve the stack and LASTX
RCL "X"
ASTO ".mvar"     ; Store the variable name into ".mvar"
FS? 64           ; See if shift was pressed
GTO G            ; Yes, VIEW "P/YR" for 1 sec if it exists
XEQ J            ; Conditional XEQ: Error check X for P/YR constraints
GTO 90           ; P/YR was illegal, VIEW the error message.
STO "P/YR"       ; P/YR was good 
XEQ B            ; Display the Status Line
RTN

; Must be called from a FUNC 00 world because it mangles the stack
LBL J            ; CONDITIONAL Function. P/YR INTEGER & Range check 
REAL?
SKIP
GTO a
FP
1000             ; Max P/YR to match Plus42
1
LASTX            ; "P/YR", 1, 1000, FP("P/YR")
0≠? ST T
GTO a            ; Invalid Type ("P/YR" not an INTEGER)
X<? ST Y
GTO b            ; Invalid data ("P/YR"<1)
X≥? ST Z
GTO b            ; Invalid data ("P/YR"≥1000)
RTNNO            ; P/YR variable is good.
LBL a
├": Invalid"
RTNYES           ; Variable is bad
LBL b
├": Range Error"
RTNYES           ; Variable is bad
;------------------------------------------------------------------------
LBL 68           ; BEGIN
XASTO ".areg"    ; Save the Alpha-register
XEQ a            ; FUNC will protect the stack & LASTX
GTO b
LBL a
FUNC 00
1
STO "BEGIN"
GTO B            ; Display the Status Line and RTN
;------------------------------------------------------------------------
LBL 69           ; END
XASTO ".areg"    ; Save the Alpha-register
XEQ a            ; FUNC will protect the stack & LASTX
GTO b
LBL a
FUNC 00
0
STO "BEGIN"
GTO B            ; Display the Status Line and RTN
;------------------------------------------------------------------------
LBL 77           ; STO/XEQ mode toggle for the next menu operation
FC?C 33          ; Toggle flag 33 (SET→XEQ, CLEAR→STO)
SF 33
GTO A            ; Back to the Run Loop
;------------------------------------------------------------------------
LBL 78           ; RESET
XASTO ".areg"    ; Save the Alpha-register
XEQ a            ; FUNC will protect the stack & LASTX
LBL b
CLA
ARCL ".areg"     ; Restore the Alpha-register
GTO A            ; Back to the Run Loop
LBL a
FUNC 00
12
STO "P/YR"
0
STO "BEGIN"
;------------------------------------------------------------------------
LBL B            ; TVM status line. Come here from a FUNC 00 place.
SF 25
RCL "P/YR"       ; In case P/YR was not set if TVM called externally
FC?C 25
12
STO "P/YR"
"???"            ; The default if P/YR is not real
REAL?
CLA
REAL?
AIP              ; append integer part to the alpha register
SF 25
RCL "BEGIN"      ; In case BEGIN was not set if TVM called externally 
FC?C 25
0
STO "BEGIN"
├" P/YR"
0=? "BEGIN"
XSTR "                      END Mode"  ; This string length is 30
0≠? "BEGIN"
XSTR "                    BEGIN Mode"  ; This string length is 30
ALENG
WIDTH            ; (WIDTH+1)/6 → number of columns in Plus42/Free42 
1                ; Plus42's "GETDS" is not a valid Free42 instruction 
+
6
÷
-                ; Negative number indicates SUBSTR is right justified 
SUBSTR
ARCL ST X        ; Right justify the MODE on the status line
AVIEW
RTN
;------------------------------------------------------------------------
LBL C            ; STO, VIEW or SOLVE  N, I%YR, PV, PMT, FV
;                  This routine does NOT modify the stack or LASTx 
ASTO ".mvar"     ; Store the variable name into ".mvar"
FS? 64           ; See if shift was pressed
GTO G            ; Yes, VIEW the variable for 1 sec if it exists
FS? 33           ; No,  Is this a sequential menu button press?  
GTO F            ; Yes, Solve for the variable
SF 33            ; Keep the menu behaving like VARMENU
SF 25            ; Check for trying a STO with an empty NSTK
STO ST X
FC?C 25
GTO b            ; Trying to STO an empty X-register :-/
REAL?            ; Validate REAL or confirm X isn't blank in NSTK
SKIP
GTO a            ; Trying to STO a number that isn't REAL
STO IND ".mvar"  ; Store the error checked variable
├"="             ; "=" signifies a STO operation 
ARCL ST X
GTO 01           ; View the Alpha-register during a PSE

LBL F            ; XEQ the program implied by the variable
XEQ IND ".mvar"  ; RTNERR: Execution stops here with an error message
                 ; or X=answer without having touched the Alpha-register 
├"→"             ; "→" signifies the result of a calculation
ARCL ST X
GTO c            ; Show the Alpha-register for 1 second

; VIEW results 
LBL G            ; ⇧MENU: VIEW the variable for 1 sec if it exists 
XEQ d            ; Existence check
GTO b            ; Variable doesn't exist
├":"             ; ":" signifies a VIEW operation
ARCL IND ".mvar"
LBL c            ; Show the Alpha-register for 1 second
AVIEW
SF 33            ; Allows big-5 XEQ during a PSE
PSE
CLD
RTN
LBL a
├": Not REAL"
GTO 90           ; View an error message that you need to dismiss
LBL b
├": Nonexistent"
LBL 90           ; View an error message that you need to dismiss
CF 33            ; Set STO data entry mode after an error
AVIEW
RTN

LBL d            ; Existence test for variable in the Alpha-register
FUNC 00
ASTO ST X        ; Store the variable name into X
SF 25
RCL IND ST X 
FC?C 25
RTNYES           ; Does not exist
RTNNO            ; Does exist
;------------------------------------------------------------------------
LBL "N"          ; Solve for N (for i=0 & i≠0)
FUNC 01
2                ; Error check all variables except N
XEQ E            ; A CONDITIONAL XEQ
GTO H            ; Variable error checking failed
XEQ I            ; creates "i" from I%YR & PMT(mode)
RCL "PV"
RCL+ "FV"        ; PV+FV, i, pmt  L=PV
0≠? ST Y         ; i≠0?
GTO a
0=? ST Z         ; pmt=0?
GTO b            ; ERROR: pmt=0, Invalid Data 
RCL÷ ST Z
+/-
STO "N"
RTN              ; Return with the result stored in "N"
LBL a            ; Calculate -log1p((PV+FV)/((pmt/i)-FV)) / log1p(i)
RCL ST Z         ; pmt, PV+FV, i, pmt
RCL÷ ST Z
RCL- "FV"
÷
LN1+X
+/-              ; -log1p((PV+FV)/((pmt/i)-FV)), i, pmt
X<>Y
LN1+X
÷
STO "N"
RTN              ; Return with the result stored in "N"
LBL b
CLA
"ERROR: PMT=0"
GTO H

;------------------------------------------------------------------------
LBL "PV"         ; Solve for PV (for i=0 & i≠0)
FUNC 01
4                ; Error check all variables except PV
XEQ E            ; A CONDITIONAL XEQ
GTO H            ; An error was detected
RCL "FV"
XEQ I            ; creates "i" from I%YR
RCL "N"
+/-              ; -N, i, pmt, FV
0=? ST Y         ; 0=? i
GTO a            ; Calculate PV(i=0)   -(FV+PMT*N)
X<>Y             ; Calculate expm1(-n*log1p(i))*pmt/i - fv*exp(-n*log1p(i)))
STO÷ ST Z        ; i, -N, pmt/i, FV
LN1+X
×                ; -N*log1p(i), pmt/i, FV
E↑X
STO× ST Z
LASTX            ; -N*log1p(i), exp(-n*log1p(i))), pmt/i, fv*exp(-n*log1p(i)))
E↑X-1
LBL a
RCL× ST Z        ; expm1(-n*log1p(i))*pmt/i, exp(-n*log1p(i))), pmt/i, fv*exp(-n*log1p(i)))
RCL- ST T
STO "PV"
RTN              ; Return with the result stored in "PV"

;------------------------------------------------------------------------
LBL "FV"         ; Solve for FV (for i=0 & i≠0)
FUNC 01
6                ; Error check all variables except FV
XEQ E            ; A CONDITIONAL XEQ
GTO H            ; An error was detected
RCL "PV"
XEQ I            ; creates "i" from I%YR
RCL "N"
+/-              ; -N, i, pmt, PV
0=? ST Y         ; 0=? i
GTO a            ; Calculate FV(i=0)   -(PV+PMT*N)
X<>Y             ; Calculate FV(i≠0)  (pmt/i*expm1(-n*log1p(i))-PV)/exp(-n*log1p(i)) 
STO÷ ST Z        ; i, -N, pmt/i, PV
LN1+X
×                ; -N*log1p(i), pmt/i, PV
E↑X
LASTX            ; -N*log1p(i), exp(-n*log1p(i)), pmt/i, PV
E↑X-1
LBL a
RCL× ST Z
RCL- ST T
RCL÷ ST Y
STO "FV"
RTN              ; Return with the result stored in "FV"

;------------------------------------------------------------------------
LBL "PMT"        ; Solve for PMT (for i=0 & i≠0)
FUNC 01
5                ; Error check all variables except PMT
XEQ E            ; A CONDITIONAL XEQ
GTO H            ; An error was detected
XEQ I            ; creates "i" from I%YR
RCL "FV"
RCL "PV"
+
RCL "N"          ; N, PV+FV, i, pmt
X=0?
GTO c            ; ERROR: N=0, Invalid Data 
0=? ST Z         ; 0=? i
GTO a            ; Calculate PMT(i=0)   -(PV+FV)/N
RCL ST Z         ; Calculate -((pv+fv)/expm1(n*log1p(i)) + pv)*i
LN1+X            ; log1p(i), N, PV+FV, i
×
E↑X-1            ; expm1(N*log1p(i)), PV+FV, i, N
÷
RCL+ "PV"
RCL× ST Y
+/-              ; -((pv+fv)/expm1(n*log1p(i)) + pv)*i, i, N
X<>Y             ; Now do  if (mode == 1) pmt /= 1+i
RCL× "BEGIN"
1
+
÷
STO "PMT"
RTN              ; Return with the result stored in "PMT"
LBL a            ; PMT(i=0) = -(PV+FV)/N
÷
+/-
STO "PMT"
RTN              ; Return with the result stored in "PMT"
LBL c
CLA
"ERROR: N=0"
GTO H

;------------------------------------------------------------------------
LBL I            ; Calculates i = "I%YR"/100/"P/YR" Called by PMT, PV, FV, N
;                  Can't do any LSTOs here because they vanish upon RTN
;                  Returns X=i, Y=PMT(mode) - that hidden in Thomas's tvm_arg_chk code!
;                  The calling Y-register will not survive in 4STK 
0.01
RCL× "I%YR"
RCL÷ "P/YR"      ; i = "I%YR"/100/"P/YR"
DUP              ; pmt = PMT*(1+M*i) Use this when calculating N, PV & FV
RCL× "BEGIN"
1
+
RCL× "PMT"
X<>Y
RTN

;------------------------------------------------------------------------
LBL "I%YR"       ;  (for Begin_mode & End_mode) Returns I%YR in X
FUNC 01
; Need to do argument checking
; i: interest factor per payment period e.g. 0.01/month.
; I%YR: %interest/yr e.g. i*100*"P/YR" 

3                ; Error check all variables except I%YR
XEQ E            ; A CONDITIONAL XEQ
GTO H            ; An error was detected
0=? "N"
GTO 91           ; ERROR: N=0 
RCL "FV"
RCL "PV"
0≠? "PMT"
GTO a            ; pv, fv   Iterate to find i
×
X≥0?
GTO 91           ; ERROR: pv*fv ≥ 0 
RCL "FV"         ; i = expm1(log(-FV/PV)/n);
RCL÷ ST L
+/-
LN
RCL÷ "N"
E↑X-1
LSTO "i"
GTO 92           ; Finish up
LBL a            ; stack is PV, FV
RCL "PMT"        ; if (M==1) {pv += pmt; fv -= pmt;}
RCL× "BEGIN"
RCL+ ST Y        ; PV+PMT×m, PV, FV
LSTO "pv"        ; pv=PV+PMT×M
RCL ST Z
RCL- ST L
LSTO "fv"        ; fv=FV-PMT×M, pv
x
X≠0?
GTO a            ; pv & fv are non-zero
RCL "PMT"        ; one or both of fv & pv are zero
LASTX            ; fv, PMT
RCL- "pv"        ; fv-pv, PMT
X=0?
GTO 91           ; ERROR: pv=fv=0 
÷                ; fv=0 or pv=0, do i=PMT/(fv-pv)
LSTO "i"
GTO b            ; Error check "i" and proceed
LBL a            ; pv & fv are non-zero
-1
LSTO "i"         ; default "i" (will → 0 if used)
RCL "PMT"
RCL÷ "pv" 
+/-              ; b=-PMT/pv, -1
ABS
LASTX            ; b, abs(b), -1
RCL "PMT"
RCL÷ "fv"        ; a=PMT/fv, b, abs(b), -1
LSTO "i"         ; default for now
ABS              ; abs(a), b, abs(b), -1
STO- ST Z
CLX
LASTX            ; a, b, abs(b)-abs(a), -1
0<? ST Z         ; This hurt my brain
X≤? ST T         ; a ≤ -1?
X<>Y             ; use b
LSTO "i"
LBL b            ; Error check i (assumes T=-1)
-1
RCL "i"
X≤Y?             ; i ≤ -1?
STO- "i"         ; yes: i=0
3                ; was 2, but use 3 and DSE command
LSTO "c"
0
LSTO "f"
LBL 93
RCL "f"
LSTO "f0"
1
RCL "i"
X↑2
RCL× "N"         ; N*i^2, 1, f0
RCL+ ST Y        ; 1+N*i^2, 1, f0
X≠? ST Y
GTO 94
CLX
RCL "pv"
RCL+ "fv"
RCL÷ "N"         ; a=(pv+fv)/N, 1, f0
DUP
RCL+ "PMT"
LSTO "f"         ; f, a, 1, f0 
RCL "N"
X↑2              ; N^2, f, a, 1
RCL- ST T
RCL× ST Z
RCL× "i"
6
÷                ; b=(n*n-1)*a/6*i, f, a
RCL "pv"
RCL- "fv"
RCL+ ST T        ; (pv-fv+a), b, f, a
-0.5
×
RCL- ST Y        ; -fp=-(pv-fv+a)/2-b, b, f
-0.5
RCL× ST Z        ; -b/2, -fp, b, f
RCL- ST Y
RCL× "i"
RCL+ ST T        ; f=f+(fp-b/2)*i, -fp, b, f(old)
LSTO "f"         ; this is used elsewhere 
RCL÷ ST Y
LSTO "eps"       ; eps=-f/fp
STO+ "i"
GTO 79
LBL 94           ; Stack: 1+N*i^2, 1, f
CLX
RCL "pv"
RCL+ "fv"        ; pv+fv, 1
RCL "i"
DUP              ; i, i, pv+fv, 1
LN1+X
RCL× "N"
E↑X-1
÷                ; x=i/expm1(n*log1p(i)), pv+fv, 1
STO× ST Y        ; x, k=(pv+fv)*x, 1
RCL+ "i"
RCL× "N"
RCL- ST Z        ; n(x+i)-1, k, 1
RCL "i"
STO- ST Y        ; i, num=n(x+i)-1-i, k, 1
RCL+ ST T
RCL× ST L        ; den=i(i+1), num, k, 1
÷                ; num/den, k, 1
RCL× ST Y
RCL "pv"
STO- ST Y        ; pv, k*num/den-pv, k,1
RCL× "i"
RCL+ "PMT"
RCL+ ST Z
; This eps formula contains 2 divides...
LSTO "f"         ; f=pv*i+pmt+k, k*num/den-pv, k, 1
X<>Y
÷
LSTO "eps"       ; eps=f/(k*num/den-pv)
STO+ "i"
LBL 79
DSE "c"          ; If you want to do 2 loops, set c=3
GTO 93
RCL "f"
X=0?
GTO 92           ; break out of the WHILE loop
RCL× "f0"
X≤0?
GTO 92           ; break out of the WHILE loop
LASTX            ; f
ABS
RCL "f0"
ABS
X>Y?
GTO 93           ; continue if |f0|>|f|
1E-6
RCL× "eps"
RCL+ "i"
X≠? "i"
GTO a            ; Error - No solution found
0.5
RCL× "eps"
STO- "i"

LBL 92           ; Finish WHILE loop (exit point) 
100              ; Convert i to I%YR
RCL× "i"
RCL× "P/YR"
STO "I%YR"
RTN              ; Return with the result stored in "I%YR"
LBL 91           ; ERROR - I%YR: Invalid arguments
CLA
"ERROR: Bad"
├" PV, FV or N"
GTO H            ; Error
LBL a            ; ERROR - No solution found 
CLA
"ERROR: "
├"No Solution"
LBL H            ; Common entry point to return all errors.
CF 33            ; Setup big-5 menus for STO after an error
XASTO ST X
CLA
RTNERR IND ST X

;------------------------------------------------------------------------
LBL E            ; Error checking. Must be called from a FUNC 00
;                  Index: 7→MODE, 6→FV, 5→PMT, 4→PV, 3→I%YR, 2→N, 1→P/YR
;                        >0 Check everything except the indexed variable
;                        ≥8 Error check everything
;                  NOTE: Uses RTNYES & RTNNO, so it behaves like a TEST!
;                  Errors: RTNYES with error message in Alpha-register
;                  Checks performed:
;                      MODE  Existence, 0 or 1
;                      FV    Existence, Real
;                      PMT   Existence, Real
;                      PV    Existence, Real
;                      I%YR  Existence, Real
;                      N     Existence, Real
;                      P/YR  Existence, Integer between 1 → 999

XEQ a            ; Create {"P/YR" "N" "I%YR" "PV" "PMT" "FV" "BEGIN"}
7
LBL 89           ; counter, arg_list, arg_skip
X=? ST Z         ; Skip this arg? 
DSE ST X         ; Won't skip because 2 ≤ Z ≤ 6. Doesn't change LASTx
GETLI ST Y       ; Get arg from the list based on the index in X
LSTO "arg"       ; arg_name, counter, arg_list, arg_skip
DROP             ; Check arg for existence and being REAL
SF 25            ; counter, arg_list, arg_skip
RCL IND "arg"
FC?C 25
GTO b            ; Invalid - Nonexistent
REAL?            ; arg_val, counter, arg_list, arg_skip
SKIP 
GTO b            ; Invalid Type (not a REAL number)
DROP             ; counter, arg_list, arg_skip
DSE ST X         ; arg exists and is real
GTO 89           ; counter, arg_list, arg_skip
RCL "P/YR"       ; At the end of the list, now check P/YR & MODE
FP
1000             ; Max P/YR to match Plus42
1
LASTX            ; "P/YR", 1, 1000, FP("P/YR")
0≠? ST T
GTO b            ; Invalid Type ("P/YR" not an INTEGER)
X<? ST Y
GTO b            ; Invalid data ("P/YR"<1)
X≥? ST Z
GTO b            ; Invalid data ("P/YR"≥1000)
XSTR "BEGIN"     ; Done checking P/YR, now check MODE for 0 or 1
LSTO "arg"
1
0≠? "BEGIN"      ; At the end, so check the mode register "BEGIN"
X=? "BEGIN"
RTNNO            ; All arguments good, skip the next instruction
LBL b            ; Error detected - illegal value or nonexistent
CLA
"ERROR: "
ARCL "arg"
├" is invalid"
RTNYES           ; Bad argument, display error message 

LBL a            ; Make the list - would have been easier with LNSTK,
FUNC 01          ; but requires Free42 users to enable Big Stack.
XSTR "P/YR"      ; 1st list element (index = 1)
XSTR "N"         ; 2nd list element (index = 2)
XSTR "I%YR"      ; 3rd list element (index = 3)
3                ; number of elements
→LIST            ; create the list
XSTR "PV"        ; 4th list element (index = 4)
APPEND
XSTR "PMT"       ; 5th list element (index = 5)
APPEND
XSTR "FV"        ; 6th list element (index = 6)
APPEND
XSTR "BEGIN"     ; 7th list element (index = 7)
APPEND
RTN
END