Changed code to use sets, memory leaks fixed. Code is also much clearer.