fixed some bugs needs more testing and clean up