[trunk] rework code from r2463. Really there has been some code duplication from...