/* 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 <stdlib.h>
#include <string.h>

#include "apr.h"
#include "stomp.h"

void execute(stomp_connection *con, apr_pool_t *pool, char *cmd, char *input, char *output, char *qname)
{
    char msgbuf[80];
    apr_status_t rc;
    stomp_frame input_frame;
    stomp_frame *output_frame;
    input_frame.command = cmd;
    if(qname != NULL)
    {
        input_frame.headers = apr_hash_make(pool);
        apr_hash_set(input_frame.headers, "destination", APR_HASH_KEY_STRING, qname);
    }
    else
    {
        input_frame.headers = NULL;
    }
    input_frame.body_length = -1;
    input_frame.body = input;
    rc = stomp_write(con, &input_frame, pool);
    if(rc != APR_SUCCESS)
    {
        apr_strerror(rc, msgbuf, sizeof(msgbuf));
        printf("Error writing %s: %s\n", cmd, msgbuf);
        exit(EXIT_FAILURE);
    }
    if(output != NULL)
    {
        rc = stomp_read(con, &output_frame, pool);
        if(rc != APR_SUCCESS)
        {
            apr_strerror(rc, msgbuf, sizeof(msgbuf));
            printf("Error reading %s: %s\n", cmd, msgbuf);
            exit(EXIT_FAILURE);
        }
        strcpy(output, output_frame->body);
    }
}

int main()
{
    char msgbuf[80];
    char res[800];
    apr_status_t rc;
    apr_pool_t *pool;
    stomp_connection *con;
    stomp_frame *frame;
    rc = apr_initialize();
    if(rc != APR_SUCCESS)
    {
        apr_strerror(rc, msgbuf, sizeof(msgbuf));
        printf("Error initializing APR: %s\n", msgbuf);
        exit(EXIT_FAILURE);
    }
    rc = apr_pool_create(&pool, NULL);
    if(rc != APR_SUCCESS)
    {
        apr_strerror(rc, msgbuf, sizeof(msgbuf));
        printf("Error creating pool: %s\n", msgbuf);
        exit(EXIT_FAILURE);
    }
    rc = stomp_connect(&con, "localhost", 61613, pool);
    if(rc != APR_SUCCESS)
    {
        apr_strerror(rc, msgbuf, sizeof(msgbuf));
        printf("Error connecting: %s\n", msgbuf);
        exit(EXIT_FAILURE);
    }
    execute(con, pool, "CONNECT", NULL, res, NULL);
    execute(con, pool, "SUB", NULL, res, "/queue/arne");
    printf("%s\n", res);
    execute(con, pool, "DISCONNECT", NULL, NULL, NULL);
    rc = stomp_disconnect(&con);
    if(rc != APR_SUCCESS)
    {
        apr_strerror(rc, msgbuf, sizeof(msgbuf));
        printf("Error disconnecting: %s\n", msgbuf);
        exit(EXIT_FAILURE);
    }
    apr_pool_destroy(pool);
    apr_terminate();
    return 0;
}
