Nine tongueless prisoners awake and see that they are all wearing hats (although they cannot see their own). The guard tells the prisoners that each hat is either red or white. In fact, he says, there is at least one white hat and one red hat! The guard explains that if anyone can tell their own hat color, they will be set free. If they guess wrong though, they will be executed. Each prisoner is given a slip of paper on which to write his response. When all the papers are collected, the guard announces that nobody will be set free, and nobody will be executed.
The guard gives the prisoners a second chance. The same result ensues.
The guard gives the prisoners one last chance. He is surprised to see that every prisoner wearing a white hat knew his hat color. As he released the white-hatted prisoners, all the remaining prisoners knew their hat color as well.
How did this happen, and how many red hats and how many white hats were there?