fixed bugs and optimized codes