Version 3: several performance optimizations and encoding fixes.