# Calculator Application Implementation Plan for AROS

## 1. Overall Design

### Application Architecture
```
+-----------------+
|   Main Entry    |
|     (main)      |
+--------+--------+
         |
         v
+--------+--------+    +-----------------+
|  Library Init   |--->| Open intuition  |
|                 |    | Open gadtools   |
|                 |    | Open graphics   |
|                 |    | Open dos        |
+-----------------+    +-----------------+
         |
         v
+--------+--------+    +-----------------+
|   Window Setup  |--->| Create context  |
|                 |    | Create gadgets  |
|                 |    | Open window     |
|                 |    | Add gadgets     |
+-----------------+    +-----------------+
         |
         v
+--------+--------+    +-----------------+
|   Event Loop    |--->| GT_GetIMsg      |
|                 |    | Handle events   |
|                 |    | GT_ReplyIMsg    |
+-----------------+    +-----------------+
         |
         v
+--------+--------+
|   Cleanup       |
|  (free memory)  |
+-----------------+
```

### Key Design Decisions

1. **Single Window Application**: A simple calculator doesn't require multiple windows
2. **Grid Layout**: 4x5 button grid (0-9, +, -, *, /, =, C, etc.)
3. **Display Area**: A string gadget at the top to show current input and results
4. **Event-Driven**: Using IDCMP (Intuition Direct Communication Message Port) events
5. **No MUI/Zune**: Using only gadtools.library for UI widgets

---

## 2. High-Level Implementation Steps

### Phase 1: Foundation (File Structure & Setup)
1. Create main source file `calculator.c`
2. Create `Makefile` for cross-compilation
3. Set up library base pointers and open required libraries
4. Implement cleanup/error handling routines

### Phase 2: UI Design & Gadget Creation
1. Define window dimensions and layout constants
2. Create visual info with `GetVisualInfoA()`
3. Create gadget context with `CreateContext()`
4. Create display string gadget (for showing numbers/results)
5. Create button gadgets using `BUTTON_KIND` in a grid layout
6. Set up IDCMP flags for event handling

### Phase 3: Calculator Logic
1. Implement calculator state machine
2. Handle digit input (0-9)
3. Handle operations (+, -, *, /)
4. Handle special functions (=, C, CE, Backspace)

### Phase 4: Event Handling
1. Set up main event loop using `GT_GetIMsg()`
2. Handle `IDCMP_GADGETUP` events from button presses
3. Handle `IDCMP_CLOSEWINDOW` for window close
4. Handle `IDCMP_VANILLAKEY` for keyboard input
5. Implement keyboard shortcuts (numbers, operators, Enter, Escape)

### Phase 5: Polish & Testing
1. Add version string
2. Add menu bar (About, Help, Quit)
3. Test on AROS emulator
4. Memory leak checking

---

## 3. Required Libraries & APIs

### Libraries to Open

| Library | Version | Purpose |
|---------|---------|---------|
| `intuition.library` | 36+ | Window management, IDCMP |
| `gadtools.library` | 36+ | UI gadgets (buttons, strings) |
| `graphics.library` | 36+ | Rendering, rastports |
| `utility.library` | 36+ | Tag item handling |
| `dos.library` | 36+ | DOS functions |
| `layers.library` | 36+ | Layer management |

### Key Functions to Use

**From gadtools.library:**
- `GetVisualInfoA()` - Get visual info for gadgets
- `FreeVisualInfo()` - Free visual info
- `CreateContext()` - Create gadget list context
- `CreateGadgetA()` - Create individual gadgets
- `FreeGadgets()` - Free all gadgets
- `GT_GetIMsg()` - Get intuition messages
- `GT_ReplyIMsg()` - Reply to messages
- `GT_SetGadgetAttrsA()` - Update gadget attributes
- `GT_RefreshWindow()` - Refresh window after opening

**From intuition.library:**
- `OpenWindowTags()` - Open window with tags
- `CloseWindow()` - Close window
- `AddGList()` - Add gadgets to window
- `RefreshGList()` - Refresh gadgets
- `ModifyIDCMP()` - Modify IDCMP flags

### Gadget Types to Use

| Gadget Kind | Purpose |
|-------------|---------|
| `STRING_KIND` | Display area for current value |
| `BUTTON_KIND` | All calculator buttons (0-9, +, -, *, /, =, C, etc.) |

---

## 4. Build System

### Makefile Structure

```makefile
# Cross-compiler prefix
CC = x86_64-aros-gcc
STRIP = x86_64-aros-strip

# Compiler flags
CFLAGS = -O2 -Wall -I/home/aros/ABIv11/AROS/cross-x86_64-aros/Development/include
LDFLAGS = -L/home/aros/ABIv11/AROS/cross-x86_64-aros/Development/lib

# Libraries to link
LIBS = -lgadtools -lintuition -lgraphics -lutility -ldos -llayers

# Target
TARGET = Calculator

# Source files
SRCS = calculator.c
OBJS = $(SRCS:.c=.o)

.PHONY: all clean

all: $(TARGET)

$(TARGET): $(OBJS)
    $(CC) $(LDFLAGS) -o $@ $^ $(LIBS)

%.o: %.c
    $(CC) $(CFLAGS) -c -o $@ $<

clean:
    rm -f $(OBJS) $(TARGET)
```

### Build Commands

```bash
# Build the application
make

# Clean build files
make clean
```

---

## 5. UI Layout Design

### Window Layout (Approximate 300x400 pixels)

```
+----------------------------------+
|  Calculator           [_][^][X] |  <- Title bar
+----------------------------------+
|                                  |
|  +----------------------------+  |
|  |                  1234567.89|  |  <- Display (STRING_KIND, right-aligned)
|  +----------------------------+  |
|                                  |
|  +----+  +----+  +----+  +----+  |
|  |  C |  | CE |  | <- |  | /  |  |  <- Row 1
|  +----+  +----+  +----+  +----+  |
|                                  |
|  +----+  +----+  +----+  +----+  |
|  | 7  |  | 8  |  | 9  |  | *  |  |  <- Row 2
|  +----+  +----+  +----+  +----+  |
|                                  |
|  +----+  +----+  +----+  +----+  |
|  | 4  |  | 5  |  | 6  |  | -  |  |  <- Row 3
|  +----+  +----+  +----+  +----+  |
|                                  |
|  +----+  +----+  +----+  +----+  |
|  | 1  |  | 2  |  | 3  |  | +  |  |  <- Row 4
|  +----+  +----+  +----+  +----+  |
|                                  |
|  +----+  +----+  +------------+  |
|  | 0  |  | .  |  |     =      |  |  <- Row 5
|  +----+  +----+  +------------+  |
|                                  |
+----------------------------------+
```

### Button Grid Specifications

- **Button Size**: 50x40 pixels each
- **Spacing**: 10 pixels between buttons
- **Display Height**: 30 pixels
- **Margins**: 15 pixels from window edges

---

## 6. Calculator Logic Design

### State Machine

```
+-----------+
|   IDLE    |<------------------+
+-----+-----+                   |
      |                         |
      v                         |
+-----+-----+   Operator    +---+---+
|  NUMBER   |-------------->|  OP   |
|  ENTRY    |               |PENDING|
+-----+-----+               +---+---+
      |                         |
      |  =                      | Number
      v                         v
+-----+-----+               +---+---+
|  RESULT   |<--------------|  CALC |
|  DISPLAY  |    =         |ULATE |
+-----------+               +-------+
```

### Data Structures

```c
typedef enum {
    STATE_IDLE,       // Waiting for first number
    STATE_NUMBER,     // Entering first/second number
    STATE_OP_PENDING, // Operator selected, waiting for second number
    STATE_RESULT      // Result displayed
} CalcState;

typedef struct {
    CalcState   state;           // Current state
    double      accumulator;     // First operand / result
    double      currentValue;    // Current input value
    char        currentOp;       // Current operator (+, -, *, /)
    BOOL        hasDecimal;      // Has decimal point been entered
    int         decimalPlaces;   // Number of decimal places entered
    char        displayBuffer[32]; // Buffer for display
} CalculatorData;
```

### Operations to Support

| Button | Function |
|--------|----------|
| 0-9 | Enter digit |
| . | Enter decimal point |
| + | Addition |
| - | Subtraction |
| * | Multiplication |
| / | Division |
| = | Calculate result |
| C | Clear all |
| CE | Clear entry |
| <- | Backspace |

---

## 7. File Structure

```
Calculator/
├── AGENTS.md           # Coding guidelines (existing)
├── PLAN.md             # This implementation plan
├── calculator.c        # Main source file
├── calculator.h        # Header file (optional, can be in .c)
├── Makefile            # Build configuration
└── README.md           # Documentation (optional)
```

---

## 8. Implementation Code Structure

### Main Source File Organization

```c
/* calculator.c */

/* 1. Version and Copyright */
#define VERSION "$VER: Calculator 1.0 (24.04.2026) AROS Dev Team"

/* 2. Includes */
#include <exec/types.h>
#include <exec/libraries.h>
#include <intuition/intuition.h>
#include <libraries/gadtools.h>
#include <proto/exec.h>
#include <proto/intuition.h>
#include <proto/gadtools.h>
#include <proto/graphics.h>
#include <proto/dos.h>

/* 3. Constants and Defines */
#define WINDOW_WIDTH  300
#define WINDOW_HEIGHT 400
#define BTN_WIDTH     50
#define BTN_HEIGHT    40
/* ... */

/* 4. Global Variables */
struct IntuitionBase *IntuitionBase = NULL;
struct GfxBase *GfxBase = NULL;
struct Library *GadToolsBase = NULL;
/* ... */

/* 5. Calculator State */
typedef struct { /* ... */ } CalculatorData;
CalculatorData calcData;

/* 6. Function Prototypes */
BOOL OpenLibraries(void);
void CloseLibraries(void);
BOOL CreateGUI(void);
void DestroyGUI(void);
void HandleEvents(void);
void ProcessButton(ULONG gadgetID);
/* ... */

/* 7. Main Function */
int main(int argc, char **argv) { /* ... */ }

/* 8. Library Functions */
BOOL OpenLibraries(void) { /* ... */ }
void CloseLibraries(void) { /* ... */ }

/* 9. GUI Functions */
BOOL CreateGUI(void) { /* ... */ }
void DestroyGUI(void) { /* ... */ }

/* 10. Event Handling */
void HandleEvents(void) { /* ... */ }

/* 11. Calculator Logic */
void ProcessButton(ULONG gadgetID) { /* ... */ }
void UpdateDisplay(void) { /* ... */ }
double Calculate(double a, double b, char op) { /* ... */ }
```

---

## 9. Design Decisions Summary

| Aspect | Decision |
|--------|----------|
| UI Framework | gadtools.library (no MUI/Zune) |
| Numeric Type | Double-precision floating point |
| Button Layout | 4-column grid, 5 rows |
| Display Gadget | STRING_KIND (read-only display) |
| Memory Management | Remember list or standard AllocMem/FreeMem |

---

## 10. Verification Steps

1. **Compilation**: `make` should compile without warnings or errors
2. **Binary Creation**: `Calculator` executable should be created
3. **Startup Test**: Run on AROS/WinUAE/FS-UAE - window should open
4. **Button Test**: Click buttons - display should update
5. **Calculation Test**: Enter `2 + 3 =` - should display `5`
6. **Error Test**: Enter `5 / 0` - should handle gracefully
7. **Memory Test**: Open/close repeatedly - no memory leaks
