Added some logging and more logic