Extend palette fix - including test cases.

Follow up PR to the two previous ones (#16 and #17).

This time bugfixes in palette extending, as usual along with the corresponding test cases.