Use state functions for message flow

The patch makes the code somewhat simpler and prepares it for
more complex initialization handshakes.
Merge pull request #542 from hurtonm/master

Use state functions for message flow