#!/usr/bin/perl -w
# $Id: importqif,v 1.3 1994/11/14 06:57:19 cbbrowne Exp cbbrowne $
# importqif [account] [file] (.qif is optional)
# Import a QIF file
#  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 != 0)
   {
   print $#ARGV;
   print "incorrect arguments\n";
   print "importqif [account] [file] (.qif is optional)\n";
   print "    imports data from a Quicken-compatible QIF file\n";
   print "Example:\n  dantzig[90]> importqif cash cash.qif\n";
   print "dantzig[91]> importqif chequing chequing # .qif gets added to the filename\n";
   die(-1);
}
($qiffile) = @ARGV;

if (index($qiffile, ".qif", 0) == -1) {
	$qiffile = $qiffile.".qif";
}

require "cbbshutils.pl";
&need_txn($name);
&need_os($name);
&need_bal($name);

&import_qif($qiffile);

# import a quicken export file (.qif)
sub import_qif {
    # in: file
    # out: result

    local($file) = @_;
    $sorted_keys = 0;
    $calced = 0;

    open(QIF, "<$qiffile");

    ($date, $check, $desc, $debit, $credit, $cat, $split, $com, 
    	$cleared) = ("", "", "", "", "", "", "", "", "");

    while ( <QIF> ) {
	s/:/-/g;		# eliminate our delimiter characters from
	s/\|/-/g;		# the import file.
	s/\r//g;		# strip the dos ^M if needed
	s/\n//g;                # strip the carriage return
	if ( m/^\!/ ) {
	    # Type
	    # print "$_\n";
	    if ( m/Type-Cat/ ) {
		&get_cats();
	    } elsif ( m/Account/ ) {
		&skip_section();
	    } else { # Some other section.  Probably investments.
		print "cbbsh doesn't know how to handle the following:\n";
		print "$_\n";
		print "Assuming that it can be skipped over...\n";
		&skip_section();
	    }
	} elsif ( m/^D/ ) {
	    # Date
	    ($month, $day, $year) = split(/\/ */, substr($_,1));
	    $month = &pad($month);
	    $day = &pad($day);
	    $date = "$year$month$day";
	    # print "$date\n";
	} elsif ( m/^T/ ) {
	    # Transaction Amount
	    s/,//g;		# remove , from numbers (i.e. thousands)
	    $amt = substr($_,1);
	    if ($amt >= 0) {
		$credit = $amt;
		$debit = 0;
	    } else {
		$debit = substr($amt,1); # remove the '-' to make amt >= 0
		$credit = 0;
	    }
	    # print "credit = $credit  debit = $debit\n";
	} elsif ( m/^C/ ) {
	    # Cleared
	    $cleared = substr($_,1);
            # Special handling of cash transactions; they are *never*
            # treated as "outstanding."  It's a pain to reconcile cash,
            # so we'll never even bother trying.
	    if ($name eq "cash") {
               $cleared = "X";
            }
	    # print "Cleared = $cleared\n";
	} elsif ( m/^N/ ) {
	    # check Number
	    $check = substr($_,1);
	    # print "Check # = $check\n";
	} elsif ( m/^P/ ) {
	    # descriPtion
	    $desc = substr($_,1);
	    # print "$desc\n";
	} elsif ( m/^L/ ) {
	    # category
	    $cat = substr($_,1);
	    #print "$cat\n";
	} elsif ( m/^S/ ) {
	    # split category
	    if ($split eq "") {
		# first split
		$split = "|".substr($_,1)."|";
	    } else {
		# not first split :)
		$split = $split.substr($_,1)."|";
	    }
	} elsif ( m/^E/ ) {
	    # split comment
	    $split = $split.substr($_,1)."|"
	} elsif ( m/^\$/ ) {
	    # split amount
	    $split = $split.substr($_,1)."|";
	} elsif ( m/^M/ ) {
	    # coMment
	    $com = substr($_,1);
	    #print "Comment = $com\n";
	} elsif ( m/^\^/ ) {
	    #print "End of record\n";
	    if ($split ne "") {
		$cat = $split;
	    }
	    
	    ($key, $txn) = split(/:ZZZZ:/, 
	     &create_trans("$date:$check:$desc:$debit:$credit:$cat:$com:$cleared:0.00", "import"));
            &adj_bals("NULL", $cleared, $debit-$credit);
	    &add_os($txn, $key);

	    ($date, $check, $desc, $debit, $credit, $cat, $split, $com, 
	    	$cleared) = ("", "", "", "", "", "", "", "", "");
	} elsif ( $_ eq "" ) {
	    # toss empty lines ...
	} else {
	    print "unknown data: $_\n";
	}
    }

    close(QIF);

    return "ok";
}

sub skip_section {
    # It's just here so that all Quicken .QIF files are accepted.
    # Keep reading until "!" is reached.
    while (<QIF>) {
	chop;
	if (m/^\!/) {
	    return;
	}
    }
}

sub get_cats {
    local ($type, $cat, $desc, $tax, $rec) = ();
    while ($rec=<QIF>) {
	chop $rec;
	$type = substr($rec, 0, 1);
	if ($type eq "!") {
	    return;
	}
	substr($rec, 0, 1) = "";
	# Turn ":" into "-"
	$rec =~ s/:/-/;
	if ($type eq "N") {
	    $cat = $rec;
	} elsif ($type eq "D") {
	    $desc = $rec;
	} elsif ($type eq "T") {
	    $tax = "T";
	} elsif ($type eq "\^") {
	    $CATS{$cat} = "$cat:$desc:$tax";
	    ($cat, $desc, $tax) = ();
	}
    }
}
