
@echo off

SETLOCAL

if "%1" EQU "-no_stamps" (
  set no_stamps=yes
  shift
)
if "%1" EQU "/no_stamps" (
  set no_stamps=yes
  shift
)
if "%1" NEQ "" (
  set dep=%1
  shift
) else (
  set usage=y
  goto usage
)
if "%1" NEQ "" (
  set obj=%1
  shift
) else (
  set usage=y
  goto usage
)
if "%1" NEQ "" (
  set src=%1
  shift
) else (
  set usage=y
  goto usage
)
if exist "%1" (
  set deps=%1
  shift
) else (
  set usage=y
  goto usage
)
if "%1" NEQ "" (
  set usage=y
  goto usage
)

if not defined CMTMSGPREFIX (
  set CMTMSGPREFIX=cmt_format_deps.bat
)
if defined makecmd (
  if defined cmtmsg echo "%CMTMSGPREFIX%" "(cmt_format_deps.bat)"
  @echo on
)

if "%no_stamps%" EQU "yes" (
  if exist %dep% del %dep% 
  if not errorlevel 0 exit /b 1
  echo %dep% %obj% : %src% \>>%dep%
  for /F "usebackq tokens=3,*" %%I in (`find "Note: including file:" %deps%`) do @echo "%%J" \>>%dep%
  if not errorlevel 0 exit /b 1
  exit /b
)

  set stamp=%dep%.stamp
  set stamptmp=%dep%.stamp.tmp
  set tmp=%dep%.tmp

  type nul >%stamptmp%
  if exist %tmp% del %tmp%
  if not errorlevel 0 exit /b 1
  echo %dep% %obj% : %stamp% %src% \>>%tmp%
  for /F "usebackq tokens=3,*" %%I in (`find "Note: including file:" %deps%`) do @echo "%%J" \>>%tmp%
  if not errorlevel 0 exit /b 1

if exist %dep% (
  echo n|comp %dep% %tmp% >nul 2>&1
  if errorlevel 0 (
    if exist %stamp% (
      del %stamptmp% || exit /b 1
    ) else (
      move /y %stamptmp% %stamp% >nul || exit /b 1
    )
  ) else (
    move /y %stamptmp% %stamp% >nul || exit /b 1
  )
) else (
  move /y %stamptmp% %stamp% >nul || exit /b 1
)
move /y %tmp% %dep% >nul || exit /b 1

if defined makecmd @echo off
exit /b

:usage
if defined usage (
  echo "Usage: cmt_format_deps.bat [-no_stamps|/no_stamps] DEP OBJ SRC DEPENDENCIES"
  echo "Create DEP [and its STAMP] containing Make rule with target DEP OBJ"
  echo "and prerequisites [STAMP] SRC SRC-DEPENDENCIES... based on DEPENDENCIES."
  exit /b 2
)

ENDLOCAL
