Make sure we only add the last TxOut of created transactions as an unspent output when that is a change output

It might be easier to review each commit individually, as the first two ones
are just refactorings to make the actual fix simpler.