Made slightly less stupid and added some logging