optimized code and removed some additional bugs