improved previous commit to avoid race conditions, code cleanup