Several bug fixes. Closes #11, #12, #19, #23 and #46