Optimized code and bug fixed