:: Script to archive files in the current directory in 7z format.
:: If a file is a Zip archive, it will be unzipped, deleted, and its
:: contents will be rearchived in 7z format.
::
:: USAGE: 7zip [filespec|filelist.txt]
::
:: If filespec is given, then only files matching the filespec will be
:: archived. If filelist.txt is given, then only files (minus extensions)
:: listed in filelist.txt will be processed.

@echo off

:: Running in Windows NT or higher?
if not "%OS%" == "Windows_NT" (
  echo This script requires Windows NT or higher.
  exit /b 1
)

:: Set variables
setlocal
set exe="C:\Program Files\7-Zip\7z.exe"
if [%1]==[] (
  set filespec=*.*
) else (
  if not exist "%~1" (
    echo Error: '%1' does not exist.
    exit /b 2
  )
  set filespec=%1
)
if exist R:\ (
  set temp=R:\7zip_tmp
) else (
  set temp=%TEMP%\7zip_tmp
)

:: BEGIN execution
if exist %temp% (
  rd /s /q %temp%
)
if %filespec%==filelist.txt (
  for /f "delims=" %%i in (%filespec%) do (
    %exe% a "%%i.7z" "%%i*.dsk"
    if errorlevel 1 (
      echo Error while archiving files.
      exit /b 2
    )
    del /f /q "%%i*.dsk"
  )
) else (
  for %%i in (%filespec%) do (
    if /i %%~xi==.zip (
      %exe% x "%%~i" -o"%temp%" -r -y
      if errorlevel 1 (
        echo Error while extracting files.
        exit /b 2
      )
      %exe% a "%%~ni.7z" "%temp%\*" -r
      if errorlevel 1 (
        echo Error while archiving files.
        exit /b 2
      )
      del /f /q "%%~i"
      rd /s /q "%temp%"
    ) else if /i %%~xi==.7z (
      :: Do nothing
      echo '%%i' is already in 7z format.
    ) else (
      %exe% a "%%~ni.7z" "%%~i"
      if errorlevel 1 (
        echo Error while archiving files.
        exit /b 2
      )
      del /f /q "%%~i"
    )
  )
)

:END
endlocal
echo.
echo DONE!