Fixed errors, optimized code