Some fixes and minor optimizations

Fix removing BOM only on first line
Fix closing previous file when opening a new one