optimizing head tails code