mostly refactored - still need to fix some bugs