#!/usr/bin/perl
# $Id: txn,v 1.5 1994/10/27 12:16:01 cbbrowne Exp $
#  Written by Christopher B. Browne
#
#  Copyright (C) 1994  Christopher B. Browne cbrowne@io.org
#
#  This program is free software; you can redistribute it and/or modify
#  it under the terms of the GNU General Public License as published by
#  the Free Software Foundation; either version 2 of the License, or
#  (at your option) any later version.
#
#  This program is distributed in the hope that it will be useful,
#  but WITHOUT ANY WARRANTY; without even the implied warranty of
#  MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
#  GNU General Public License for more details.
#
#  You should have received a copy of the GNU General Public License
#  along with this program; if not, write to the Free Software
#  Foundation, Inc., 675 Mass Ave, Cambridge, MA 02139, USA.

$name = shift(@ARGV); $name =~ tr/A-Z/a-z/;

# error checking:
if ($#ARGV != 5)
   {
   print $#ARGV;
   print "incorrect arguments\n";
   print "txn  [Source_acct]  [Date]  [Ref#]  [Payee]  [Category]  [Amount]  [Comment]\n\n";
   print "    Adds a financial transaction to a cbb file\n";
   print "    use '-t' to fill in today's date\n\n";
   print "Example:\n  dantzig[90]> txn cash -t 'n/a' '1st Cdn Place' 'Lunch' 4.27 ''\n";
   die(-1);
}
($tdate, $check, $payee, $cat, $amount, $desc) = @ARGV;

if ($tdate eq "-t")
{
  ($g,$g,$g,$day,$month,$year,$g,$g,$g)=localtime(time);
  $tdate = sprintf ("%02d%02d%02d", $year, $month+1, $day+1);
}

if ($amount < 0) 
	{
	$credit = -$amount;
	$credit = int($credit*100.0+0.5)/100.0;
	$debit=0.0;
	}
else
	{
	$debit = int($amount*100.0+0.5)/100.0;
	$credit=0.0;
	}

# Verify general validity of date
if (length($tdate) != 8) {
    $tdate = "19$tdate";
}
$year = substr($tdate, 0, 4);
$month = substr($tdate, 4, 2);
$day = substr($tdate, 6, 2);
# This really ought to consider the number of days in each month;
# e.g., February 30th never exists.  I haven't bothered.
if ((length($tdate) != 8) || ($month < 1) || ($month > 12)
    || ($day < 1) || ($day > 31)) {
  print "Date [$tdate] formatted incorrectly - use YYYYMMDD\n";
  die -1;
}

# Load up categories...
require "cbbshutils.pl";

&need_txn($name);
# Builds up the outstanding list(s)
&need_os($name);
&need_bal($name);

# Handle category information.
$cat = &split_txn($cat, $amount);

if ($name eq "cash") {		# Cash transactions don't make sense to 
    $rec = "X";			# reconcile, as there's no reconciling balance
} else {
    $rec = "";
}

$txn = "$tdate:$check:$payee:$debit:$credit:$cat:$desc:$rec::";
($key, $txn) = split(/:ZZZZ:/, &create_TXNS($txn, "txn"));
&add_os($txn, $key);
$currbal = $BALS{"Namount"} + $BALS{"*amount"} + $BALS{"Xamount"};
&listtxn($key, $txn);
printf "Latest Balance for %s is %9.2f\n", $name, $currbal;

sub split_txn {
   local ($cat, $amount, $total) = @_;
   if (index($cat, "|", 0) != -1) {
      # Split transaction; look for the pieces, see if they add up
      @PIECES=split(/\|/, $cat);
      if (($#PIECES % 2) == 1) {
         print "Split does not have appropriate number of pieces\n";
         die -1;
      }
      @SPLIT = ();  # Initialize the result array
      shift(@PIECES);  # First item gets trashed
      while (@PIECES) {
         $cat = &find_cats(shift(@PIECES));
         $samount = &remove_commas(shift(@PIECES));
         push(@SPLIT, $cat);
         push(@SPLIT, $samount);
         $total -= $samount;
         if (substr($cat, 0, 1) eq "[") {
	    # This is a transfer inside a split
	    $tftxn = "txn '$cat' '$tdate' '$ref' 'Funds Transfer (split)' '[$name]' $samount '$comment'";
	    push(@TFTXNS, $tftxn);
	 }
      }
      if ((($total - $amount) > 0.005) || (($total - $amount) < -0.005)) {
         printf "Split amounts add up to %.2f; not the same as the total %.2f\n",
                $total, $amount;
         die -1;
      } else {
         # Re-assemble the string using what was determined here
         $cat = "|".join("|", @SPLIT);
	 while (@TFTXNS) {
	    system (pop(@TFTXNS));
	 }
      }
   } else {
      $cat = &find_cats($cat);
   }
}
