/*
 * Puppeteer 1.1
 *
 * Copyright (c) 1994 Primitive Software Ltd.  All rights reserved.
 *
 * Author: Dave Griffiths <dave@prim.demon.co.uk>
 */

#import "Puppeteer.h"

void
output(id puppet, FILE *fp, int delay)
{
	char buf[1024], *s;
	
	/*
	 * Make the app the active application.
	 */
	[puppet postActivate:YES];
	
	/*
	 * Process one line at a time.
	 */
	while (fgets(buf, sizeof(buf), fp)) {
		/*
		 * Wait the specified time before outputting the line.
		 */
		usleep(delay);
		
		/*
		 * Send the line.
		 */
		for (s=buf; *s && s<&buf[1024]; s++)
			[puppet postKeyCode:*s window:NX_KEYWINDOW flags:0];
	}
}

void
main(argc, argv)
int argc;
char **argv;
{
	int c, errflg = 0, delay = 250000;
	char *ifile = NULL, *application = "Terminal";
	id puppet;
	FILE *fp;
	extern char *optarg;

	while ((c = getopt(argc, argv, "a:d:f:")) != EOF)
	switch (c) {
	case 'a':
		application = optarg;
		break;
	case 'd':
		delay = atoi(optarg)*1000;
		break;
	case 'f':
		ifile = optarg;
		break;
	case '?':
	default:
		errflg++;
		break;
	}
	if (errflg) {
		fprintf(stderr, "Usage: terminalPuppet [-a application] [-d delay] [-f file]\n");
		exit(2);
	}
	
	/*
	 * Create the application puppet, launching the app if necessary.
	 */
	puppet = [Puppeteer connectToApp:application launch:YES];
	if (!puppet) {
		fprintf(stderr, "Could not connect to %s\n", application);
		exit(1);
	}
	
	/*
	 * Attach the strings. The app will then be ready to accept events.
	 */	
	[puppet attachStrings];
	
	/*
	 * Now output the file to the application. If no file was specified, read
	 * from standard input.
	 */
	if (ifile) {
		if (!(fp = fopen(ifile, "r")))
			fprintf(stderr, "Could not open %s\n", ifile);
	} else
		fp = stdin;
	if (fp)
		output(puppet, fp, delay);

	/*
	 * Release strings. This is necessary for the app to continue to respond to
	 * real user events.
	 */
	[puppet releaseStrings];
}