Cleaned up and rearranged code