#!/bin/bash

INPUT_IMAGE="$1"
OUTPUT_TEMPLATE="$2"

# Check if arguments are provided
if [ -z "$INPUT_IMAGE" ] || [ -z "$OUTPUT_TEMPLATE" ]; then
    echo "Usage: $0 <input_image> <output_template>"
    echo "Example: $0 input.png tile_%d.png"
    exit 1
fi

# Check if input file exists
if [ ! -f "$INPUT_IMAGE" ]; then
    echo "Error: Input file '$INPUT_IMAGE' not found"
    exit 1
fi

TILE_WIDTH=$(( $(identify -format "%w" "$INPUT_IMAGE") / 4 ))
TILE_HEIGHT=$(identify -format "%h" "$INPUT_IMAGE")

for i in $(seq 0 3); do
    X_OFFSET=$(( i * TILE_WIDTH ))
    TEMP_FILE="_temp_${i}.png"
    OUTPUT_FILE=$(printf "$OUTPUT_TEMPLATE" "$i")
    
    magick "$INPUT_IMAGE" -crop "${TILE_WIDTH}x${TILE_HEIGHT}+${X_OFFSET}+0" +repage "$TEMP_FILE"
    
    # Trim white background from each generated tile
    magick "$TEMP_FILE" -fuzz 10% -trim +repage "$OUTPUT_FILE"
    
    # Clean up temporary file
    rm "$TEMP_FILE"
done