In fact, it is already improved by the commit I did after your comment due to other problems (in addition to being huge, it was buggy! probably a consequence). There is no code duplication anymore. I don't know if it is really worth a function.