Multiple code fixes

Fixes #222, #225, #226, #238, #239, #240, #242