Well, I had to rewrite the balance reporting code yet again, because
it wouldn't work with --depth correctly. Here's the new algorithm.
STEP 1: Walk all postings, looking for those that match the user's
query.
As a match is found, mark its account VISITED.
STEP 2: Do a traversal of all accounts, sorting as need be, and collect
them all into an ordered list.
STEP 3: Keeping that list on the side, do a *depth-first* traversal of
the account tree.
visited = 0
to_display = 0
(visited, to_display) += <recurse for all immediate children>
if account is VISITED or (no --flat and visited > 0):
if account matches display predicate and
(--flat or to_display != 1):
mark account as TO_DISPLAY
to_display = 1
visited = 1
return (visited, to_display)
STEP 4: top_displayed = 0
for every account in the ordered list:
if account has been marked TO_DISPLAY:
mark account as DISPLAYED
format the account and print
if --flat and account is DISPLAYED:
top_displayed += 1
if no --flat:
for every top-most account:
if account is DISPLAYED or any children or DISPLAYED:
top_displayed += 1
if no --no-total and top_displayed > 1 and
top-most accounts sum to a non-zero balance:
output separator
output balance sum
John