This same strange block of code appears without comment in 3 places, which will need to be kept in synch.
Should extract this into some kind of util class/function or at least cross-reference the code blocks to help ensure that they stay in sync.