New state machine design for applications.

Should make it easier to customize for each site.

Lots of bugs fixed, including some potential security issues.

Improve working tests.

Documentation required.

Change-Id: I7116a3df7eed763a7e4a836471afef88c94237f1