Refactor and performance upgrades thanks to @tizoc