Code restructuring and encoding fixes