Bug fixes, mostly caused by stage 1 refactoring. Some other improvements.