Refactored the whole thing