This algorithm appears to work but it's pretty sketchy