// Hold the pendulum inverted, tap it, and compare what the controller does between solves.
//
//   ./policy <tap in rad/s> <plan|feedback> <measured|predicted> [stages between solves]
//
// loop.h has the loop itself: a simulated pendulum that moves every millisecond, a solver
// that runs once per stage or less often, and an inner loop that applies either the plan's
// torque alone ("plan") or the plan's torque corrected by its stored gain ("feedback"). Each
// solve starts either from the measured state or from the state the plan itself predicted
// for that instant. This program taps the pendulum half a second in and measures the result.
#include <cstdio>
#include <cstdlib>
#include <cstring>

#include "loop.h"
#include "trace.h"

int main(int argc, char** argv) {
    Trace trace(argc, argv);
    const double tap = argc > 1 ? std::atof(argv[1]) : 1.0;

    static Loop::Solver::Workspace workspace;
    static Loop loop(workspace);  // inverted and at rest
    loop.feedback = argc > 2 ? std::strcmp(argv[2], "feedback") == 0 : true;
    loop.from_measured = argc > 3 ? std::strcmp(argv[3], "measured") == 0 : false;
    loop.period = argc > 4 && argv[4][0] != '-' ? std::atoi(argv[4]) : 1;

    const long tap_tick = 505;
    Recovery recovery;
    for (long tick = 0; tick < 4500; tick++) {
        if (!loop.command()) return 1;
        if (tick == tap_tick) loop.x(1) += tap;  // the tap: a sudden change of rate
        if (tick >= tap_tick) recovery.measure(loop.x, (tick - tap_tick) * loop.tick_s());
        if (tick == tap_tick) {
            // The gain that was holding the rod still, in N m per rad and N m per rad/s.
            trace.value("gain_angle", loop.gain(0, 0));
            trace.value("gain_rate", loop.gain(0, 1));
        }
        loop.advance();
    }

    std::printf("tap %.1f rad/s, %s, each solve from the %s state, every %d stage(s):\n", tap,
                loop.feedback ? "plan with feedback" : "plan's torque only",
                loop.from_measured ? "measured" : "predicted", loop.period);
    std::printf("  furthest from inverted %.3f rad; ", recovery.peak);
    if (recovery.at_rest >= 0.0) std::printf("still again %.2f s after the tap\n", recovery.at_rest);
    else std::printf("not back at rest by the end of the run\n");
    trace.value("peak", recovery.peak);
    trace.value("recovered", recovery.at_rest);
    return 0;
}
