Slightly modified and refactored some stuff.