code rearrangement, hopefully a bit more readable