fixed first and last functions and refactorized code