Cheeses

What a long code !
Also there is no good problem explanation. Try to use form:
1) What you do
2) What you expect
3) What you get
Would be helpfull if you wrote to log data which is sent/received over network and used this data in the explanation.