Refactor MF script, optimize, fix encoding bugs.