First version that seems to function (not optimally yet)