Oh god, this whole function is a mess. Any way you could try to clean it completely? :p