working, but really slow, refactored version