#!/bin/sh

# backward compatibility script
echo 'Warning: use "monitor_ddc resbest" instead of "ddcresbest"' > /dev/stderr


# figure out optimal pixel resolution from these:

# $1, $2: horizontal and vertical display size in centimeters
#         e.g. from ddcsize [28 21]
# stdin:  list of VxH pixel resolutions, one per line
#         e.g. from ddcreslist [1024x768][800x600][...]

# and this:
dpi=96

#(X cm * dpi) / 2.54
near_size()
{
    echo $((  ($1 * $dpi * 100) / 254 ))
}

delta()
{
    local z=$(($1 - $2))
    echo "${z#-}"
}

size_x="$1";shift
size_y="$1";shift

near_x=$(near_size "$size_x")
near_y=$(near_size "$size_y")


best_d=
best_x=
best_y=

IFS='x'
while read x y;do
    d="$(( $(delta "$x" "$near_x") + $(delta "$y" "$near_y")))"

    if [ -z $best_d ] || [ $d -le $best_d ] ;then
	best_d=$d
	best_x=$x
	best_y=$y
    fi
done

[ -n "$best_x" ] && printf '%sx%s\n' $best_x $best_y
