adding debugged and far faster version, uses sets instead of lists