fixed some bugs and improved the code