This code is unbelievably ugly, has never been fixed up to work with