Refactored transpose function