basic idea seems ok, need to clean up and add test cases