Cost base calculations

I am trying to work out how to create the cost base for my various share parcels. I realise Sharesight does this very well, but I would like to do this in my excel sheet.

When you buy, say BHP shares, the cost base is calculated by totalling all the buys, and the cost base per share is dividing the number of shares into the cost base.
However, when you throw a few SELL transactions into the arena, the calculations get a bit(lot) more messy. I have set the method as FIFO.

Any ideas would be greatly appreciated.