functional implimentation of tail function (NEEDS TESTS)