moved function into the right place and added logging