#!/usr/bin/perl -w
# $Id: exportqf,v 1.1 1994/10/27 12:16:01 cbbrowne Exp $
# exportqif [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 "exportqif [account] [file] (.qif is optional)\n";
   print "    exports data to a Quicken-compatible QIF file\n";
   print "Example:\n  dantzig[90]> exportqif cash cash.qif\n";
   print "dantzig[91]> exportqif 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);

&export_qif($qiffile);
sub export_qif {
    # in: file
    # out: result

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

    if (-e $file) {
	system ("mv $file $file.old");
    }
    open(QIF, ">$file");

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

    foreach $key (keys (%TRANS))
	{
        ($date, $check, $desc, $debit, $credit, $cat, $com, $cleared, 
	       	$junk) = split(/:/, $TRANS{$key});
	
	# Handle date
	substr($date, 2, 0) = "/";
	substr($date, 5, 0) = "/";
	print "!\n\r";
	print "D$date\n\r";    # This SHOULD be ok;
	
	# Handle amount
	$amount = $credit-$debit;
	printf "T%.2lf\n\r", $amount;
	
	# Handle Ref. #
	print "N$check\n\r" unless ($check eq "");
	print "P$desc\n\r" unless ($desc eq "");
	print "L$cat\n\r";
	if ($split eq "")
		{
		}
	else
		{
		}
	print "M$com\n\r" unless ($com eq "");
	}

    close(QIF);

    return "ok";
}
