Rebuilt functions with more structure and moved into class