cleaning code and fixing some bugs