Also, all of this logic should be unit-tested.