Several bug fixes, fixes #8, fixes #7, fixes #1, fixes #5