This whole function needs testing.