#!/usr/bin/perl -w
# $Id: tag,v 1.6 1994/11/14 07:07:34 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.
require "getopts.pl";
require "cbbshutils.pl";
$name = shift(@ARGV); $name =~ tr/A-Z/a-z/;
&need_txn($name);
&need_os($name);
&need_bal($name);

$untag = (@ARGV[0] eq "-u");
if ($untag) {
    shift(@ARGV);
}

@LIST = &construct_sorted_os_list();

foreach $tag (@ARGV) {
    if ($tag > $#LIST) {
	print "Tag $tag out of range 0..$#LIST\n";
    } else {
	$key = &get_OSLIST($LIST[$tag]);
	$value = &get_TXNS($key);
	($date, $check, $desc, $debit, $credit, $cat, $com, $cleared, $total) =
	    split(/:/, $value);
	$nicedate = &nice_date($date);
	if ($cleared eq "") {
	    if (!$untag) {
		$cleared = "*";
		$value = "$date:$check:$desc:$debit:$credit:$cat:$com:$cleared:$total";
		&put_TXNS($key, $value, "Tag *", "N", "*", $debit-$credit);
		print "Tagged item $tag\n";
		&listtxn($tag, $value);
	    } else {   # We're trying to untag...
		print "Item $tag is not tagged\n";
		$value = "$date:$check:$desc:$debit:$credit:$cat:$com:$cleared:$total";
		write;
	    }
	} elsif ($cleared eq "*") {
	    if (!$untag) {
		print "Item $tag has already been set as cleared (*)\n";
		$value = "$date:$check:$desc:$debit:$credit:$cat:$com:$cleared:$total";
		&listtxn($tag, $value);
	    } else { # Untagging it...
		$cleared = "";
		$value = "$date:$check:$desc:$debit:$credit:$cat:$com:$cleared:$total";
		&put_TXNS($key, $value, "Remove *", "*", "N", $debit-$credit);
		print "Cleared item $tag\n";
		&listtxn($tag, $value);
	    }
	} elsif ($cleared eq "D") {
            print "Item [$tag] was tagged for deletion; the tag will be cleared altogether.\n";
	    $value = "$date:$check:$desc:$debit:$credit:$cat:$com::$total";
	    &put_TXNS($key, $value, "Undelete", "D", "", $debit-$credit);
	} else {
	    print "How odd - item $tag has an invalid clearing code [$cleared]\n";
	}
    }
}
&list_bals();
