Tweaks and refactoring for #150, still no testing
fixed some bugs in the last commit for #150