Issue #31 and some bugfixes