// randProbe.c -- verify that crt0's __srandInitFromTime hook ran.
//
// With the old (pre-Phase 1.8) crt0 the seed was a constant 1, so the
// first rand() output was deterministically:
//     (1*1103515245 + 12345) = 0x41C64E4D
//     (>> 16) & 0x7FFF       = 0x41C6 & 0x7FFF = 0x41C6 (16838)
// If __srandInitFromTime ran, rand() now starts from a time-derived
// seed and the first output is overwhelmingly unlikely to be 0x41C6.
//
// We probe via bank-0 single-byte writes ($70..$73) because the
// runViaFinder harness reads u8 and the const-int byte-store path in
// our codegen (STA8long) MASKS the address to 16 bits by design
// (W65816AsmPrinter.cpp:780-782 -- "users who need a banked address
// should construct a far pointer rather than casting an int").  Using
// addresses in zero-page / first-page bank-0 sidesteps that limitation
// and keeps the probe self-contained.
//
//   $70 (u8) : low byte of rand() #1
//   $71 (u8) : high byte of rand() #1
//   $72 (u8) : non-zero IF rand1 != the deterministic 0x41C6.
//              0x99 = seeded ok, 0x00 = still seed=1 default = test failed.
//   $73 (u8) : marker 0x99 -- proves the program executed at all.
//
// Build + run (GS/OS Finder path):
//   bash demos/build.sh randProbe
//   bash scripts/runViaFinder.sh demos/randProbe.omf \
//        --check 0x72=0x99 0x73=0x99
// Build + run (GNO command path):
//   bash demos/buildGno.sh randProbe
//   bash scripts/runInGno.sh demos/randProbe.omf --check 0x72=9999

#include <stdint.h>
#include <stdlib.h>
#include "iigs/toolbox.h"

extern void iigsToolboxInit(void);


int main(void) {
    iigsToolboxInit();   // TL up under GS/OS already; explicit init keeps
                         // the demo bare-metal-runnable too.
    uint16_t r1 = (uint16_t)rand();
    *(volatile uint8_t *)0x70 = (uint8_t)(r1 & 0xFFu);
    *(volatile uint8_t *)0x71 = (uint8_t)((r1 >> 8) & 0xFFu);
    *(volatile uint8_t *)0x72 = (r1 == 0x41C6u) ? 0x00u : 0x99u;
    *(volatile uint8_t *)0x73 = 0x99u;
    for (volatile unsigned long i = 0; i < 300000UL; i++) {}
    return 0;
}
