cleaned up code, has some bugs