the functionality is now correct but the program is slow