Refactoring: moved sorts casting routine into a separate function