one of the ugliest functions I've written in a long time.