logic seems to work, memory leaks everywhere