Fix logic and code style issues
fixes #5