This code could be a lot simpler.