Improved error handling and REPL function