Refactored reversing logic into seperate function