Refactored most of the code and cleaned up the init function.