Unpolished fixes

This needs cleanup (i.e. make sure everything is tabs, additional testing, etc) but appears to work for me. Let me know if you notice any problems