Re-wrote and refactored major code