Fix issue #4 and some other bugs