Add more error handling, fix bug