Cleaned up code with better use of function