@echo off

set Psave=%PATH%
set path=bin

set BIN=bin
set DIR=temp
set SRC=%1

if not exist "%SRC%" exit

set DST=%SRC%.flifraw
del %DST% >nul 2>nul

rd /S /Q temp >nul 2>nul
md temp >nul 2>nul
echo %DIR%/alarms.bin  >%DIR%\file.list
echo %DIR%/begin       >>%DIR%\file.list
echo %DIR%/orig.sha256 >>%DIR%\file.list

%BIN%\sha256sum - <"%SRC%" > %DIR%\orig.sha256

echo dcraw_hack "%SRC%"
%BIN%\dcraw_hack "%SRC%" > %DIR%/temp.rgba 2> %DIR%/err

for /F "delims=;" %%a in ('%BIN%\head -n1 %DIR%/err ^| %BIN%\sed -e "s/^.*half=\([0-9]*x[0-9]*\)/\1/"') do set HALF_SIZE=%%a

echo convert -depth 16 -size %HALF_SIZE% rgba:%DIR%/temp.rgba png:%DIR%/temp.png
%BIN%\convert -depth 16 -size %HALF_SIZE% rgba:%DIR%/temp.rgba png:%DIR%/temp.png

%BIN%\grep ALARM %DIR%/err | %BIN%\cut -c 8- | %BIN%\xxd -r -ps > %DIR%/alarms.bin

for /F "delims=;" %%a in ('%BIN%\tail -n1 %DIR%/err') do set LAST_LINE=%%a

set PADDING_BYTE=00
echo %LAST_LINE% | grep -q PADDING
if not errorlevel 1 for /F "delims=PADDING: " %%a in ("%LAST_LINE%") do set PADDING_BYTE=%%a
echo %PADDING_BYTE% | %BIN%\xxd -r -ps > %DIR%/padding
echo %DIR%/padding >> %DIR%\file.list

for /F "delims=;" %%a in ('%BIN%\head -n1 %DIR%/err ^| %BIN%\sed -e "s/^.*data_at=//" -e "s/, .*$//"') do set START=%%a

for /F "delims=;" %%a in ('echo %HALF_SIZE% ^| %BIN%\sed -e "s/x.*$//"') do set HALF_WIDTH=%%a

echo flif -e --keep-invisible-rgb %DIR%/temp.png %DIR%/result.flif
%BIN%\flif -e --keep-invisible-rgb %DIR%/temp.png %DIR%/result.flif

echo Verifying compression

echo flif -d %DIR%/result.flif %DIR%/result.flif.png
%BIN%\flif -d %DIR%/result.flif %DIR%/result.flif.png

%BIN%\head -c %START% "%SRC%" > %DIR%\begin

echo convert %DIR%/result.flif.png -depth 16 rgba:- 
%BIN%\convert %DIR%/result.flif.png -depth 16 rgba:- >temp\1

echo arw_encode %HALF_WIDTH% %START% %DIR%\alarms.bin %PADDING_BYTE%
%BIN%\arw_encode %HALF_WIDTH% %START% %DIR%\alarms.bin %PADDING_BYTE% <temp\1 >temp\2

copy /b %DIR%\begin +temp\2 temp\3 >nul 2>nul

%BIN%\xdelta3.exe -9 -f -e -s %DIR%\3 %SRC% %DIR%\delta
echo %DIR%/delta  >>%DIR%\file.list
for %%a in (%DIR%\delta) do set DELTA_SIZE=%%~za

%BIN%\cat %DIR%/file.list | %BIN%\xargs %BIN%\tar --transform "s=^.*/==" -Jcf %DIR%/extra.tar.xz
%BIN%\tar --transform "s=^.*/==" -cf %DST% %DIR%/extra.tar.xz %DIR%/result.flif
rd /S /Q %DIR%
echo See %DST%, delta size=%DELTA_SIZE%

set path=%Psave%
