working recursive function (almost)