/* SPDX-License-Identifier: GPL-3.0-or-later */
/* Descent Computer. Use the CoCo BASIC float backend and link vcccompat. */
#include <cmoc.h>
#include <coco.h>
#include <vcc/decimal.h>

/* Print a complete instrument reading or mark the field unavailable. */
static void reading(const char *label, float value, byte places, const char *unit)
{
    char field[12];
    int length = vcc_fixed(field, sizeof(field), value, places);
    if (length < 0 || (unsigned)length >= sizeof(field))
        printf("%s--- %s\n", label, unit);
    else
        printf("%s%s %s\n", label, field, unit);
}

static void report(float firstHeight, float lastHeight, float seconds)
{
    float speed;
    if (seconds <= 0.0f) {
        printf("CHECK RADAR INTERVAL\n");
        return;
    }

    /* Falling gives a negative speed. Keep the full value for the estimate. */
    speed = (lastHeight - firstHeight) / seconds;
    reading("HEIGHT  ", lastHeight, 2, "M");
    reading("SPEED   ", speed, 2, "M/S");
    if (speed < 0.0f)
        reading("ETA     ", lastHeight / -speed, 1, "S");
    else
        printf("ETA     NO DESCENT\n");
}

int main(void)
{
    cls(1);
    printf("DESCENT COMPUTER\n\n");
    /* Two radar heights in metres, measured two seconds apart. */
    report(105.50f, 101.75f, 2.0f);
    printf("\nRADAR PASS COMPLETE\n");
    return 0;
}
