#! /usr/bin/perl

use utf8;		# This sourcefile in utf-8

use IO::Socket::INET;
use POSIX qw(:termios_h);

die "Usage: $0 host:port\n"
	unless @ARGV == 1;

my $sock = IO::Socket::INET->new (PeerAddr => $ARGV[0])
	or die "No connection: $!\n";

# Could get rid of this initial stuff and merge it into the main
# loop.  That would be more "correct" in telnet terms, but shou;d
# be unnecessary.

my $buf;
my $initial = sysread $sock, $buf, 4096;

my $reply = "";

for (my $i = 0; $i < length $buf; ++$i) {
	my $ch = substr ($buf, $i, 1);
	if (ord $ch == 255) {
		$ch = ord substr ($buf, ++$i, 1);

		if ($ch == 251) {
			$ch = ord substr ($buf, ++$i, 1);
			# print STDERR "WILL $ch\n";
			next;
		}
		elsif ($ch == 252) {
			$ch = ord substr ($buf, ++$i, 1);
			# print STDERR "WONT $ch\n";
			next;
		}
		elsif ($ch == 253) {
			$ch = ord substr ($buf, ++$i, 1);
			# print STDERR "DO $ch\n";
			$reply .= chr(255) . chr(251). chr ($ch);
			next;
		}
		elsif ($ch == 254) {
			$ch = ord substr ($buf, ++$i, 1);
			# print STDERR "DONT $ch\n";
			$reply .= chr(255) . chr(252). chr ($ch);
			next;
		}

		# print STDERR "cmd ", $ch, "\n";
		next;
	}
	print $ch;
}

$reply .= chr (255) . chr (253) . chr (3); # DO suppress GO AHEAD
if ($reply) {
	print $sock $reply;
}

# Put terminal into some kind of RAW I/O mode

# Save original

my $savein = POSIX::Termios->new;
$savein->getattr(fileno(STDIN));

my $saveout = POSIX::Termios->new;
$saveout->getattr(fileno(STDOUT));

# On exit restore modes

END {
	$savein->setattr(fileno STDIN, TCSANOW) if $savein;
	$saveout->setattr(fileno STDOUT, TCSANOW) if $saveout;
}

# Input side

my $in = POSIX::Termios->new;
$in->getattr(fileno(STDIN));

my $lflag = $in->getlflag();
my $iflag = $in->getiflag();
$lflag &= ~(ICANON | ECHO | ECHONL | ISIG);	# Turn off canonical mode
$iflag &= ~(INLCR | IGNCR | ICRNL | IXON);
$in->setcc(VMIN, 1); 				# min chars to read
$in->setcc(VTIME, 1);   			# timeout
$in->setlflag($lflag);
$in->setiflag($iflag);

$in->setattr(fileno STDIN, TCSANOW);

# Output side

my $out = POSIX::Termios->new;
$out->getattr(fileno(STDOUT));

my $oflag = $out->getoflag();
$oflag &= ~OPOST;
$out->setoflag($oflag);

$out->setattr(fileno STDOUT, TCSANOW);

my $read = "";
vec ($read, fileno STDIN, 1) = 1;
vec ($read, fileno $sock, 1) = 1;

my $EOL = 0;	# nonzero if doing EOL sequence from George
my $UTF = 0;	# UTF-8 char being assembled from keyboard
my $UTFLEN = 0;

my $POUND = chr (0x9c);	# ICL7903.class works in code page 437

# UTF-8 to ICL
my %XLAT_OUT = (
	"£" => $POUND,
	"\\" => $POUND,
	"_" => "`",
	"↑" => "^",
	"←" => "_",
);

# ICL to UTF-8 
my %XLAT_IN = (
	"_" => "←",
	"`" => "_",
	"^" => "↑",
	$POUND => "£",
);

binmode STDOUT, ":utf8";
binmode STDERR, ":utf8";

MAIN:
for (;;) {
	my $r = $read;
	my $e;

	unless (select ($r, undef, $e = $r, undef)) {
		break;
	}

	$r |= $e;

	my $buf;

	if (vec ($r, fileno STDIN, 1)) {
		my $l = sysread (STDIN, $buf, 4096);
		last unless defined $l;

		$sock->autoflush (0);
		for (my $i = 0; $i < $l; ++$i) {
			my $chr = substr ($buf, $i, 1);
			my $val = ord $chr;
			last MAIN if $val == 0x1d;   	#	^]
			if ($val > 0x80) {	# Part of utf-8 sequence
				if ($UTFLEN) {	# building utf-8 char
					if (($val & 0xc0) == 0x80) {
						$UTF = ($UTF << 6) + 
							($val & 0x3f);
						next if --$UTFLEN;
						$chr = chr $UTF;
						goto ch;
					}
				}
				if ($val >= 0xf0) { #Start 4 byte sequence
					$UTFLEN = 3;
					$UTF = $val & 0x07;
					next;
				}
				if ($val >= 0xe0) { # start 3 byte sequence
					$UTFLEN = 2;
					$UTF = $val & 0x0f;
					next;
				}
				if ($val >= 0xc2) { # start 2 byte sequence
					$UTFLEN = 1;
					$UTF = $val & 0x1f;
					next;
				}

				$UTFLEN = 0;	# Broken
				next;
			}
			$UTFLEN = 0;
		    ch:
			$chr = $XLAT_OUT {$chr} if exists $XLAT_OUT {$chr};
			$chr = "?" if ord $chr > 127 && $chr ne $POUND;
			print $sock $chr;
			print $sock "\r" if $chr eq chr (030); # CAN
		}
		$sock->autoflush (1);
	}
	if (vec ($r, fileno $sock, 1)) {
		my $l = sysread ($sock, $buf, 4096);
		last unless defined $l;

		$| = 0;

		for (my $i = 0; $i < $l; ++$i) {
			my $chr = substr ($buf, $i, 1);
			if ($chr eq chr (023)) {
				$EOL = 1;
				next;
			}
			elsif ($chr eq chr (0) || $chr eq chr (021) ||
				 $chr eq chr (030))
			{
				# ignore
			}
			elsif ($chr ne chr (033) || ! $EOL) {
				$chr = "?" if ord $chr > 127 && $chr ne $POUND;
				$chr = $XLAT_IN {$chr}
					if exists $XLAT_IN {$chr};
				print $chr;
			}
			$EOL = 0;
		}

		$| = 1;
	}
}
