fixed some bugs but needs debugging