@echo off
cls

set version=20170830-beta
set BEAUTY=0
set o=2^>nul ^>nul 

call :level

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

:init
if (%1)==() goto :EOF
if exist "%~f1\*" ( 
	call :dir "%~f1"
) else (
	call :file "%~f1"
)
shift
goto :init

:dir
for /f "delims=" %%a in ('dir /b /s "%~f1"') do call :file "%%a"
goto :EOF

:file
cls
set fdoc=%~dpn1
set pdoc=%~dp1
set doc=%~n1
set ext=%~x1

if /I not (%ext%)==(.docx) goto :EOF

call :inplace

call :decompress
call :wipe
call :compress
pause
goto :EOF

:level
	for /f "tokens=2 delims=." %%a in ('dir /b "%~dp0level.?"') do set LEVEL=%%a
	if (%level%)==(0) title %~n0 v. %version%
	if not (%level%)==(0) title %~n0 v. %version% Level %level%
	goto :EOF

:inplace
	for /f "tokens=2 delims=." %%a in ('dir /b "%~dp0inplace.*"') do set inplace=%%a
	if (%inplace%)==() goto :EOF
	echo %fdoc% | %o% find "%inplace%" && goto :EOF
	%o% md "%pdoc%\%inplace%"
	goto :EOF

:decompress
	md "%temp%\%doc%"
	pushd "%temp%\%doc%"
	echo Exploding "%doc%.docx" ...
	%o% "%~dp0bin\7z.exe" x -y "%fdoc%.docx"
	goto :EOF
	
:compress
	echo\
	echo Imploding "%doc%.docx" ...
	%o% "%~dp0bin\7z.exe" a -mx3 -y -r "%doc%.zip" *.*
	if (%inplace%)==() %o% copy /y "%doc%.zip" "%fdoc%.docx"
	if not (%inplace%)==() %o% copy /y "%doc%.zip" "%pdoc%\%inplace%\%doc%.docx"
	popd
	rd /s /q "%temp%\%doc%"
	echo\
	echo Done!
	goto :EOF

:wipe
	echo\
	for /f "delims=" %%a in ('dir /b /s docu*.xml endn*.xml footn*.xml') do call :do_wipe "%%a"
	goto :EOF
	
:do_wipe
	echo Wiping "%~n1" ...
	"%~dp0bin\SBperl\bin\perl" -w "%~dp0tagwipe.pl" "%~1"
	goto :EOF

:help
	cls
	echo Drag and drop a .DOCX file on TagWipe
	echo\
	pause
	goto :EOF

