Major performance improvement, minor bug fix