Moved cursor repositioning logic in separate function