
//_______________________________________________________________________________________
//       nois  - generate non-deterministic random numbers between -1. and 1.
//               on all POSIX systems.
//
//               cc -o nois nois.c -lpthread
//
// Usage:
//   ./nois 100000
//   ./nois 100000 b (for binary output)
//_______________________________________________________________________________________

// Expose OS CPU-count extensions (_SC_NPROCESSORS_ONLN) alongside POSIX APIs
#if defined(__APPLE__)
#define _DARWIN_C_SOURCE
#else
#define _DEFAULT_SOURCE
#endif

#include <pthread.h>
#include <stdint.h>
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
#include <time.h>
#include <unistd.h>
#include <errno.h>

// Size of each thread's scratchpad array in 32-bit words (65536 * 4 bytes = 256 KB)
#define JITTER_MEM_WORDS 65536

// Number of float samples generated per worker in each processing block
#define CHUNK_SIZE 2048

// Fallback worker count if sysconf cannot determine online processor count
#define DEFAULT_WORKERS 4

// Per-thread state holding a read-only full-period permutation table and index
typedef struct {
    volatile uint32_t buf[JITTER_MEM_WORDS];
    uint32_t idx;
} jitter_ctx_t;

// Arguments passed to each POSIX worker thread
typedef struct {
    jitter_ctx_t *ctx;
    float *out;
    size_t count;
} worker_arg_t;

//_______________________________________________________________________________________
// Read monotonic clock in nanoseconds
static inline uint64_t get_nanos(void) {
    struct timespec ts;

    if (clock_gettime(CLOCK_MONOTONIC, &ts) != 0) {
        perror("clock_gettime");
        exit(EXIT_FAILURE);
    }

    return (uint64_t)ts.tv_sec * 1000000000ULL
         + (uint64_t)ts.tv_nsec;
}

//_______________________________________________________________________________________
// Query the number of online logical processors via sysconf
static size_t detect_worker_count(void) {
    long nprocs = sysconf(_SC_NPROCESSORS_ONLN);

    if (nprocs < 1) {
        return DEFAULT_WORKERS;
    }

    return (size_t)nprocs;
}

//_______________________________________________________________________________________
// Build a single full-period permutation cycle across all 65536 words
// (Sattolo's algorithm)
// Every index visits all 256 KB before repeating, preventing short cache-line cycles
static void init_ctx(jitter_ctx_t *ctx, uint32_t seed_offset) {
    uint32_t *perm = malloc(JITTER_MEM_WORDS * sizeof(uint32_t));

    if (!perm) {
        perror("malloc");
        exit(EXIT_FAILURE);
    }

    for (uint32_t i = 0; i < JITTER_MEM_WORDS; i++) {
        *(perm + i) = i;
    }

    // Mix timing + thread offset to shuffle the single-cycle permutation
    uint64_t s = get_nanos()
               ^ ((uint64_t)seed_offset * 0x9E3779B97F4A7C15ULL);

    for (uint32_t i = JITTER_MEM_WORDS - 1; i > 0; i--) {
        s ^= get_nanos();
        s = (s ^ (s >> 30)) * 0xBF58476D1CE4E5B9ULL;
        s = (s ^ (s >> 27)) * 0x94D049BB133111EBULL;
        s ^= (s >> 31);

        uint32_t j = (uint32_t)(s % i);

        uint32_t tmp = *(perm + i);
        *(perm + i) = *(perm + j);
        *(perm + j) = tmp;
    }

    for (uint32_t i = 0; i < JITTER_MEM_WORDS; i++) {
        *(ctx->buf + i) = *(perm + i);
    }

    ctx->idx = *(perm + 0);

    free(perm);
}

//_______________________________________________________________________________________
// Measure elapsed nanoseconds across a read-only pointer-chasing walk
static inline uint64_t measure_walk(jitter_ctx_t *ctx, int steps) {
    uint32_t idx = ctx->idx;
    volatile uint32_t *buf = ctx->buf;

    uint64_t t1 = get_nanos();

    for (int i = 0; i < steps; i++) {
        idx = *(buf + idx);
    }

    uint64_t t2 = get_nanos();

    ctx->idx = idx;

    return t2 - t1;
}

//_______________________________________________________________________________________
// Accumulate 32 physical timing measurements into a 24-bit integer
static uint32_t jitter_u24(jitter_ctx_t *ctx) {
    uint64_t acc = 0;

    for (int i = 0; i < 32; i++) {

        // int steps = 32 + (int)(acc & 31); // original
        int steps = 48;                     // simplified

        uint64_t delta = measure_walk(ctx, steps);

        acc ^= delta + 0x9E3779B97F4A7C15ULL
             + (acc << 6) + (acc >> 2);
    }

    // Finalize bit diffusion across all 64 bits before extracting top 24 bits
    acc ^= acc >> 33;
    acc *= 0xFF51AFD7ED558CCDULL;
    acc ^= acc >> 33;
    acc *= 0xC4CEB9FE1A85EC53ULL;
    acc ^= acc >> 33;

    return (uint32_t)(acc >> 40);
}

//_______________________________________________________________________________________
// Map a 24-bit unsigned integer strictly inside (-1.0f, 1.0f)
static inline float u24_to_bipolar_f32(uint32_t r) {
    return (float)(((double)r + 0.5) / 8388608.0 - 1.0);
}

//_______________________________________________________________________________________
// Thread entry point: fills an assigned output slice with jitter-derived floats
static void *worker_fn(void *arg) {
    worker_arg_t *w = (worker_arg_t *)arg;

    for (size_t i = 0; i < w->count; i++) {
        *(w->out + i) = u24_to_bipolar_f32(jitter_u24(w->ctx));
    }

    return NULL;
}

//_______________________________________________________________________________________
int main(int argc, const char *argv[]) {

    // Validate argument count: requires <num_samples> and optional 'b' flag
    if (argc < 2 || argc > 3) {
        fprintf(stderr, "Usage: %s <num_samples> [b]\n", *argv);
        return 1;
    }

    // Parse and validate requested sample count
    char *endptr = NULL;
    errno = 0;

    long long num_samples = strtoll(*(argv + 1), &endptr, 10);

    if (errno == ERANGE || endptr == argv[1] ||
        *endptr != '\0' || num_samples <= 0) {
        fprintf(stderr, "Error: <num_samples> must be a positive integer.\n");
        return 1;
    }

    // Check whether optional binary output mode ('b') was requested
    int binary_mode = 0;

    if (argc == 3) {
        if (strcmp(*(argv + 2), "b") == 0) {
            binary_mode = 1;
        } else {
            fprintf(stderr, "Error: optional second argument must be 'b'.\n");
            return 1;
        }
    }

    // Use a 256 KB stdout buffer to minimize write system-call overhead
    setvbuf(stdout, NULL, _IOFBF, 262144);

    // Detect available CPU cores and size buffers dynamically
    const size_t workers = detect_worker_count();
    const size_t block_size = workers * CHUNK_SIZE;

    jitter_ctx_t *ctxs = malloc(workers * sizeof(jitter_ctx_t));
    float *block_buf = malloc(block_size * sizeof(float));
    pthread_t *threads = malloc(workers * sizeof(pthread_t));
    worker_arg_t *args = malloc(workers * sizeof(worker_arg_t));

    if (!ctxs || !block_buf || !threads || !args) {
        perror("malloc");
        free(ctxs);
        free(block_buf);
        free(threads);
        free(args);
        return 1;
    }

    // Initialize each worker's full-period permutation table
    for (size_t w = 0; w < workers; w++) {
        init_ctx(ctxs + w, (uint32_t)(w + 1));
    }

    long long remaining = num_samples;

    // Stream samples in blocks until the full requested count is generated
    while (remaining > 0) {

        size_t count = (remaining < (long long)block_size)
                     ? (size_t)remaining
                     : block_size;

        size_t active_workers = (count + CHUNK_SIZE - 1) / CHUNK_SIZE;

        // Spawn worker threads to fill disjoint slices of block_buf
        size_t created_workers = 0;
        int thread_error = 0;

        for (size_t w = 0; w < active_workers; w++) {

            size_t start = w * CHUNK_SIZE;
            size_t len = count - start;

            if (len > CHUNK_SIZE) {
                len = CHUNK_SIZE;
            }

            (args + w)->ctx = ctxs + w;
            (args + w)->out = block_buf + start;
            (args + w)->count = len;

            int rc = pthread_create(
                threads + w,
                NULL,
                worker_fn,
                args + w
            );

            if (rc != 0) {
                fprintf(stderr, "pthread_create failed: %s\n",
                        strerror(rc));
                thread_error = 1;
                break;
            }

            created_workers++;
        }

        // Join every thread that was successfully created
        for (size_t w = 0; w < created_workers; w++) {

            int rc = pthread_join(*(threads + w), NULL);

            if (rc != 0) {
                fprintf(stderr, "pthread_join failed: %s\n",
                        strerror(rc));
                thread_error = 1;
            }
        }

        // Never release shared memory if a thread join has failed
        if (thread_error) {
            exit(EXIT_FAILURE);
        }

        // Write generated block to stdout in binary or fixed-point text format
        if (binary_mode) {

            if (fwrite(block_buf, sizeof(float), count, stdout) != count) {
                perror("fwrite");

                free(ctxs);
                free(block_buf);
                free(threads);
                free(args);

                return 1;
            }

        } else {

            for (size_t i = 0; i < count; i++) {

                if (printf("%.8f\n", *(block_buf + i)) < 0) {
                    perror("printf");

                    free(ctxs);
                    free(block_buf);
                    free(threads);
                    free(args);

                    return 1;
                }
            }
        }

        remaining -= count;
    }

    // Check that all buffered output has been successfully written
    if (fflush(stdout) != 0) {
        perror("fflush");
        free(ctxs);
        free(block_buf);
        free(threads);
        free(args);

        return 1;
    }

    // Release heap memory before exit
    free(ctxs);
    free(block_buf);
    free(threads);
    free(args);

    return 0;
}
