@ECHO OFF

::
:: rename.bat --
::
:: Extensible Adaptable Generalized Logic Engine (Eagle)
:: File Rename Tool
::
:: Copyright (c) 2007-2012 by Joe Mistachkin.  All rights reserved.
::
:: See the file "license.terms" for information on usage and redistribution of
:: this file, and for a DISCLAIMER OF ALL WARRANTIES.
::
:: RCS: @(#) $Id: $
::

SETLOCAL

REM SET __ECHO=ECHO
IF NOT DEFINED _AECHO (SET _AECHO=REM)
IF NOT DEFINED _CECHO (SET _CECHO=REM)
IF NOT DEFINED _VECHO (SET _VECHO=REM)

%_AECHO% Running %0 %*

SET SOURCE=%1

IF NOT DEFINED SOURCE (
  GOTO usage
)

CALL :fn_UnquoteVariable SOURCE

SET SOURCEDIR=%~dp1

CALL :fn_UnquoteVariable SOURCEDIR

SET TARGET=%2

IF NOT DEFINED TARGET (
  GOTO usage
)

CALL :fn_UnquoteVariable TARGET

SET TARGETDIR=%~dp1

CALL :fn_UnquoteVariable TARGETDIR

SET DUMMY2=%3

IF DEFINED DUMMY2 (
  GOTO usage
)

IF DEFINED SOURCE (
  IF DEFINED TARGET (
    IF DEFINED SOURCEDIR (
      IF DEFINED TARGETDIR (
        CALL :fn_ResetErrorLevel

        IF EXIST "%TARGETDIR%\%TARGET%" (
          %__ECHO% DEL "%TARGETDIR%\%TARGET%"

          IF ERRORLEVEL 1 (
            ECHO Could not delete "%TARGETDIR%\%TARGET%".
            GOTO errors
          ) ELSE (
            %_AECHO% Deleted "%TARGETDIR%\%TARGET%".
          )
        )

        %__ECHO% RENAME "%SOURCE%" "%TARGET%"

        IF ERRORLEVEL 1 (
          ECHO Could not rename from "%SOURCE%" to "%TARGET%".
          GOTO errors
        ) ELSE (
          %_AECHO% Renamed from "%SOURCE%" to "%TARGET%".
        )
      ) ELSE (
        ECHO Invalid target directory.
        GOTO errors
      )
    ) ELSE (
      ECHO Invalid source directory.
      GOTO errors
    )
  ) ELSE (
    GOTO usage
  )
) ELSE (
  GOTO usage
)

GOTO no_errors

:fn_UnquoteVariable
  IF NOT DEFINED %1 GOTO :EOF
  SETLOCAL
  SET __ECHO_CMD=ECHO %%%1%%
  FOR /F "delims=" %%V IN ('%__ECHO_CMD%') DO (
    SET VALUE=%%V
  )
  SET VALUE=%VALUE:"=%
  REM "
  ENDLOCAL && SET %1=%VALUE%
  GOTO :EOF

:fn_ResetErrorLevel
  VERIFY > NUL
  GOTO :EOF

:fn_SetErrorLevel
  VERIFY MAYBE 2> NUL
  GOTO :EOF

:usage
  ECHO.
  ECHO Usage: %~nx0 ^<source^> ^<target^>
  GOTO errors

:errors
  CALL :fn_SetErrorLevel
  ENDLOCAL
  ECHO.
  ECHO Rename failure, errors were encountered.
  GOTO end_of_file

:no_errors
  CALL :fn_ResetErrorLevel
  ENDLOCAL
  ECHO.
  ECHO Rename success, no errors were encountered.
  GOTO end_of_file

:end_of_file
%__ECHO% EXIT /B %ERRORLEVEL%
