#!/usr/athena/bin/perl

require 'chat2.pl';
$* = 1;
sub start {
    $msg = 0;
    &chat'open_proc('/mit/sipb/bin/pop');
    system("stty onlcr icrnl");
    print("Ran pop\n");
    print "Ran...", &chat'expect(5, "pop:  ", '$`');
    print("Connecting\n");
    &chat'print("c\n");
	print("sent\n");
    print &chat'expect(15, "pop:  ", '$`');
	print("\nReady to find out what's going on...\n");
    &chat'print("s\n");
    $status =  &chat'expect(5, "pop:  ", '$`');
    print("Status: $status\n");
#    $status =  &chat'expect(5, "pop:  ", '$`');
#	$status =~ s/[\n\r]/\*/g;
	print("I think I know what's going on...($status)\n");
    print("You have $status");
}

&start;
while(1){
	$dowhat = &prompt;
	&$dowhat();
}

sub gresp {
	local($cmd) = @_;
#	print("Getting response from \"$cmd\"\n");
	&chat'print("$cmd\n");
	$resp = &chat'expect(4, "pop:  ", '$`');
#	print("Response of len ", length($resp), "\n");
	$resp;
	
}

sub help {
	print("<CR> for next message\n");
	print("\"d\" to delete last message\n");
	print("\"r\" to restart from msg 1\n");
	print("\"h\" for this message\n");
	print("\"q\" to quit\n");
}

sub mesg {
	$msg++;
	print("Getting message $msg\n");
	&more(&gresp("retr $msg"));
}

sub dele {
    print("Deleting $msg\n");
    &more(&gresp("dele $msg\n"));
    &chat'expect(4, "pop:  ", '$`');
}

sub restart {
	$msg=0;
	print("Message number has been reset\n");
}

sub rerun{
    &chat'print("q\n");
    &chat'close();
    &start;
}
sub prompt {
	local($in);
	print("\"pop!\"; ");
	$in = (<STDIN>);
	
	if($in eq "\n"){
		"mesg";
	}
	elsif($in eq "d\n"){
		"dele";
	}
	elsif($in eq "h\n"){
		"help";
	}
	elsif($in eq "r\n"){
		"restart";
	}
	elsif($in eq "q\n"){
		&chat'print("q\n");
		sleep(2);
		exit(0);
	}
	elsif($in eq "x\n"){
		"rerun";
	}
	elsif($in =~ /(\d+)/){
	    $msg = $1-1;
	    "mesg";
	}	  
	else {
		"help";
}
}
sub more {
	local($string) =@_;
#	print "String of length: ", length($string), "\n";
#	$string =~ s/\r/\*/g;
#	print "------------\n$string\n--------------\n";
#	return;

	if(fork()){
		wait;
	}
	else{
#		print STDOUT $string;
#		print("\n");
		open(MORE, "|more");
		print MORE $string;
		close(MORE);
		exit;
	}
}
