common code factored, some variable renaming