#!/usr/bin/perl

# currency.pl - convert between different currencies.
# This software is PUBLIC DOMAIN
# Version 1.0

use Finance::Currency::Convert::Yahoo;
# $Finance::Currency::Convert::Yahoo::CHAT = 1; # Debug

sub deb {
	if (defined($DEBUG)) {
		print($_);
	}
}

# $DEBUG = 1;

sub parse {
	$amount = 0;
	$source = 0;
	$target = 0;
	$args = 0;
	if ($_[0] =~ m/.+ .+/) {
		# We assume that the user just entered their query as one argument.
		@args = split(' ', $_[0]);
	} else { @args = @_; }

	foreach (@args) {
		my $happy = 0; # This will change to 1 if we get something out of the str
		deb("Processing: $_\n");
		
		# We do substitutions here
		$_ =~ s/US$/USD/i;
		$_ =~ s/\$/USD/g;
		$_ =~ s/NIS/ILS/i; # Yahoo compatibility
		$_ =~ s/shekel/ILS/i;
		$_ =~ s/swedish/SEK/i;
		$_ =~ s/danish/DKK/i;
		
		# We start matching the string.
		if ($_ =~ m/^(in)|(to)/i) {
			deb("Garbage.\n");
			$happy = 1;
			#Ignore
		}
		elsif ($_ =~ m/^(([0-9]+)|([0-9]+\.[0-9]+))([A-Z,a-z]{3,3})$/) {
			deb("Hybrid-R. Number $1, currency $4\n"); # Ugh, I know
			$happy = 1;
			
			if ($source) {
				$target = $4;
			}
			elsif ($source and $target) {
				die("Too many currencies");
			} else { $source = $4; }
			
			if (!$amount) {
				$amount = $1
			} else {die("Too many numbers");}
			
		} elsif ($_ =~ m/^([A-Z,a-z]{3,3})(([0-9]+)|([0-9]+\.[0-9]+))$/) {
			deb("Hybrid-L. Number $2, currency $1\n");
			$happy = 1;
			
			if ($source) {
				$target = $1;
			}
			elsif ($source and $target) {
				die("Too many currencies");
			} else { $source = $1 }
			
			if (!$amount) {
				$amount = $2
			} else {die("Too many numbers") }
			
		} elsif (	$_ =~ m/(^[0-9]+$)|(^[0-9]+\.[0-9]+$)/) {
			# Probably a number
			deb("Number\n");
			$happy = 1;
			
			if (!$amount) {
				$amount = $_
			} else {die("Too many numbers");}
		} elsif ($_ =~ m/^[A-Z,a-z]{3,3}$/) {
			# Probably a currency
			deb("Currency\n");
			$happy = 1;
			
			if ($source) {
				$target = $_;
			} elsif ($source and $target) {
				die("Too many currencies");
			} else { $source = $_; }
		}
		
		if (!$happy) { deb("Nothing matched? Garbage.\n"); }
	}
	
	# By this point we should have everything we want and nothing more. But let's check.
	if (!$amount) { die("Missing amount"); }
	if (!$source) { die("Missing source"); }
	if (!$target) { die("Missing target"); }
	return ($amount, $source, $target);
}

@input = parse(@ARGV);
foreach (@input) { $_ = uc($_);}
$_ = Finance::Currency::Convert::Yahoo::convert($input[0],$input[1],$input[2]);
print($_ . " $input[2]\n");
