Use a CTE instead of querying the database in a loop when finding the start of a branch. This can bring significant speedup on some machines. (Edit by moved to 'mistake' branch because (A) it generates different results than before and (B) triggers an assert in the blob class in at least one test case.)