This function really needs some tests.