If you make this a utils function, the logic below only needs a few small tweaks to work here too.  Exercise for the reader.