factor out common code
put back teared-off code
some optimization