Fully functional now with suggestion from StackOverflow