fixed some bugs, cleaned up code a bit