fixed some bugs, cleaned code, added debug mode