final solution with functions