Refactored code to allow for huge speed increase