[wip] Consolidate some common functions, and fix edge cases