Massive cleanup of some ugly code