tweaked the code, fixed some bugs