Outer iteration code
Many, many bugfixes