"but for tax purposes their (cost) basis should remain unaltered."
You can elect (at least in the US) to use average basis (which is what you are talking about), FIFO (IIRC LIFO is not permitted), maximum capital gains or minimum capital gains. You can elect to minimize capital gains this year, but that comes at the expense of reducing the tax basis of the residual to 0