Filenames changed, plus refactoring from original StackOverflow code