refactored rotate function