Cleaned up the code for clarity and added JSON tests.