Minor reordering.
Rewriting central loop to reduce dependency on xpath construction.