The previous commit at [1] introduced a bug due to last
minute reordering of code, this fixes the ordering
and adds a couple of tests to verify the functionaility.
[1]: I2e3d74168976868ea1e4dd6c797f6340faa50d0f
Change-Id: Ia6f8df92b2700f63b2208290ede85f247b33bc63