Refactored existing code from K2 and added some comments / exceptions.