Clean up code and add comments
Split log function into two subfunctions