Reorganized code to be more reusable. Made json parsing more robust.