General improvements, fix security hole and bugs.

Plus code re-organization and cleanup.