Fix some bugs and error handling