@echo off
title Italic

if (%1)==() goto :help

if /i not (%~x1)==(.docx) (
        cls
        echo Document must be in .DOCX format
        echo\
        pause
        goto :EOF
)

set fdoc=%~dpn1
set doc=%~n1
set inplace=-italic
::set inplace=

echo Processing "%~n1" ...
echo\

2>nul rd /s /q "%temp%\%doc%"
md "%temp%\%doc%"
pushd "%temp%\%doc%"

if (%LOCALAPPDATA%)==() (
    "%~dp0\unzip" -q "%fdoc%.docx"
) else (
    "C:\Program Files\7-Zip\7z.exe" x "%fdoc%.docx"
)

for /f "delims=" %%a in ('dir /b /s docu*.xml endn*.xml footn*.xml') do call :wipe "%%a"

if (%LOCALAPPDATA%)==() (
    "%~dp0\zip" -r -q "%doc%.zip" *.*
    copy "%doc%.zip" "%fdoc%%inplace%.docx" >nul
) else (
    "C:\Program Files\7-Zip\7z.exe" a -r "%doc%.zip" *.*
    copy "%doc%.zip" "%fdoc%%inplace%.docx"
)

popd
rd /s /q "%temp%\%doc%"
goto :EOF

:help
        cls
        echo USE: Drag and drop a .DOCX file on %~n0
        echo\
        pause
        goto :EOF

:wipe
set beauty=0
if (%LOCALAPPDATA%)==() (
    "%~dp0perl514" -x "%~f0" "%~f1"
) else (
    "C:\Pgm\DGTapps\Perl516\bin\perl" -x "%~f0" "%~f1"
)
::	"C:\Pgm\DGTapps\Perl518-x64\bin\perl" -x "%~f0" "%~f1"


goto :EOF

#!perl

$/ = "<\/w:p>";

$file = $ARGV[0];

print "$file\n";

open (IN, "<:encoding(utf-8)", $file);

while (<IN>) {
    #	s!<w:r>(.+?)\{</w:t></w:r><w:r>(.+?)<w:t>!<w:r>$1\{!g;	# remove useless <w:r> before {
    #	s!</w:t></w:r><w:r>(.+?)<w:t>\}!$2!g;	# remove useless <w:r> before }
    #   s!(\{)</w:t></w:r><w:r[\s>].*?<w:t>!$1!g; 
    #   s!</w:t></w:r><w:r[\s>].*?<w:t>(\})!$1!g;
    #   s!(<w:r[\s>].*?<w:t[^>]*>)(.+?)(\s*)\x{2460}(.+?)\x{2776}(\s*)!$1$2</w:t></w:r><w:r><w:rPr><w:i/></w:rPr><w:t xml:space="preserve">$3$4$5</w:t></w:r>$1!g;
    s!(\s*)\x{2460}(.+?)\x{2776}(\s*)!</w:t></w:r><w:r><w:rPr><w:i/></w:rPr><w:t xml:space="preserve">$1$2$3</w:t></w:r><w:r><w:t xml:space="preserve">!g;	
    s!(\s*)\x{2461}(.+?)\x{2777}(\s*)!</w:t></w:r><w:r><w:rPr><w:b/></w:rPr><w:t xml:space="preserve">$1$2$3</w:t></w:r><w:r><w:t xml:space="preserve">!g;	
    s!(\s*)\x{2462}(.+?)\x{2778}(\s*)!</w:t></w:r><w:r><w:rPr><w:u/></w:rPr><w:t xml:space="preserve">$1$2$3</w:t></w:r><w:r><w:t xml:space="preserve">!g;	
    s!(\s*)\x{2463}(.+?)\x{2779}(\s*)!</w:t></w:r><w:r><w:rPr><w:vertAlign w:val="superscript" /></w:rPr><w:t xml:space="preserve">$1$2$3</w:t></w:r><w:r><w:t xml:space="preserve">!g;	
    s!(\s*)\x{2464}(.+?)\x{277A}(\s*)!</w:t></w:r><w:r><w:rPr><w:vertAlign w:val="subscript" /></w:rPr><w:t xml:space="preserve">$1$2$3</w:t></w:r><w:r><w:t xml:space="preserve">!g;	
} continue {
#### output formatting ####
    push(@out, $_);
}

close IN;

open (OUT, ">:encoding(utf-8)", $file);
print OUT @out;
close OUT;


