/* Copyright (C) 2010,2013 G.P. Halkes
   This program is free software: you can redistribute it and/or modify
   it under the terms of the GNU General Public License version 3, as
   published by the Free Software Foundation.

   This program is distributed in the hope that it will be useful,
   but WITHOUT ANY WARRANTY; without even the implied warranty of
   MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
   GNU General Public License for more details.

   You should have received a copy of the GNU General Public License
   along with this program.  If not, see <http://www.gnu.org/licenses/>.
*/

#include <stdio.h>
#include <stdlib.h>
#include <unistd.h>
#include <ctype.h>
#include <sys/wait.h>
#include <float.h>
#include <signal.h>
#include <sys/time.h>
#include <sys/ioctl.h>
#include <sys/types.h>
#include <stdarg.h>

#include "optionMacros.h"
#include "common.h"
#include "replay.h"
#include "input.h"
#ifdef HAVE_CURSES
#include "curses_handling.h"
#ifdef HAVE_UNISTRING
#include "write_stringlist.h"
#if defined(HAVE_CAIRO) && defined(HAVE_PTHREAD)
#include "picture_queue.h"
#endif
#endif
#endif

/*
TODO:

- add the posibility to require keypress for next send event (except 0 delay events)
- it may be a good idea to have a simultaneous replay mode such that one can
  verify wether the visual results are still the same. This would require some
  form of synchronisation between multiple instances of the replay program.
- restore the terminal size after completing the replay. This should be done
  the same for the view program.
- the information requests to the terminal may cause more problems: different
  version of the same terminal may respond differently. That would mean that
  the output may look slightly off. That is not so much of a problem. What is a
  problem though is that we should clear the input buffer before switching to
  interact mode. Furthermore, if we wish to rerecord for the new version of the
  terminal, we need the proper response and not the recorded one. This may
  require some new construct to make replay aware of this.
- allow user to specify different client to start from the command line
- should we allow some way to return to the original script after an interact command?

*/

#define BUFFER_SIZE 1024

typedef enum {
	ON_ERROR_ABORT,
	ON_ERROR_INTERACT,
	ON_ERROR_CONTINUE
} OnError;

static FILE *log_file;
static char *input;
static char *alert;
static double key_delay_scale = 1.0;
static double key_delay;
static td_bool display;
static OnError on_error = ON_ERROR_ABORT;
static td_bool no_resize;
static const char *log_name;
#if defined(HAVE_CURSES) && defined(HAVE_UNISTRING)
static td_bool visual_compare;
static td_bool describe;
#ifdef HAVE_CAIRO
static const char *picture_name;
#ifdef HAVE_PTHREAD
static const char *picture_series;
#endif
#endif
#endif

static td_bool resize_capable;
static td_bool exited;
static int status;
static struct timeval timestamp;
static int master;
static pid_t pid;
static int already_waited;

static port_pollfd fdset[2];

#if defined(HAVE_CURSES) && defined(HAVE_UNISTRING)
static window_t *expectWin, *realWin;
#endif

static void printUsage(void) {
	printf("Usage: tdreplay [OPTIONS] <recording>\n");
	printf("  -a<cmd>, --alert=<cmd>              Run <cmd> on error\n");
	printf("  -d, --display                       Show the output of the running program\n");
	printf("  -e<action>, --on-error=<action>     On error perform <action> (one of\n"
	       "                                        interact, continue, abort)\n");
	printf("  -k<delay>, --key-delay=<delay>      Set key delay\n");
	printf("  -l<log>, --log=<log>                Save a log file to <log>\n");
	printf("  -R, --no-resize                     Do not try to resize the terminal\n");
#if defined(HAVE_CURSES) && defined(HAVE_UNISTRING)
	printf("  -v, --visual-compare                Check for visual equality\n");
	printf("  -D, --describe                      Print a description of the first visual difference found\n");
#ifdef HAVE_CAIRO
	printf("  -p<name>, --picture=<name>          Write a picture of the differences to <name>\n"
	       "                                        (only valid with -v)\n");
	printf("  -f<font>, --font=<font>             Use <font> to show text in picture.\n");
	printf("  -W<width>, --cell-width=<width>     Use <width> as cell width in picture.\n");
	printf("  -H<height>, --cell-height=<height>  Use <height> as cell width in picture.\n");
#ifdef HAVE_PTHREAD
	printf("  -P<name>, --picture-series=<name>   Create a series of picutes use <name> as template\n");
#endif
#endif
#endif
	printf("  -V, --version                       Print version and copyright information\n");
	exit(EXIT_SUCCESS);
}

static PARSE_FUNCTION(parse_options)
	OPTIONS
		OPTION('a', "alert", REQUIRED_ARG)
			alert = optArg;
		END_OPTION
		OPTION('d', "display", NO_ARG)
			display = td_true;
		END_OPTION
		OPTION('e', "on-error", REQUIRED_ARG)
			if (strcmp(optArg, "interact") == 0) {
				on_error = ON_ERROR_INTERACT;
			} else if (strcmp(optArg, "continue") == 0) {
				on_error = ON_ERROR_CONTINUE;
			} else if (strcmp(optArg, "abort") == 0) {
				on_error = ON_ERROR_ABORT;
			} else {
				fatal("Invalid argument for on-error option: %s\n", optArg);
			}
		END_OPTION
		OPTION('k', "key-delay", REQUIRED_ARG)
			while (*optArg && isspace(*optArg))
				optArg++;
			if (optArg[0] == '/') {
				optArg++;
				PARSE_DOUBLE(key_delay_scale, DBL_MIN, DBL_MAX);
				key_delay = 0;
			} else if (isdigit(*optArg)) {
				PARSE_INT(key_delay, 1, INT_MAX);
				key_delay_scale = 1.0;
			} else {
				fatal("Invalid argument for key-delay option: %s\n", optArg);
			}
		END_OPTION
		OPTION('l', "log", REQUIRED_ARG)
			log_name = optArg;
		END_OPTION
		OPTION('R', "no-resize", NO_ARG)
			no_resize = td_true;
		END_OPTION
		OPTION('v', "visual-compare", NO_ARG)
#if defined(HAVE_CURSES) && defined(HAVE_UNISTRING)
			visual_compare = td_true;
#else
			fatal("termdebug was built without (n)curses and/or libunistring, and therefore tdreplay does not provide " OPTFMT "\n", OPTPRARG);
#endif
		END_OPTION
		OPTION('p', "picture", REQUIRED_ARG)
#ifdef HAVE_CAIRO
			if (picture_name != NULL)
				fatal("Option " OPTFMT " specified twice\n", OPTPRARG);
			picture_name = optArg;
#else
			fatal("termdebug was built without cairo, and therefore tdreplay does not provide " OPTFMT "\n", OPTPRARG);
#endif
		END_OPTION
		OPTION('f', "font", REQUIRED_ARG)
#ifdef HAVE_CAIRO
			option_font = optArg;
#else
			fatal("termdebug was built without cairo, and therefore tdreplay does not provide " OPTFMT "\n", OPTPRARG);
#endif
		END_OPTION
		OPTION('W', "cell-width", REQUIRED_ARG)
#ifdef HAVE_CAIRO
			PARSE_INT(cell_width, 6, 16);
#else
			fatal("termdebug was built without cairo, and therefore tdreplay does not provide " OPTFMT "\n", OPTPRARG);
#endif
		END_OPTION
		OPTION('H', "cell-heigth", REQUIRED_ARG)
#ifdef HAVE_CAIRO
			PARSE_INT(cell_width, 6, 24);
#else
			fatal("termdebug was built without cairo, and therefore tdreplay does not provide " OPTFMT "\n", OPTPRARG);
#endif
		END_OPTION
		OPTION('P', "picture-series", REQUIRED_ARG)
#ifndef HAVE_CAIRO
			fatal("termdebug was built without cairo, and therefore tdcompare does not provide " OPTFMT "\n", OPTPRARG);
#else
#ifndef HAVE_PTHREAD
			fatal("termdebug was built without pthreads, and therefore tdcompare does not provide " OPTFMT "\n", OPTPRARG);
#else
			if (!check_fmt(optArg))
				fatal(OPTFMT " argument must have exactly one d-type printf conversion\n", OPTPRARG);
			picture_series = optArg;
#endif
#endif
		END_OPTION
		OPTION('D', "describe", NO_ARG)
#if defined(HAVE_CURSES) && defined(HAVE_UNISTRING)
			describe = td_true;
#else
			fatal("termdebug was built without (n)curses and/or libunistring, and therefore tdreplay does not provide " OPTFMT "\n", OPTPRARG);
#endif
		END_OPTION
		OPTION('h', "help", NO_ARG)
			printUsage();
		END_OPTION
		OPTION('V', "version", NO_ARG)
			fputs("tdreplay " VERSION_STRING "\nCopyright (C) 2010,2013 G.P. Halkes\nLicensed under the GNU General Public License version 3\n", stdout); /* @copyright */
			exit(0);
		END_OPTION

		DOUBLE_DASH
			NO_MORE_OPTIONS;
		END_OPTION

		fatal("Unknown option " OPTFMT "\n", OPTPRARG);
	NO_OPTION
		if (input != NULL)
			fatal("More than one recording specified\n");
		input = optcurrent;
	END_OPTIONS
	if (input == NULL)
		fatal("No recording specified\n");
#if defined(HAVE_CURSES) && defined(HAVE_UNISTRING) && defined(HAVE_CAIRO) && defined(HAVE_PTHREAD)
	if (picture_series != NULL && !visual_compare)
		fatal("Picture series can only be generated in visual compare mode\n");
#endif
END_FUNCTION

static void interact(void);

static void end_client(void) {
	kill(pid, SIGTERM);

	/* Give client time to respond to SIGTERM */
	while (port_poll(fdset + 1, 1, 2000) < 0) {}
	HANDLE_SIG_BYTES()
		case SIGNAL_CHILD:
			if (waitpid(pid, &status, WNOHANG) == pid)
				return;
			break;
	END_HANDLE

	kill(pid, SIGKILL);
	waitpid(pid, &status, WNOHANG);
}

static void unexpected(const char *reason, const char *received, size_t recv_length, int line, ...) {
	(void) reason;

	if (alert != NULL) {
		/* Add reason to the environment to allow the user to be notified of the problem. */
		setenv("REASON", reason, 1);
		ignore_result(system(alert));
		/* Only alert user once. */
		alert = NULL;
	}

	if (log_file != NULL) {
		va_list args;

		fprintf(log_file, "!! ");
		va_start(args, line);
		vfprintf(log_file, reason, args);
		va_end(args);
		if (received) {
			fprintf(log_file, ": \n");
			write_escaped_string(log_file, received, recv_length);
		} else {
			fprintf(log_file, "\n");
		}
	}

	switch (on_error) {
		case ON_ERROR_ABORT: {
			va_list args;

			end_client();
			/* Reset tty to show message. */
			if (display) {
#ifdef HAVE_CURSES
				sanitize_term();
#endif
				reset_tty();
				putc('\n', stderr);
			}
			fprintf(stderr, "Different behaviour from client at line %d: ", line);

			va_start(args, line);
			vfprintf(stderr, reason, args);
			va_end(args);
			exit(EXIT_FAILURE);
		}
		case ON_ERROR_INTERACT:
			interact();
			/* We should not even get here, but just to make sure */
			exit(EXIT_SUCCESS);
		case ON_ERROR_CONTINUE:
			break;
		default:
			fatal("Internal error\n");
	}
}

static void unexpected_death(void) {
	if (alert != NULL)
		ignore_result(system(alert));

	if (log_file != NULL)
		fprintf(log_file, "!! Client stopped unexpectedly with status: %d\n", WEXITSTATUS(status));
	/* Reset tty to show message. */
	if (display)
		reset_tty();
	fprintf(stderr, "Client stopped unexpectedly with status: %d\n", WEXITSTATUS(status));
	exit(EXIT_FAILURE);
}

static void handle_signals(ExpNode *exp, const char *activity) {
	if (fdset[1].revents & PORT_POLLIN) {
		HANDLE_SIG_BYTES()
			case SIGNAL_CHILD:
				if (waitpid(pid, &status, WNOHANG | WUNTRACED) == pid) {
					unexpected("Process stopped unexpectedly while waiting %s", NULL, 0, exp->line, activity);
					if (WIFSTOPPED(status)) {
						if (display) {
							printf("Process has stopped. Will send continue signal in 3 seconds\n");
							sleep(3);
						}
						kill(pid, SIGCONT);
					} else {
						unexpected_death();
					}
				}
				break;
		END_HANDLE
	}
}

static void handle_client_output(ExpNode *exp, const char *activity) {
	if (fdset[0].revents & PORT_POLLIN) {
		char buffer[BUFFER_SIZE];
		ssize_t result;

		result = safe_read(master, buffer, sizeof(buffer));
		if (result <= 0)
			return;
		if (display)
			safe_write(STDOUT_FILENO, buffer, result);
		unexpected("Received unexpected output while waiting %s", buffer, result, exp->line, activity);
	}
}

static void set_window_size_internal(ExpNode *size) {
	struct winsize wsz;
	memset(&wsz, 0, sizeof(wsz));

	if (log_file != NULL)
		fprintf(log_file, "Changing window size to: %d %d\n", size->un.size.columns, size->un.size.rows);

	if (display && resize_capable && !no_resize) {
		char buffer[64];
		size_t result;
		result = sprintf(buffer, "\x1b[8;%d;%dt", size->un.size.rows, size->un.size.columns);
		safe_write(STDOUT_FILENO, buffer, result);
	}

	wsz.ws_col = size->un.size.columns;
	wsz.ws_row = size->un.size.rows;
	if (ioctl(master, TIOCSWINSZ, &wsz))
		fatal("Error setting window size: %s\n", strerror(errno));
}

static void set_window_size(ExpNode *size) {
	ssize_t result;
	int delay;
	struct timeval start, now;

	if (size->un.size.min_delay > 0)
		delay = size->un.size.min_delay;
	else if (key_delay)
		delay = key_delay;
	else
		delay = size->un.size.delay / key_delay_scale;

	if (delay < 0 || delay < already_waited)  {
		set_window_size_internal(size);
		already_waited = 0;
		return;
	}

	gettimeofday(&start, NULL);
	while (1) {
		result = port_poll(fdset, 2, delay - already_waited);

		if (result == -1) {
			if (errno != EINTR)
				fatal("Error during poll: %s\n", strerror(errno));
		}

		handle_signals(size, "to resize window");

		if (display)
			copy_attrs_to_terminal(master);

		gettimeofday(&now, NULL);
		already_waited += timevaldiff(start, now);

		if (result == 0 || delay <= already_waited) {
			set_window_size_internal(size);
			already_waited = 0;
			return;
		} else {
			handle_client_output(size, "to resize window");
		}
	}
}

static int get_next_delay(ExpNode *exp, int *min_delay) {
	*min_delay = 0;
	for (; exp != NULL; exp = exp->next) {
		if (exp->type == EXP_WINDOW_SIZE) {
			return exp->un.size.delay;
		} else if (exp->type == EXP_SEND) {
			if (exp->un.args->min_delay > 0)
				*min_delay = exp->un.args->min_delay;
			return exp->un.args->delay;
		}
	}
	return -1;
}

static void expect(ExpNode *exp) {
	static td_bool first_expect = td_true;
	StringListNode *current = exp->un.args;
	int todo = current->length;
	char buffer[BUFFER_SIZE];
	ssize_t result;
	struct timeval start, now;
	int remaining_timeout, timeout, min_delay;

	if (log_file != NULL) {
		fprintf(log_file, "Expecting client output: \n");
		write_escaped_string(log_file, current->string, current->length);
		fprintf(log_file, "\n");
	}

	if (key_delay) {
		timeout = get_next_delay(exp, &min_delay);

		if (key_delay < timeout || timeout < 0)
			timeout = key_delay;

		if (timeout < 10)
			timeout = 10;
	} else {
		timeout = get_next_delay(exp, &min_delay);
		timeout /= key_delay_scale;
		if (timeout < 10)
			timeout = 10;
	}

	if (min_delay > timeout)
		timeout = min_delay;

	remaining_timeout = timeout;

	/* The first time we try to read from the socket, we are faced with a
	   problem: the program start up time must be taken into account. Sometimes
	   the program may be slow to start, which would normally cause the timeout
	   to pass before the program is even started. Thus we cheat, and set the
	   initial timeout to a full second, and then reset the start time to the
	   first return from poll. */
	if (first_expect)
		remaining_timeout = 1000;

	gettimeofday(&start, NULL);
	while (current != NULL && remaining_timeout > 0) {
		result = port_poll(fdset, 2, remaining_timeout);

		if (result == -1) {
			if (errno != EINTR)
				fatal("Error during poll: %s\n", strerror(errno));
			continue;
		}

		/* See comment above. */
		if (first_expect) {
			first_expect = td_false;
			gettimeofday(&start, NULL);
		}

		handle_signals(exp, "for output");

		if (display)
			copy_attrs_to_terminal(master);

		if (result == 0) {
			unexpected("No output received within timeout\n", NULL, 0, exp->line);
			return;
		} else if (fdset[0].revents & PORT_POLLIN) {
			/* Read data from the client */
			result = safe_read(master, buffer, MIN((int) sizeof(buffer), todo));
			if (result <= 0)
				continue;

			if (display)
				safe_write(STDOUT_FILENO, buffer, result);

			/* Check that the data read from the client matches what we expect */
			if (memcmp(buffer, current->string + current->length - todo, result) == 0) {
				todo -= result;
				/* Prepare next string to wait for. The while loop takes care of
				   empty strings. */
				while (todo == 0 && current != NULL) {
					current = current->next;
					if (current == NULL && exp->next != NULL && exp->next->type == EXP_EXPECT) {
						exp = exp->next;
						current = exp->un.args;
					}

					if (current != NULL) {
						todo = current->length;
						if (log_file != NULL) {
							fprintf(log_file, "Expecting client output:\n");
							write_escaped_string(log_file, current->string, current->length);
							fprintf(log_file, "\n");
						}
					}
				}
			} else {
				unexpected("Different output received then expected", buffer, result, exp->line);
			}
		}
		gettimeofday(&now, NULL);
		remaining_timeout = timeout - timevaldiff(start, now);
	}

	if (current != NULL) {
		if (log_file != NULL) {
			fprintf(log_file, "Remaining expected client output:\n");
			write_escaped_string(log_file, current->string + current->length - todo, todo);
			fprintf(log_file, "\n");
		}
		unexpected("Differences after timeout", NULL, 0, exp->line);
	}
	already_waited = timevaldiff(start, now);
}

#if defined(HAVE_CURSES) && defined(HAVE_UNISTRING)
static void visual_expect(ExpNode *exp) {
	static td_bool first_expect = td_true;
	char buffer[BUFFER_SIZE];
	ssize_t result;
	struct timeval start, now;
	int remaining_timeout, timeout, min_delay;
	td_bool do_handle_signals = td_true;

	win_write_stringlist(expectWin, exp->un.args);

	if (log_file != NULL) {
		StringListNode *string;
		fprintf(log_file, "Expecting client output:\n");
		string = exp->un.args;
		while (string != NULL) {
			for (; string != NULL; string = string->next) {
				write_escaped_string(log_file, string->string, string->length);
				fprintf(log_file, "\n");
			}
			if (exp->next != NULL && exp->next->type == EXP_EXPECT) {
				exp = exp->next;
				string = exp->un.args;
			}
		}
	}

	if (log_file != NULL)
		fprintf(log_file, "Received client output:\n");

	if (key_delay) {
		timeout = get_next_delay(exp, &min_delay);

		if (timeout == -1)
			do_handle_signals = td_false;

		if (key_delay < timeout || timeout < 0)
			timeout = key_delay;

		if (timeout < 10)
			timeout = 10;
	} else {
		timeout = get_next_delay(exp, &min_delay);
		if (timeout == -1)
			do_handle_signals = td_false;
		timeout /= key_delay_scale;
		if (timeout < 10)
			timeout = 10;
	}

	if (min_delay > timeout)
		timeout = min_delay;

	remaining_timeout = timeout;

	/* The first time we try to read from the socket, we are faced with a
	   problem: the program start up time must be taken into account. Sometimes
	   the program may be slow to start, which would normally cause the timeout
	   to pass before the program is even started. Thus we cheat, and set the
	   initial timeout to a full second, and then reset the start time to the
	   first return from poll. */
	if (first_expect)
		remaining_timeout = 1000;


	gettimeofday(&start, NULL);
	while (remaining_timeout > 0) {
		result = port_poll(fdset, 2, remaining_timeout);

		/* See comment above. */
		if (first_expect) {
			first_expect = td_false;
			gettimeofday(&start, NULL);
		}

		if (result == -1) {
			if (errno != EINTR)
				fatal("Error during poll: %s\n", strerror(errno));
			continue;
		}

		if (display)
			copy_attrs_to_terminal(master);


		if (fdset[0].revents & PORT_POLLIN) {
			/* Read data from the client */
			result = safe_read(master, buffer, sizeof(buffer));
			if (result <= 0)
				continue;

			if (display)
				safe_write(STDOUT_FILENO, buffer, result);

			win_write_data(realWin, buffer, result);
			if (log_file != NULL) {
				write_escaped_string(log_file, buffer, result);
				fprintf(log_file, "\n");
			}
		}

		if (fdset[1].revents & PORT_POLLIN) {
			if (do_handle_signals)
				handle_signals(exp, "for output");
			else
				break;
		}

		gettimeofday(&now, NULL);
		remaining_timeout = timeout - timevaldiff(start, now);
	}

#if defined(HAVE_CAIRO) && defined(HAVE_PTHREAD)
	if (picture_series != NULL) {
		static int step_count = 1;
		char output_name_buffer[1024];
		snprintf(output_name_buffer, sizeof(output_name_buffer), picture_series, step_count++);
		enqueue_pictures(expectWin, realWin, output_name_buffer);
	}
#endif

	if (!win_compare(expectWin, realWin, describe ? stderr : NULL)) {
#ifdef HAVE_CAIRO
		if (picture_name != NULL)
#ifdef HAVE_PTHREAD
			enqueue_pictures(expectWin, realWin, picture_name);
#else
			win_write_image(expectWin, realWin, picture_name);
#endif
#endif
		unexpected("Visual differences after timeout", NULL, 0, exp->line);
		describe = td_false;
	}
	already_waited = timevaldiff(start, now);
}
#endif

static void send_keys(ExpNode *keys) {
	StringListNode *current = keys->un.args;
	ssize_t result;

	while (current != NULL) {
		int delay;

		/* Calculate the delay that has to be taken into account before sending
		   the key(s) to the application. */
		if (current->delay - already_waited < 5) {
			/* The delay is so small, just send now before the terminal decides to continue.
			   This should solve issues like the one with vi, which sends information requests
			   to the terminal and then doesn't wait for the response. */
			if (display)
				copy_attrs_to_terminal(master);
			if (log_file != NULL) {
				fprintf(log_file, "Sending key(s): ");
				write_escaped_string(log_file, current->string, current->length);
				fprintf(log_file, "\n");
			}
			safe_write(master, current->string, current->length);
			current = current->next;
			already_waited = 0;
			continue;
		} else if (key_delay) {
			delay = key_delay;
		} else {
			delay = current->delay / key_delay_scale;
		}

		if (delay < current->min_delay - already_waited)
			delay = current->min_delay - already_waited;
		already_waited = 0;

		result = port_poll(fdset, 2, delay);

		if (result == -1) {
			if (errno != EINTR)
				fatal("Error during poll: %s\n", strerror(errno));
		}

		handle_signals(keys, "to send key(s)");

		if (display)
			copy_attrs_to_terminal(master);

		if (result == 0) {
			if (log_file != NULL) {
				fprintf(log_file, "Sending key(s): ");
				write_escaped_string(log_file, current->string, current->length);
				fprintf(log_file, "\n");
			}
			safe_write(master, current->string, current->length);
			current = current->next;
		} else {
			handle_client_output(keys, "to send key(s)");
		}
	}
}

static void handle_exit(ExpNode *exit_data) {
	if (WEXITSTATUS(status) != exit_data->un.number) {
		if (alert != NULL)
			ignore_result(system(alert));

		if (log_file != NULL)
			fprintf(log_file, "!! Program ended with different status: %d iso %d\n", WEXITSTATUS(status), exit_data->un.number);
		exit(EXIT_FAILURE);
	}
	if (log_file != NULL)
		fprintf(log_file, "Program ended with expected status: %d\n", exit_data->un.number);
	exit(EXIT_SUCCESS);
}

static void expect_signal(ExpNode *signal_data) {
	ssize_t result;

	if (log_file != NULL)
		fprintf(log_file, "Waiting for exit\n");

	while (1) {
		result = port_poll(fdset, 2, -1);

		if (result == -1) {
			if (errno != EINTR)
				fatal("Error during poll: %s\n", strerror(errno));
		}

		if (fdset[1].revents & PORT_POLLIN) {
			HANDLE_SIG_BYTES()
				case SIGNAL_CHILD:
					if (waitpid(pid, &status, WNOHANG | WUNTRACED) == pid) {
						if (WIFSTOPPED(status)) {
							if (signal_data->type == EXP_EXPECT_EXIT)
								unexpected("Process stopped unexpectedly while waiting for exit", NULL, 0, signal_data->line);
							if (display) {
								printf("Process has stopped. Will send continue signal in 3 seconds\n");
								sleep(3);
							}
							kill(pid, SIGCONT);
							if (signal_data->type == EXP_EXPECT_SUSPEND)
								return;
						} else {
							if (signal_data->type == EXP_EXPECT_EXIT)
								handle_exit(signal_data);
							else
								unexpected_death();
						}
					}
					break;
			END_HANDLE
		}

		if (display)
			copy_attrs_to_terminal(master);

		handle_client_output(signal_data, signal_data->type == EXP_EXPECT_EXIT ? "for exit" : "for suspend");
	}
}

static void interact(void) {
	copy_attrs_to_terminal(master);
	interact_loop(master, pid, NULL, -1);
	exit(EXIT_SUCCESS);
}

int tdreplay_main(int argc, char *argv[]) {
#if defined(HAVE_CURSES) && defined(HAVE_UNISTRING)
	struct winsize wsz;
#endif
	int slave;

	parse_options(argc, argv);

	if (display && !isatty(STDIN_FILENO))
		fatal("Can only replay to a terminal devices\n");

	if (log_name != NULL) {
		if ((log_file = fopen(log_name, "w")) == NULL)
			fatal("Can't open log: %s\n", strerror(errno));
		/* FIXME: do we want this??
		setvbuf(log_file, NULL, _IONBF, 0);
		*/
	}

	reset_lexer(input);
	parse();

	gettimeofday(&timestamp, NULL);

	if (display) {
		resize_capable = detect_resize_capable();
		install_signal_handler(SIGWINCH, sigwinch_handler, "SIGWINCH");
		/* Get terminal attributes. */
		save_tty();
	}
	install_signal_handler(SIGCHLD, sigchld_handler, "SIGCHLD");

	unsetenv("TERM");
	unsetenv("LINES");
	unsetenv("COLUMS");
	unsetenv("LANG");
	unsetenv("LC_CTYPE");

	if (port_openpty(&master, &slave, NULL) < 0)
		fatal("Error opening pty: %s\n", strerror(errno));

	set_non_block(STDIN_FILENO, "terminal", td_true);
	set_non_block(master, "pty", td_true);
	set_non_block(signal_pipe[PIPE_READ], "pipe", td_true);

	fdset[0].fd = master;
	fdset[0].events = PORT_POLLIN;
	fdset[1].fd = signal_pipe[PIPE_READ];
	fdset[1].events = PORT_POLLIN;

#if defined(HAVE_CURSES) && defined(HAVE_UNISTRING)
	if (visual_compare) {
		const char *term;

		init_attr_map();

		if ((term = get_script_env(script, "TERM")) == NULL)
			fatal("Recording does not contain a TERM environment variable\n");
		setup_ti_strings(term, get_script_env(script, "LANG"));

		/* Get terminal size. */
		if (ioctl(STDIN_FILENO, TIOCGWINSZ, &wsz) < 0 || wsz.ws_col == 0 || wsz.ws_row == 0) {
			fprintf(stderr, "Warning: could not obtain window size: %s\n", strerror(errno));
			wsz.ws_col = 80;
			wsz.ws_row = 24;
		}

		if ((realWin = win_new(wsz.ws_row, wsz.ws_col)) == NULL)
			fatal("Out of memory\n");
		if ((expectWin = win_new(wsz.ws_row, wsz.ws_col)) == NULL)
			fatal("Out of memory\n");

#if defined(HAVE_CAIRO) && defined(HAVE_PTHREAD)
		if (picture_series != NULL || picture_name != NULL)
			start_picture_writer_thread();
#endif
	}
#endif


	while (script != NULL) {
		if (exited) {
			if (script->type != EXP_EXPECT_EXIT)
				unexpected_death();
			else
				handle_exit(script);
		}
		switch (script->type) {
			case EXP_START:
				pid = start_client(script, slave, log_file);
				break;
			case EXP_EXPECT:
#if defined(HAVE_CURSES) && defined(HAVE_UNISTRING)
				if (visual_compare)
					visual_expect(script);
				else
#endif
				expect(script);
				while (script->next != NULL && script->next->type == EXP_EXPECT)
					script = script->next;
				break;
			case EXP_SEND:
				send_keys(script);
				break;
			case EXP_EXPECT_EXIT:
			case EXP_EXPECT_SUSPEND:
				expect_signal(script);
				break;
			case EXP_INTERACT:
				if (display)
					interact();
				break;
			case EXP_WINDOW_SIZE:
				set_window_size(script);
				break;
			case EXP_ENV:
				if (log_file != NULL)
					fprintf(log_file, "Setting environment variable %s to %s\n", script->un.args->string, script->un.args->next->string);
				setenv(script->un.args->string, script->un.args->next->string, 0);
				break;
			case EXP_REQUIRE_VERSION:
				break;
			default:
				fatal("Internal error\n");
		}
		script = script->next;
	}
	end_client();
	return EXIT_SUCCESS;
}
