Several bug fixes. Closes #31, #76 and #77