could probably factor out this block into a static function, since it is almost the same as line 1793.