#!/bin/bash

# Aggressive lossless JXL encoding for scaled pixel art. Stores downscaled pixel data where possible while using the best compression settings in general.

cjxl="cjxl"
convert="convert"
compare="compare"

name=""
pretend=""

while [[ $# -gt 0 ]]; do
    case "$1" in
    	-i)
            name="$2"
            shift 2
            ;;
        --pretend)
            pretend="--disable_output"
            shift
            ;;
        *)
            echo "Unknown option: $1"
            exit 1
            ;;
    esac
done

ds_values=("50" "25" "12.5")
us_values=("2" "4" "8")
choice=-1
ds_name="${name}_d_.png"

for i in {0..2}; do
	test=$("$convert" "$name" -sample "${ds_values[$i]}%" -sample "${us_values[$i]}00%" PNG:- | "$compare" -metric pae "$name" - NULL: 2>&1)

    if [ "$test" = "0 (0)" ]; then
        choice=$i
    else
    	break
	fi
done

if [ "$choice" != -1 ]; then
	"$convert" "$name" -sample "${ds_values[$choice]}%" "$ds_name"
	"$cjxl" $pretend --num_threads 0 --already_downsampled --upsampling_mode=0 --resampling=${us_values[$choice]} -d 0 -e 10 -E 4 -I 100 -g 1 -X 0 --patches 0 "$ds_name" "${name%.*}.jxl"
	rm "$ds_name"
else
	"$cjxl" $pretend --num_threads 0 -d 0 -e 10 -P 0 -I 0 -g 3 --modular_palette_colors 70000 --patches 0 "$name" "${name%.*}.jxl"
fi