Added JSON output option and more error handling throughout.