Second version, with comments

Also reordered the top node checks to save flops (I think).