##################################################
## some telnet-protocol routines
##################################################

sub talk {
	local($text) = @_;
	print "{$text}" if $trace;
	&chat'print($text);
}

sub listen {
	local($secs) = @_;
	local($return,$tmp) = "";
	while (length($tmp = &telnet_read($secs))) {
		print $tmp if $trace;
		$return .= $tmp;
	}
	$return;
}

sub listenr {
	local($secs,$regex) = @_;
	local($return,$tmp) = "";
	while (length($tmp = &telnet_read($secs))) {
		print $tmp if $trace;
		$return .= $tmp;
		last if $return =~ /$regex/i;
	}
	$return;
}

sub telnet_read {
	local($secs) = @_;
	&chat'expect($secs,
		'^\377[\375\376](.|\n)',
		q#&chat'print ("\377\374".$1); redo LOOP#,
			# WON'T do these do/don't requests
		'^\377[\373\374](.|\n)', 'redo LOOP',
			# ignore these will/won't changes
		'^\377\377', '"\377"',
			# escaping the IAC
		'^\377(.|\n)', 'redo LOOP',
			# ignoring these
		'^[^\377]+', '$&'
			# return these
		);
}
