#!/bin/bash
##################################################################################
## Bashish, a console theme engine
## Copyright (C) 2010 Thomas Eriksson
##
## This program is free software; you can redistribute it and/or
## modify it under the terms of the GNU General Public License
## as published by the Free Software Foundation; either version 2
## of the License, or (at your option) any later version.
##
## This program is distributed in the hope that it will be useful,
## but WITHOUT ANY WARRANTY; without even the implied warranty of
## MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
## GNU General Public License for more details.
## 
##
## along with this program; if not, write to the Free Software
## Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA  02110-1301, USA.
##################################################################################
##
## _bashish_prompt_testloc is a prompt helper
##
## it makes sure that the prompt is never printed below a specified line
## number
##
## USAGE:
## _bashish_prompt_testloc [LINECUT]
##
## LINECUT is the amount of lines from the bottom of the terminal, where the prompt
##         should not be displayed
##
##################################################################################

_bashish_prompt_testloc ()
{
	test "x$1" = x && return 0
	## running background jobs makes the shell spew out I/O error messages. don't go further.
	case $(jobs) in
	*Running*) return 0
	esac
	stty -echo
	printf "\033[6n"
	## $POS is a variable used by several themes, it cannot be declared local
	local i=0 CURPOS="" LINECUT=${1} TOPCUT="${2}" IFS CHAR
	test "x$TOPCUT" = x && TOPCUT=0

	until test "$i" = 7
	do
		CHAR=""
		read -n1 CHAR
		case "$CHAR" in
		|[|[0-9]|\;) CURPOS="$CURPOS$CHAR";let i++;;
		R)CURPOS="$CURPOS$CHAR";break;;
		esac
		#printf $i
	done
	#printf "\033[8D"
	local IFS="[;" i=0
	for POS in $CURPOS
	do
		test $i = 1 && break
		let i++
	done
	IFS=""
	test "$POS" -gt $(($LINES - $LINECUT)) && {
			printf "\n\033["$(($LINES - $LINECUT))";0H"
	}
	test "$POS" -lt "$TOPCUT" && {
		printf "[${2};0H"
	}
	stty echo
}

test x$BASHISH_FNLOAD != x1 && _bashish_prompt_testloc "$@"
