 : trim-root ( root -- root' )
     dup redundant-root-node? [ children>> values first trim-root ] when ;
 
-: (top-down) ( samples -- tree )
-    collect-threads
-    [ [ collect-tops ] <profile-root-node> trim-root ] assoc-map ;
+:: (top-down) ( samples depth -- tree )
+    samples collect-threads
+    [ [ depth collect-tops ] <profile-root-node> trim-root ] assoc-map ;
 
 : top-down ( -- tree )
-    get-raw-profile-data (top-down) ;
+    get-raw-profile-data 0 (top-down) ;
+
+:: counts+at ( key assoc sample -- )
+    key assoc [ zero-counts or sample sample-counts-slice v+ ] change-at ;
 
 :: collect-flat ( samples -- flat )
     IH{ } clone :> per-word-samples
     samples [| sample |
         sample sample-callstack unique keys [ ignore-word? not ] filter [
-            per-word-samples [ zero-counts or sample sample-counts-slice v+ ] change-at
+            per-word-samples sample counts+at
         ] each
     ] each
-    per-word-samples [ f <profile-node> ] assoc-map ;
+    per-word-samples [ f 0 <profile-node> ] assoc-map ;
 
 : redundant-flat-node? ( child-node root-node -- ? )
     [ total-time>> ] bi@ = ;

    } cleave ;

:: (profile-node.) ( word node depth -- )
    depth depth. node times. ": " write word pprint-short nl
    node children>> depth 1 + (profile.) ;

: (profile.) ( nodes depth -- )


: flat ( -- tree )
    get-raw-profile-data (flat) ;

: nth-or-last ( n seq -- elt )
    [ drop f ] [
        2dup bounds-check? [ nth ] [ nip last ] if
    ] if-empty ;

:: collect-cross-section ( samples depth -- cross-section )
    IH{ } clone :> per-word-samples
    samples [| sample |
        depth sample sample-callstack [ ignore-word? ] trim-tail nth-or-last :> word
        word [
            word per-word-samples sample counts+at
        ] when
    ] each
    per-word-samples [ f depth <profile-node> ] assoc-map ;

:: (cross-section) ( depth samples -- flat )
    samples collect-threads
    [ [ depth collect-cross-section ] <profile-root-node> ] assoc-map ;

: cross-section ( depth -- tree )
    get-raw-profile-data (cross-section) ;

: depth. ( depth -- )
    [ "| " write ] times ;
