Fix bugs and improve error reporting