some refactoring and optimization. it's sort of broken though....
added some debugging info, also it seems to work properly now for some reason