code re-factored to avoid global sharing of variables