/* 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 <fcntl.h>
#include <io.h>

#include <jni.h>

#include "Nat1.h"

#define MAXBUF 20480

static int oldstdout;
static int pipehandles[2];
static char buf[MAXBUF];

JNIEXPORT void JNICALL Java_Nat2_init(JNIEnv *cntx, jobject me)
{
    oldstdout = _dup(_fileno(stdout));
    _pipe(pipehandles,MAXBUF,_O_BINARY);
    _dup2(pipehandles[1],_fileno(stdout));
 }

JNIEXPORT jstring JNICALL Java_Nat2_done(JNIEnv *cntx, jobject me)
{
    int n;
    fflush(stdout);
    _dup2(oldstdout,_fileno(stdout));
    n = _read(pipehandles[0],buf,sizeof(buf));
    buf[n] = '\0';
    return (*cntx)->NewStringUTF(cntx,buf);
}
