Rewrote some of this to be better/faster