Refactored some code. not finished yet.