misc changes and debugging

This is a working version of the code, ugly as it is.