#!/usr/bin/perl -w

use strict;
package Units;

# depends on external 'units' command, which half looks like it was meant to
# be parsed.

my $precision = 10;

sub convertUnits {
	my ($from, $to) = @_;
	my (@parts, $buf);
	my $result = '';
	my $definition = 0;
	my $res;
	
	# this is a bit of a hack to get definitions

	if ($to eq '') {
		# awful.
		$res = open(UNITFD, '-|', 'units', '--output-format', '%.' . $precision . 'g', '--', $from);
	} else {
		$res = open(UNITFD, '-|', 'units', '--output-format', '%.' . $precision . 'g', '--', $from, $to);
	}

	if (!$res) {
		&::performStrictReply("error: you need to install 'units'!");
		return;
	}

	while (defined($buf = <UNITFD>)) {
		chomp $buf;
		
		$buf =~ /(\t)(.*)/;

		if (!defined($1) || $1 ne "\t") {
			&::performStrictReply("error: $buf");
			close(UNITFD);
			return;
		}
		@parts = split(/ /, $2);

		if ($parts[0] eq "*") {
			$result = $parts[1];
		} elsif ($parts[0] eq 'Definition:') {
			shift @parts;
			$result = join(' ', @parts);
			$definition = 1;
		} elsif (!defined($parts[1])) {
			# func(x) result
			$result = $parts[0];
		}
	}
	close(UNITFD);

	if ($result eq '') {
		&::performStrictReply("error: my mind is going, Dave.  I can feel it.");
		return;
	}
	if ($definition) {
		&::performStrictReply("$from is defined as \002$result\002.\n");
	} else {
		&::performStrictReply("$from is approx. \002$result\002 $to.\n");
	}
}
