This whole function is a mess.