working version with debug output