#!/bin/bash
#This script attempts to change resolution to the desired mode. 
#Invoke it as "chres 1600x1200" or whatever resolution desired. 
#The resolution must be available - check XF86Config-4 and xvidtune.
#Original script from Case Jones -  philipj AT interchange.ubc.ca
#Modified by Richard Neill - <chres AT richardneill.org>

#N.B. This will switch resolution of the *monitor*, leaving it as a viewport which may be moved around a larger desktop.
# To change the size of the *display* too, use xrandr. In both cases, the size of the KDE *desktop* is unchanged.

if [ $# != 1 ]; then
	echo -e "\aWrong number of arguments. Invoke as 'chres XXXxYYY'"
	exit
fi

NEW_RES=$1				        		#Want this eg 1600x1200 or 800x600.
ORIG_RES=`xvidtune -show |awk '{print $1}'| sed 's/\"//g'` 	#We are here to begin with.

if [ "$NEW_RES" == "$ORIG_RES" ]; then				#Check if we are already there.
	echo Already at $NEW_RES. Nothing changed.
	exit 0
else
	COUNT=0
	while [ "`xvidtune -show |awk '{print $1}'`" != "\"$NEW_RES\"" ] && [ $COUNT -lt 20 ] ; do 
		xvidtune -next;
		COUNT=$(($COUNT+1))				#Cycle resolutions upto 20 times
	done
	if [ $COUNT -lt 20 ]; then	
		echo Switched to $NEW_RES.
		exit 0
	else
		while [ "`xvidtune -show |awk '{print $1}'`" != "\"$ORIG_RES\"" ] ; do 
			xvidtune -next;
		done
		echo -e "\aFailed to locate resolution $NEW_RES after $COUNT attempts. Returned to $ORIG_RES."
		exit 1
	fi
fi
