Fixed some bugs, small optimization