#!/usr/bin/perl
#-*-perl-*-

# ------------------------------------------------------------------------
# convert from a currency to another
# usage : change.pl <change rate> <decimal number> <account file>
# ------------------------------------------------------------------------

use strict;

sub convert {
    my($rate,$dec,$file)=@_;

# preserve file permissions for new file
    my($dev, $ino, $mode, $nlink, $uid, $gid, $rdev, $size, $atime, $mtime, 
       $ctime, $blksize, $blocks) = stat($file);
    unlink("$file.bak");
    rename("$file", "$file.bak") || die "rename $file : $!\n";
    open(OLD,"<$file.bak") || die "open $file.bak : $!\n";
    open(NEW,">$file") || die "create $file : $!\n";

    while(<OLD>) {
# balance from headers
	if(/^\# (\w+) Balance = (.+)$/) {
	    printf NEW "# $1 Balance = %.${dec}f\n",$2 * $rate;
# comments headers
	} elsif(/^\#/) {
	    print NEW "$_";
# empty lines
	} elsif(/^$/) {
	    print NEW "$_";
# transactions
	} else {
	    my($date, $check, $desc, $debit, $credit,
	       $cat, $com, $cleared)=split(/\t/,$_);
	    print NEW "$date\t$check\t$desc";
	    printf NEW "\t%.${dec}f\t%.${dec}f", $debit*$rate, $credit*$rate;
	    print NEW "\t$cat\t$com\t$cleared";
	}
    }

    close(NEW);
    close(OLD);
    chown($uid, $gid, $file);
    chmod($mode, $file);
}

my($rate) = shift(@ARGV);
my($dec) = shift(@ARGV);
my($file) = shift(@ARGV);

if ( defined($rate) && defined($dec) && defined($file) ) {
    if ( -f $file ) {
	convert($rate, $dec, $file);
    } else {
	die "can't find $file\n";
    }
} else {
    die "usage : change.pl <change rate> <decimal number> <account file>\n";
}
