Refactored code and cleaned up with tpls etc.