#!/usr/bin/perl -w
use strict;

#(C) 2003 John B. Silvestri
#include <license/gpl.txt>

my ($to, $from, $proto);
print "From: [choose from list] ";
chomp($from=<STDIN>);
if ($from eq ""){
	my @info=qx/gaim-remote info/;
	my $count=0;
	foreach (@info){
		chomp;
		my ($info_acct, $info_proto)=split(/\,/);
		print "${count}. ${info_acct} (${info_proto})\n";
		$count++;
	}
	print "Send from account #: ";
	chomp (my $choice=<STDIN>);
	my $line=$info[$choice];
	($from, $proto)=split(/\,/,$line);
	print "From ${from} (${proto})\n";#DEBUG
}else{
	print "Protocol: "; #autochosen by 'from'
	chomp($proto=<STDIN>);
}
print "To: [choose from list]";
chomp($to=<STDIN>);
if ($to eq ""){
#Begin 'list' code
my @list=qx/gaim-remote list/;

my $count=0;
my $lastgroup=0;
my @outstrings;
my @buddies;
foreach (@list){
	chomp;
	my @line=split /\t/;
	my $first=shift @line;
	my $tmpstring;
	if ($first eq ""){
		my ($user, $away, $alias, $b_acct, $b_proto)=split(/\,/,"@line");
		if (($b_acct eq $from) && ($b_proto eq $proto)){
			$tmpstring .= "${count}. ${alias} (${user})";
			$tmpstring .= " is away" if ($away==1);
			$tmpstring .= ".\n";
			push @outstrings, $tmpstring;
			push @buddies, @line;
			$lastgroup=0;
			$count++;
		}
	}else{
		if ($lastgroup==1){
			pop @outstrings;
		}
		push @outstrings, "${first}\n";
		$lastgroup=1;
	}
}
	if ($lastgroup==1){pop @outstrings;}
	print @outstrings;

#End 'list' code
	print "Send to buddy #: ";
	chomp (my $choice=<STDIN>);
	my $line=$buddies[$choice];
	($to)=split(/\,/,"$line");
	print "Sending to: $to\n"; #DEBUG
} #End if($to eq "")
print "Message (press CTRL-D to send / CTRL-C to exit): \n";
while(1){ #Infinite loops are *fun*
	my @msg=<STDIN>;
	my $smsg=join ("", @msg);
	my @args=("gaim-remote", "send", "-t", $to, "-f", $from, "-p", $proto, "-m", $smsg);
	system(@args) == 0
		 or die "system @args failed: $?";
	print "\n-----------\n";
}