Perhaps factoring this block out would improve readability - there is too many nested functions here, and the `else`-branch uses a standalone function already.