I believe my last PR may have introduced some if not all logic for this. This needs to be reviewed as incomplete (TODO). 