This is a complex function. It should be it's own standalone module in `lib/`