Bugfixes & cleanup

Fixed some bugs and tidied up a bit - thanks @acabunoc!