fixed bugs, optimized code