/*
 *	Copyright (C) 1990 The Board of Trustees of The Leland Stanford Junior University. 
 *	All Rights Reserved.
 * 	Transparent mode command on NeXT for tn3270	
 * 	Not to be directly called from shell.		
 * 	Specify	'ps3270' as tn3270 '-t' option. e.g. 'tn3270 -t ps3270 hostname'
 *	Requires tn3270 4.1.1 or later, which was NOT supplied with NeXTOS 1.0!, but
 *	you can get it from the usual sources.
 *
 *	ps3270 captures PostScript to a temporary file, 
 *  then messages Preview on a NeXT
 *  by Paul Kunz, pfkeb@ebnextk.slac.stanford.edu or pfkeb@slacvm.bitnet
 *	Stanford Linear Accelerator Center 	1/90
 */
#include <stdio.h>
#include <stdlib.h>
#include <strings.h>

#import <appkit/Listener.h>
#import <appkit/Speaker.h>

char *mktemp(char *template);
int	read( int d, char *buf, int nbytes);
int	write( int d, char *buf, int nbytes);

void main(int argc, char *argv[])
{
	id aSpeaker;
	port_t ws_port;
	char fnameo[] = "/tmp/psoXXXXXX";
	char psname[] = "/tmp/psoXXXXXX.ps";
	char inbuf[BUFSIZ];
	int c, irc;
	int returnOk;
	FILE *fopen(), *fpo;

	(void) mktemp(fnameo);
	if ((fpo = fopen(fnameo, "w")) == NULL) {
	   exit(EXIT_FAILURE);
	}
/* endless read loop until tn3270 closes pipe */
	while ((c = read(fileno(stdin), inbuf, sizeof(inbuf))) != 0) {
	      if (c > 0) {
		 write(fileno(fpo), inbuf, c);
	      }
	}
	(void) fclose(fpo);
	(void) strcpy(psname,fnameo);
	(void) strcat(psname,".ps" );
	irc = rename(fnameo,psname);
	
	aSpeaker = [Speaker new];
	ws_port = NXPortFromName(getenv(NX_WORKSPACEREQUEST), NULL);
	if ( ws_port == PORT_NULL )
		fprintf(stderr, "ps3270: error in attempting to find Workspace\n" );
	[aSpeaker setSendPort:ws_port]; 
	irc = [aSpeaker openTempFile:psname ok:&returnOk];	 
	[aSpeaker free];
	exit(EXIT_SUCCESS);
}
