Improved document encoding helper
Added simple BOM detection