Fixed bug and optimized code