/* Collection of code snippets by Arne Vajhøj */
/* (likely posted to comp.os.vms/INFO-VAX, INFO-TPU, MACRO32, eksperten.dk, newz.dk, LinkedIn or other place sometime between 1990 and now) */
#include <stdio.h>
#include <string.h>
#include <stdint.h>

#include <descrip.h>
#include <tpudef.h>
#include <starlet.h>
#include <lib$routines.h>
#include <tpu$routines.h>

static const uint32_t MATCH_DELIM_ACTION = 1;

static void setup_timer();

static void do_match()
{
    tpu$trigger_async_action(&MATCH_DELIM_ACTION);
    setup_timer();
}

static void setup_timer()
{
    uint64_t tmo = 1000000; // 0.1 second
    sys$setimr(0, &tmo, do_match, 0, 0);
}

static uint32_t cmd_handler()
{
    char cmdlin[1024];
    $DESCRIPTOR(cmdlin_desc, cmdlin);
    uint16_t cmdlin_len;
    uint32_t fileio_desc[2] = { (uint32_t)&tpu$fileio, 0 };
    strcpy(cmdlin, "tpu ");
    cmdlin_desc.dsc$a_pointer += 4;
    cmdlin_desc.dsc$w_length -= 4;
    lib$get_foreign(&cmdlin_desc, 0, &cmdlin_len);
    cmdlin_desc.dsc$a_pointer -= 4;
    cmdlin_desc.dsc$w_length = 4 + cmdlin_len;
    return tpu$cliparse(&cmdlin_desc, fileio_desc, NULL);
}

int main(int argc, char *argv[])
{
    $DESCRIPTOR(matchdelim_desc, "EVE_AUTO_MATCH()");
    uint32_t cmd_handler_desc[2] = { (uint32_t)&cmd_handler, 0 };
    uint32_t flags = TPU$M_DELETE_CONTEXT;
    lib$establish(tpu$handler);
    tpu$initialize(cmd_handler_desc, 0);
    tpu$execute_inifile();
    tpu$specify_async_action(&MATCH_DELIM_ACTION, &matchdelim_desc);
    setup_timer();
    tpu$control();
    tpu$cleanup(&flags);
    return 0;
}
