Merged fixes proposed by dbungert to avoid race conditions.