Fixed errors and optimized code