Jace #25: Refactored and cleaned up code. Added documentation where appropriate.