Cleaned up some very ugly code