fix bugs, improve error handling