Modified to use functions and be cleaner