#define _POSIX_C_SOURCE 200809L
#include <errno.h>
#include <signal.h>
#include <stdio.h>
#include <stdlib.h>
#include <time.h>

enum { WIDTH = 30, HEIGHT = 12 };
static volatile sig_atomic_t stopped;

static void stop_animation(int signal_number)
{
    (void)signal_number;
    stopped = 1;
}

static int argument(const char *text, int maximum)
{
    char *end;
    errno = 0;
    long value = strtol(text, &end, 10);
    if (errno || !*text || *end || value < 0 || value > maximum) return -1;
    return (int)value;
}

static void delay_ms(int milliseconds)
{
    struct timespec left = {milliseconds / 1000, (milliseconds % 1000) * 1000000L};
    while (!stopped && nanosleep(&left, &left) < 0 && errno == EINTR) {}
}

static void install_controls(void)
{
    struct sigaction action = {0};
    action.sa_handler = stop_animation;
    sigemptyset(&action.sa_mask);
    if (sigaction(SIGINT, &action, NULL) || sigaction(SIGTERM, &action, NULL)) {
        perror("signal setup");
        exit(1);
    }
    fputs("\033[?25l", stdout);
}

static void finish(void)
{
    fputs("\033[0m\033[2J\033[H\033[?25h", stdout);
    fflush(stdout);
}

struct object { int x, y, dx, dy; };

static void advance(int *coordinate, int *direction, int limit)
{
    if (*coordinate + *direction < 1 || *coordinate + *direction > limit)
        *direction = -*direction;
    *coordinate += *direction;
}

static void line(struct object a, struct object b)
{
    int dx = abs(b.x - a.x), dy = -abs(b.y - a.y);
    int sx = a.x < b.x ? 1 : -1, sy = a.y < b.y ? 1 : -1;
    int error = dx + dy;
    for (;;) {
        printf("\033[%d;%dH.", a.y, a.x);
        if (a.x == b.x && a.y == b.y) return;
        int twice = 2 * error;
        if (twice >= dy) { error += dy; a.x += sx; }
        if (twice <= dx) { error += dx; a.y += sy; }
    }
}

int main(int argc, char **argv)
{
    int frames = argc >= 2 ? argument(argv[1], 10000) : 0;
    int delay = argc >= 3 ? argument(argv[2], 1000) : 100;
    int seed = argc >= 4 ? argument(argv[3], 1000000) : 0;
    if (argc > 4 || frames < 0 || delay < 0 || seed < 0) {
        fputs("Usage: terminal [frames 0-10000] [delay_ms 0-1000] [seed 0-1000000]\n", stderr);
        return 2;
    }
    srand(argc >= 4 ? (unsigned)seed : (unsigned)time(NULL));
    struct object objects[4];
    for (int i = 0; i < 4; ++i) {
        objects[i].x = 1 + rand() % WIDTH;
        objects[i].y = 1 + rand() % HEIGHT;
        objects[i].dx = rand() % 2 ? 1 : -1;
        objects[i].dy = rand() % 2 ? 1 : -1;
    }
    install_controls();
    for (unsigned frame = 0; !stopped && (!frames || frame < (unsigned)frames); ++frame) {
        fputs("\033[2J\033[36m", stdout);
        for (int i = 1; i < 3; ++i) line(objects[i-1], objects[i]);
        for (int i = 0; i < 4; ++i)
            printf("\033[%d;%dH\033[%dm%c", objects[i].y, objects[i].x, 31+i, 'A'+i);
        fflush(stdout);
        delay_ms(delay);
        for (int i = 0; i < 4; ++i) {
            advance(&objects[i].x, &objects[i].dx, WIDTH);
            advance(&objects[i].y, &objects[i].dy, HEIGHT);
        }
    }
    finish();
    return 0;
}
