Added helper functions and cleaned up the code