head and tail code modified and tested