fixed up logic, seems to work fine, need to test for memory leaks