Complete rewrite, compatibility kept.
Reconcile with mainline