Cleaned up code to make it reviewable