problem 24 fast and ugly
cleaned up, still magic