Sultan's hats and his wise counselors

The sultan has a collection of three different colored hats- green, red and blue. He wants to test the wiseness of his Wise Couselors, he tells them that they will have to stand in a row, where everyone can see the hats of the counselors ahead of him, but none of the counselors behind him. He shows them his collection of red, blue and green hats- he has more than enough of each to allow any possible combination. He explains to them that they will each have to say the color hat that will be placed upon their heads and will only allow at most one mistake.

He lets them confer for a bit, then has them blindfolded, arranged in a row, hatted, un-blindfolded, and waits. The counselors call their own hat color, one by one, starting from the back. Only the first caller is wrong. They found a strategy that will always work. How can they do this?

Assume that there are 3, 4 or 5 Wise Counsellors that make up the group.

Next, the sultan gets a lot of yellow hats to add to his collection. Will the counselors still be able to pass the same test if there are 4 colors of hats?

Re: Sultan's hats and his wise counselors

Let's give each colour a value

0 = green

1 = red

2 = blue

The first person adds together the values for all of the hats except for his own and calls out the colour of the hat with that value (mod 3)

The next person can calculate the value of his own hat by adding together the values for all of the hats except for his own and the one before him (mod 3) his hat has the required value to increase this to equal the value that was called out by the first person.

The third and subsequent people have sufficient information to calculate their own hat's value.

e.g.

red green blue green red

1 0 2 0 1

First person calculates 3 which is 0 mod 3

Second person also calculates 3 which is 0 mod 3 and hence knows his hat is value 0. He calls green

Third person calculates 1 and knows that the hat before him is 0. Therefore his hat must be 2 and he calls blue

Fourth person also calculates 1, knows that the hats before him are green/blue and calculates the colour of his hat.