@ECHO off 
SETLOCAL EnableExtensions EnableDelayedExpansion
SET "parent_dir=%~dp0"
IF EXIST log.txt del log.txt
REM Internal, we'll create two scripts to offer mtr creation
SET "opt_generate_mtr=0"


REM Supported file extensions
SET "supported_ext=.tga .bmp .png .jpg"


REM Options
REM Default values
SET "opt_use_metallicness=1"
SET "opt_use_glossiness=1"
SET "opt_filename_limit=0"
SET "opt_auto_flip=1"
SET "opt_suffix_delimiter=_"
SET "opt_mtr_remove_delimiter=1"
REM Read from settings.ini
FOR /f "tokens=1,2 delims==" %%a IN (settings.ini) DO (
IF %%a==USE_METALLICNESS SET opt_use_metallicness=%%b
IF %%a==USE_GLOSSINESS SET opt_use_glossiness=%%b
IF %%a==FILENAME_LIMIT SET opt_filename_limit=%%b
IF %%a==AUTO_FLIP SET opt_auto_flip=%%b
IF %%a==SUFFIX_DELIMITER SET opt_suffix_delimiter=%%b
IF %%a==MTR_REMOVE_DELIMITER SET opt_mtr_remove_delimiter=%%b
)


REM Texture suffixes indicating their type (default values)
REM NOTE: # No suffix = diffuse, but suffix_diffuse takes precendence for writung to mtr
SET "suffix_diffuse=d"
SET "suffix_normal=n"
SET "suffix_specular=s"
SET "suffix_metallicness=m"
SET "suffix_roughness=r"
SET "suffix_glossiness=g"
SET "suffix_height=h"
SET "suffix_illumination=i"


REM Conversion options for all files
SET "copt_all= -quiet -nostats -fileformat dds -logfile log.txt"
IF !opt_auto_flip! GTR 0 (
    SET "copt_all=!copt_all! -unflip -yflip"
)

REM Conversion options by texture type
SET "copt_diffuse= "
SET "copt_normal= -DXN -normalize -uniformMetrics"
SET "copt_specular= -DXT5A"
SET "copt_metallicness= -DXT5A -minvalue 5"
SET "copt_roughness= -DXT5A"
SET "copt_glossiness= -DXT5A -invertcolors"
SET "copt_height= -DXT5A"
SET "copt_illumination= -DXT1"


REM Helper to select file types
SET "valid_ext=%supported_ext:.=in\*%"
REM Helper to detect suffixes
SET "suffix_matcher=%opt_suffix_delimiter%[%suffix_diffuse%%suffix_normal%%suffix_specular%%suffix_roughness%%suffix_height%%suffix_illumination%"
REM Optional: Metallicness can be converted to specular
IF !opt_use_metallicness! GTR 0 (
    SET "suffix_matcher=!suffix_matcher!%suffix_metallicness%"  
)
REM Optional: Glossiness can be converted to roughness by inverting
IF !opt_use_glossiness! GTR 0 (
    SET "suffix_matcher=!suffix_matcher!%suffix_glossiness%"
)
SET "suffix_matcher=!suffix_matcher!]$"


REM Process files
SET "previous_basename=null"
SET "previous_out_dir=out/"
SET "mtr_tex0=null"
SET "mtr_tex1=null"
SET "mtr_tex2=null"
SET "mtr_tex3=null"
SET "mtr_tex4=null"
SET "mtr_tex5=null"
FOR /f "tokens=*" %%F IN ('dir /s /b /o:n %valid_ext%') DO (
    SET "tex_fullpath=%%F"
    SET "tex_name=%%~nF"
    SET "tex_ext=%%~xF"
    REM get the subdir within the in/ directory
    SET "tex_dir=!tex_fullpath:%parent_dir%in=!"
    CALL SET "tex_dir=%%tex_dir:!tex_name!!tex_ext!=%%"

    ECHO --------------------------------------------------
    ECHO Processing: in!tex_dir!!tex_name!!tex_ext!
       
    REM Match filename with a known suffix to get the basename
    ECHO !tex_name!|FINDSTR /I /R %suffix_matcher% >nul
    IF errorlevel 1 (
        SET "tex_basename=!tex_name!"
        SET "suffix=#####"
    ) ELSE (
        SET "tex_basename=!tex_name:~0,-1!"
        SET "suffix=!tex_name:~-1!"
    )

    REM Optional: Limit filename length to 16
    IF !opt_filename_limit! GTR 0 (
        CALL :strlen name_length tex_name
        REM: Cut something off in the middle to preserve file suffix
        IF !name_length! GTR 16 (
            SET "tex_name=!tex_name:~0,9!!tex_name:~-7!"
            ECHO Filename too long: !name_length!
            ECHO Shortening name to: !tex_name!
        )
    )

    REM Generate new path for output file
    SET out_dir=out!tex_dir!
    IF NOT EXIST "!out_dir!" mkdir "!out_dir!"
    SET out_path=!out_dir!!tex_name!.dds
    
    REM Flush mtr values to file if basename or directory has changed
    IF NOT "!previous_basename!" == "null" (
        SET "doonce="
        IF NOT "!out_dir!" == "!previous_out_dir!" SET doonce=1
        IF NOT "!tex_basename!" == "!previous_basename!" SET doonce=1
        IF DEFINED doonce (
            IF !opt_generate_mtr! GTR 0 (
                REM We may need to remove the delimiter for the mtr filename
                if !opt_mtr_remove_delimiter! GTR 0 (
                    SET "mtr_filename=!previous_basename:~0,-1!"
                ) ELSE (
                    SET "mtr_filename=!previous_basename!"
                )
                SET "mtr_fullpath=!previous_out_dir!!mtr_filename!.mtr"
                CALL :WRITE_MTR "!mtr_fullpath!" "!mtr_tex0!" "!mtr_tex1!" "!mtr_tex2!" "!mtr_tex3!" "!mtr_tex4!" "!mtr_tex5!"
            )
            SET "mtr_tex0=null"
            SET "mtr_tex1=null"
            SET "mtr_tex2=null"
            SET "mtr_tex3=null"
            SET "mtr_tex4=null"
            SET "mtr_tex5=null"
        )
    )

    REM Set options based on suffix
    SET "out_options=%copt_all%"
    IF /I !suffix! == %suffix_diffuse% (
        ECHO Type: Diffuse
        SET "out_options=!out_options!%copt_diffuse%"
        SET "mtr_tex0=!tex_name!"
    ) ELSE IF /I !suffix! == %suffix_normal% (
        ECHO Type: Normal
        SET "out_options=!out_options!%copt_normal%"
        SET "mtr_tex1=!tex_name!"
    ) ELSE IF /I !suffix! == %suffix_specular% (
        ECHO Type: Specular
        SET "out_options=!out_options!%copt_specular%"
        SET "mtr_tex2=!tex_name!"
    ) ELSE IF /I !suffix! == %suffix_metallicness% (
        ECHO Type: Metallicness
        SET "out_options=!out_options!%copt_metallicness%"
        REM Rename (metallicness will be used as specular texture)
        SET out_path=!out_dir!!tex_basename!%suffix_specular%.dds
        SET "mtr_tex2=!tex_basename!%suffix_specular%"        
    ) ELSE IF /I !suffix! == %suffix_roughness% (
        ECHO Type: Roughness
        SET "out_options=!out_options!%copt_roughness%"
        SET "mtr_tex3=!tex_name!"
    ) ELSE IF /I !suffix! == %suffix_glossiness% (
        ECHO Type: Glossiness
        SET "out_options=!out_options!%copt_glossiness%"
        REM Rename (glossiness will be inverted to roughness)
        SET out_path=!out_dir!!tex_basename!%suffix_roughness%.dds
        SET "mtr_tex3=!tex_basename!%suffix_roughness%"
    ) ELSE IF /I !suffix! == %suffix_height% (
        ECHO Type: Height ^(Displacement^)
        SET "out_options=!out_options!%copt_height%"
        SET "mtr_tex4=!tex_name!"        
    ) ELSE IF /I !suffix! == %suffix_illumination% (
        ECHO Type: Illumination
        SET "out_options=!out_options!%copt_illumination%"
        SET "mtr_tex5=!tex_name!"
    ) ELSE (
        ECHO Type: Diffuse ^(No Suffix^)
        SET "out_options=!out_options!%copt_diffuse%"
        REM Don't overwrite existing (suffixed diffuse) in mtr
        IF !mtr_tex0! == null (
            SET "mtr_tex0=!tex_name!"
        )
    )
    REM ECHO Writing to: !out_path!
    nwn_crunch -file "!tex_fullpath!" -out "!out_path!" !out_options!
    SET "previous_basename=!tex_basename!"
    SET "previous_out_dir=!out_dir!"
)
REM Flush last mtr values
IF !opt_generate_mtr! GTR 0 (
    REM We may need to remove the delimiter for the mtr filename
    if !opt_mtr_remove_delimiter! GTR 0 (
        SET "mtr_filename=!previous_basename:~0,-1!"
    ) ELSE (
        SET "mtr_filename=!previous_basename!"
    )
    SET "mtr_fullpath=!previous_out_dir!!mtr_filename!.mtr"
    CALL :WRITE_MTR "!mtr_fullpath!" "!mtr_tex0!" "!mtr_tex1!" "!mtr_tex2!" "!mtr_tex3!" "!mtr_tex4!" "!mtr_tex5!"
)

EXIT /B %ERRORLEVEL%


:WRITE_MTR
SET "filepath=%~1"
ECHO      Creating MTR: !mtr_fullpath!
SET "tex0=%~2"
SET "tex1=%~3"
SET "tex2=%~4"
SET "tex3=%~5"
SET "tex4=%~6"
SET "tex5=%~7"
ECHO. > "%filepath%"
ECHO renderhint NormalAndSpecMapped >> "%filepath%"
ECHO. >> "%filepath%"
ECHO // Textures >> "%filepath%"
ECHO texture0 %tex0% >> "%filepath%"
ECHO texture1 %tex1% >> "%filepath%"
ECHO texture2 %tex2% >> "%filepath%"
ECHO texture3 %tex3% >> "%filepath%"
ECHO texture4 %tex4% >> "%filepath%"
ECHO texture5 %tex5% >> "%filepath%"
EXIT /B 0


:STRLEN <resultVar> <stringVar>
(   
    SETLOCAL EnableDelayedExpansion
    SET "s=!%~2!#"
    SET "len=0"
    FOR %%P in (4096 2048 1024 512 256 128 64 32 16 8 4 2 1) do (
        IF "!s:~%%P,1!" NEQ "" ( 
            SET /a "len+=%%P"
            SET "s=!s:~%%P!"
        )
    )
)
( 
    ENDLOCAL
    SET "%~1=%len%"
    EXIT /b
)
