Refactored stuff from @CraftMine