# Payas Reckoner Calculator — Documentation

> Multi-mode browser calculator · Part of Payas Web Kit · GPLv2
> Developer: Saman Udayanga Wijesinghe

---

## Table of Contents

1. [Project Overview](#1-project-overview)
2. [Installation](#2-installation)
3. [Usage Guide](#3-usage-guide)
4. [Calculator Reference](#4-calculator-reference)
5. [Keyboard Shortcuts](#5-keyboard-shortcuts)
6. [Data Files](#6-data-files)
7. [Custom Units](#7-custom-units)
8. [Programmable Calculator Language](#8-programmable-calculator-language)
9. [API / Internals](#9-api--internals)
10. [Contributing](#10-contributing)
11. [Changelog](#11-changelog)
12. [Credits](#12-credits)

---

## 1. Project Overview

**Payas Reckoner** is a fully client-side web calculator with 10 distinct modes:

| Mode | Purpose |
|---|---|
| Basic | Everyday arithmetic + memory registers |
| Scientific | Trigonometry, logarithms, complex numbers |
| Graphing | Function plotter with regression |
| Financial | TVM, NPV/IRR, amortization, bonds |
| Programmable | Custom scripting language with step debugger |
| RPN | HP-style reverse Polish notation |
| Statistical | Descriptive stats, distributions, hypothesis testing |
| Unit/Currency | Unit conversion + live currency rates |
| Programmer | Binary/hex/octal with bit manipulation |
| Matrix | Linear algebra operations |

**Licence:** GPLv2  
**No external JS dependencies** beyond Bootstrap CSS and Material Icons.

---

## 2. Installation

No build step or server required:

```bash
# Open directly in browser
xdg-open index.html        # Linux
open index.html            # macOS
start index.html           # Windows

# Or serve locally (enables currency fetch without CORS issues)
python3 -m http.server 8080
# Visit: http://localhost:8080/payas-reckoner/
```

---

## 3. Usage Guide

### Switching Modes
- **Desktop**: Click any mode tab in the top navigation bar.
- **Mobile/Tablet**: Tap the ☰ hamburger button to open the mode drawer.
- **Keyboard**: `Ctrl+M` opens the mode drawer.

### Theme Toggle
Click the `dark_mode` / `light_mode` icon in the top-right, or press `Ctrl+D`. Preference persists to `localStorage`.

### History Panel
Click the `history` icon or press `Ctrl+H`. The panel slides open from the right (desktop) or overlays (mobile). Click any entry to recall its result into the active calculator. Export history to a `.md` file with the download button.

### Saving Data
All data (history, memory, programs, favourites) is stored in `localStorage`. Export any data to a Markdown file using the export buttons in each module.

---

## 4. Calculator Reference

### Basic Calculator
- **Operations**: + − × ÷, % (contextual percent)
- **Memory**: MC (clear), MR (recall), M+ (add), M− (subtract), MS (store)
- **Sign toggle**: +/− button
- **Keyboard**: full numpad + operators

### Scientific Calculator
- **Angle modes**: DEG / RAD / GRAD (persisted per session)
- **Trig**: sin, cos, tan; inverses with **2nd** shift; hyperbolic with **HYP** modifier
- **Logs**: log (base 10), ln, log₂; inverses with 2nd
- **Powers/Roots**: xʸ, √, ∛, EE (scientific notation entry)
- **Constants**: π, e, φ (golden ratio)
- **Factorial**: n! (applied to the last digit sequence)
- **Combinatorics**: nPr, nCr

### Graphing Calculator
- **Traces**: up to 5 simultaneous functions; each has colour picker + visibility toggle
- **Input**: standard mathematical notation (`sin(x)`, `x^2`, `sqrt(x)`)
- **Interaction**: scroll to zoom, click-drag to pan, touch pinch-zoom
- **Regression**: Linear, Exponential, Quadratic — enter `x1,y1; x2,y2` pairs and click Fit
- **Export**: Download graph as PNG

### Financial Calculator
**TVM (Time Value of Money)**
- Enter 4 of 5 values (N, I%, PV, PMT, FV) and click Solve for the fifth
- Payment frequency: Annual → Daily

**NPV / IRR**
- Enter comma-separated cash flows (first = initial investment as negative)
- Click NPV for net present value, IRR for internal rate of return

**Amortization Schedule**
- Generates full period-by-period table; exportable to `.md`

**Bond Pricing**
- Calculates price, premium/discount, Macaulay duration, modified duration

### Programmable Calculator
See [Section 8](#8-programmable-calculator-language) for full language reference.
- Save/load programs by name
- Run, Step, Reset, Clear controls
- Output console shows PRINT results and runtime errors

### RPN Calculator
- Stack levels labelled T (top), Z, Y, X (entry)
- `ENTER` pushes entry to stack; operators consume top stack values
- **Stack ops**: SWAP, ROT, DROP, DUP, CLR
- **UNDO**: restores the previous stack state (last 10 states)
- Full scientific function set accessible from stack

### Statistical Calculator
- **Data input**: comma or newline separated; paste from clipboard
- **Descriptive**: count, sum, min/max, mean (arithmetic, geometric, harmonic), median, mode, quartiles, IQR, variance, std dev, skewness, kurtosis, SEM
- **Charts**: histogram (10 bins), box-and-whisker plot (canvas-based)
- **Regression**: Linear, Exponential, Logarithmic, Power (fit to X/Y data)
- **Distributions**: Normal (PDF, CDF, inverse CDF), Binomial (PMF, CDF), Poisson
- **Hypothesis testing**: one-sample t-test with confidence interval

### Unit & Currency Conversion
- **Categories**: Length, Mass, Volume, Temperature, Area, Speed, Pressure, Energy, Power, Data, Time, Angle, Currency
- **Dual-entry**: edit either field, both update
- **Swap**: exchange from/to units with the ⇄ button
- **Currency**: fetches live rates from open.er-api.com; falls back to cached rates
- **Favourites**: star any conversion pair for quick access

### Programmer's Calculator
- **Base display**: BIN, OCT, DEC, HEX simultaneously; active base highlighted
- **Word size**: 8 / 16 / 32 / 64 bit
- **Signed/Unsigned**: toggle two's complement interpretation
- **Bitwise**: AND, OR, XOR, NOT, NAND, NOR
- **Shifts**: SHL (`<<`), SHR (`>>`), SAR (`>>>` arithmetic), ROL (rotate left)
- **Bit grid**: interactive — click any bit to toggle; value updates live
- **Pop count**: number of set bits displayed in info bar
- **Hex keypad**: A–F buttons active only in HEX mode

### Matrix Calculator
- **3 matrices** (A, B, C); resize from 2×2 to 8×8 via dropdown
- **Fill helpers**: Identity, Random, Zero
- **Operations**: A+B, A−B, A×B, sA (scalar), Aᵀ (transpose), det(A), A⁻¹, trace(A), REF, RREF, cofactor, adjugate
- **Decompositions**: LU (displays L and U factor matrices)
- **Eigenvalues**: computed for 2×2 matrices (real and complex)

---

## 5. Keyboard Shortcuts

### Global

| Shortcut | Action |
|---|---|
| `Ctrl+D` | Toggle dark/light theme |
| `Ctrl+H` | Toggle history panel |
| `Ctrl+M` | Open mode selector drawer |
| `F1` | Open this documentation |
| `Escape` | Close drawer / clear entry |

### Basic / Scientific

| Key | Action |
|---|---|
| `0–9` | Digit input |
| `+ - * /` | Operators |
| `Enter` / `=` | Evaluate |
| `Backspace` | Delete last character |
| `Escape` | All Clear |
| `.` | Decimal point |
| `%` | Percent |
| `^` | Power (scientific) |
| `( )` | Parentheses (scientific) |

### RPN

| Key | Action |
|---|---|
| `0–9` `.` | Entry |
| `Enter` | Push to stack |
| `+ - * /` | Binary operations |
| `Backspace` | Delete entry character |
| `Escape` | Clear stack |

### Programmer

| Key | Action |
|---|---|
| `0–9` `A–F` | Digit (base-dependent) |
| `Backspace` | Delete |
| `Escape` | Clear |
| `Enter` | Evaluate |

---

## 6. Data Files

All data is stored in `localStorage`. Each module also supports exporting to a `.md` file.

### history.md format
```markdown
# Calculation History

## 2025-10-04 14:32:10
- **Mode:** Basic
- **Expression:** `125 × 8`
- **Result:** `1000`
```

### memory.md format
```markdown
# Memory & Stack

## Memory Registers (Basic)
- M1: `1000`

## RPN Stack
- T: `0`
- Z: `0`
- Y: `42`
- X: `3.14159`
```

### programs.md format
```markdown
# Saved Programs

## ProgramName
\`\`\`
LET x = 10
PRINT x
\`\`\`
```

### custom-units.md format
```markdown
# Custom Unit Sets

## Category
- `unit_symbol` = value base_unit
```
_(Currently informational — custom units are managed in localStorage)_

---

## 7. Custom Units

Custom unit definitions are stored in `localStorage` via `Storage.saveCustomUnits()`. The `custom-units.md` file in `data/` documents the format for human reference.

To add a custom conversion programmatically:
```js
const units = Storage.getCustomUnits();
units.push({ symbol: 'myunit', toBase: 3.5, fromBase: 1/3.5, category: 'Length', baseUnit: 'm' });
Storage.saveCustomUnits(units);
```

---

## 8. Programmable Calculator Language

### Variables
```
LET x = 42
LET result = x * 2 + 1
```

### Output
```
PRINT result
PRINT "literal string"   (not yet supported — use variable)
```

### Input
```
INPUT "Enter value: ", x
```

### Arithmetic
Operators: `+`, `-`, `*`, `/`, `^` (power)  
Functions: `sqrt`, `abs`, `sin`, `cos`, `tan`, `exp`, `ln`, `log`

### Conditionals
```
IF x > 10 THEN
  PRINT x
ELSE
  PRINT 0
END
```

### For Loop
```
FOR i = 1 TO 10 STEP 1
  PRINT i
NEXT i
```

### While Loop
```
WHILE x > 0
  LET x = x - 1
WEND
```

### Labels and GOTO
```
start:
  LET i = i + 1
  IF i < 5 THEN GOTO start
```

### Example — Fibonacci
```
LET a = 0
LET b = 1
FOR i = 1 TO 15
  PRINT a
  LET temp = b
  LET b = a + b
  LET a = temp
NEXT i
```

---

## 9. API / Internals

### Module Pattern

Each calculator is a self-contained module registered via:
```js
App.register('mode-id', ModuleObject);
```

Every module must expose:
```js
{
  render(container),      // Build DOM inside container element
  handleKeydown(event),   // Handle keyboard input (optional)
  onActivate(),           // Called when mode becomes active (optional)
  onDeactivate(),         // Called when switching away (optional)
  recallValue(val),       // Insert a recalled history value (optional)
}
```

### MathEngine API

```js
MathEngine.evaluate(expr, angleMode)  // Evaluate string expression
MathEngine.mean(data)                 // Arithmetic mean of array
MathEngine.normalCDF(x, mu, sigma)    // Normal CDF
MathEngine.matInverse(A)              // Matrix inverse
MathEngine.tvmFV(pv, pmt, rate, n)   // Future value
MathEngine.linearRegression(xs, ys)   // { slope, intercept, r2 }
// ... full API in assets/js/utils/math-engine.js
```

### Storage API

```js
Storage.pushHistory(entry)      // { mode, expr, result }
Storage.getHistory()            // Returns array (newest first)
Storage.setMemory(slot, value)  // slot: 'M1'–'M5'
Storage.getMemory(slot)
Storage.saveProgram(name, code)
Storage.loadProgram(name)
Storage.saveFavourites(favs)
Storage.getFavourites()
```

---

## 10. Contributing

1. Fork the repo
2. Create a feature branch: `git checkout -b feature/my-feature`
3. Follow the **GPLv2 licence header** template in every new source file
4. Use `var(--token)` for all colours — never hardcode
5. Add `aria-label` to every new interactive element
6. Test in Firefox ≥ ESR and Chrome/Edge
7. Test both light and dark themes at 375px, 768px, and 1280px viewport widths
8. Submit a pull request with a clear description of changes

---

## 11. Changelog

### v1.0.0 — 2025
- Initial release with 10 calculator modes
- Payas Design System integration (light + dark theme)
- History panel with Markdown export
- GPLv2 licence

---

## 12. Credits

| Role | Name |
|---|---|
| Developer | Saman Udayanga Wijesinghe |
| Design System | Payas Web Kit |
| CSS Framework | Bootstrap 5.3.3 (grid/utilities) |
| Icons | Material Icons — Google |
| Fonts | DM Sans, JetBrains Mono — Google Fonts |
| Currency API | open.er-api.com (live rates) |
| Licence | GNU General Public License v2.0 |

---

_Payas Reckoner Calculator — built with care by Saman Udayanga Wijesinghe_
