The algorithm keeps searching for a better key, and we do that by scoring the decrypted text(always with a different key). We are scoring the decrypted text, by computing the probability of a piece of text being english(by multiplying the quadgram probabilities).
The main idea of the code is inspired by practicalcryptography.com