Code audit and assorted bugfixes

Audit done. Assorted bugs and many potential papercuts fixed.