draft of most of the logic needed to collapse loops