#!/usr/athena/bin/perl

use IPC::Open3;

$*=1;
$pid = open3("WICQ", "RICQ", "EICQ", "/stuff/micq/micq");
select(RICQ); $|=1;
select(WICQ); $|=1;
select(STDIN); $|=1;
select(STDOUT); $|=1;
print WICQ "\n";
while(1){
$rin = 0;
vec($rin, fileno(RICQ), 1) = 1;
while(select($rout=$rin, undef, undef, 0) >0){
#	print "!!!!!!!!!Stuff from micq!!!!!!!!!!\n";
	sysread(RICQ, $ricqin, 1, 0);
	print $ricqin;
	$ricq .= $ricqin;
	if(($imp = index($ricq, "Instant Message")) > 0){
		$begin = rindex($ricq, "\n", $imp);
		if(($end = index($ricq, "Micq>", $imp)) > 0){
			&zwrite("mkgray", substr($ricq, $begin, ($end-$begin)));
			$ricq = substr($ricq, $end);
		}
	}
}
$rin = 0;
vec($rin, fileno(STDIN), 1) = 1;
$gotstuff = 1;
while($gotstuff){
	$sir = select($rout=$rin, undef, undef, 0);
	
	if(vec($rout, fileno(STDIN), 1) == 1){
	$nofh=0;
	sysread(STDIN, $stdinin, 1, 0);
	$stdin .= $stdinin;
	while($stdin =~ s/(.*[\n\r]+)//){
		print WICQ $1;
		if($1 eq "?\n"){
			print "$ricq\n";
		}
	}
	}
	else{
	$gotstuff = 0;
}
}
}

sub zwrite {
	$to = shift;
	$what = shift;
	$what =~ s/\033\[\d\;\d\dm//g;
	$what =~ s/\033\[0m//g;
	print "Sending a zephyr to $to\n";
	open(Z, "|zwrite -n -q $to");
	print Z $what;
	close(Z);
}
