fixed bugs and optimized code