fix threading KeyError, minor code cleanup