Cleaned up api and refactored some confusing code.