first and last functions, refactored