#!/usr/bin/perl -w
# $Id: report,v 1.1 1994/11/14 07:06:31 cbbrowne Exp cbbrowne $
#  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.

# Parse arguments...
# This list is used to construct the key
%KEYLIST = ("date", "\$date",
	    "cat", "\$cat",
	    "payee", "\$desc",
	    "ref", "\$check",
	    "cleared", "\$cleared");

# Set up default values: FROM/TO deal with the current year
($g1,$g2,$g3,$day,$month,$year,$g4,$g5,$g6)=localtime(time);
$FROM = $year."0101";
$TO = $year."1231";

@ORIGARGS = @ARGV;
$all = "FALSE";
while (@ARGV) {
    $option = shift(@ARGV);
    $value = shift(@ARGV);
    if ($option eq "-account") {
        push(@ACCT, $value);
    } elsif (($option eq "-from") || ($option eq "-f")) {
	$FROM = $value;
    } elsif (($option eq "-to") || ($option eq "-t")) {
  	$TO = $value;	    
    } elsif (($option eq "-category") || ($option eq "-c")) {
  	$CATEGORY = $value;
    } elsif (($option eq "-payee") || ($option eq "-p")) {
	$PAYEE = $value;
    } elsif (($option eq "-ref") || ($option eq "-r")) {
  	$REF = $value;       
    } elsif (($option eq "-any") || ($option eq "-a")) {
  	$ANY = $value;
    } elsif (($option eq "-all") || ($option eq "-a")) {
        if ($#ORIGARGS != 0) {
	    print "l1";
	    &bad_args();
        } else {
	    $all = "TRUE";
        }
    } else {
	print "$option\n";
	&bad_args();
    }	
}

require "cbbshutils.pl";

if ($#ACCT == -1) {
   opendir (DIR, '$home') || die "Can't open $dir";
   @FILENAMES = readdir(DIR);
   foreach $file (@FILENAMES) {
     if (index($file, ".txn.dir") != -1) {
       push(@ACCT, substr($file, 0, length($file) - length(".txn.dir")));
     }
   }
}

# Load up amounts
foreach $acct (@ACCT) {
  &need_txn($acct);
  &zeroth_TXNS();
  while (($key, $value) = &next_TXNS()) {
    $skip = 0;
    $skip |= (($FROM ne "") && ($FROM ge $key));
    $skip |= (($TO ne "") && ($TO le $key));
    if ($all eq "TRUE") {$skip = 0;}
    if (!$skip) {
	($date, $check, $desc, $debit, $credit, $cat, $com, $cleared, $total) =
	    split(/:/, $value);
      if ((&match($ref, $REF) &&
          &match($cat, $CATEGORY) &&
	  &match($value, $ANY) &&
	  &match($desc, $PAYEE)) ||
	  ($all eq "TRUE")) {
	if (grep(!/\[*\]/, ($cat))) {  # Filter out [accounts]
          $TEMP{$cat} += $debit - $credit;
	}
      }
    }
  }
}

# Now, report on it...
print "Income Statement for the period $FROM to $TO\n\n";

# Two phase: First do "positive" values, then "negative."
print "Income:\n";
foreach $key (sort keys %TEMP) {
  if ($TEMP{$key} > 0) {
    ($desc, $tx) = split(/:/, $CATS{$key});  # Get the nice descriptions
    if ($desc eq "") {
      $desc = $key;        # If there is no description, go with category name
    }
    $value = sprintf("%12.2f", $TEMP{$key});
    write STD1;
    $INCOME += $TEMP{$key};
  }
}
$desc = "";
$value = "------------------";
write STD1;

$desc = "Total Income";
$value = $INCOME;
write STD1;

print "Expenses:\n";
foreach $key (sort keys %TEMP) {
  if ($TEMP{$key} > 0) {
    ($desc, $tx) = split(/:/, $CATS{$key});  # Get the nice descriptions
    if ($desc eq "") {
      $desc = $key;        # If there is no description, go with category name
    }
    $value = sprintf("%12.2f", $TEMP{$key});
    write STD1;
    $INCOME += $TEMP{$key};
  }
}

$desc = "";
$value = "------------------";
write STD1;

$desc = "Total Expenses";
$value = $EXPENSES;
write STD1;

$desc = "";
$value = "------------------";
write STD1;
$desc = "Net Income:";
$value = $INCOME-$EXPENSES;
write STD1;

$desc = "";
$value = "==================";
write STD1;

format STD1 =
   @<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<     @>>>>>>>>>>>
   $desc, $value
.

sub bad_args {
    print "Bad arguments for report.\n";
    print "Correct arguments need to be documented here.\n";
    print "Next version...\n";
    die -1;
}
sub match {
    local ($field, $query) = ($_[0], $_[1]);
    return ($query eq "") || (index ($field, $query, 0) != -1);
}
