fixed #5 and several other bugs