slightly reordered and removed dead code