#!/usr/bin/perl
# $Id: clearos,v 1.4 1994/11/14 06:49:10 cbbrowne Exp cbbrowne $
require "cbbshutils.pl";
# Builds up the outstanding list(s)
#  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 = $ARGV[0];
$newbal = $ARGV[1];

system("buildos $name");
&need_txn($name);
&need_bal($name);
&need_os($name);

$out = ($BALS{"Xamount"} + $BALS{"*amount"})-$newbal;
printf "Previous verified balance:        %9.2f %4d\n", $BALS{"Xamount"}, $BALS{"Xcount"};
printf "Recent transactions:              %9.2f %4d\n", $BALS{"Namount"}+$BALS{"*amount"}, $BALS{"Ncount"}+$BALS{"*count"};
print  "                                 ---------------\n";
printf "Book balance:                     %9.2f %4d\n", $BALS{"Namount"}+$BALS{"*amount"}+$BALS{"Xamount"}, $BALS{"Ncount"}+$BALS{"*count"}+$BALS{"Xcount"};
printf "Add back items still O/S:         %9.2f %4d\n", $BALS{"Namount"}, $BALS{"Ncount"};
print  "                                 ---------------\n";
printf "Balance for reconciliation:       %9.2f %4d\n", $BALS{"Xamount"}+$BALS{"*amount"}, $BALS{"Xcount"}+$BALS{"*count"};
print "\n";
printf "Difference:                       %9.2f\n\n", $BALS{"Xamount"}+$BALS{"*amount"} - $newbal;
printf "Transactions tagged for deletion   %9.2f %4d\n", $BALS{"Damount"}, $BALS{"Dcount"};
print "\n";
printf "Amount currently being cleared:   %9.2f %4d\n", $BALS{"*amount"}, $BALS{"*count"};

if ($out < 0.005 && $out > -0.005) {
    # Update "*" to "X"
    &zeroth_TXNS();
    while (($key, $value) = &next_TXNS()) {
	($date, $check, $desc, $debit, $credit, $cat, $com, $cleared, 
	 $junk) = split(/:/, $value);
	if ($cleared eq "*") {
	    $value = "$date:$check:$desc:$debit:$credit:$cat:$com:X:$total"; 
	    &put_TXNS($key, $value, "Clear *->X", "*", "X", $debit-$credit);
	} elsif ($cleared eq "D") {
            &del_TXNS($key, $value, "D", $debit-$credit);
        }
    }
    system ("buildos $name");
} else {
    printf "Does not reconcile - out by %9.2f\n", $out;
}
