Cleaned and reorganized code