File: engine.pl

package info (click to toggle)
cbb 1%3A0.8.1-2
  • links: PTS
  • area: main
  • in suites: potato
  • size: 1,868 kB
  • ctags: 551
  • sloc: tcl: 5,221; perl: 4,512; sh: 376; makefile: 152
file content (1382 lines) | stat: -rw-r--r-- 36,359 bytes parent folder | download | duplicates (3)
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
1001
1002
1003
1004
1005
1006
1007
1008
1009
1010
1011
1012
1013
1014
1015
1016
1017
1018
1019
1020
1021
1022
1023
1024
1025
1026
1027
1028
1029
1030
1031
1032
1033
1034
1035
1036
1037
1038
1039
1040
1041
1042
1043
1044
1045
1046
1047
1048
1049
1050
1051
1052
1053
1054
1055
1056
1057
1058
1059
1060
1061
1062
1063
1064
1065
1066
1067
1068
1069
1070
1071
1072
1073
1074
1075
1076
1077
1078
1079
1080
1081
1082
1083
1084
1085
1086
1087
1088
1089
1090
1091
1092
1093
1094
1095
1096
1097
1098
1099
1100
1101
1102
1103
1104
1105
1106
1107
1108
1109
1110
1111
1112
1113
1114
1115
1116
1117
1118
1119
1120
1121
1122
1123
1124
1125
1126
1127
1128
1129
1130
1131
1132
1133
1134
1135
1136
1137
1138
1139
1140
1141
1142
1143
1144
1145
1146
1147
1148
1149
1150
1151
1152
1153
1154
1155
1156
1157
1158
1159
1160
1161
1162
1163
1164
1165
1166
1167
1168
1169
1170
1171
1172
1173
1174
1175
1176
1177
1178
1179
1180
1181
1182
1183
1184
1185
1186
1187
1188
1189
1190
1191
1192
1193
1194
1195
1196
1197
1198
1199
1200
1201
1202
1203
1204
1205
1206
1207
1208
1209
1210
1211
1212
1213
1214
1215
1216
1217
1218
1219
1220
1221
1222
1223
1224
1225
1226
1227
1228
1229
1230
1231
1232
1233
1234
1235
1236
1237
1238
1239
1240
1241
1242
1243
1244
1245
1246
1247
1248
1249
1250
1251
1252
1253
1254
1255
1256
1257
1258
1259
1260
1261
1262
1263
1264
1265
1266
1267
1268
1269
1270
1271
1272
1273
1274
1275
1276
1277
1278
1279
1280
1281
1282
1283
1284
1285
1286
1287
1288
1289
1290
1291
1292
1293
1294
1295
1296
1297
1298
1299
1300
1301
1302
1303
1304
1305
1306
1307
1308
1309
1310
1311
1312
1313
1314
1315
1316
1317
1318
1319
1320
1321
1322
1323
1324
1325
1326
1327
1328
1329
1330
1331
1332
1333
1334
1335
1336
1337
1338
1339
1340
1341
1342
1343
1344
1345
1346
1347
1348
1349
1350
1351
1352
1353
1354
1355
1356
1357
1358
1359
1360
1361
1362
1363
1364
1365
1366
1367
1368
1369
1370
1371
1372
1373
1374
1375
1376
1377
1378
1379
1380
1381
1382
#!/usr/local/bin/perl
#  engine.pl - the CBB 'engine'.
#              This script implements a transaction abstract data type
#              It encapsulates a list a transactions and the functions
#              required to manipulate the transactions.
#
#  Written by Curtis Olson.  Started August 22, 1994.
#
#  Copyright (C) 1994 - 1999  Curtis L. Olson  - curt@me.umn.edu
#
#  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.

# $Id: engine.pl,v 1.2 2000/01/02 19:08:02 curt Exp $


package CBB;

use strict;   # don't take no guff


# @INC specifies the installed location of the necessary pieces.
# It should already be setup by wrapper.pl

require "common.pl";
require "log.pl";


$| = 1;				# flush buffers after every write

if ( $CBB::logging != 0 && $CBB::logging != 1) {
    # if not specified elsewhere, turn on logging
    $CBB::logging = 1;			# 0 = off,  1 = on
}

if ( $CBB::debug != 0 && $CBB::debug != 1) {
    # if not specified elsewhere, turn off debugging.
    $CBB::debug = 0;			# 0 = off,  1 = on
}

# Global variables

# %CBB::TRANS - an associative array of transactions and transaction keys
# @CBB::KEYS - a sorted list of transaction keys (for traversing the trans list)
# $CBB::sorted_keys - specifies whether the list in @CBB::KEYS is valid
# $CBB::calced - specified whether the transactions have been properly calculated
# $CBB::current - specifies the "current" position in the @CBB::KEYS array
# $CBB::current_file - full name of currently opened transaction file
# %CBB::BALS - an associative array used to store account information
# $CBB::version - version number (set in common.pl)
# $CBB::duplicate - flag to decide what to do with duplicate read-in entries


&init_trans();		   # initialize %CBB::TRANS, @CBB::KEYS, and $CBB::sorted_keys
open(DEBUG, ">debug") if $CBB::debug;


# toggle debugging
sub debug {
    # in: flag
    # out: flag

    my($newdebug) = @_;

    if ($newdebug == 1) {
	# turning debugging on

	if ($CBB::debug == 1) {
	    # already on, do nothing
	} else {
	    $CBB::debug = 1;
	    open(DEBUG, ">debug");
	}
    } else {
	# turning of debugging

	if ($CBB::debug == 0) {
	    # already off, do nothing
	} else {
	    $CBB::debug = 0;
	    close(DEBUG);
	}
    }

    return $CBB::debug;
}
  

# get next available key for a specified date
sub get_next_key {
    # in: date, transaction information
    # out: key

    my($date) = shift;
    my($info) = shift;
    my($count) = 0;
    my($trans);
    my($key);
    my($founddup) = 0;

    # Take off the total, that changes with each entry so
    # we don't want to compare it
    $info =~ s/\t[^\t]*$//;

    # If we are to check for duplicates and the date field is unchecked
    # in the "compare for duplicates" preference window, then we need to
    # check every date.
    if ($CBB::duplicate && !($CBB::compare & 0x01)) {
      foreach $key (keys(%CBB::TRANS)) {
        $trans = $CBB::TRANS{$key};

	# Check if the key doesn't contain the date for this transaction
	return(undef)
	  if(!&CheckTrans(\$founddup, $info, $trans));
      }
    }

    # Keep adding to the count if we already have a key with a certain
    # count and the check number (if there is one) for the transaction
    # with that key is less (or equal) than the check number of the transaction
    # to insert.  If both transactions don't have check numbers, the return
    # value will be 0 (the same as if both transactions had the same check
    # number).  We do this to order same-day transactions with
    # different check numbers in the correct order.  This will happen
    # if not entering check transactions in numerical order.
    #
    # We still might need to check for duplicates when the date field is
    # being compared (which means the above check wouldn't have been done).
    # This loop insures that every comparison will be on the same date so
    # in case, checking dates is easy.  We only need to compare if we
    # have to compare dates.
    $trans = $CBB::TRANS{"$date-".&pad($count)};
    while (defined($trans) && &CompareCheckNums($trans, $info) <= 0) {
	# Check for duplication
	return(undef)
	  if ($CBB::duplicate && ($CBB::compare & 0x01) &&
	      !&CheckTrans(\$founddup, $info, $trans));

	$count++;
        $trans = $CBB::TRANS{"$date-".&pad($count)};
    }

    # If we exited the while() loop with a key that is already being used,
    # then that means we have a new transaction that needs to be inserted
    # ahead of other transactions already posted on this date.  This will
    # sort transactions, not only based on date, but on check number.
    #
    # If we have this situation, then we need to change the keys of some
    # of the already posted transactions to fit this new one in
    if (defined($trans)) {
      # Change the key for the transaction with this count
      &ChangeKey($date, $count);
    }

    return "$date-".&pad($count);
}


sub CheckTrans {
    # in: found duplicate flag
    # out: 1 = keep processing, 0 = don't insert

    my($founddup) = shift;
    my($info) = shift;
    my($trans) = shift;
    my($arg1);
    my($arg2);

    # If we already found a duplicate, then we have already asked the user,
    # the user had said to insert, and we might match another
    # entry that is exactly the same (which would happen if there
    # were already 2 or more entries that are the same)
    if(!$$founddup && &CompareTrans($info, $trans)) {
      return(0) if ($CBB::duplicate == 1);	# Never insert

      # Found a duplicate
      $$founddup = 1;

      # Set up transactions for dialog box argument
      SetupForArg($info, \$arg1);
      SetupForArg($trans, \$arg2);

      # Ask user how to handle the duplicate transaction
      system("dialog4duplicate $arg1 $arg2");

      return(0) if ($? != 0);	# User elected to NOT insert trans
    }

    return(1);
}

sub SetupForArg {
  # in: transaction
  # out: message suitable for a dialog box

  my($info) = shift;
  my($message) = shift;
  my($amt);
  my($bit);
  my(@cmp);
  my($category);
  my($check);
  my($comment);
  my(@trans);

  # Set up the strings to put into the dialog box to ask the user
  @trans = split(/\t/, $info);

  # Fix up the date into the form MM/DD/YY (since it's always
  # a fixed size, we can just rearrange the digits)
  $trans[0] =~ s?..(..)(..)(..)?$2/$3/$1?;

  # Find out if amount is + or -
  $amt = sprintf("%.2f", ($trans[3] > 0) ? -$trans[3] : $trans[4]);

  # If we don't have a check #, comment, or category (since those are
  # optional), put <none>
  $check = (length($trans[1])) ? $trans[1] : "<none>";
  $comment = (length($trans[6])) ? $trans[6] : "<none>";
  $category = (length($trans[5])) ? $trans[5] : "<none>";

  # Figure out which fields were compared
  for($bit = 0;$bit < 6;++$bit) {
    $cmp[$bit] = (($CBB::compare >> $bit) & 0x01) ? "*" : " ";
  }

  $$message .= "\"\n$cmp[0]Date:        $trans[0]\" ";
  $$message .= "\"$cmp[1]Check #:     $check\" ";
  $$message .= "\"$cmp[2]Description: $trans[2]\" ";
  $$message .= "\"$cmp[3]Amount:      $amt\" ";
  $$message .= "\"$cmp[4]Comment:     $comment\" ";
  $$message .= "\"$cmp[5]Category:    $category\n\" ";
}

sub CompareTrans {
  # in: two transactions to compare for equality
  # out: 1 if equal, 0 if different

  my($trans1) = shift;
  my($trans2) = shift;
  my($cmp1);
  my($cmp2);

  # Retrieve fields to compare
  $cmp1 = &GetFields($trans1);
  $cmp2 = &GetFields($trans2);

  return(($cmp1 eq $cmp2) ? 1 : 0);
}

sub GetFields {
  # in: transaction
  # out: wanted fields of transaction

  my($trans) = shift;
  my($pos);
  my(@splitf);
  my(@fields);
  my($indx);

  # Split apart to get to separate fields
  @splitf = split(/\t/, $trans);

  # Retrieve fields to compare
  for($indx = $pos = 0;$indx < scalar(@splitf);++$indx, ++$pos) {
    # When indx == 3, this is a special case for the amount
    if ($indx != 3) {
      push(@fields, $splitf[$indx]) if ((1 << $pos) & $CBB::compare);
    } else {
	     # We have to figure out which amount to get if we are
	     # checking the amount field
	     if ((1 << $pos) & $CBB::compare) {
	       if ($splitf[$indx] > 0.0) {
	         push(@fields, sprintf("%.2f", $splitf[$indx]));
	       } else {
		        push(@fields, sprintf("%.2f", $splitf[++$indx]));
		      }
	     }
	   }
  }

  return(join(" ", @fields));
}

sub ChangeKey {
  # in: date, count of key to modify

  my($date) = shift;
  my($count) = shift;

  # We'll change this key by seeing if a transaction exists with
  # a key of "count+1".  If so, we call this routine again, and so
  # on recursively until we reach a "count+1" that is not assigned yet.
  ChangeKey($date, $count + 1) if($CBB::TRANS{"$date-".&pad($count + 1)});

  $CBB::TRANS{"$date-".&pad($count + 1)} = $CBB::TRANS{"$date-".&pad($count)};
}

sub CompareCheckNums {
  # in: two transactions
  # out: < 0, 0, > 0 depending on if the first transaction has a check number
  #      less than, equal to, or greater than the check number of the 2nd
  #	 transaction

  my($trans1) = shift;
  my($trans2) = shift;
  my(@trans1);
  my(@trans2);

  # Split the transactions into parts to easily fetch the check numbers
  @trans1 = split(/\t/, $trans1);
  @trans2 = split(/\t/, $trans2);

  return($trans1[1] - $trans2[1]);
}


# set @CBB::KEYS = sorted list of transaction keys
sub sort_keys {
    $CBB::sorted_keys = 1;
    $CBB::current = 0;

    print DEBUG "sort_keys()\n" if $CBB::debug;
    @CBB::KEYS = sort(keys %CBB::TRANS);
}


# recalculate the transactions
sub calc_trans {
    my($total, $ntotal, $stotal, $ctotal) = (0.00, 0.00, 0.00, 0.00);
    my($count, $ncount, $scount, $ccount) = (0, 0, 0, 0);
    my($key);
    my($date, $check, $desc, $debit, $credit, $cat, $com, $cleared, $junk);

    my($current_date) = &raw_date();
	
    $CBB::calced = 1;

    print DEBUG "calc_trans()\n" if $CBB::debug;

    if ($CBB::sorted_keys == 0) {
	&sort_keys();
    }

    $CBB::BALS{"Current"} = 0.00;

    foreach $key (@CBB::KEYS) {
        ($date, $check, $desc, $debit, $credit, $cat, $com, $cleared, 
        	$junk) = split(/\t/, $CBB::TRANS{$key});

	$total = $total + $credit - $debit;
	$count++;

	if ( $date <= $current_date ) {
	    $CBB::BALS{"Current"} = $total;
	}

	if ( ($cleared eq "x") || ($cleared eq "X") ) {
	    $ctotal = $ctotal + $credit - $debit;
	    $ccount++;
	} elsif ( $cleared eq "*" ) {
	    $stotal = $stotal + $credit - $debit;
	    $scount++;
	} else {
	    $ntotal = $ntotal + $credit - $debit;
	    $ncount++;
	}

	$CBB::TRANS{$key} = 
	  "$date\t$check\t$desc\t$debit\t$credit\t$cat\t$com\t$cleared\t".
	  	sprintf("%.2f", $total);
    }

    $CBB::BALS{"Amount"} =  $total;
    $CBB::BALS{"Count"} =   $count;

    $CBB::BALS{"Xamount"} = $ctotal;
    $CBB::BALS{"Xcount"} =  $ccount;

    $CBB::BALS{"*amount"} = $stotal;
    $CBB::BALS{"*count"} =  $scount;

    $CBB::BALS{"Namount"} = $ntotal;
    $CBB::BALS{"Ncount"} =  $ncount;
}


# create a transaction (and add to the transaction list)
sub create_trans {
    # in: transaction
    # out: keyed_transaction

    my($trans) = @_;
    my($key);

    $CBB::sorted_keys = 0;
    $CBB::calced = 0;

    &insert_and_update_mem($trans);

    my($date, $check, $desc, $debit, $credit, $cat, $com, $cleared, $total) =
	split(/\t/, $trans);

    if ( length($date) == 6 ) {
	# for backwards compatibility ... shouldn't be needed now.
	# year >= 80, 1900 ... year < 80, 2000
	my($century) = (substr($date, 0, 2) lt '80' ? '20' : '19');
	$date = "$century$date";
	$trans = "$century$trans";
    }

    $key = &get_next_key($date, $trans);

    if ($key) {
	$trans = "$date\t$check\t$desc\t$debit\t$credit\t$cat" 
	    . "\t$com\t$cleared\t$total";

	$CBB::TRANS{$key} = "$trans";

	print DEBUG "created:  $key\t$trans\n" if $CBB::debug;

	return "$key\t$trans";
    } else {
	return(undef);
    }
}


# create a transfer transaction in the current file and the transfer to file
sub create_xfer {
    # in: transaction
    # out: keyed_transaction

    my($trans) = @_;
    my($date, $check, $desc, $debit, $credit, $cat, $com, $cleared, $total) =
	split(/\t/, $trans);    
    my($orig_file) = $CBB::current_file;
    my($to_trans, $to_file, $from_cat);
    my($key, $result);
    my($returned_result);

    $CBB::sorted_keys = 0;
    $CBB::calced = 0;

    print DEBUG "(xfer) current_file = $CBB::current_file\n" if $CBB::debug;
    # determine the "from" category
    $from_cat = "[".&file_basename(&file_root($CBB::current_file))."]";

    # determine the "to" file name
    $to_file = $cat;
    chop($to_file);
    $to_file = substr($to_file, 1);
    $to_file = &file_dirname($CBB::current_file)."/$to_file";
    print DEBUG "to file = '$to_file' ($to_file.cbb)\n" if $CBB::debug;
    if ( -e "$to_file.cbb" ) {
	$to_file .= ".cbb";
    } elsif ( -e "$to_file.dir" ) {
	$to_file .= ".dir";
    } else {
	return "error";
    }

    print DEBUG "Transfer to $to_file\n" if $CBB::debug;

    # create the "to" transaction.  Note: future transfers (i.e. those
    # created by recur.pl are marked '-' for recur.pl processing
    if ( $cleared eq "?" ) {
	$to_trans = "$date\t$check\t$desc\t".$credit."\t".$debit."\t".
	    $from_cat."\t$com\t-\t$total";
    } else {
	$to_trans = "$date\t$check\t$desc\t".$credit."\t".$debit."\t".
	    $from_cat."\t$com\t$cleared\t$total";
    }

    # we need special handling here to preserve the .cbb file
    # save the current transactions to a temporary file
    # before loading the "to" account
    $result = &save_trans("$orig_file.$$.tmp");
    return "error" if ( $result eq "error" );
    %CBB::TRANS = ();  # clear out any transactions from the current file

    # open the "to" account
    $result = &load_trans($to_file);
    return "error" if ( $result eq "error" );
    
    $result = &create_trans($to_trans);
    
    $result = &save_trans($to_file);

    $result = &load_cbb_trans("$orig_file.$$.tmp");
    return "error" if ( $result eq "error" );
    unlink("$orig_file.$$.tmp");
    $CBB::current_file = $orig_file;

    # create the "from" transaction
    $returned_result = &create_trans($trans);

    return "$returned_result";
}


# update a transaction (replace in the transaction list)
sub update_trans {
    # in: keyed_transaction
    # out: keyed_transaction

    my($keyed_trans) = @_;
    my($key, $trans, $result);

    $CBB::sorted_keys = 0;
    $CBB::calced = 0;

    ($key, $trans) = split(/\t/, $keyed_trans, 2);

    &delete_trans($key);
    $result = &create_trans($trans);

    print DEBUG "updated:  $key\n" if $CBB::debug;
    print DEBUG "     to:  $result\n" if $CBB::debug;

    return "$result";
}


# update a transfer transaction (replace in the transaction list)
sub update_xfer {
    # in: keyed_transaction
    # out: keyed_transaction

    my($keyed_trans) = @_;
    my($key, $trans, $result);

    $CBB::sorted_keys = 0;
    $CBB::calced = 0;

    ($key, $trans) = split(/\t/, $keyed_trans, 2);

    &delete_xfer($key);
    $result = &create_xfer($trans);

    print DEBUG "updated:  $key\n" if $CBB::debug;
    print DEBUG "     to:  $result\n" if $CBB::debug;

    return "$result";
}


# delete a transaction given the key
sub delete_trans {
    # in: key

    my($key) = @_;
    $CBB::sorted_keys = 0;
    $CBB::calced = 0;

    delete $CBB::TRANS{$key};

    if ($CBB::current > 0) {
	--$CBB::current;
    }

    print DEBUG "deleted:  $key\n" if $CBB::debug;

    return "ok";
}

# delete an transfer transaction in the transfer to file
sub delete_xfer {
    # in: key

    my($key) = @_;
    my($orig_file, $orig_current) = ($CBB::current_file, $CBB::current);
    my($count) = 0;

    my($to_file, $from_cat, $found_key, $found_trans);
    my($result);

    my($date, $check, $desc, $debit, $credit, $cat, $com, $cleared, $total) 
	= split(/\t/, $CBB::TRANS{$key});

    $CBB::sorted_keys = 0;
    $CBB::calced = 0;

    # determine the "from" category
    $from_cat = "[".&file_basename(&file_root($CBB::current_file))."]";

    # determine the "to" file name
    $to_file = $cat;
    chop($to_file);
    $to_file = substr($to_file, 1);
    $to_file = &file_dirname($CBB::current_file)."/$to_file";
    print DEBUG "to file = '$to_file' ($to_file.cbb)\n" if $CBB::debug;
    if ( -e "$to_file.cbb" ) {
	$to_file .= ".cbb";
    } else {
	return "error";
    }

    print DEBUG "Deleting transfer to $to_file\n" if $CBB::debug;

    # We need special handling here to preserve the .cbb file.  Save
    # the current transactions to a temporary file before loading the
    # "to" account.
    $result = &save_trans("$orig_file.$$.tmp");
    return "error" if ( $result eq "error" );
    
    # open the "to" account
    $result = &load_trans($to_file);
    return "error" if ( $result eq "error" );

    # now search for the transaction
    while ( $found_trans = $CBB::TRANS{"$date-".&pad($count)} ) {
	my($found_date, $found_check, $found_desc, $found_debit, 
	      $found_credit, $found_cat, $found_com, $found_cleared, 
	      $found_total) = split(/\t/, $found_trans);

	last if (($found_check eq $check) && 
		 ($found_desc eq $desc) &&
		 ($found_debit == $credit) && 
		 ($found_credit == $debit) &&
		 ($found_com eq $com) && 
		 ($found_cat eq $from_cat) && 
		 ($found_key = "$date-".&pad($count)) );

	$count++;
    }

    print DEBUG "Found key: $found_key\n" if $CBB::debug;

    if ( $found_key ) {
	delete $CBB::TRANS{$found_key};
    
	$CBB::calced = 0;
	$CBB::sorted_keys = 0;
    } else {
	print DEBUG "Transaction not found in $to_file\n" if $CBB::debug;
    }

    # now save the "to" account
    $result = &save_trans($to_file);

    # revert to orig account
    $result = &load_cbb_trans("$orig_file.$$.tmp");
    return "error" if ( $result eq "error" );
    unlink("$orig_file.$$.tmp");

    # restore global variables
    $CBB::current_file = $orig_file;
    $CBB::current = $orig_current;
    $CBB::calced = 0;
    $CBB::sorted_keys = 0;

    delete $CBB::TRANS{$key};

    if ($CBB::current > 0) {
	--$CBB::current;
    }

    print DEBUG "deleted:  $key\n" if $CBB::debug;

    return "ok";
}


# return the next transaction
sub next_trans {
    my($trans);

    if ($CBB::sorted_keys == 0) {
	&sort_keys();
    }

    if ($CBB::calced == 0) {
	&calc_trans();
    }

    ++$CBB::current;
    $trans = $CBB::TRANS{$CBB::KEYS[$CBB::current]};
    if ( $trans ) {
        return "$CBB::KEYS[$CBB::current]\t$trans";
    } else {
        return "none";
    }
}


# return the transaction specified by a key
sub find_trans {
    # uses a binary search so that we can keep $CBB::current current.   
    # Yeeeks! I have to think for a change.
    # Hmmm, maybe I should rethink my data structures ... nah. :)

    my($key) = @_;
    my($left, $middle, $right) = (0, 0, $#CBB::KEYS);
    my($trans);

    if ($CBB::sorted_keys == 0) {
	&sort_keys();
    }

    if ($CBB::calced == 0) {
	&calc_trans();
    }

    $trans = "";

    while ( $left <= $right ) {
	$middle = int( ($left + $right) / 2 );
        print DEBUG "$left < $middle < $right\n" if $CBB::debug;
	if ( $CBB::KEYS[$middle] lt $key ) {
	    $left = $middle + 1;
	    print DEBUG "  left = middle + 1\n" if $CBB::debug;
        } elsif ( $CBB::KEYS[$middle] gt $key ) {
	    $right = $middle - 1;
	    print DEBUG "  right = middle - 1\n" if $CBB::debug;
        } else {
	    # we found it, set $trans to what we want and force an exit of
	    # the while loop
	    $trans = $CBB::TRANS{$CBB::KEYS[$middle]};
	    print DEBUG "  found it: $trans\n" if $CBB::debug;
	    $CBB::current = $middle;
	    $left = $right + 1;
        }
    }

    print DEBUG "found:  $key\t$trans\n" if $CBB::debug;

    if ( $trans ) {
        return "$key\t$trans";
    } else {
        return "none";
    }
}


# returns the current index
sub get_current_index {
    return ($CBB::current + 1);
}


# return the first transaction
sub first_trans {
    my($trans);

    if ($CBB::sorted_keys == 0) {
	&sort_keys();
    }

    if ($CBB::calced == 0) {
	&calc_trans();
    }

    $CBB::current = 0;
    $trans = $CBB::TRANS{$CBB::KEYS[$CBB::current]};
    if ( $trans ) {
        return "$CBB::KEYS[$CBB::current]\t$trans";
    } else {
        return "none";
    }
}


# returns the entire transaction list in one big chunk.
sub all_trans {
    # in: date
    # out: result

    my($date_fmt) = @_;
    my($key, $nicecat, $cutcom, $cutdesc, $cutcheck, $nicedate, $checklen);
    my($date, $check, $desc, $debit, $credit, $cat, $com, $cleared, $total);
    my($day, $month, $year);

    $| = 0;				# turn off buffer flushing

    if ($CBB::calced == 0) {
	&calc_trans();
    }

    if ($CBB::sorted_keys == 0) {
	&sort_keys();
    }

    foreach $key (@CBB::KEYS) {
	# print ("$key\t$CBB::TRANS{$key}\n");
        ($date, $check, $desc, $debit, $credit, $cat, $com, $cleared, $total) =
	    split(/\t/, $CBB::TRANS{$key});

        if ( length($date) == 6 ) {
	    # for backwards compatibility ... shouldn't be needed now.
            ($year, $month, $day) = $date =~ /(\d\d)(\d\d)(\d\d)/;
	    my($century) = ($year lt '80' ? '20' : '19');
	    $year = "$century$year";
        } else {
            ($year, $month, $day) = $date =~ /(\d\d\d\d)(\d\d)(\d\d)/
        }

        $checklen = length($check);
        if ( $checklen > 5 ) {
            $cutcheck = substr($check, $checklen - 5, 5);
        } else {
            $cutcheck = $check;
        }

        if ( $date_fmt == 1 ) {
            $nicedate = "$month/$day/$year";
        } else {
            $nicedate = "$day.$month.$year";
        }

        $cutdesc = substr($desc, 0, 15);
        $cutcom = substr($com, 0, 15);
        if ( $cat =~ m/\|/ ) {
            $nicecat = "-Splits-";
        } else {
            $nicecat = $cat;
        }
	$nicecat = substr($nicecat, 0, 9);

	printf("%5s  %-10s  %-15s  %9.2f  %9.2f  %-1s %10.2f %14s\n",
	       $cutcheck, $nicedate, $cutdesc, $debit, $credit, $cleared, 
	       $total, $key);
        printf("%5s  %-10s  %-15s  %-9s %39s\n", "", "", $cutcom, $nicecat, 
	       $key);
    }

    $| = 1;				# turn buffer flushing back on

    return "none";
}

# returns part of the transaction list in one big chunk. (since a date)
sub part_trans {
    # in: date
    # out: result

    my($sdate_fmt) = @_;
    my($left, $middle, $right) = (0, 0, $#CBB::KEYS);
    my($date_fmt, $sdate);
    my($key, $nicecat, $cutcom, $cutdesc, $cutcheck, $nicedate, $checklen);
    my($date, $check, $desc, $debit, $credit, $cat, $com, $cleared, $total);
    my($day, $month, $year);

    # two arguments: data_format and start date
    ($date_fmt, $sdate) = split(" ", $sdate_fmt, 2);

    $| = 0;				# turn off buffer flushing

    if ($CBB::calced == 0) {
	&calc_trans();
    }

    if ($CBB::sorted_keys == 0) {
	&sort_keys();
    }

    # look for first key past starting with sdate (borrowed from find_trans)
    $sdate = "$sdate-".&pad(0);

    while ( $left <= $right ) {
	$middle = int( ($left + $right) / 2 );
	if ( $CBB::KEYS[$middle] lt $sdate ) {
	    $left = $middle + 1;
        } elsif ( $CBB::KEYS[$middle] gt $sdate ) {
	    $right = $middle - 1;
        } else {
	    # we found it, force an exit of the while loop
	    $left = $right + 1;
        }
    }
    if ($CBB::KEYS[$middle] != $sdate) {
	 # we found the first past sdate
	 $middle = $left;
    }

    for (; $middle <= $#CBB::KEYS ; ++$middle) {
	$key=$CBB::KEYS[$middle];

	# print ("$key\t$CBB::TRANS{$key}\n");
        ($date, $check, $desc, $debit, $credit, $cat, $com, $cleared, $total) =
	    split(/\t/, $CBB::TRANS{$key});

        if ( length($date) == 6 ) {
	    # for backwards compatibility ... shouldn't be needed now.
            ($year, $month, $day) = $date =~ /(\d\d)(\d\d)(\d\d)/;
	    my($century) = ($year lt '80' ? '20' : '19');
	    $year = "$century$year";
        } else {
            ($year, $month, $day) = $date =~ /(\d\d\d\d)(\d\d)(\d\d)/
        }

        $checklen = length($check);
        if ( $checklen > 5 ) {
            $cutcheck = substr($check, $checklen - 5, 5);
        } else {
            $cutcheck = $check;
        }

        if ( $date_fmt == 1 ) {
            $nicedate = "$month/$day/$year";
        } else {
            $nicedate = "$day.$month.$year";
        }

        $cutdesc = substr($desc, 0, 15);
        $cutcom = substr($com, 0, 15);
        if ( $cat =~ m/\|/ ) {
            $nicecat = "-Splits-";
        } else {
            $nicecat = $cat;
        }
	$nicecat = substr($nicecat, 0, 9);

	printf("%5s  %-10s  %-15s  %9.2f  %9.2f  %-1s %10.2f %14s\n",
	       $cutcheck, $nicedate, $cutdesc, $debit, $credit, $cleared, 
	       $total, $key);
        printf("%5s  %-10s  %-15s  %-9s %39s\n", "", "", $cutcom, $nicecat, 
	       $key);
    }

    $| = 1;				# turn buffer flushing back on

    return "none";
}

# return the first uncleared transaction
sub first_uncleared_trans {
    my($trans);
    my($date, $check, $desc, $debit, $credit, $cat, $com, $cleared, $junk);
    
    if ($CBB::sorted_keys == 0) {
	&sort_keys();
    }

    if ($CBB::calced == 0) {
	&calc_trans();
    }

    $CBB::current = 0;
    $trans = $CBB::TRANS{$CBB::KEYS[$CBB::current]};
    ($date, $check, $desc, $debit, $credit, $cat, $com, $cleared, $junk) = 
    	    split(/\t/, $trans);
    while ( ($cleared eq "x") || ($cleared eq "X") ) {
        ++$CBB::current;
        $trans = $CBB::TRANS{$CBB::KEYS[$CBB::current]};
        ($date, $check, $desc, $debit, $credit, $cat, $com, $cleared, $junk) = 
    	        split(/\t/, $trans);
    }

    if ( $trans ) {
        return "$CBB::KEYS[$CBB::current]\t$trans";
    } else {
        return "none";
    }
}


# return the next uncleared transaction
sub next_uncleared_trans {
    my($trans);
    my($date, $check, $desc, $debit, $credit, $cat, $com, $cleared, $junk);

    if ($CBB::sorted_keys == 0) {
	&sort_keys();
    }

    if ($CBB::calced == 0) {
	&calc_trans();
    }

    ++$CBB::current;
    $trans = $CBB::TRANS{$CBB::KEYS[$CBB::current]};
    ($date, $check, $desc, $debit, $credit, $cat, $com, $cleared, $junk) = 
    	    split(/\t/, $trans);
    while ( ($cleared eq "x") || ($cleared eq "X") ) {
        ++$CBB::current;
        $trans = $CBB::TRANS{$CBB::KEYS[$CBB::current]};
        ($date, $check, $desc, $debit, $credit, $cat, $com, $cleared, $junk) = 
    	        split(/\t/, $trans);
    }

    if ( $trans ) {
        return "$CBB::KEYS[$CBB::current]\t$trans";
    } else {
        return "none";
    }
}


# select transaction -- primes a transaction for future clearing
sub select_trans {
    # in: key
    # out: keyed_transaction

    my($key) = @_;
    my($trans);
    my($date, $check, $desc, $debit, $credit, $cat, $com, $cleared, $total);

    $CBB::sorted_keys = 0;
    $CBB::calced = 0;

    $trans = $CBB::TRANS{$key};
    ($date, $check, $desc, $debit, $credit, $cat, $com, $cleared, $total) = 
    	    split(/\t/, $trans);

    $cleared = "*";

    $CBB::TRANS{$key} = 
	  "$date\t$check\t$desc\t$debit\t$credit\t$cat\t$com\t$cleared\t$total";

    print DEBUG "selected:  $key to be cleared\n" if $CBB::debug;

    return "$key\t$CBB::TRANS{$key}";
}


# select transaction -- primes a transaction for future clearing
sub unselect_trans {
    # in: key
    # out: keyed_transaction

    my($key) = @_;
    my($trans);
    my($date, $check, $desc, $debit, $credit, $cat, $com, $cleared, $total);

    $CBB::sorted_keys = 0;
    $CBB::calced = 0;

    $trans = $CBB::TRANS{$key};
    ($date, $check, $desc, $debit, $credit, $cat, $com, $cleared, $total) = 
    	    split(/\t/, $trans);

    $cleared = "";

    $CBB::TRANS{$key} = 
	  "$date\t$check\t$desc\t$debit\t$credit\t$cat\t$com\t$cleared\t$total";

    print DEBUG "unselected:  $key will not be cleared\n" if $CBB::debug;

    return "$key\t$CBB::TRANS{$key}";
}


# clear all selected transactions
sub clear_trans {
    my($key, $trans);
    my($date, $check, $desc, $debit, $credit, $cat, $com, $cleared, $total);

    if ($CBB::calced == 0) {
	&calc_trans();
    }

    if ($CBB::sorted_keys == 0) {
	&sort_keys();
    }

    foreach $key (@CBB::KEYS) {
        $trans = $CBB::TRANS{$key};
        ($date, $check, $desc, $debit, $credit, $cat, $com, $cleared, $total) = 
    	        split(/\t/, $trans);

	if ( $cleared eq "*" ) {
            $cleared = "x";

            $CBB::TRANS{$key} = 
	          "$date\t$check\t$desc\t$debit\t$credit\t$cat\t$com\t$cleared\t$total";
        }
    }
}


# return the cleared balance (this should be the last statement ending bal)
sub get_cleared_bal {
    return sprintf("%.2f", $CBB::BALS{"Xamount"});
}


# initialize the transactions data structure
sub init_trans {
    # out: result

    $CBB::sorted_keys = 0;
    $CBB::calced = 0;
    @CBB::KEYS = ();

    return "ok";
}


# make a new account
sub make_acct {
    # in: acct-name acct-desc acct-type
    # out: result
    
    my($name, $desc) = split(/ /, $_[0], 2);
    my($pos, $short_name);

    print DEBUG "Make account $name - $desc\n" if $CBB::debug;
    # print "Make account $name - $desc\n";

    print DEBUG "Making cbb account\n" if $CBB::debug;

    open(SAVE, ">$name.cbb.new");
    close(SAVE);
    unlink("$name.cbb.bak");
    rename("$name.cbb", "$name.cbb.bak");
    rename("$name.cbb.new", "$name.cbb");
    
    $CBB::current_file = "$name.cbb";
    %CBB::TRANS = ();

    # Assume we have category already open ... :| ??? :(

    # strip leading path from $name
    &insert_cat("[".&file_basename($name)."]\t$desc\t");

    # save the categories file before it gets toasted
    &save_cats(&file_dirname($name) . "/categories");

    return "ok";
}


# determine the file type and call the correct load routine
sub load_trans {
    # in: file base
    # out: result

    my($file) = @_;
    my($ext) = &file_extension($file);

    # print "$ext\n";
    # print &file_root($file) . "\n";

    print DEBUG "file extension is: $ext\n" if $CBB::debug;

    if ($CBB::cache) {
    	no strict 'vars';	# necessary for this special hack
    	no strict 'refs';

	# save current data to cache
	my($hname) = "ACC_" . &file_basename($CBB::current_file);
    print DEBUG "$hname $CBB::current_file\n" if $CBB::debug;
	%$hname = %CBB::TRANS;

	# test if new table already in cache
	$hname = "ACC_" . &file_basename($file);
    print DEBUG "$hname\n" if $CBB::debug;
	if (scalar (%$hname) ) {
		print DEBUG "$hname defined , load from cache\n" if $CBB::debug;

		$CBB::sorted_keys = 0;
		$CBB::calced = 0;
		
		%CBB::TRANS = %$hname;	# take values from the cache
		&calc_trans();

		$CBB::current_file = $file;

		return "ok";
	}
    }

    return &load_cbb_trans($file);
}


# load the data from a cbb file
sub load_cbb_trans {
    # in: file name (including .cbb extension)
    # out: result

    my($file) = @_;
    my($file_version) = "";
    my($junk);

    $CBB::sorted_keys = 0;
    $CBB::calced = 0;

    print DEBUG "Loading the cbb format file: $file\n" if $CBB::debug;

    if ( $CBB::decrypt ne "" ) {
	open(LOAD, "$CBB::decrypt < $file|") || return "error";
    } else {
    	open(LOAD, "<$file") || return "error";
    }

    %CBB::TRANS = ();	# clear out any transactions from the previous file

    while ( <LOAD> ) {
	if ( m/^#/ ) {
	    # toss the comment (but first check for any goodies.)
	    if ( m/version/i ) {
		($junk, $junk, $junk, $file_version) = split;
		print DEBUG "Data file version = $file_version\n" if $CBB::debug;
	    }
	} else {
	    if ( $file_version eq "") {
		print DEBUG "no data file version, file encrypted ?" if $CBB::debug;
		close(LOAD);
		return "error";
	    }
            chop;
	    if ( ! m/\t/ ) {
		s/:/\t/g;
		$_ = &fix_splits($_);
	    }
            &create_trans($_);
	}
    }

    close(LOAD);

    &calc_trans();

    $CBB::current_file = $file;

    return "ok";
}


sub fix_splits {
    # in: transaction with old two field per record splits
    # out: transaction with new three field per record splits

    my($line) = @_;
    my($date, $check, $desc, $debit, $credit, $cat, $com, $cleared, $total) =
	split(/\t/, $line);
    my(@cats, $i, $max, $newcat);

    if ( $cat =~ m/\|/ ) {
        @cats = split(/\|/, $cat);

        $i = 0;
        $max = ($#cats - 1) / 2;
        $newcat = "|";

        while ( $i < $max ) {
    	    $newcat .= $cats[$i * 2 + 1] . "||" . 
		       $cats[$i * 2 + 2] . "|";
	    $i++;
        }
    } else {
	$newcat = $cat;
    }

    return "$date\t$check\t$desc\t$debit\t$credit\t$newcat\t$com\t$cleared\t$total";
}


# load the data from a dbm file
sub load_dbm_trans {
    # in: file base name
    # out: result

    my($file) = @_;
    print DEBUG "Loading the dbm format file: $file\n" if $CBB::debug;

    if ( -e "$file" ) {
	$CBB::current_file = $file;
	$CBB::sorted_keys = 0;
	$CBB::calced = 0;

	dbmclose(%CBB::TRANS);
	dbmopen(%CBB::TRANS, &file_root($file), 0666) || return "error";
	
	# test to see if this file is <tab> delimited
	&sort_keys();
	# never ever call calc_trans() at this point (or call something that
	# calls it
	if (defined($CBB::TRANS{$CBB::KEYS[0]}) && 
	    !($CBB::TRANS{$CBB::KEYS[0]} =~ m/\t/) ) {
	    print DEBUG "'$CBB::TRANS{$CBB::KEYS[0]}' = old version of CBB dbm file\n"
		if $CBB::debug;
	    return "error - old version of CBB dbm file";
	} else {
	    print DEBUG "valid txn: '$CBB::TRANS{$CBB::KEYS[0]}'\n" 
		if $CBB::debug;
        }

	return "ok";
    } else {
	return "error";
    }
}


# save all the precious data to a file
sub save_trans {
    # in: file name (including .cbb extension)
    # out: result

    my($file) = @_;
    my($auto_save_file, $key);
    my(@trans);
    my($file_exists) = 0;
    my($dev, $ino, $mode, $nlink, $uid, $gid, $rdev, $size, $atime, $mtime, 
       $ctime, $blksize, $blocks);

    print DEBUG "Saving the cbb format file: $file\n" if $CBB::debug;

    if ($CBB::calced == 0) {
	&calc_trans();
    }

    if ($CBB::sorted_keys == 0) {
	&sort_keys();
    }

    if ( $CBB::encrypt ne "" ) {
	open(SAVE, "|$CBB::encrypt > $file.new") || return "error";
    } else {
    	open(SAVE, ">$file.new") || return "error";
    }

    # Print some header stuff
    print (SAVE "# CBB Data File -- $file\n");
    print (SAVE "#\n");
    print (SAVE "# CBB Version = $CBB::version_num\n");
    printf (SAVE "# Current Balance = %.2f\n", $CBB::BALS{Current});
    printf (SAVE "# Ending Balance = %.2f\n", $CBB::BALS{Amount});
    print (SAVE "# Transaction Count = $CBB::BALS{Count}\n");
    printf (SAVE "# Cleared Balance = %.2f\n", $CBB::BALS{Xamount});
    print (SAVE "# Cleared Txn Count = $CBB::BALS{Xcount}\n");
    print (SAVE "# Saved on (US Date Fmt) " . &nice_date("1") . " ");
    print (SAVE "by $CBB::user_name\n");
    print (SAVE "#\n");
    print (SAVE "# date  check  desc  debit  credit  cat  com  cleared\n");
    print (SAVE "# ---------------------------------------------------\n");

    foreach $key (@CBB::KEYS) {
	# strip off last total
	@trans = split(/\t/, $CBB::TRANS{$key});
	print SAVE join ("\t", @trans[0..7]) . "\n";
    }

    close(SAVE);

    # preserve file permissions if the file exists
    if ( -e $file ) {
	$file_exists = 1;
	($dev, $ino, $mode, $nlink, $uid, $gid, $rdev, $size, $atime, $mtime, 
	 $ctime, $blksize, $blocks) = stat($file);
	print DEBUG "file permissions = $mode\n" if $CBB::debug;
	print DEBUG "file owner = $uid  group = $gid\n" if $CBB::debug;
    }

    if ( $file_exists ) {
	unlink("$file.bak");
	rename("$file", "$file.bak");
    }

    rename("$file.new", "$file");

    if ( $file_exists ) {
	chown($uid, $gid, $file);
	chmod($mode, $file);
    }

    $auto_save_file = &file_dirname($file) . "#" . &file_basename($file) . "#";
    print DEBUG "auto_save_file = $auto_save_file\n" if $CBB::debug;
    if ( -e $auto_save_file ) {
	unlink("$auto_save_file");
	unlink("$auto_save_file.bak");
    }

    return "ok";
}


1;