Refactor and overhaul for efficiency