Updated implementation with some performance tweaks.