adds logging and some optimization