Major rewrite for better error handling