#!/bin/sh
#
# Take the contents of /etc/pointercal and convert it to a series
# of xinput commands suitable for calibration of a touchscreen in
# upstream Xorg
#
# Copyright (C) 2009 Cory Maccarrone <darkstar6262@gmail.com>
#
#
# This program is free for any use, so long as the above copyright
# notice is maintained.
#
#
# Pointercal files contain a series of 7 numbers:
#
#   a, b, c, d, e, f, s
#
# Together with screen coordinates (Xs, Ys) and device coordinates
# (Xd, Yd), we have the following relation:
#
#   s*Xs = a*Xd + b*Yd + c
#   s*Ys = d*Xd + e*Yd + f
#
# Thus, to get the min/max device values, it's important to know the
# size of the screen.
#
#
#              -b*f + b*s*Ys + c*e - e*s*Xs
# Xd(Xs, Ys) = ----------------------------
#                       b*d - a*e
#
#              a*f - a*s*Ys - c*d + d*s*Xs
# Yd(Xs, Ys) = ---------------------------
#                       b*d - a*e
#
# Where b != 0 and b*d - a*e != 0

POINTERCAL=/etc/pointercal

# Read in the values of pointercal
if [ ! -f "$POINTERCAL" ]; then
    echo "No pointercal file found, aborting"
    exit 1
fi

read A B C D E F S < $POINTERCAL

# Determine the screen resolution
fbset | grep geometry | sed -e 's/.*geometry \([0-9]*\) \([0-9]*\).*/\1 \2/g' > /tmp/fbres
cat /tmp/fbres
read XS YS < /tmp/fbres
rm -f /tmp/fbres

# Calculate the minimum/maximum values
XMAX=$(perl -e "print int((-($B) * ($F) + ($B) * ($S) * ($YS) + ($C) * ($E) - ($E) * ($S) * ($XS)) / (($B) * ($D) - ($A) * ($E)));")
YMAX=$(perl -e "print int((($A) * ($F) - ($A) * ($S) * ($YS) - ($C) * ($D) + ($D) * ($S) * ($XS)) / (($B) * ($D) - ($A) * ($E)));")

XMIN=$(perl -e "print int((-($B) * ($F) + ($B) * ($S) * (0) + ($C) * ($E) - ($E) * ($S) * (0)) / (($B) * ($D) - ($A) * ($E)));")
YMIN=$(perl -e "print int((($A) * ($F) - ($A) * ($S) * (0) - ($C) * ($D) + ($D) * ($S) * (0)) / (($B) * ($D) - ($A) * ($E)));")

# Write out a script suitable for xinit.d
cat << __END__ > pointercal.sh
#!/bin/sh
xinput set-int-prop "MSM touchscreen" "Evdev Axis Calibration" 32 $XMAX $XMIN $YMAX $YMIN
xinput set-int-prop "MSM touchscreen" "Evdev Axis Inversion" 8 0 1
xinput set-int-prop "MSM touchscreen" "Evdev Axes Swap" 8 1
__END__


