Refactored codes and improved the performance.