initial working version, has some bugs and missing edge cases