#!/bin/bash
########################################################################
####  Script Name: simple/system graphics installer: sgfxi
####  Debian Sid, Testing, and Stable graphic driver install.
####  New: Ubuntu support in progress. Arch/Fedora Support under development
####  version: 4.24.70
####  Date: 2016-04-19
########################################################################
####  Copyright (C) Harald Hope 2007-2016
####  Code contributions copyright: Latino 2008
####  Contributors: ati card driver and xorg configuration in general: damentz and d2kx
####  function check_ia32_libs by Steven Barrett (damentz, maintainer of zen/liquorix projects).
####  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.
####
####  Get the full text of the GPL here: http://www.gnu.org/licenses/gpl.txt
########################################################################
####  Script URL: http://smxi.org/sg/sgfxi
####  Script GIT: https://github.com/smxi/sgfxi
####  Script Documentation: http://smxi.org/docs/
####  Script Home page: http://techpatterns.com/forums/about933.html
########################################################################
#### DEFINE:
#### TRUE: -eq 0; == 'true'; function return 0
#### FALSE: -gt 0; == ''; function return > 0
########################################################################
####  CONVENTIONS:
####  Indentation: TABS
####  Do not use `....`, those are totally non-reabable, use $(....)
####  Do not use one liner flow controls. The ONLY time you should use ; is in
####  this single case: if [ condition ];then (ie, never: [ condition ] && statement)
####
####  All new code/methods must be in a function.
####  For all boolean tests, use 'true' / 'false'. Do NOT use 0 or 1 unless
####  it's a function return. Avoid complicated tests in the if condition itself.
####
####  VARIABLE/FUNCTION NAMING:
####  All variables should explain what they are, except counters like i, j
####  All variables MUST be initialized / declared explicitly
####, globals UPPER CASE, at top of script, SOME_VARIABLE='' (words separated by _ ).
####  Locals always: local someVariable= (lower case, all except first word started upper case)
####  and at the top of the function. ie: testTrunkData
####
####  Booleans should start with b_ or B_ and state clearly what is being tested
####	Arrays should start with a_ or A_
####  All functions should follow standard naming, ie, verb adjective noun, get_cpu_data
########################################################################
####  TESTING FLAGS
####  sgfxi supports advanced testing triggers to do various things, using -! <arg>
####  -! 1 - triggers default B_TESTING_1='true' - triggers testing data function
####  -! 2 - triggers default B_TESTING_2='true' - triggers post test exit
####  -! 3 - triggers default B_SKIP_FUNCTION='true' to turn off functions for script testing
####  -! 4 - triggers B_TESTING_1='true' and B_TESTING_2='true'
####  -! 5 - triggers B_TESTING_1='true', B_TESTING_2='true', and B_SKIP_FUNCTION='true'
####  -! 6 - triggers B_TESTING_3='true' - overrides xorg/kernel support tests
####  -! 7 - triggers B_TESTING_4='true' - overrides patch tests
####  -! 8 - triggers B_TESTING_5='true' - triggers advanced, beta tests for general script
####  -! 9 - triggers B_TESTING_6='true' - triggers new distro development tests
####  -! 10 - triggers an update from the primary dev download server
####  -! 11 - triggers an update from svn branch one - if present, of course
####  -! 12 - triggers an update from svn branch two - if present, of course
####  -! <http://......> - Triggers an update from whatever server you list.
####  -! 20 - uses patch from svn branch one server (must be in branch/one/patches)
####  -! 21 - uses patch from svn branch two server (must be in branch/two/patches)
########################################################################
####  EXTRA DATA
####  Cross referenced table of package manager commands (apt/yum/pacman etc):
####  https://wiki.archlinux.org/index.php/Pacman_Rosetta
########################################################################
#### VARIABLES
########################################################################

## Distro maintainers: set these variables to meet your needs ##
# maintainers can turn this to false to stop allowing script auto updates. Only set
# to false if this script will be packaged and you want to not allow script auto updates
B_ALLOW_AUTO_UPDATE='true'
# maintainers change this to script default path please to keep things simple if different
SCRIPT_HOME='/usr/local/bin'
SCRIPT_NAME='sgfxi'
SCRIPT_WORKING_DIR="/usr/src/$SCRIPT_NAME-downloads"
SM_KERNEL_DOWNLOADS='/usr/src/sm-kernel-downloads'

# script global data
NON_DEBIAN_PATTERN='(deb-ats|deb-mep|deb-mm|deb-multimedia|deb-op|deb-sdx|deb-skp|deb-swift|deb-vb|alphagemini|aptosid|byteme|cathbard|debian-multimedia|dotdeb|edevelop|eeepc|freevo|giss.tv|google|java|kanotix|kde|kiberpipa|kplayer|lamaresh|liquorix|lxde|mepis|moblock|opera|noreply|prodeia.de|rarewares|rox4debian|siduction|sidux|skype|swiftfox|tovid|videolan|virtualbox|wine-hq|xadras)'

APT_TYPE='apt-get'
CARD='' # card type: fglrx or nvidia
DISTRIB_CODENAME=''
DISTRIB_ID=''
DISTRIB_RELEASE=''
# this is for the run installers, sometimes we may want to pass them an option/arg in specific cases
EXTRA_ARGS=''
FED_KERNEL_PAE=''
NON_FREE_DRIVER=''
SYSTEM_BASE=''
SYSTEM_CODENAME=''
NATIVE_OVERRIDE=''
# this is the actual pattern that will be used to search for this stuff in script
#NATIVE_OVERRIDE_SUPPORTED='ati|i128|i740|i810|i810-modesetting|intel|mga|neomagic|nv|openchrome|radeon|radeonhd|sis|tdfx|vesa|via|vga|voodoo'
# http://blog.mecheye.net/2014/04/xwayland/ - good info on xwayland, and general xorg architecture
NATIVE_OVERRIDE_SUPPORTED='apm|ark|ati|chips|cirrus|fbdev|geode|glide|glint|i128|i740|intel|imstt|mach64|mga|modesetting|neomagic|nsc|openchrome|nouveau|r128|radeon|rendition|s3|s3virge|savage|siliconmotion|sis|sisusb|tdfx|tga|trident|tseng|vesa|vga|via|voodoo|vmware|v4l'
PACKAGE_MANAGER=''
# options: 0 - monochrome; 1 default; more coming?
SCRIPT_COLORS=1
START_OPTIONS_PRINT='' # for output to user of what options they used
START_OPTIONS=''
SUDO_START=''
WITHOUT_RECOMMENDS=''
X_NAME=''

## main script boolean switches
B_AMD='true'
B_AUTORUN='false'
B_BETA_EXISTS='false'
B_BUILD_KERNEL_MODULES='false'
B_CHECK_IA32='false' # if users want, they can disable this feature in config file
B_COMPOSITE='false' 
B_DEFAULT_NATIVE_DRIVER='false'
# I cannot figure out the logic here, this must be some old thing that was used for a specific purpose.
# I think it was an option set here to trigger use distro driver flag, but I don't see why that would
# have been done in the first place, it was probably something very specific.
B_DISTRO_FLAG='false'
B_DISPLAY_DEVICES='false'
B_EXPERIMENTAL='false'
B_EXTRA_EXPERIMENTAL='false'
B_FGLRX_DEB_BUILDER='false'
B_FGLRX_DIRECT='true' # raising the white flag of surrender...
B_FORCE_OPTION='false'
B_FORCE_NO_COMPOSITE='false'
B_FORCE_UPDATE='false'
B_GET_LIVE_DRIVERS='false'
B_GUI_MODE='false'
B_IS_APTOSID_KERNEL='false'
B_IS_XEN='false'
B_KERNEL_MODULE_ONLY='false'
B_LAUNCH_FROM_X='false'
B_LOGGING_STARTED='false'
B_MOVE_X_CONF='false'
B_NATIVE_DRIVER='false'
B_NO_XVMC='false'
B_PRINT_VER='false' # utilities for smxi
B_REMOVE_MODELINES='false'
B_RESTORE_DEFAULTS='false'
# B_RENDER_ACCEL='true' # default use, true
B_SET_IGNOREABI='false'
B_SKIP_AUTOSTART='false' # deprecated, not used
B_SKIP_CONFIG='false'
B_SKIP_CONNECT='false' # deprecated, not used
B_SKIP_GRUB_TEST='false'
B_SKIP_INSTALL='false'
B_SKIP_RESTART='false'
B_SKIP_WGET='false'
B_SKIP_X_QUESTION='false'
B_SKIP_X_TEST='false'
B_SM_INSTALL='false' # utilities for smxi
B_SYSTEMD='false'
B_SYSTEMD_GRAPHICAL='false'
B_SYSTEMD_SYSINIT='false'
B_TRIPLE_BUFFER='false'
B_TWINVIEW='false' # deprecated, commented out use
B_UPDATED='false'
B_UPSTART='false'
B_USE_BETA='false' 
B_USE_DIRECT_KERNEL_HEADER='false' # deprecated, commented out use
B_USE_DISTRO_DRIVER='false'
# force (for nvidia), using old method of kernel source /m-a module build. New default dkms
B_USE_DISTRO_MODULE_MA='false' 
B_USE_EVENTS='true'
B_USE_XVMC='false'
B_XORG_BACKED_UP='false'

## debugger/testing boolean switches
B_SKIP_FUNCTION='false'
B_TESTING_1='false' # triggers testing function
B_TESTING_2='false' # triggers post driver extract/patch exit
B_TESTING_3='false' # overrides testing cases xorg/kernel for driver support
B_TESTING_4='false' # triggers advanced general development testing cases
B_TESTING_5='false' # overrides patch tests
B_TESTING_6='false' # triggers new distro development tests

# kernel variables strings are now evaluated in kernel_string_info().
INSTALL_TO_KERNEL=''
KERNEL_ARCH=''
KERNEL_BASE='' # like: 2.6 or 3
KERNEL_MATH='' # like: 19, for math use
KERNEL_NUMBER='' # like: 2.6.19 or 3.19
KERNEL_FULL='' # full kernel name

# check for 64 bit first
if [ -n "$( uname -m | grep -o 'x86_64' )" ];then
	BITS="64"
else
	BITS="32"
fi

X_VERSION=''
# this handles the 1.x syntax used by newer xorg versions
# it also handles the change in ID text they did with 1.4
# slicing out parts prior to parentheses: X.Org X Server 1.7.7
# NOTE: grep -o behavior has CHANGED! Now it will slice out separate instances, like:
# 1.11
# 2.902
# from one string, like: 1.11.2.902
if [ -n "$( type -p X )" ];then
	X_VERSION=$( X -version 2>&1 | grep -Eis -m 1 '^(X.Org X Server|X Window System)' | cut -d '(' -f 1 | awk '{ print $NF }' | grep -Eo '^[12347]\.[0-9]+(\.[0-9]+)?' )
# some users only want to be running a very light xorg, which won't have X, only Xorg
# Tested and works Debian/Arch
elif [ -n "$( type -p Xorg )" ];then
	# X.Org X Server 1.7.7
	# xorg-server 2:1.7.7-7 (Julien Cristau <jcristau@debian.org>)
	X_VERSION=$( Xorg -version 2>&1 | grep -Eis -m 1 '^(X\.org|xorg)' | cut -d ':' -f 2 | cut -d '(' -f 1 | awk '{ print $NF }' | grep -Eo '^[12347]\.[0-9]+' )
fi
CC=''
GL=''
# specific card types
FGLRX='fglrx'
INTEL='intel'
NEOMAGIC='neomagic'
NVIDIA='nvidia'
TDFX='tdfx'

# Position matters: 1-latest; 2-middle; 3-older; 4-oldest
VERSIONS=''
OTHER_VERSIONS=''
# main url: ftp://download.nvidia.com/XFree86/
# http://us.download.nvidia.com/XFree86/Linux-x86/latest.txt
# 304.88, 310.44, 313.30 fix buffer overflow issue
NV_VERSIONS='361.42:340.96:304.131:173.14.39:96.43.23:71.86.15'
# in case the new ones don't support 3.10 kernel
# NV_VERSIONS='325.15:304.88:173.14.37:96.43.23:71.86.15'
NV_DEFAULT=$( echo $NV_VERSIONS | cut -d ':' -f 1 ) # >= 6xxx
NV_LEGACY_1=$( echo $NV_VERSIONS | cut -d ':' -f 6 ) # old, tnt etc
NV_LEGACY_2=$( echo $NV_VERSIONS | cut -d ':' -f 5 ) # ge4xx cards
NV_LEGACY_3=$( echo $NV_VERSIONS | cut -d ':' -f 4 ) # 5xxx cards
NV_LEGACY_4=$( echo $NV_VERSIONS | cut -d ':' -f 3 ) # 6/7xxx cards
NV_LEGACY_5=$( echo $NV_VERSIONS | cut -d ':' -f 2 ) # 8xxx/21x cards

## beta drivers 
# use null for position (ie, ::) if no newer beta is availablet than current stable
NV_VERSIONS_BETA='364.15:::::'
NV_DEFAULT_BETA=$( echo $NV_VERSIONS_BETA | cut -d ':' -f 1 ) # >= 6xxx
NV_LEGACY_BETA_1=$( echo $NV_VERSIONS_BETA | cut -d ':' -f 6 ) # old, tnt etc
NV_LEGACY_BETA_2=$( echo $NV_VERSIONS_BETA | cut -d ':' -f 5 ) # ge4xx cards
NV_LEGACY_BETA_3=$( echo $NV_VERSIONS_BETA | cut -d ':' -f 4 ) # 5xxx cards
NV_LEGACY_BETA_4=$( echo $NV_VERSIONS_BETA | cut -d ':' -f 3 ) # 6/7xxx cards
NV_LEGACY_BETA_5=$( echo $NV_VERSIONS_BETA | cut -d ':' -f 2 ) # 8xxx/21x cards

# latest quad: http://www.nvidia.com/object/linux_display_archive.html
NV_QUAD=$NV_DEFAULT # no more individual quad drivers
# this is what gets tested, and any other beta drivers remaining
NV_BETA="$NV_VERSIONS_BETA:::"
# stable primary: 355.11
# stable primary: 343.36 346.35 346.47 346.59 349.16 346.72 352.21 352.30 352.41
# stable primary: 325.15 331.20 331.38 331.49 334.21 337.25 340.24 340.32 343.22
# stable primary: 304.60 304.64 310.19 313.18 313.26 313.30 319.17 319.23 319.32
# stable primary: 295.49 295.53 295.59 295.71 302.17 304.30 304.37 304.43 304.51
# stable primary: 280.13 285.05.09 290.10 295.20 295.33 295.40
# stable primary: 275.09.07 275.19 275.21 
# lt stable primary: 346.72 346.82 346.87 352.41 352.55 352.63 361.28 361.42
# lt stable primary: 331.89 340.24 340.32 340.46 340.58 340.65 346.35 346.47 346.59
# lt stable primary: 319.49 319.60 319.82 319.72 331.20 331.38 331.49 331.67 331.79
# lt stable primary: 304.37 304.43 304.51 310.19 310.32 310.40 310.44 319.17 319.23
# lt stable primary: 275.28 275.36 275.43 295.20 295.40 295.49 295.53 295.59 295.71
# stable primary: 270.41.06 270.41.19 
# stable primary: 260.19.12 260.19.21 260.19.29 260.19.36 260.19.44
# stable primary: 256.35 256.44 256.53 
# stable primary: 195.36.08 ( bad, recalled ) 195.36.15 195.36.24 195.36.31
# stable primary: 190.42 190.53 
# stable primary: 185.18.14 185.18.29 185.18.31 185.18.36 
# stable primary: 180.44 180.51 180.60 
# stable primary: 177.82
# stable primary: 100.14.19 169.12
# stable legacy 1: 71.86.06 71.86.09 71.86.11 71.86.13 71.86.14 71.86.15
# stable legacy 2: 96.43.11 96.43.13 96.43.14 96.43.16 96.43.18 96.43.19 96.43.20 96.43.23 (ends with xorg 11/12 support)
# stable legacy 3: 173.14.12 173.14.18 173.14.20 173.14.22 173.14.25 173.14.27 173.14.28 173.14.30
#                  173.14.31 173.14.35 173.14.36 173.14.37 173.14.38 173.14.39 (ends with xorg 1.15 support)
# stable legacy 4: 304.128
# stable legacy 4: 304.64 304.84 304.88 304.108 304.116 304.117 304.119 304.121 304.123 304.125 304.131
# stable legacy 5: 340.24 340.32 340.46 340.58 340.65 340.76 340.93 340.96

# beta/others: 310.14 313.09 319.12 355.06
## note: no earlier 302 or 295 drivers offered because they had a security hole
NV_OTHERS='361.42:361.28:358.16:355.11:352.63:352.55:346.87:346.82:343.36:340.96:340.93:337.25:334.21:331.89:325.15:319.72:313.30:310.44:304.131:304.128:295.71:290.10:285.05.09:280.13:275.43:270.41.19:260.19.44:256.53:195.36.31:190.53:185.18.36:180.60:177.82:173.14.37:169.12:100.14.19:96.43.20:71.86.14'

# distro legacies (default to Debian packages):
NV_DEBIAN_LEGACY_5='340xx'
NV_DEBIAN_LEGACY_4='304xx'
NV_DEBIAN_LEGACY_3='173xx'
NV_DEBIAN_LEGACY_2='96xx'
NV_DEBIAN_LEGACY_1='71xx'
# arch linux
NV_AR_CURRENT=''
NV_AR_LEGACY_5='340xx'304.128
NV_AR_LEGACY_4='304xx'
NV_AR_LEGACY_3='173xx'
NV_AR_LEGACY_2='96xx'
# ubuntu 
NV_UB_CURRENT='343'
NV_UB_LEGACY_5='340'
NV_UB_LEGACY_4='304'
NV_UB_LEGACY_3='173'
NV_UB_LEGACY_2='96'
# fedora
NV_FED_CURRENT="-$NV_DEFAULT" # note this will be out of sync until repo catches up, needs tests
NV_FED_LEGACY_5='-340xx'
NV_FED_LEGACY_4='-304xx'
NV_FED_LEGACY_3='-173xx'
NV_FED_LEGACY_2='-96xx'

# set dynamically in fixes, line 529 or so
NVIDIA_DOWNLOAD_SITE='' 
# needs dynamic assignment because new drivers won't use this in the string
NV_PKG_NO=''
NV_64_ARCH='' # if nvidia changes file name use this

# other options: nothing now
# zip file only: http://support.amd.com/us/gpudownload/embedded/Pages/embedded_linux.aspx
# actual run: http://support.amd.com/us/gpudownload/linux/Pages/radeon_linux.aspx
# IMPORTANT: on function set_download_info the actual path file name is set:
# note, as distressingly usual, amd AGAIN has changed their driver name syntax. 
## Driver data:
# amd has no discipline whatsoever, look at the ridiculous failure to name the f#cking download file
# consistently release to release, clearly this organization is run by incompetents of the highest order.
# hint: use real package numbering and you avoid all this 'legacy/beta' nonsense.
# amd-driver-installer-12-8-x86.x86_64.zip
# amd-driver-installer-catalyst-12.10-x86.x86_64.zip
# amd-driver-installer-catalyst-13.1-linux-x86.x86_64.zip
# amd-driver-installer-catalyst-13.3-beta3-linux-x86.x86_64.zip
# amd-driver-installer-catalyst-13-4-linux-x86.x86_64.zip
# amd-driver-installer-catalyst-13-6-beta-x86.x86_64.zip
# amd-catalyst-13.8-beta1-linux-x86.x86_64.zip 
# Linux_AMD_Catalyst_14.3_Beta_V1.0_B22_March12_2014.zip
# www2.ati.com/drivers/legacy/amd-driver-installer-catalyst-13.1-legacy-linux-x86.x86_64.zip
# www2.ati.com/drivers/beta/amd-driver-installer-catalyst-12.11-beta-x86.x86_64.zip
# www2.ati.com/drivers/linux/amd-driver-installer-catalyst-12.10-x86.x86_64.zip
# www2.ati.com/drivers/beta/amd-driver-installer-catalyst-13.2-beta3-linux-x86.x86_64.zip
# www2.ati.com/drivers/beta/amd-driver-installer-catalyst-13-6-beta-x86.x86_64.zip
# www2.ati.com/drivers/beta/amd-driver-installer-catalyst-13-6-beta-x86.x86_64.zip 
# www2.ati.com/drivers/beta/amd-catalyst-13.8-beta1-linux-x86.x86_64.zip 
# www2.ati.com/drivers/beta/amd-catalyst-13.11-beta-v9.4-linux-x86.x86_64.run.zip
# www2.ati.com/drivers/linux/amd-catalyst-13.12-linux-x86.x86_64.zip
# www2.ati.com/drivers/linux/amd-catalyst-14-4-rev2-linux-x86-x86-64-may6.zip
# www2.ati.com/drivers/linux/linux-amd-catalyst-14.4-rc-v1.0-apr17.zip
# www2.ati.com/drivers/beta/linux-amd-catalyst-14.6-beta-v1.0-may23.zip
FG_VERSIONS='15.12.1:15.11.1:15.9.1'
FG_DEFAULT='15.12.1'
FG_LEGACY_2='' # random releases/xorg support, hard to follow. note as of 2012-1, legacy uses changed paths
# note, the programming supports various formats for these because AMD simply is incapable of 
# making a file name format decision and sticking to it. ie: betav1 beta beta6 and so on.
FG_DEFAULT_BETA=''
FG_BETA="$FG_DEFAULT_BETA:"

# note: amd release a zip file that contains a space in the name, so I'm not spending 
# any more of my time on this group of undisciplined incompetents at this point.
FG_BETA_VERSION='' # legacy, but leaving in case needed in future
#FG_BETA_VERSION='betav1.0'
FGLRX_PACKAGE_PREFIX='' # set to amd or ati, amd is for >= 12-1

### Stable Series: ###
# 13.12.1 14.4.1 14.4.2 14.5.1 14.9.1 14.12.1 15.6.1 15.7.1 15.9.1 15.11.1 15.12.1
# 12-1 12-2 12-3 12-4 12-6 12-7 12.10 13.1 13-4 13.9 13:12
# 11-12 11-11 11-10 11-9 11-8 11-7 11-6 11-5 11-4 11-3 11-2 11-1
# 10-12 10-11 10-10 10-9 10-8 10-7 10-6 10-5 10-4 10-3 10-2 10-1
# 9-12 9-11 9-10 9-9 9-8 9-7 9-6 9-5 9-4 9.2 9-1 8-12 8-11 8-10 8-9 8-8 8-7 8-6 8-5 8-4
### FG Legacy 2: ###
# 12-6 13.1
### Beta Series: ###
# 14.3.14 14.5.2 14.7.1
### Older Betas: ###
# 13.8-beta2
FG_OTHERS='15.12.1:15.11.1:15.9.1:15.7.1:15.6.1:14.12.1:14.9.1:14.5.2:13.12.1:13.12:13.9:13-4:13.1:12.10:12-7:12-6:12-4:12-3:12-2:12-1:11-12:11-11:11-10:11-9:11-8:11-7:11-6:11-5:11-4:11-3:11-2:11-1'

# set to sid/lenny/etch
FG_DISTRIB_ID=''
FG_DISTRIB_CODENAME=''
DRIVER_INSTALL=''
DRIVER_DEFAULT=''
DRIVER_OVERRIDE=''
DRIVER_QUAD=''
DRIVER_BETA=''
# 0 - unsupported completely by any non-free driver
# 1 - nvidia oldest card versions supported / fglrx < x2000 cards
# 2 - nvidia midrange legacy card versions supported
# 3 - nvidia 5xxx cards only
# 100 - fully supported with latest driver
LEGACY_LEVEL=''
DRIVER_FILE=''

# here we're cutting out both card type and version number for cases with > 1 card
# match this, line starts: xx:xx.0 space bus type 300 (VGA compat)/302 (3D cont)/380 (Display cont)
# 00:02.0 0380: 8086:2572 (rev 02)
# 01:00.0 0300: 10de:0221 (rev a1)
CARD_COUNT=$( lspci -n | grep -cE '^[^[:space:]]+\.0[[:space:]]+(0300|0302|0380)' )
#CARD_DATA=$( lspci -n | grep 0300 | cut -d ':' -f 3-4  | cut -d ' ' -f2 )
CARD_DATA=$( lspci -n | grep -E '^[^[:space:]]+\.0[[:space:]]+(0300|0302|0380)' | \
grep -Eio '[a-f0-9]{4}:[a-f0-9]{4}' )
CARD_NUMBER=''
CARD_BRAND=''
# this is reset for multiple gfx cards in select_card()
# " around CARD_DATA is mandatory for avoiding new grep issue
BUS_ID=$( lspci -n | grep "$CARD_DATA" | \
grep -Eio '^[^[:space:]]+[\.:]0' | sed 's/\./:/')

# system paths
EAA='/etc/apt/apt.conf'
EAS='/etc/apt/sources.list'
EXXC='/etc/X11/xorg.conf'
EAR='/etc/arch-release'
EDV='/etc/debian_version'
EDVV='/etc/devuan_version'
EFR='/etc/fedora-release'
EIT='/etc/inittab'
ELR='/etc/lsb-release'
ELRC='/etc/lsb-release-crunchbang'
GRUB1='/boot/grub/menu.lst'
GRUB1_FED='/boot/grub/grub.conf'
GRUB2='/boot/grub/grub.cfg'
GRUBED='/etc/default/grub'
KERNEL_HEADER_DIRECT='/usr/include/linux/kernel.h'
USRS='/usr/src/' 

INSTALL_DIRECTORY=''
FG_WORKING_DIR='fglrx-install'
# file and patch urls
FG_LIVE_DRIVERS='http://smxi.org/sg/data/fg-drivers'
NV_LIVE_DRIVERS='http://people.freedesktop.org/~aplattner/nvidia-versions'
PATCH_DOWNLOAD='http://smxi.org/sg/'
SCRIPT_DOWNLOAD='http://smxi.org/sg/'
SCRIPT_DOWNLOAD_DATA='http://smxi.org/sg/data/'
# alt for some data
# "http://liquorix.net/sgfxi/"
A_BASE_URLS=(
"http://liquorix.net/sgfxi/"
"$SCRIPT_DOWNLOAD_DATA"
)
BASE_INDEX=$(( $( date +%s ) % ${#A_BASE_URLS[@]} ))
SCRIPT_DOWNLOAD_ALT=${A_BASE_URLS[${BASE_INDEX}]}
SCRIPT_DOWNLOAD_VERSION='http://smxi.org/sm/sm-versions'
SCRIPT_DOWNLOAD_DEV='http://techpatterns.com/downloads/distro/'
SCRIPT_DOWNLOAD_BRANCH_1='https://github.com/smxi/sgfxi/raw/one/'
SCRIPT_DOWNLOAD_BRANCH_2='https://github.com/smxi/sgfxi/raw/one/'

ARCH_FGLRX='arch-fglrx'
ARCH_NVIDIA='arch-nvidia'
DEBIAN_FGLRX='debian-fglrx'
DEBIAN_NVIDIA='debian-nvidia'
DISTRO_FGLRX=''
DISTRO_NVIDIA=''
FEDORA_FGLRX='fedora-fglrx'
FEDORA_NVIDIA='fedora-nvidia'
UBUNTU_FGLRX='ubuntu-fglrx'
UBUNTU_NVIDIA='ubuntu-nvidia'

LOG_FILE_DIR="/var/log/$SCRIPT_NAME/"
LOG_FILE="$SCRIPT_NAME.log"
LOGPS='log_function_data ps $FUNCNAME "$( echo $@ )"'
LOGPE='log_function_data pe $FUNCNAME'
LOGUS='log_function_data us $FUNCNAME "$( echo $@ )"'
LOGUE='log_function_data ue $FUNCNAME'

SCRIPT_ROTATE="/etc/logrotate.d/$SCRIPT_NAME"
SM_VALUES="/usr/local/bin/$SCRIPT_NAME-values"

EXPERIMENTAL_XORG_ATI='xserver-xorg-video-ati_6.6.193-1'
EXPERIMENTAL_LIBDRM2='libdrm2_2.4.0~git20070625-1'
EXPERIMENTAL_LIBDRM_DEV='libdrm-dev_2.4.0~git20070625-1'

# this handles two cases: 1 where user logged in directly as 'root', and
# 2, where user su to root.
LOGIN_PID=$( ps | grep ' login' )
if [ "$LOGIN_PID" == '' ];then
	LOGIN_PID=$( ps | grep ' su' )
fi
LOGIN_PID=$( awk '{print $1}' <<< $LOGIN_PID | grep -Eo "^[0-9]+$" )

# do some distro specific tweaks here too. Don't do this if
# distro maintainers have set package defaults above.
if [ -f "$EAR" -a "$B_ALLOW_AUTO_UPDATE" == 'true' ];then
	SCRIPT_HOME='/usr/bin'
fi

# allow user set globals to override script globals
if [ -f $SM_VALUES ];then
	source $SM_VALUES
fi

########################################################################
#### FUNCTIONS: UTILITY TOOLS
########################################################################

### -------------------------------------------------------------------
### test data - only for dev/debugging purposes
### -------------------------------------------------------------------

# only for debugging purposes
set_test_data()
{
	local username=''

	if [ "$B_TESTING_1" == 'true' ];then # set testing directories etc
## NOTE: it's important to start all comments in here at first character for cleanup updater
#		# this is required for testing to make sure we always are starting with true
#		# latest script versions

# 		# note: devs: double check this output to make sure it's your user name
#		username=$( getent passwd 1000|cut -d \: -f1 )
#		SCRIPT_HOME="/home/$username/bin/scripts/sgfxi/dev/"
#		SCRIPT_WORKING_DIR="/home/$username/bin/scripts/sgfxi/dev"
#		# INSTALL_DIRECTORY='' # for stuff like patches etc
#		LOG_FILE_DIR="/home/$username/bin/scripts/sgfxi/dev/logs/"
# 		PATCH_DOWNLOAD='http://smxi.org/sg/'
#		cd $SCRIPT_HOME
#		rm -f $LOG_FILE_DIR$SCRIPT_NAME.log
# 		# sgfxi doesn't support any legacy ATI stuff
# 		CARD_DATA=1002:7280 # fake ati pre x2000 card
# 		CARD_DATA=1002:9442 # fake ati hd2000-hd4xxx
#  		CARD_DATA=1002:9805 # fake ati hd 6250 card
# 		CARD_DATA=10de:0020 # fake nvidia oldest legacy (7x.xx.xx drivers)
# 		CARD_DATA=10de:0280 # fake nvidia mid legacy (9x.xx.xx drivers)
# 		CARD_DATA=10de:0322 # fake nvidia 5xxx legacy (173.xx.xx drivers)
# 		CARD_DATA=10de:0392 # fake nvidia 7xxx legacy (304.xx drivers)
# 		CARD_DATA=10de:0422 # fake nvidia 8-9xxx- (GS 8400)
# 		FG_DEFAULT='8-5'
# 		NV_DEFAULT='177.80'
# 		# set system bits to test 32/64 specific behaviors
# 		BITS=64
# 		# if you want to test for/without aptosid kernels, set to null '' or 'true'
# 		B_IS_APTOSID_KERNEL='false'
# 		# to test patches/error handling for a specific kernel major version,
# 		# ie: 3-7 here
#		KERNEL_BASE=3
#		KERNEL_MATH=14
# 		# values: '' or 'true'
# 		B_IS_XEN='false'
# 		# check for specific system base tests, can be:
# 		# 'sid' 'testing' 'stable' 'etch'
#		SYSTEM_BASE='debian'
# 		SYSTEM_CODENAME='testing'
# 		X_VERSION='1.11' # override for patching etc
# leave this at first character or errors in updater tools will occur
:
	fi
}

### -------------------------------------------------------------------
### driver+kernel support tests, and patch handlers:
### -------------------------------------------------------------------

## these are first to make it easy to update each new driver release support data

# forced overrides for fringe / weird cases, these tests will vary. Note that you can't put this in a subshell
# unless it is only returning a driver, not setting a global flag.
# args: $1 - driver to test
driver_version_hacks()
{
	eval $LOGUS
	local driverUsed=$1 bReturnDriver='false' results='' testData=''
	
	# short term hack because amd hasn't released a stable driver since 13.4 as of 13.11 beta
	case $driverUsed in
		13.9)
			B_USE_BETA='true'
			log_function_data "Forcing beta driver for current with fglrx"
			;;
		331.*)
			testData=$( grep -Es '^[[:space:]]*CONFIG_UIDGID_STRICT_TYPE_CHECKS[[:space:]]*=[[:space:]]*y' \
			/boot/config-${KERNEL_FULL}* )
			# new option for 3.12, we think.
			if [ -n "$testData" ];then
				EXTRA_ARGS='--no-unified-memory'
			fi
			log_function_data "testData: $testData\nForcing nvidia installer option: $EXTRA_ARGS"
			;;
	esac
	
	# make sure that the call either sets globals OR returns a driver, not both.
	if [ "$bReturnDriver" == 'true' ];then
		log_function_data "Driver returned: $driverUsed"
		echo $driverUsed
	fi
	
	eval $LOGUE
}

# args: $1- test type
driver_support_tests()
{
	eval $LOGUS
	# test for binary only tests here
	case $1 in
		supported-driver)
			case $CARD in
				$FGLRX)
					# xorg info: http://www.x.org/wiki/Releases/7.4
					# first dump if legacy level 1 and pre 9-4
					if [ "$LEGACY_LEVEL" -eq 1 -a "$B_USE_DISTRO_DRIVER" != 'true' ];then
						case $DRIVER_DEFAULT in
							8-*|9-1|9.2|9-3)
								: # these drivers are fine
								;;
							*)
								if [ "$B_TESTING_3" != 'true' ];then
									error_handler 221
								fi
								;;
						esac
					fi
					# no hd2xxx-4xxx support now, as of 12-6
					if [ "$LEGACY_LEVEL" -eq 2 -a "$B_USE_DISTRO_DRIVER" != 'true' ];then
						case $DRIVER_DEFAULT in
							8-*|9-*|10-*|11-*|12-[1-5])
								: # these drivers are fine
								;;
							*)
								if [ "$B_TESTING_3" != 'true' ];then
									error_handler 212
								fi
								;;
						esac
					fi
					# amd-catalyst-14.1-betav1.3-linux-x86.x86_64.zip
					case $DRIVER_DEFAULT in
						14.*|15.*)
							FGLRX_PACKAGE_PREFIX='amd-catalyst'
							B_AMD='false'
							;;
						13[-.][8-9]|13[-.]1[0-2]|14[-.]*|15[-.]*)
							FGLRX_PACKAGE_PREFIX='amd-catalyst'
							;;
						13[-.][4-6])
							FGLRX_PACKAGE_PREFIX='amd-driver-installer-catalyst'
							;;
						12[-.]1[0-2]|13[-.][0-3])
							FGLRX_PACKAGE_PREFIX='amd-driver-installer-catalyst'
							;;
						12[-.][1-9])
							FGLRX_PACKAGE_PREFIX='amd-driver-installer'
							;;
						*)
							FGLRX_PACKAGE_PREFIX='ati-driver-installer'
							;;
					esac
					# incredibly, yet another pointless spastic amd file name change
					case $DRIVER_DEFAULT in
						13[-.]*|14[-.]*|15[-.]*)
							FG_POST='linux-'
							;;
					esac
					# test for >= xorg 1.6 support, using a whitelist of current drivers
					# drivers for now until old driver support is dropped, then change to
					# blacklist
					case $X_VERSION in
						1.17*|1.16.99*)
							case $DRIVER_DEFAULT in
								15.9.*|15.1[0-9].*|$DISTRO_FGLRX)
									if [ "$LEGACY_LEVEL" -lt 3 ];then
										if [ "$B_TESTING_3" != 'true' ];then
											error_handler 212
										fi
									fi
									;;
								*)
									if [ "$B_TESTING_3" != 'true' ];then
										error_handler 226
									fi
									;;
							esac
							;;
						1.16*|1.15.99*)
							case $DRIVER_DEFAULT in
								16.*|15.*|14.12.*|$DISTRO_FGLRX)
									if [ "$LEGACY_LEVEL" -lt 3 ];then
										if [ "$B_TESTING_3" != 'true' ];then
											error_handler 212
										fi
									fi
									;;
								*)
									if [ "$B_TESTING_3" != 'true' ];then
										error_handler 226
									fi
									;;
							esac
							;;
						1.15.[0-8].*)
							case $DRIVER_DEFAULT in
								16.*|15.*|14.*|$DISTRO_FGLRX)
									if [ "$LEGACY_LEVEL" -lt 3 ];then
										if [ "$B_TESTING_3" != 'true' ];then
											error_handler 212
										fi
									fi
									;;
								*)
									if [ "$B_TESTING_3" != 'true' ];then
										error_handler 226
									fi
									;;
							esac
							;;
						1.14*)
							case $DRIVER_DEFAULT in
								16.*|15.*|14.*|13[.-][6-9]|13[.-]1[0-2]|$DISTRO_FGLRX)
									if [ "$LEGACY_LEVEL" -lt 3 ];then
										if [ "$B_TESTING_3" != 'true' ];then
											error_handler 212
										fi
									fi
									;;
								*)
									if [ "$B_TESTING_3" != 'true' ];then
										error_handler 226
									fi
									;;
							esac
							;;
						1.13*)
							case $DRIVER_DEFAULT in
								16.*|15.*|14.*|13[-.][3-9]|13[-.]1[0-2]|$DISTRO_FGLRX)
									if [ "$LEGACY_LEVEL" -lt 3 ];then
										if [ "$B_TESTING_3" != 'true' ];then
											error_handler 212
										fi
									fi
									;;
								*)
									if [ "$B_TESTING_3" != 'true' ];then
										error_handler 226
									fi
									;;
							esac
							;;
						1.12*)
							case $DRIVER_DEFAULT in
								16.*|15.*|14.*|13[.-]*|12[-.][6-9]|12[-.]1[0-2]|$DISTRO_FGLRX)
									if [ "$LEGACY_LEVEL" -lt 3 ];then
										if [ "$B_TESTING_3" != 'true' ];then
											error_handler 212
										fi
									fi
									;;
								*)
									if [ "$B_TESTING_3" != 'true' ];then
										error_handler 226
									fi
									;;
							esac
							;;
						1.11*)
							case $DRIVER_DEFAULT in
								16.*|15.*|14.*|13[.-]*|12[.-]*|11-1[0-2]|$DISTRO_FGLRX) 
									: # all other drivers fail to support xorg >= 1.9
									;;
								*)
									if [ "$B_TESTING_3" != 'true' ];then
										error_handler 226
									fi
									;;
							esac
							;;
						1.10*)
							case $DRIVER_DEFAULT in
								16.*|15.*|14.*|13[.-]*|12[.-]*|11-[4-9]|11-1[0-2]|$DISTRO_FGLRX) 
									: # all other drivers fail to support xorg >= 1.9
									;;
								*)
									if [ "$B_TESTING_3" != 'true' ];then
										error_handler 226
									fi
									;;
							esac
							;; 
						1.9.*)
							case $DRIVER_DEFAULT in
								16.*|15.*|14.*|13[.-]*|12[.-]*|11[.-]*|10-1[0-2]|$DISTRO_FGLRX) 
									: # all other drivers fail to support xorg >= 1.9
									;;
								*)
									if [ "$B_TESTING_3" != 'true' ];then
										error_handler 226
									fi
									;;
							esac
							;;
						1.8.*|7.6)
							case $DRIVER_DEFAULT in
								16.*|15.*|14.*|13[.-]*|12[.-]*|11[.-]*|10-[7-9]|10-1[0-2]|$DISTRO_FGLRX) # update when 1.8 is actually supported
									: # all other drivers fail to support xorg >= 1.8
									;;
								*)
									if [ "$B_TESTING_3" != 'true' ];then
										error_handler 226
									fi
									;;
							esac
							;;
						1.7.*|7.5)
							case $DRIVER_DEFAULT in
								16.*|15.*|14.*|13[.-]*|12[.-]*|11[.-]*|10-[4-9]|10-1[0-2]|$DISTRO_FGLRX)
									: # all other drivers fail to support xorg >= 1.7
									;;
								*)
									if [ "$B_TESTING_3" != 'true' ];then
										error_handler 226
									fi
									;;
							esac
							;;
						1.6.*|7.[3-4])
							case $DRIVER_DEFAULT in
								16.*|15.*|14.*|13[.-]*|12[.-]*|11[.-]*|10-*|9-[4-9]|9-1[0-2]|$DISTRO_FGLRX)
									: # all other drivers fail to support xorg >= 1.6
									;;
								*)
									if [ "$B_TESTING_3" != 'true' ];then
										error_handler 226
									fi
									;;
							esac
							;;
					esac
					# handle no aptosid kernel support first for < 2.6.32
					# fglrx is working on all Debian/Liquorix kernels
					# for testing/debugging set this re:
					# http://techpatterns.com/docs/sgfxi-set-test-data.htm
					case $KERNEL_BASE in
						2.6)
							case $KERNEL_MATH in
								2[5-9]|3[0-1])
									if [ "$B_IS_APTOSID_KERNEL" == 'true' ];then
										error_handler 229
									fi
									;;
							esac
							;;
					esac

					# handle libdrm > 2.3 version errors first
					case $DRIVER_DEFAULT in
						8-[4-9]|8-1[0-2]|9-1|9.2|9-[3-5])
							misc_fixes 'drm-2-x-test'
							;;
					esac
					# now the main support tests...
					case $KERNEL_BASE in
						2.6)
							case $KERNEL_MATH in
								26)
									case $DRIVER_DEFAULT in
										8-4|8-5)
											if [ "$B_TESTING_3" != 'true' ];then
												error_handler 234 $KERNEL_NUMBER
											fi
											;;
									esac
									;;
								27)
									case $DRIVER_DEFAULT in
										8-4|8-5|8-6|8-7|8-8|8-9)
											if [ "$B_TESTING_" != 'true' ];then
												error_handler 234 $KERNEL_NUMBER
											fi
											;;
										*)
											: 
											;;
									esac
									;;
								28)
									case $DRIVER_DEFAULT in
										8-4|8-5|8-6|8-7|8-8|8-9)
											if [ "$B_TESTING_3" != 'true' ];then
												error_handler 234 $KERNEL_NUMBER
											fi
											;;
										*)
											: 
											;;
									esac
									;;
								29)
									case $DRIVER_DEFAULT in
										16.*|15.*|14.*|13[.-]*|12[.-]*|11-*|10-*|9.2|9-[3-9]|9-1[0-2]|$DISTRO_FGLRX)
											: 
											;;
										*)
											if [ "$B_TESTING_3" != 'true' ];then
												error_handler 234 $KERNEL_NUMBER
											fi
											;;
									esac
									;;
								30)
									case $DRIVER_DEFAULT in
										16.*|15.*|14.*|13[.-]*|12[.-]*|11-*|10-*|9-8|9-9|9-1[0-2]|$DISTRO_FGLRX)
											: 
											;;
										*)
											if [ "$B_TESTING_3" != 'true' ];then
												error_handler 234 $KERNEL_NUMBER
											fi
											;;
									esac
									;;
								31|32)
									case $DRIVER_DEFAULT in
										16.*|15.*|14.*|13[.-]*|12[.-]*|11-*|10-*|9-1[0-2]|$DISTRO_FGLRX)
											: 
											;;
										*)
											if [ "$B_TESTING_3" != 'true' ];then
												error_handler 234 $KERNEL_NUMBER
											fi
											;;
									esac
									;;
								33)
									case $DRIVER_DEFAULT in
										16.*|15.*|14.*|13[.-]*|12[.-]*|11-*|10-[2-9]|10-1[0-2]|$DISTRO_FGLRX)
											:
											;;
										*)
											if [ "$B_TESTING_3" != 'true' ];then
												error_handler 234 $KERNEL_NUMBER
											fi
											;;
									esac
									;;
								34)
									case $DRIVER_DEFAULT in
										16.*|15.*|14.*|13[.-]*|12[.-]*|11-*|10-[5-9]|10-1[0-2]|$DISTRO_FGLRX)
											:
											;;
										*)
											if [ "$B_TESTING_3" != 'true' ];then
												error_handler 234 $KERNEL_NUMBER
											fi
											;;
									esac
									;;
								35)
									case $DRIVER_DEFAULT in
										16.*|15.*|14.*|13[.-]*|12[.-]*|11-*|10-[8-9]|10-1[0-2]|$DISTRO_FGLRX)
											:
											;;
										*)
											if [ "$B_TESTING_3" != 'true' ];then
												error_handler 234 $KERNEL_NUMBER
											fi
											;;
									esac
									;;
								36|37)
									case $DRIVER_DEFAULT in
										# note: unknown if -11 will support 36, -10 doesn't, assume -12 will
										# patch from Arch works in application, don't know if it really works
										16.*|15.*|14.*|13[.-]*|12[.-]*|11-*|10-1[0-2]|$DISTRO_FGLRX) 
											:
											;;
										*)
											if [ "$B_TESTING_3" != 'true' ];then
												error_handler 234 $KERNEL_NUMBER
											fi
											;;
									esac
									;;
								38)
									case $DRIVER_DEFAULT in
										# note: unknown if -11 will support 36, -10 doesn't, assume -12 will
										# patch from Arch works in application, don't know if it really works
										16.*|15.*|14.*|13[.-]*|12[.-]*|11-*|$DISTRO_FGLRX) 
											:
											;;
										*)
											if [ "$B_TESTING_3" != 'true' ];then
												error_handler 234 $KERNEL_NUMBER
											fi
											;;
									esac
									;;	
								39)
									case $DRIVER_DEFAULT in
										16.*|15.*|14.*|13[.-]*|12[.-]*|11-[6-9]|11-1[0-2]|$DISTRO_FGLRX)
											:
											;;
										*)
										if [ "$B_TESTING_3" != 'true' ];then
											error_handler 234 $KERNEL_NUMBER
										fi
										;;
									esac
									;;
							esac
							# end kernel math
							;;
						3)
							case $KERNEL_MATH in
								0)
									case $DRIVER_DEFAULT in
										16.*|15.*|14.*|13[.-]*|12[.-]*|11-[6-9]|11-1[0-2]|$DISTRO_FGLRX)
											: # do nothing
											;;
										*) # use 225 for beta testing errors
											if [ "$B_TESTING_3" != 'true' ];then
												error_handler 234 $KERNEL_NUMBER
											fi
									esac
									;;
								1)
									case $DRIVER_DEFAULT in
										16.*|15.*|14.*|13[.-]*|12[.-]*|11-[8-9]|11-1[0-2]|$DISTRO_FGLRX)
											: # do nothing
											;;
										*) # use 225 for beta testing errors
											if [ "$B_TESTING_3" != 'true' ];then
												error_handler 234 $KERNEL_NUMBER
											fi
									esac
									;;
								2)
									case $DRIVER_DEFAULT in
										16.*|15.*|14.*|13[.-]*|12[.-]*|$DISTRO_FGLRX)
											: # do nothing
											;;
										*) # use 225 for beta testing errors
											if [ "$B_TESTING_3" != 'true' ];then
												error_handler 234 $KERNEL_NUMBER
											fi
									esac
									;;
								3)
									case $DRIVER_DEFAULT in
										16.*|15.*|14.*|13[.-]*|12-[4-9]|12-1[0-2]|$DISTRO_FGLRX)
											: # do nothing
											;;
										*) # use 225 for beta testing errors
											if [ "$B_TESTING_3" != 'true' ];then
												error_handler 234 $KERNEL_NUMBER
											fi
									esac
									;;
								4)
									case $DRIVER_DEFAULT in
										16.*|15.*|14.*|13[.-]*|12-[7-9]|12-1[0-2]|$DISTRO_FGLRX)
											: # do nothing
											;;
										*) # use 225 for beta testing errors
											if [ "$B_TESTING_3" != 'true' ];then
												error_handler 234 $KERNEL_NUMBER
											fi
									esac
									;;
								5)
									case $DRIVER_DEFAULT in
										16.*|15.*|14.*|13[.-]*|12-9|12-1[0-2]|$DISTRO_FGLRX)
											: # do nothing
											;;
										*) # use 225 for beta testing errors
											if [ "$B_TESTING_3" != 'true' ];then
												error_handler 234 $KERNEL_NUMBER
											fi
									esac
									;;
								6)
									case $DRIVER_DEFAULT in
										16.*|15.*|14.*|13[.-]*|12-9|12-1[0-2]|$DISTRO_FGLRX)
											: # do nothing
											;;
										*) # use 225 for beta testing errors
											if [ "$B_TESTING_3" != 'true' ];then
												error_handler 234 $KERNEL_NUMBER
											fi
									esac
									;;
								7)
									case $DRIVER_DEFAULT in
										# amd release notes say it only supports kernel 3.5, but that's probably wrong
										16.*|15.*|14.*|13[.-][3-9]|13[.-]1[0-2]12.10|$DISTRO_FGLRX)
											: # do nothing
											;;
										*) # use 225 for beta testing errors
											if [ "$B_TESTING_3" != 'true' ];then
												error_handler 234 $KERNEL_NUMBER
											fi
									esac
									;;
								8)
									case $DRIVER_DEFAULT in
										# amd release notes say it only supports kernel 3.5, but that's probably wrong
										16.*|15.*|14.*|13[.-][4-9]|13[.-]1[0-2]|$DISTRO_FGLRX)
											: # do nothing
											;;
										*) # use 225 for beta testing errors
											if [ "$B_TESTING_3" != 'true' ];then
												error_handler 234 $KERNEL_NUMBER
											fi
									esac
									;;
								9)
									case $DRIVER_DEFAULT in
										16.*|15.*|14.*|13[.-][8-9]|13[.-]1[0-2]|$DISTRO_FGLRX)
											: # do nothing
											;;
										*) # use 225 for beta testing errors
											if [ "$B_TESTING_3" != 'true' ];then
												error_handler 234 $KERNEL_NUMBER
											fi
									esac
									;;
								10)
									case $DRIVER_DEFAULT in
										16.*|15.*|14.*|13[.-][8-9]|13[.-]1[0-2]|$DISTRO_FGLRX)
											: # do nothing
											;;
										*) # use 225 for beta testing errors
											if [ "$B_TESTING_3" != 'true' ];then
												error_handler 234 $KERNEL_NUMBER
											fi
									esac
									;;
								11)
									case $DRIVER_DEFAULT in
										16.*|15.*|14.*|13[.-][9]|13[.-]1[0-2]|$DISTRO_FGLRX)
											: # do nothing
											;;
										*) # use 225 for beta testing errors
											if [ "$B_TESTING_3" != 'true' ];then
												error_handler 234 $KERNEL_NUMBER
											fi
									esac
									;;
								12)
									case $DRIVER_DEFAULT in
										16.*|15.*|14.*|13[.-][9]|13[.-]1[0-2]|$DISTRO_FGLRX)
											: # do nothing
											;;
										*) # use 225 for beta testing errors
											if [ "$B_TESTING_3" != 'true' ];then
												error_handler 234 $KERNEL_NUMBER
											fi
									esac
									;;
								13)
									case $DRIVER_DEFAULT in
										16.*|15.*|14.*|13[.-][9]|13[.-]1[0-2]|$DISTRO_FGLRX)
											: # do nothing
											;;
										*) # use 225 for beta testing errors
											if [ "$B_TESTING_3" != 'true' ];then
												error_handler 234 $KERNEL_NUMBER
											fi
									esac
									;;
								14)
									case $DRIVER_DEFAULT in
										16.*|15.*|14.*|$DISTRO_FGLRX)
											: # do nothing
											;;
										*) # use 225 for beta testing errors
											if [ "$B_TESTING_3" != 'true' ];then
												error_handler 234 $KERNEL_NUMBER
											fi
									esac
									;;
								15)
									case $DRIVER_DEFAULT in
										16.*|15.*|14.[5-9].*|14.1[0-2].*|$DISTRO_FGLRX)
											: # do nothing
											;;
										*) # use 225 for beta testing errors
											if [ "$B_TESTING_3" != 'true' ];then
												error_handler 234 $KERNEL_NUMBER
											fi
									esac
									;;
								16)
									case $DRIVER_DEFAULT in
										16.*|15.*|14.9.*|14.1[0-2].*|$DISTRO_FGLRX)
											: # do nothing
											;;
										*) # use 225 for beta testing errors
											if [ "$B_TESTING_3" != 'true' ];then
												error_handler 234 $KERNEL_NUMBER
											fi
									esac
									;;
								17)
									case $DRIVER_DEFAULT in
										16.*|15.*|14.9.*|14.1[0-2].*|$DISTRO_FGLRX)
											: # do nothing
											;;
										*) # use 225 for beta testing errors
											if [ "$B_TESTING_3" != 'true' ];then
												error_handler 234 $KERNEL_NUMBER
											fi
									esac
									;;
								18|19)
									case $DRIVER_DEFAULT in
										16.*|15.*|14.1[0-2].*|$DISTRO_FGLRX)
											: # do nothing
											;;
										*) # use 225 for beta testing errors
											if [ "$B_TESTING_3" != 'true' ];then
												error_handler 234 $KERNEL_NUMBER
											fi
									esac
									;;
							esac
							# end kernel math
							;;
						4)
							case $KERNEL_MATH in
								0)
									case $DRIVER_DEFAULT in
										16.*|15.*|$DISTRO_FGLRX)
											: # do nothing
											;;
										*) # use 225 for beta testing errors
											if [ "$B_TESTING_3" != 'true' ];then
												error_handler 234 $KERNEL_NUMBER
											fi
									esac
									;;
								1)
									case $DRIVER_DEFAULT in
										16.*|15.9.*|15.12.*|$DISTRO_FGLRX)
											: # do nothing
											;;
										*) # use 225 for beta testing errors
											if [ "$B_TESTING_3" != 'true' ];then
												error_handler 234 $KERNEL_NUMBER
											fi
									esac
									;;
								2)
									case $DRIVER_DEFAULT in
										16.*|15.9.*|15.12.*|$DISTRO_FGLRX)
											: # do nothing
											;;
										*) # use 225 for beta testing errors
											if [ "$B_TESTING_3" != 'true' ];then
												error_handler 234 $KERNEL_NUMBER
											fi
									esac
									;;
								3)
									case $DRIVER_DEFAULT in
										16.*|15.12.*|$DISTRO_FGLRX)
											: # do nothing
											;;
										*) # use 225 for beta testing errors
											if [ "$B_TESTING_3" != 'true' ];then
												error_handler 234 $KERNEL_NUMBER
											fi
									esac
									;;
								4)
									case $DRIVER_DEFAULT in
										16.*|15.12.*|$DISTRO_FGLRX)
											: # do nothing
											;;
										*) # use 225 for beta testing errors
											if [ "$B_TESTING_3" != 'true' ];then
												error_handler 234 $KERNEL_NUMBER
											fi
									esac
									;;
							esac
							# end kernel math
							;;
					esac
					;;
				$NVIDIA)
# 					if [ "$DRIVER_DEFAULT" == "$DISTRO_NVIDIA" -a "$SYSTEM_CODENAME" == 'testing' ];then
# 						print_information_continue 'standard' "Your system appears to be Debian Testing based.\nThe $DISTRO_NVIDIA driver cannot build on Debian Testing because of a missing package.\nIf your system is Sid based, continue, otherwise exit now."
# 					else
						# test for >= xorg 1.5 support, using a blacklist now of previous
						# drivers rather than whitelisting
						# xorg info: http://www.x.org/wiki/Releases/7.4
						case $X_VERSION in
							1.[5-9].*|1.10*|2.[0-9]*|7.[4-9])
								case $DRIVER_DEFAULT in
									169.12|100.14.19)
										if [ "$B_TESTING_3" != 'true' ];then
											error_handler 226
										fi
										;;
									# 180.*|177.*|173.14.15|96.43.09|71.86.07
									*)
										: ## support should be working, see feedback
										;;
								esac
								;;
						esac
						# note: the legacy 1 latest should handle xorg 1.7
						case $X_VERSION in
							1.18*|1.17.99*)
								case $DRIVER_DEFAULT in
									364.*|361.*|358.*|355.*|352.*|349.*|340.[8-9][0-9]|304.1[2-9][0-9]|$DISTRO_NVIDIA)
										:
										;;
									*)
										if [ "$B_TESTING_3" != 'true' ];then
											error_handler 226
										fi
										;;
								esac
								;;
							1.17*|1.16.99*)
								case $DRIVER_DEFAULT in
									364.*|361.*|358.*|355.*|352.*|349.*|346.*|343.[3-9][0-9]|340.[6-9][0-9]|304.1[2-9][0-9]|$DISTRO_NVIDIA)
										:
										;;
									*)
										if [ "$B_TESTING_3" != 'true' ];then
											error_handler 226
										fi
										;;
								esac
								;;
							1.16*|1.15.99*)
								# note: 173.14.39 is last legacy 3/5xxx card branch release so xorg support cuts off here
								case $DRIVER_DEFAULT in
									364.*|361.*|358.*|355.*|352.*|349.*|346.*|343.*|340.*|337.*|304.12[3-9]|304.1[3-9]*|$DISTRO_NVIDIA)
										:
										;;
									*)
										if [ "$B_TESTING_3" != 'true' ];then
											error_handler 226
										fi
										;;
								esac
								;;
							1.15.[0-8]*)
								# note: 173.14.39 is last legacy 3/5xxx card branch release so xorg support cuts off here
								case $DRIVER_DEFAULT in
									364.*|361.*|358.*|355.*|352.*|349.*|346.*|343.*|340.*|337.*|334.*|331.*|304.11[7-9]|304.1[2-9][0-9]|173.14.3[9]|$DISTRO_NVIDIA)
										:
										;;
									*)
										if [ "$B_TESTING_3" != 'true' ];then
											error_handler 226
										fi
										;;
								esac
								;;
							1.14*)
								case $DRIVER_DEFAULT in
									364.*|361.*|358.*|355.*|352.*|349.*|346.*|343.*|340.*|337.*|334.*|331.*|325.*|319.*|313.*|31[4-9].[0-9][0-9]|304.[89][0-9]|304.[1-9][0-9][0-9]|310.[4-9][0-9]|173.14.3[7-9]|$DISTRO_NVIDIA)
										:
										;;
									*)
										if [ "$B_TESTING_3" != 'true' ];then
											error_handler 226
										fi
										;;
								esac
								;;
							1.13*)
								case $DRIVER_DEFAULT in
									364.*|361.*|358.*|355.*|352.*|349.*|346.*|343.*|340.*|337.*|334.*|331.*|325.*|319.*|313.*|310.*|304.[3-9][0-9]|304.[1-9][0-9][0-9]|173.14.3[6-9]|$DISTRO_NVIDIA)
										:
										;;
									*)
										if [ "$B_TESTING_3" != 'true' ];then
											error_handler 226
										fi
										;;
								esac
								;;
							1.12*)
								case $DRIVER_DEFAULT in
									364.*|361.*|358.*|355.*|352.*|349.*|346.*|346.*|343.*|340.*|337.*|334.*|331.*|325.*|319.*|313.*|310.*|304.*|302.*|295.[3-9][0-9]|173.14.[3][4-9]|96.43.2[3-9]|$DISTRO_NVIDIA)
										:
										;;
									*)
										if [ "$B_TESTING_3" != 'true' ];then
											error_handler 226
										fi
										;;
								esac
								;;
							1.11*)
								case $DRIVER_DEFAULT in
									364.*|361.*|358.*|355.*|352.*|349.*|346.*|343.*|340.*|337.*|334.*|331.*|325.*|319.*|313.*|310.*|304.*|302.*|295.*|290.*|285.0[5-9].*|173.14.[3][4-9]|96.43.2[3-9]|$DISTRO_NVIDIA)
										:
										;;
									285.03|280.*|275.28)
										B_SET_IGNOREABI='true'
										: # this is speculative but let's see if it works
										;;
									*)
										if [ "$B_TESTING_3" != 'true' ];then
											error_handler 226
										fi
										;;
								esac
								;;
							1.10*)
								case $DRIVER_DEFAULT in
									# not positive about legacy drivers yet
									364.*|361.*|358.*|355.*|352.*|349.*|346.*|343.*|340.*|337.*|334.*|331.*|325.*|319.*|313.*|310.*|304.*|302.*|295.*|290.*|285.*|280.*|275.*|270.*|173.14.3*|96.43.2[0-9]|$DISTRO_NVIDIA)
										: # all other drivers fail to support xorg >= 1.9
										;;
									*)
										if [ "$B_TESTING_3" != 'true' ];then
											error_handler 226
										fi
										;;
								esac
								;;
							1.9.*)
								case $DRIVER_DEFAULT in
									# not positive about 256 series + 1.9, or 96
									364.*|361.*|358.*|355.*|352.*|349.*|346.*|343.*|340.*|337.*|334.*|331.*|325.*|319.*|313.*|310.*|304.*|302.*|295.*|290.*|285.*|280.*|275.*|270.*|260.*|256.*|173.14.3*|173.14.2[89]|96.43.19|96.43.2[0-9]|$DISTRO_NVIDIA)
										: # all other drivers fail to support xorg >= 1.9
										;;
									*)
										if [ "$B_TESTING_3" != 'true' ];then
											error_handler 226
										fi
										;;
								esac
								;;
							1.8.*)
								case $DRIVER_DEFAULT in
									364.*|361.*|358.*|355.*|352.*|349.*|346.*|343.*|340.*|337.*|334.*|331.*|325.*|319.*|313.*|310.*|304.*|302.*|295.*|290.*|285.*|280.*|275.*|270.*|260.*|256.*|195.36.[2-9][0-9]|173.14.3*|173.14.2[789]|96.43.19|96.43.2[0-9]|$DISTRO_NVIDIA)
										: # all other drivers fail to support xorg >= 1.8
										;;
									*)
										if [ "$B_TESTING_3" != 'true' ];then
											error_handler 226
										fi
										;;
								esac
								;;
							1.7.*|7.[5])
								case $DRIVER_DEFAULT in
									364.*|361.*|358.*|355.*|352.*|349.*|346.*|343.*|340.*|337.*|334.*|331.*|325.*|319.*|313.*|310.*|304.*|302.*|295.*|290.*|285.*|280.*|275.*|270.*|260.*|256.*|195.*|190.53|173.14.3*|173.14.2*|96.43.1*|96.43.2*|71.86.1[34567]|$DISTRO_NVIDIA)
										: # all other drivers fail to support xorg >= 1.7
										;;
									*)
										if [ "$B_TESTING_3" != 'true' ];then
											error_handler 226
										fi
										;;
								esac
								;;
							1.6.*|7.[3-4])
# 							1.[6-9]|2.[0-9]|7.[4-9])
								case $DRIVER_DEFAULT in
									71.86.11|71.86.09)
										if [ "$B_TESTING_3" != 'true' ];then
											error_handler 226
										fi
										;;
									*)
										: ## support should be working, see feedback
										;;
								esac
								;;
						esac
						
						# white list of known http downloads, otherwise use ftp, this will be required
						# for any future drivers auto detected beta drivers anyway.
						# driver=71.86.13;wget --spider http://download.nvidia.com/XFree86/Linux-x86/$driver/NVIDIA-Linux-x86-$driver-pkg0.run 
						# default download site for nvidia, return http://us.download if problems
						case $DRIVER_DEFAULT in
							190.53|190.42|185.18.36|180.60|177.82|173.14.2[25]|169.12|100.14.19|96.43.1[46]|71.86.1[134]|71.86.09)
								NVIDIA_DOWNLOAD_SITE='http://download.nvidia.com'
								;;
							343.22|340.46|302.17|285.03|280.13|275.*|173.14.39)
								NVIDIA_DOWNLOAD_SITE='http://us.download.nvidia.com'
								;;
							*)
								NVIDIA_DOWNLOAD_SITE='ftp://download.nvidia.com'
								;;
						esac
						# ftp://download.nvidia.com/XFree86/Linux-x86/256.35/NVIDIA-Linux-x86-256.35.run
						#ftp://download.nvidia.com/XFree86/Linux-x86_64/256.35/NVIDIA-Linux-x86_64-256.35.run
						#ftp://download.nvidia.com/XFree86/Linux-x86_64/256.35/NVIDIA-Linux-x86-256.35.run
						# white list of old path version drivers
						# new download urls, no -pkgx in file name string
						case $DRIVER_DEFAULT in
							# old download urls, with -pkgx in file name string
							195.36.*|190.*|185.18.*|180.60|177.82|173.14.*|169.12|100.14.19|96.43.*|71.86.*)
								# this tweak thanks to ajw1980, who pointed out that pkg2 installs
								# 32 bit compatibility libs in 64 bit without further fuss.
								if [ "$BITS" == '64' ];then
									NV_PKG_NO='-pkg2'
								else
									NV_PKG_NO='-pkg0'
								fi
								;;
						esac
						# handle change to legacy 5xxx level cards
						case $DRIVER_DEFAULT in
							173.*.*|169.12|100.*.*|96.*.*|71.*.*|$DISTRO_NVIDIA)
								:
								;;
							# 180.11|180.08|180.06|177.82|177.80
							*)
								if [ "$LEGACY_LEVEL" -eq 3 ];then
									error_handler 227
								fi
								;;
						esac
						# basic version handling and support tests, unless otherwise reported,
						# $DISTRO_NVIDIA will be supported by default
						case $KERNEL_BASE in
							2.6)
								case $KERNEL_MATH in
									24) # going to try just 2.6.24 links, see if any issues appear
										# this doesn't work on debian kernels
										if [ "$B_IS_APTOSID_KERNEL" == 'true' ];then
											misc_fixes nvidia-24-link # this might always be needed, all cases?
										fi
										;;
									26)
										case $DRIVER_DEFAULT in
											364.*|361.*|358.*|355.*|352.*|349.*|346.*|343.*|340.*|337.*|334.*|331.*|325.*|319.*|313.*|310.*|304.*|302.*|295.*|290.*|285.*|280.*|275.*|270.*|260.*|256.*|195.*|190.*|185.*|180.*|177.*|173.*.*|100.*.*|96.*.*|71.*.*|$DISTRO_NVIDIA)
												: # do nothing
												;;
											*)
												if [ "$B_TESTING_3" != 'true' ];then
													error_handler 234 $KERNEL_NUMBER
												fi
												;;
										esac
										;;
									27)
										case $DRIVER_DEFAULT in
											364.*|361.*|358.*|355.*|352.*|349.*|346.*|343.*|340.*|337.*|334.*|331.*|325.*|319.*|313.*|310.*|304.*|302.*|295.*|290.*|285.*|280.*|275.*|270.*|260.*|256.*|195.*|190.*|185.*|180.*|177.*|173.*.*|100.*.*|96.*.*|71.*.*|$DISTRO_NVIDIA)
												: # do nothing
												;;
											*)
												if [ "$B_TESTING_3" != 'true' ];then
													error_handler 234 $KERNEL_NUMBER
												fi
												;;
										esac
										;;
									28)
										case $DRIVER_DEFAULT in
											364.*|361.*|358.*|355.*|352.*|349.*|346.*|343.*|340.*|337.*|334.*|331.*|325.*|319.*|313.*|310.*|304.*|302.*|295.*|290.*|285.*|280.*|275.*|270.*|260.*|256.*|195.*|190.*|185.*|180.*|177.*|173.14.[23]*|96.43.[12]*|71.86.1*|71.86.09|$DISTRO_NVIDIA)
												: # do nothing
												;;
											*)
												if [ "$B_TESTING_3" != 'true' ];then
													error_handler 234 $KERNEL_NUMBER
												fi
												;;
										esac
										;;
									29)
										case $DRIVER_DEFAULT in
											364.*|361.*|358.*|355.*|352.*|349.*|346.*|343.*|340.*|337.*|334.*|331.*|325.*|319.*|313.*|310.*|304.*|302.*|295.*|290.*|285.*|280.*|275.*|270.*|260.*|256.*|195.*|190.*|185.*|180.*|177.*|173.14.[23]*|96.43.[12]*|71.86.1*|71.86.09|$DISTRO_NVIDIA)
												: # do nothing
												;;
											*) # use 225 for beta testing errors
												if [ "$B_TESTING_3" != 'true' ];then
													error_handler 234 $KERNEL_NUMBER
												fi
												;;
										esac
										;;
									30)
										case $DRIVER_DEFAULT in
											364.*|361.*|358.*|355.*|352.*|349.*|346.*|343.*|340.*|337.*|334.*|331.*|325.*|319.*|313.*|310.*|304.*|302.*|295.*|290.*|285.*|280.*|275.*|270.*|260.*|256.*|195.*|190.*|185.*|173.14.[23]*|96.43.[12]*|71.86.1*|71.86.09|$DISTRO_NVIDIA)
												: # do nothing
												;;
											*) # use 225 for beta testing errors
												if [ "$B_TESTING_3" != 'true' ];then
													error_handler 234 $KERNEL_NUMBER
												fi
												;;
										esac
										;;
									# note: 34 not fully confirmed yet for all drivers/legacy levels
									31|32|33|34)
										case $DRIVER_DEFAULT in
											364.*|361.*|358.*|355.*|352.*|349.*|346.*|343.*|340.*|337.*|334.*|331.*|325.*|319.*|313.*|310.*|304.*|302.*|295.*|290.*|285.*|280.*|275.*|270.*|260.*|256.*|195.*|190.*|185.*|173.14.[23]*|96.43.[12]*|71.86.1*|$DISTRO_NVIDIA)
												: # do nothing
												;;
											*) # use 225 for beta testing errors
												if [ "$B_TESTING_3" != 'true' ];then
													error_handler 234 $KERNEL_NUMBER
												fi
												;;
										esac
										;;
									35|36|37|38)
										# we'll assume the older drivers don't work here
										case $DRIVER_DEFAULT in
											364.*|361.*|358.*|355.*|352.*|349.*|346.*|343.*|340.*|337.*|334.*|331.*|325.*|319.*|313.*|310.*|304.*|302.*|295.*|290.*|285.*|280.*|275.*|270.*|260.*|173.14.[23]*|96.43.[12]*|71.86.1*|$DISTRO_NVIDIA)
												: # do nothing
												;;
											*) # use 225 for beta testing errors
												if [ "$B_TESTING_3" != 'true' ];then
													error_handler 234 $KERNEL_NUMBER
												fi
												;;
										esac
										;;
									39)
										# we'll assume the older drivers don't work here
										case $DRIVER_DEFAULT in
											# note that the current 96xx can be patched if xorg version
											# is old, 1.7, but that's an unusual case
											364.*|361.*|358.*|355.*|352.*|349.*|346.*|343.*|340.*|337.*|334.*|331.*|325.*|319.*|313.*|310.*|304.*|302.*|295.*|290.*|285.*|280.*|275.*|270.*|173.14.[3]*|96.43.[2]*|$DISTRO_NVIDIA)
												: # do nothing
												;;
											*) # use 225 for beta testing errors
												if [ "$B_TESTING_3" != 'true' ];then
													error_handler 234 $KERNEL_NUMBER
												fi
												;;
										esac
										;;
								esac # end KERNEL_MATH
								;;
							3)
								case $KERNEL_MATH in
									0)
										case $DRIVER_DEFAULT in
											364.*|361.*|358.*|355.*|352.*|349.*|346.*|343.*|340.*|337.*|334.*|331.*|325.*|319.*|313.*|310.*|304.*|302.*|295.*|290.*|285.*|280.*|275.*|270.*|173.14.[3]*|96.43.[2]*|$DISTRO_NVIDIA)
												: # do nothing
												;;
											*) # use 225 for beta testing errors
												if [ "$B_TESTING_3" != 'true' ];then
													error_handler 234 $KERNEL_NUMBER
												fi
												;;
										esac
										;;
									1)
										case $DRIVER_DEFAULT in
											364.*|361.*|358.*|355.*|352.*|349.*|346.*|343.*|340.*|337.*|334.*|331.*|325.*|319.*|313.*|310.*|304.*|302.*|295.*|290.*|285.*|173.14.[3]*|96.43.[2]*|$DISTRO_NVIDIA)
												: # do nothing
												;;
											*) # use 225 for beta testing errors
												if [ "$B_TESTING_3" != 'true' ];then
													error_handler 234 $KERNEL_NUMBER
												fi
												;;
										esac
										;;
									2)
										case $DRIVER_DEFAULT in
											364.*|361.*|358.*|355.*|352.*|349.*|346.*|343.*|340.*|337.*|334.*|331.*|325.*|319.*|313.*|310.*|304.*|302.*|295.*|290.*|285.05.09|173.14.[3][0-9]|96.43.[2]*|$DISTRO_NVIDIA)
												: # do nothing
												;;
											*) # use 225 for beta testing errors
												if [ "$B_TESTING_3" != 'true' ];then
													error_handler 234 $KERNEL_NUMBER
												fi
												;;
										esac
										;;
									3)
										case $DRIVER_DEFAULT in
											# note that patches are needed for rc 3.3 kernels, we'll wait
											# http://weltall.heliohost.org/wordpress/2012/01/20/linux-kernel-3-3-rc1-and-nvidia-drivers/
											364.*|361.*|358.*|355.*|352.*|349.*|346.*|343.*|340.*|337.*|334.*|331.*|325.*|319.*|313.*|310.*|304.*|302.*|295.*|173.14.[3][4-9]|96.43.23|$DISTRO_NVIDIA)
												: # do nothing
												;;
											*) # use 225 for beta testing errors
												if [ "$B_TESTING_3" != 'true' ];then
													error_handler 234 $KERNEL_NUMBER
												fi
												;;
										esac
										;;
									4)
										case $DRIVER_DEFAULT in
											364.*|361.*|358.*|355.*|352.*|349.*|346.*|343.*|340.*|337.*|334.*|331.*|325.*|319.*|313.*|310.*|304.*|302.*|295.*|173.14.[3][4-9]|96.43.23|$DISTRO_NVIDIA)
												: # do nothing
												;;
											*) # use 225 for beta testing errors
												if [ "$B_TESTING_3" != 'true' ];then
													error_handler 234 $KERNEL_NUMBER
												fi
												;;
										esac
										;;
									5)
										case $DRIVER_DEFAULT in
											364.*|361.*|358.*|355.*|352.*|349.*|346.*|343.*|340.*|337.*|334.*|331.*|325.*|319.*|313.*|310.*|304.*|302.*|173.14.[3][4-9]|96.43.23|$DISTRO_NVIDIA)
												: # do nothing
												;;
											*) # use 225 for beta testing errors
												if [ "$B_TESTING_3" != 'true' ];then
													error_handler 234 $KERNEL_NUMBER
												fi
												;;
										esac
										;;
									6)
										case $DRIVER_DEFAULT in
											364.*|361.*|358.*|355.*|352.*|349.*|346.*|343.*|340.*|337.*|334.*|331.*|325.*|319.*|313.*|310.*|304.*|173.14.[3][6-9]|96.43.23|$DISTRO_NVIDIA)
												: # do nothing
												;;
											*) # use 225 for beta testing errors
												if [ "$B_TESTING_3" != 'true' ];then
													error_handler 234 $KERNEL_NUMBER
												fi
												;;
										esac
										;;
									7)
										case $DRIVER_DEFAULT in
											# note: 173 probably does not work with 3.7 kernel but wait for error reports.
											364.*|361.*|358.*|355.*|352.*|349.*|346.*|343.*|340.*|337.*|334.*|331.*|325.*|319.*|313.*|310.*|304.[689][0-9]|304.[1-9][0-9][0-9]|173.14.[3][6-9]|$DISTRO_NVIDIA)
												: # do nothing
												;;
											*) # use 225 for beta testing errors
												if [ "$B_TESTING_3" != 'true' ];then
													error_handler 234 $KERNEL_NUMBER
												fi
												;;
										esac
										;;
									8)
										case $DRIVER_DEFAULT in
											364.*|361.*|358.*|355.*|352.*|349.*|346.*|343.*|340.*|337.*|334.*|331.*|325.*|319.*|313.*|310.*|304.[89][0-9]|304.[1-9][0-9][0-9]|173.14.[3][6-9]|$DISTRO_NVIDIA)
												: # do nothing
												;;
											*) # use 225 for beta testing errors
												if [ "$B_TESTING_3" != 'true' ];then
													error_handler 234 $KERNEL_NUMBER
												fi
												;;
										esac
										;;
									9)
										case $DRIVER_DEFAULT in
											364.*|361.*|358.*|355.*|352.*|349.*|346.*|343.*|340.*|337.*|334.*|331.*|325.*|319.*|313.*|310.*|304.[89][0-9]|304.[1-9][0-9][0-9]|173.14.[3-9][6-9]|$DISTRO_NVIDIA)
												: # do nothing
												;;
											*) # use 225 for beta testing errors
												if [ "$B_TESTING_3" != 'true' ];then
													error_handler 234 $KERNEL_NUMBER
												fi
												;;
										esac
										;;
									10)
										case $DRIVER_DEFAULT in
											364.*|361.*|358.*|355.*|352.*|349.*|346.*|343.*|340.*|337.*|334.*|331.*|325.*|319.[4-9][0-9]|304.[89][0-9]|304.[1-9][0-9][0-9]|173.14.[3-9][0-9]|$DISTRO_NVIDIA)
												: # do nothing
												;;
											*) # use 225 for beta testing errors
												if [ "$B_TESTING_3" != 'true' ];then
													error_handler 234 $KERNEL_NUMBER
												fi
												;;
										esac
										;;
									11)
										case $DRIVER_DEFAULT in
											364.*|361.*|358.*|355.*|352.*|349.*|346.*|343.*|340.*|337.*|334.*|331.*|325.*|319.[4-9][0-9]|304.1[0-9][0-9]|173.14.[3-9][0-9]|$DISTRO_NVIDIA)
												# trigger installer flag if needed
												driver_version_hacks "$DRIVER_DEFAULT"
												;;
											*) # use 225 for beta testing errors
												if [ "$B_TESTING_3" != 'true' ];then
													error_handler 234 $KERNEL_NUMBER
												fi
												;;
										esac
										;;
									12)
										case $DRIVER_DEFAULT in
											364.*|361.*|358.*|355.*|352.*|349.*|346.*|343.*|340.*|337.*|334.*|331.*|325.*|319.[6-9][0-9]|304.1[0-9][0-9]|173.14.[3-9][0-9]|$DISTRO_NVIDIA)
												# trigger installer flag if needed
												driver_version_hacks "$DRIVER_DEFAULT"
												;;
											*) # use 225 for beta testing errors
												if [ "$B_TESTING_3" != 'true' ];then
													error_handler 234 $KERNEL_NUMBER
												fi
												;;
										esac
										;;
									13)
										# echo driver default $DRIVER_DEFAULT
										case $DRIVER_DEFAULT in
											# waiting for patches and confirmations
											364.*|361.*|358.*|355.*|352.*|349.*|346.*|343.*|340.*|337.*|334.*|331.3[89]|331.[4-9][0-9]|304.119|304.[1-9][2-9][0-9]|$DISTRO_NVIDIA)
												# trigger installer flag if needed
												driver_version_hacks "$DRIVER_DEFAULT"
												;;
											331.*|319.[6-9][0-9]|304.1[0-9][0-9]|173.14.[3-9][0-9]|$DISTRO_NVIDIA)
												# trigger installer flag if needed
												echo "${M}Waiting for a full working ${C}3.13 kernel${M} driver patch!${N}"
												if [ "$B_TESTING_3" != 'true' ];then
													error_handler 234 $KERNEL_NUMBER
												fi
												driver_version_hacks "$DRIVER_DEFAULT"
												;;
											*) # use 225 for beta testing errors
												if [ "$B_TESTING_3" != 'true' ];then
													error_handler 234 $KERNEL_NUMBER
												fi
												;;
										esac
										;;
									14)
										# echo driver default $DRIVER_DEFAULT
										case $DRIVER_DEFAULT in
											# waiting for patches and confirmations
											364.*|361.*|358.*|355.*|352.*|349.*|346.*|343.*|340.*|337.*|334.*|331.[4-9][0-9]|304.[1-9][2-9][0-9]|$DISTRO_NVIDIA)
												# trigger installer flag if needed
												driver_version_hacks "$DRIVER_DEFAULT"
												;;
											*) # use 225 for beta testing errors
												if [ "$B_TESTING_3" != 'true' ];then
													error_handler 234 $KERNEL_NUMBER
												fi
												;;
										esac
										;;
									15)
										# echo driver default $DRIVER_DEFAULT
										case $DRIVER_DEFAULT in
											# waiting for patches and confirmations
											364.*|361.*|358.*|355.*|352.*|349.*|346.*|343.*|340.*|304.[1-9][2-9][0-9]|$DISTRO_NVIDIA)
												# trigger installer flag if needed
												driver_version_hacks "$DRIVER_DEFAULT"
												;;
											*) # use 225 for beta testing errors
												if [ "$B_TESTING_3" != 'true' ];then
													error_handler 234 $KERNEL_NUMBER
												fi
												;;
										esac
										;;
									16|17)
										# echo driver default $DRIVER_DEFAULT
										case $DRIVER_DEFAULT in
											# waiting for patches and confirmations
											364.*|361.*|358.*|355.*|352.*|349.*|346.*|343.*|340.*|304.[1-9][2-9][0-9]|$DISTRO_NVIDIA)
												# trigger installer flag if needed
												driver_version_hacks "$DRIVER_DEFAULT"
												;;
											*) # use 225 for beta testing errors
												if [ "$B_TESTING_3" != 'true' ];then
													error_handler 234 $KERNEL_NUMBER
												fi
												;;
										esac
										;;
									18)
										# echo driver default $DRIVER_DEFAULT
										case $DRIVER_DEFAULT in
											# waiting for patches and confirmations
											364.*|361.*|358.*|355.*|352.*|349.*|346.*|343.*|340.[6-9][0-9]|340.[1-9][0-9][0-9]|304.[1-9][2-9][0-9]|$DISTRO_NVIDIA)
												# trigger installer flag if needed
												driver_version_hacks "$DRIVER_DEFAULT"
												;;
											*) # use 225 for beta testing errors
												if [ "$B_TESTING_3" != 'true' ];then
													error_handler 234 $KERNEL_NUMBER
												fi
												;;
										esac
										;;
									19)
										# echo driver default $DRIVER_DEFAULT
										case $DRIVER_DEFAULT in
											# waiting for patches and confirmations
											364.*|361.*|358.*|355.*|352.*|349.*|346.*|340.[7-9][0-9]|340.[1-9][0-9][0-9]|304.[1-9][2-9][0-9]|$DISTRO_NVIDIA)
												# trigger installer flag if needed
												driver_version_hacks "$DRIVER_DEFAULT"
												;;
											*) # use 225 for beta testing errors
												if [ "$B_TESTING_3" != 'true' ];then
													error_handler 234 $KERNEL_NUMBER
												fi
												;;
										esac
										;;
								esac
								# end KERNEL_MATH
								;;
							4)
								case $KERNEL_MATH in
									0)
										case $DRIVER_DEFAULT in
											364.*|361.*|358.*|355.*|352.*|349.*|346.*|340.[7-9][0-9]|340.[1-9][0-9][0-9]|304.[1-9][2-9][0-9]|$DISTRO_NVIDIA)
												: # do nothing
												;;
											*) # use 225 for beta testing errors
												if [ "$B_TESTING_3" != 'true' ];then
													error_handler 234 $KERNEL_NUMBER
												fi
												;;
										esac
										;;
									1) # reports build failure with 340.46 AND 340.93 but some work with 340.93
										case $DRIVER_DEFAULT in
											364.*|361.*|358.*|355.*|352.*|340.9[3-9]|340.[1-9][0-9][0-9]|304.12[89]|304.1[3-9][0-9]|$DISTRO_NVIDIA)
												: # do nothing
												;;
											*) # use 225 for beta testing errors
												if [ "$B_TESTING_3" != 'true' ];then
													error_handler 234 $KERNEL_NUMBER
												fi
												;;
										esac
										;;
									2) # reports build failure with 340.46 AND 340.93
										case $DRIVER_DEFAULT in
											364.*|361.*|358.*|355.*|352.*|340.9[3-9]|340.[1-9][0-9][0-9]|304.12[89]|304.1[3-9][0-9]|$DISTRO_NVIDIA)
												: # do nothing
												;;
											*) # use 225 for beta testing errors
												if [ "$B_TESTING_3" != 'true' ];then
													error_handler 234 $KERNEL_NUMBER
												fi
												;;
										esac
										;;
									3) # reports build failure with 340.46
										case $DRIVER_DEFAULT in
											364.*|361.*|358.*|355.*|352.*|340.9[6-9]|340.[1-9][0-9][0-9]|304.12[89]|304.1[3-9][0-9]|$DISTRO_NVIDIA)
												: # do nothing
												;;
											*) # use 225 for beta testing errors
												if [ "$B_TESTING_3" != 'true' ];then
													error_handler 234 $KERNEL_NUMBER
												fi
												;;
										esac
										;;
									4) # reports build failure with 340.46
										case $DRIVER_DEFAULT in
											364.*|361.*|358.*|355.*|340.9[6-9]|340.[1-9][0-9][0-9]|304.1[3-9][0-9]|$DISTRO_NVIDIA)
												: # do nothing
												;;
											*) # use 225 for beta testing errors
												if [ "$B_TESTING_3" != 'true' ];then
													error_handler 234 $KERNEL_NUMBER
												fi
												;;
										esac
										;;
								esac
								# end KERNEL_MATH
								;;
						esac
# 					fi
					;;
			esac
			;;
		nvidia-supported-driver)
			:
			;;
		ati-supported-driver)
			:
			;;
	esac
	eval $LOGUE
}

# these patch calls used to be in lib files but this is cleaner/simpler long term
# args: $1 - [optional] standard (implied)/test
check_patch_driver()
{
	eval $LOGPS
	local patchFile=''

	case $CARD in
		$NVIDIA)
			case $KERNEL_BASE in
				2.6)
					case $KERNEL_MATH in
						28)
							case $DRIVER_DEFAULT in
								177.80)
									# post 21:http://www.nvnews.net/vbulletin/showthread.php?t=121790
									patchFile='NVIDIA_2.6.28-177.80-2990799.diff'
									apply_patch_file $patchFile "$1"
									;;
								177.82)
									# post 44: http://www.nvnews.net/vbulletin/showthread.php?t=121790&page=2
									patchFile='NVIDIA_2.6.28-177.82.diff'
									apply_patch_file $patchFile "$1"
									;;
							esac
							;;
						30)
							case $DRIVER_DEFAULT in
								71.86.09)
									# post 1:  http://www.nvnews.net/vbulletin/showthread.php?t=133990
									# alt: http://www.nvnews.net/vbulletin/showthread.php?p=1984486
									patchFile='NVIDIA_96.43.11-2.6.30.diff'
									apply_patch_file $patchFile "$1"
									;;
								185.18.*)
									#http://www.nvnews.net/vbulletin/showthread.php?t=133112
									patchFile='NVIDIA-185.18.14-2.6.30.diff'
									apply_patch_file $patchFile "$1"
									;;
							esac
							;;
						31)
							case $DRIVER_DEFAULT in
								185.18.*)
									#http://www.nvnews.net/vbulletin/showthread.php?t=133112
									patchFile='NVIDIA-185.18.14-2.6.30.diff'
									apply_patch_file $patchFile "$1"
									;;
							esac
							;;
						32|33)
							# test if the /generated directory exists, if it does, then use patch.
							if [ -n "$( misc_fixes linux-generated-patch )" -o "$B_TESTING_4" == 'true' ];then
								case $DRIVER_DEFAULT in
									# this is fixed in newest beta, it does auto testing for /generated/
									195.30)
										# http://www.nvnews.net/vbulletin/showthread.php?t=142794&page=2#20
										patchFile='NVIDIA-195-2.6.33.diff'
										apply_patch_file $patchFile "$1"
										;;
									190.53) # won't be needed for new version, it will be fixed
										# http://www.nvnews.net/vbulletin/showthread.php?t=142794&page=2#20
										patchFile='NVIDIA-190.53-2.6.33.diff'
										apply_patch_file $patchFile "$1"
										;;
								esac
							fi
							;;
					esac
					;;
				3)
					case $KERNEL_MATH in
						7)
							case $DRIVER_DEFAULT in
								# patch from kmathern: http://techpatterns.com/forums/about2234-10.html
								# current live patch: https://447566.bugs.gentoo.org/attachment.cgi?id=336106
								173.14.36)
									run_prepatch_fixes '3.7-path-fix'
									# patchFile='NVIDIA_173.14.36_3.7.patch'
									patchFile='NVIDIA_173.14.36_3.7.patch'
									apply_patch_file $patchFile "$1"
									;;
								#patch url: http://www.lwfinger.com/nvidia_patches/patch_nvidia_304_60.run_for_3.7
								# current patch: https://447566.bugs.gentoo.org/attachment.cgi?id=338262
								304.6[04])
									run_prepatch_fixes '3.7-path-fix'
									patchFile='NVIDIA_304_60_3.7.patch'
									apply_patch_file $patchFile "$1"
									;;
								# requires patch to run on kernels > 3.7.5 but 313.18 patch does not work
								310.*)
									run_prepatch_fixes '3.7-path-fix'
									#patchFile='NVIDIA-uapi-313.18_kernel-3.7-8.patch'
									# apply_patch_file $patchFile
									;;
								# patch url: https://bugs.gentoo.org/show_bug.cgi?id=447566
								313.18)
									run_prepatch_fixes '3.7-path-fix'
									# patchFile='NVIDIA-uapi-310-313_kernel-3.7.patch'
									patchFile='NVIDIA_313.18-3.8.patch' "$1"
									apply_patch_file $patchFile
									;;
							esac
							;;
						8)
							case $DRIVER_DEFAULT in
								# patch from kmathern: http://techpatterns.com/forums/about2234-10.html
								# current live patch: https://447566.bugs.gentoo.org/attachment.cgi?id=336106
								173.14.36)
									run_prepatch_fixes '3.7-path-fix'
									# patchFile='NVIDIA_173.14.36_3.7.patch'
									patchFile='NVIDIA-173.14.36-3.8.patch'
									apply_patch_file $patchFile "$1"
									;;
								#patch url: http://www.lwfinger.com/nvidia_patches/patch_nvidia_304_60.run_for_3.7
								# current patch: https://447566.bugs.gentoo.org/attachment.cgi?id=338262
								304.6[04])
									run_prepatch_fixes '3.7-path-fix'
									patchFile='NVIDIA_304.64-3.8.patch'
									apply_patch_file $patchFile "$1"
									;;
								# patch url: https://bugs.gentoo.org/show_bug.cgi?id=447566
								313.18)
									run_prepatch_fixes '3.7-path-fix'
									patchFile='NVIDIA_313.18-3.8.patch'
									apply_patch_file $patchFile "$1"
									;;
							esac
							;;
						10)
							case $DRIVER_DEFAULT in
								# patch from kmathern: 
								# current live patch: http://techpatterns.com/forums/about2308.html
								173.14.37)
									#run_prepatch_fixes '3.7-path-fix'
									# patchFile='NVIDIA_173.14.36_3.7.patch'
									patchFile='NVIDIA-173.14.37-3.10.patch'
									apply_patch_file $patchFile "$1"
									;;
								#patch url: https://devtalk.nvidia.com/default/topic/549532/linux-3-10-incompatibility-in-function-lsquo-nv_i2c_del_adapter-rsquo-error-void-value-not-igno/
								# rjmx post 13
								304.88)
									#run_prepatch_fixes '3.7-path-fix'
									patchFile='NVIDIA-304.88-3.10.patch'
									apply_patch_file $patchFile "$1"
									;;
								#patch url: https://bugzilla.kernel.org/attachment.cgi?id=102881
								319.32)
									#run_prepatch_fixes '3.7-path-fix'
									patchFile='NVIDIA-319.32-3.10.patch'
									apply_patch_file $patchFile "$1"
									;;
								# patch url: https://devtalk.nvidia.com/cmd/default/download-comment-attachment/58795/
								325.08)
									#run_prepatch_fixes '3.7-path-fix'
									patchFile='NVIDIA-325.08-3.10.patch'
									apply_patch_file $patchFile "$1"
									;;
							esac
							;;
						11|12)    
							case $DRIVER_DEFAULT in
								# old patch url: https://devtalk.nvidia.com/default/topic/616962/331-13-beta-drivers-feedback-thread/?offset=15
								# old patch: NVIDIA-331.13-3.11.patch
								## new patch url:  https://devtalk.nvidia.com/default/topic/628864/unix-graphics-announcements-and-news/num_physpages-and-support-for-3-11-and-later-kernels
								331.13|331.17|325.15)
									patchFile='NVIDIA-3.11-get_num_physpages_325-331.patch'
									apply_patch_file $patchFile "$1"
									;;
								# patch url: http://cvs.rpmfusion.org/viewvc/*checkout*/rpms/nvidia-kmod/devel/kernel_v3.11.patch?revision=1.2&root=nonfree
								# https://devtalk.nvidia.com/default/topic/602829/-solved-nvidia-linux-3-11-compatibility-error-lsquo-num_physpages-rsquo-undeclared-first-use-i/
								# old patch: NVIDIA_325.19-3.11.patch
								319.60|319.49)
									#run_prepatch_fixes '3.7-path-fix'
									patchFile='NVIDIA-3.11-get_num_physpages_319.patch'
									apply_patch_file $patchFile "$1"
									;;
								304.108)
									#run_prepatch_fixes '3.7-path-fix'
									# old patch: NVIDIA_304.108-3.11.patch
									patchFile='NVIDIA-3.11-get_num_physpages_304.patch'
									apply_patch_file $patchFile "$1"
									;;
							esac
							;;
						13)    
							case $DRIVER_DEFAULT in
								## patch url: https://devtalk.nvidia.com/default/topic/686157/linux/334-16-won-t-compile-for-linux-v3-13-patch-included-/2/
								334.16)
									patchFile='NVIDIA-334.16-3.0-3.14.patch'
									apply_patch_file $patchFile "$1"
									;;
								## patch url: http://cvs.rpmfusion.org/viewvc/rpms/nvidia-kmod/devel/nvidia_3.13_kernel.patch?revision=1.3&root=nonfree&view=markup
								331.38)
									patchFile='NVIDIA-331.38-3.13.patch'
									apply_patch_file $patchFile "$1"
									;;
								304.119)
									patchFile='NVIDIA-304.119-3.13.patch'
									apply_patch_file $patchFile "$1"
									;;
							esac
							;;
						14)    
							case $DRIVER_DEFAULT in
								# patch url: https://devtalk.nvidia.com/default/topic/699422/nvidia-linux-334-21-drivers/?offset=4
								334.21|331.49)
									patchFile='NVIDIA-334.21-3.14.patch'
									apply_patch_file $patchFile "$1"
									;;
								## patch url: https://devtalk.nvidia.com/default/topic/686157/linux/334-16-won-t-compile-for-linux-v3-13-patch-included-/2/
								334.16)
									patchFile='NVIDIA-334.16-3.0-3.14.patch'
									apply_patch_file $patchFile "$1"
									;;
								## patch url: http://cvs.rpmfusion.org/viewvc/rpms/nvidia-kmod/devel/nvidia_3.13_kernel.patch?revision=1.3&root=nonfree&view=markup
								331.38)
									patchFile='NVIDIA-331.38-3.13.patch'
									apply_patch_file $patchFile "$1"
									;;
								304.119)
									patchFile='NVIDIA-304.119-3.13.patch'
									apply_patch_file $patchFile "$1"
									;;
							esac
							;;
						15)    
							case $DRIVER_DEFAULT in
								# patch url: https://devtalk.nvidia.com/default/topic/699422/nvidia-linux-334-21-drivers/?offset=4
								334.21|331.49)
									patchFile='NVIDIA-334.21-3.14.patch'
									apply_patch_file $patchFile "$1"
									;;
								304.119)
									patchFile='NVIDIA-304.119-3.13.patch'
									apply_patch_file $patchFile "$1"
									;;
							esac
							;;
					esac
					;;
			esac
			;;
		$FGLRX)
			case $KERNEL_BASE in
				2.6)
					case $KERNEL_MATH in
						25|26)
							case $DRIVER_DEFAULT in
		# 						8-4|8-5)
		# 							# debian kernls work normally, no patch required
		# 							# note: due to concerns raised, this patch is not going to be used
		# 							if [ "$B_IS_APTOSID_KERNEL" == 'true' ]
		# 							then
		# 								# pre patch link required, just to keep the information for future reference:
		# 								ln -s arch/x86/usr/X11R6/lib/libfglrx_gamma.so.1.0 arch/x86/usr/X11R6/lib/libfglrx_gamma.so.1
		# 								ln -s arch/x86_64/usr/X11R6/lib64/libfglrx_gamma.so.1.0 arch/x86_64/usr/X11R6/lib64/libfglrx_gamma.so.1
		# 								patchFile=''
		# 								#apply_patch_file $patchFile
		# 							fi
		# 							;;
								8-6)
									patchFile='0001-catalyst-8.6-linux-2.6.26.patch'
									apply_patch_file $patchFile "$1"
									patchFile='0002-catalyst-8.6-linux-2.6.26.patch'
									apply_patch_file $patchFile "$1"
									patchFile='0003-catalyst-8.6-linux-2.6.26.patch'
									apply_patch_file $patchFile "$1"
									;;
								8-7)
									# patch url: http://bugs.gentoo.org/attachment.cgi?id=161335
									# found at: http://bugs.gentoo.org/show_bug.cgi?id=232609
									patchFile='FGLRX-8.7-2.6.26.patch'
									# this one is crap, bad hunks
									#patchFile='FGLRX-0004-Linux-2.6.26.x-kernels-support.patch'
									apply_patch_file $patchFile "$1"
									;;
							esac
							;;
						29)
							case $DRIVER_DEFAULT in
								9.2|9-3|9-4|9-5|9-6|9-7)
									# src: http://www.phoronix.com/forums/showthread.php?t=15165
									patchFile='FGLRX-2.6.29-9.2-5.diff'
									apply_patch_file $patchFile "$1"
									:
									;;
							esac
							;;
						30)
							case $DRIVER_DEFAULT in
								9-6)
									if [ "$B_TESTING_3" == 'true' ];then
										patchFile='FGLRX-2.6.30-9-6.diff'
										apply_patch_file $patchFile "$1"
									fi
									;;
								esac
							;;
						32)
							case $DRIVER_DEFAULT in
								9-11|9-12)
									patchFile='FGLRX-2.6.32-9-11.diff'
									apply_patch_file $patchFile "$1"
									;;
							esac
							;;
						33)
							# these handle that /generated/ path change in kernel headers
							# test if the /generated directory exists, if it does, then use patch.
							if [ -n "$( misc_fixes linux-generated-patch )" -o "$B_TESTING_4" == 'true' ];then
								case $DRIVER_DEFAULT in
									10-2)
										patchFile='FGLRX-2.6.33-10-2.diff'
										apply_patch_file $patchFile "$1"
										;;
									10-[3-5])
										patchFile='FGLRX-2.6.33-10-x.diff'
										apply_patch_file $patchFile "$1"
										;;
								esac
							fi
							;; 
						34)
							# these handle that /generated/ path change in kernel headers
							# test if the /generated directory exists, if it does, then use patch.
							if [ -n "$( misc_fixes linux-generated-patch )" -o "$B_TESTING_4" == 'true' ];then
								case $DRIVER_DEFAULT in
									10-[4-5])
										patchFile='FGLRX-2.6.33-10-x.diff'
										apply_patch_file $patchFile "$1"
										patchFile='FGLRX-2.6.34-rc4-10-4.diff'
										apply_patch_file $patchFile "$1"
										;;
									10-[6])
		# 								patchFile='FGLRX-2.6.33-10-x.diff' # fails
		# 								apply_patch_file $patchFile
										patchFile='FGLRX-2.6.34-rc4-10-4.diff' # works
										apply_patch_file $patchFile "$1"
										;;
								esac
							fi
							;; 
						36|37)
							case $DRIVER_DEFAULT in
								10-1[0-2]) # run this for -11 too maybe it will work
									patchFile='FGLRX-2.6.36-10-10.diff'
									apply_patch_file $patchFile "$1"
									patchFile='FGLRX-2.6.36-10-10-makefile-compat.diff'
									apply_patch_file $patchFile "$1"
									;;
							esac
							;;
					esac
					;;
				3)
					case $KERNEL_MATH in
						7|8)
							case $DRIVER_DEFAULT in
								#patch url: http://catalyst.apocalypsus.net/files/arch-fglrx-3.7.patch
								12.10|13.1)
									run_prepatch_fixes '3.7-path-fix'
									patchFile='FGLRX-12.10-3.7.patch'
									apply_patch_file $patchFile "$1"
									;;
							esac
							:
							;;
						10)
							case $DRIVER_DEFAULT in
								#patch url: http://catalyst.apocalypsus.net/files/arch-fglrx-3.7.patch
								13.9)
									# run_prepatch_fixes '3.7-path-fix'
									patchFile='FGLRX_13.9-3.10.patch'
									apply_patch_file $patchFile "$1"
									;;
							esac
							;;
						11)
							case $DRIVER_DEFAULT in
								#patch url: http://catalyst.apocalypsus.net/files/arch-fglrx-3.7.patch
								13.9)
									# run_prepatch_fixes '3.7-path-fix'
									patchFile='FGLRX_13.9-3.10.patch'
									apply_patch_file $patchFile "$1"
									;;
								# patch url: http://phoronix.com/forums/showthread.php?91885-AMD-Catalyst-13-12-GPU-Driver-For-Linux-Released&p=381943#post381943
								13.12)
									patchFile='FGLRX_13.12-3.11-3.13.patch'
									apply_patch_file $patchFile "$1"
									;;
							esac
							;;
						12|13)
							case $DRIVER_DEFAULT in
								# patch url: http://phoronix.com/forums/showthread.php?91885-AMD-Catalyst-13-12-GPU-Driver-For-Linux-Released&p=381943#post381943
								13.12)
									patchFile='FGLRX_13.12-3.11-3.13.patch'
									apply_patch_file $patchFile "$1"
									;;
							esac
							;;
						1[4-9])
							case $DRIVER_DEFAULT in
								# patch url: http://www.forums.fedoraforum.org/showpost.php?p=1696887&postcount=117
								14.[45].*|14.7.1)
									patchFile='FGLRX-14.5-3.14.patch'
									apply_patch_file $patchFile "$1"
									;;
							esac
							;;
					esac
					;;
			esac 
			;;
	esac

	# this is for dev testing of patches or fixes
	if [ "$B_TESTING_4" == 'true' ];then
		: # doing nothing for now
	fi
	eval $LOGPE
}

# ln -s /usr/src/linux/include/generated/uapi/linux/version.h /usr/src/linux/include/linux/version.h
# arg: $1 - which fix to run
run_prepatch_fixes()
{
	eval $LOGPS
	local path1='' path2='' file1='' file2='' outcome=''

	# assume that distro drivers have the fixes done
	if [ "$B_USE_DISTRO_DRIVER" != 'true' ];then
		case $1 in
			3.7-path-fix)
				file1='version.h'
				path1="/usr/src/linux-headers-$KERNEL_FULL/include/generated/uapi/linux/$file1"
				path2="/usr/src/linux-headers-$KERNEL_FULL/include/linux/"
				echo "${S}Running pre-install patch for kernel header ${C}uapi${S} path tweak...${N}"
				if [ -e $path1 ];then
					if [ -d $path2 ];then
						if [ ! -e $path2$file1 ];then
							ln -s $path1 $path2$file1
							outcome="${S}Link created here: ${C}$path2$file1${N}"
						else
							outcome="${S}Target file exists: ${C}$path2$file1${S}${N}"
						fi
					else
						outcome="${E}Target directory ${C}$path2${E} not found.\nUnable to patch for ${C}uapi${E}!!${N}"
					fi
				else
					outcome="${E}Path ${C}$path1${E} not found.\nDriver install may fail!!${N}"
				fi
				log_function_data "$outcome"
				echo -e "$outcome"
				;;
		esac
	fi
	eval $LOGPE
}

# not used currently
# arg: $1 - pre/post
run_patch_fixes()
{
	eval $LOGPS
	local lmkv="/lib/modules/$KERNEL_FULL"

	# the debian sid nvidia drivers are now working fine with xen enabled sid kernels
	if [ "$B_USE_DISTRO_DRIVER" != 'true' ] && [ -d "$lmkv" -a "$B_IS_XEN" == 'true' ];then
		# patch source: http://blog.creonfx.com/linux/how-to-install-nvidia-driver-on-2625-2-debian-kernel-with-xen
		cd $lmkv
		case $1 in
			pre)
				echo "${S}Running pre-install module patches (this might take a while)...${N}"
				grep 'CONFIG_XEN' . -Rl 2> /dev/null | xargs -i sed -i -e 's/CONFIG_XEN/CONFIG_LUPO/g' {}
				export IGNORE_XEN_PRESENCE=1
				;;
			post)
				echo "${S}Reverting pre-install module patches (this might take a while)...${N}"
				grep 'CONFIG_LUPO' . -Rl 2> /dev/null | xargs -i sed -i -e 's/CONFIG_LUPO/CONFIG_XEN/g' {}
				;;
		esac
		cd $SCRIPT_WORKING_DIR/$INSTALL_DIRECTORY
	fi
	eval $LOGPE
}

### -------------------------------------------------------------------
### primary startup - colors
### -------------------------------------------------------------------

# set global color variables
# options: 0 - turns off all colors; 1 - defaults
set_script_colors()
{
	# set colors
	case $SCRIPT_COLORS in
		0)
			W='' # red: Warning message
			E='' # yellow: script Error
			S='' # green: Standard message
			Q='' # CYAN: Questions
			M='' # CYAN: Message
			B='' # BLUE: Message
			C='' # MAGENTA: Command or Path
			N='' # default system console color: Normal :: make last in colors
			;;
		1)
			W="" # red: Warning message
			E="" # yellow: script Error
			S="" # green: Standard message
			Q="" # CYAN: Questions
			M="" # CYAN: Message
			B="" # BLUE: Message
			C="" # MAGENTA: Command or Path
			N="" # default system console color: Normal :: make last in colors
			;;
		2)
			W="" # red: Warning message
			E="" # yellow: script Error
			S="" # Standard message
			Q="" # CYAN: Questions
			M="" # CYAN: Message
			B="" # BLUE: Message
			C="" # MAGENTA: Command or Path
			N="" # default system console color: Normal :: make last in colors
			;;
		3)
			W="" # red: Warning message
			E="" # magenta: script Error
			S="" # brown
			Q="" # light blue: Questions
			M="" # cyan: Message
			B="" # brown: Message
			C="" # green: Command or Path
			N="" # default system console color: Normal :: make last in colors
			;;
		4)
			W="" # red: Warning message
			E="" # brown: script Error
			S="" # blue: Standard message
			Q="" # dark gray: Questions
			M="" # dark gray: Message
			B="" # blue: Message
			C="" # purple: Command or Path
			N="" # default system console color: Normal :: make last in colors
			;;
	esac

	CALLER_DEF=${S} # will switch default output color to the calling script's
	S=${B} # this is slightly tricky, making standard blue AFTER the caller def is set.
	PLINE='- - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - -'
	LINE="${S}$PLINE${N}"
	ELINE="${E}$PLINE${N}"
	MLINE="${M}$PLINE${N}"
	WLINE="${W}$PLINE${N}"
}

### -------------------------------------------------------------------
### Error handling
### -------------------------------------------------------------------
# args: $1 - error number; $2 error extra data, optional
error_handler()
{
	local errorCode=$1 # error number
	local errorExtra=$2 # this is secondary info, like failed package name
	local errorData='' errorData2=''
	local ErrorMessage=''

	case $errorCode in
		# general system checks
		254)
			errorData="No supported $CARD card found!"
			;;
		253)
			errorData="No supported $CARD card found!\nYou can use this script to install the native Xorg drivers: $SCRIPT_NAME -n"
			;;
		252)
			errorData="This does not appear to be a Debian/Ubuntu/Arch based system! If you know that it is\nand received this error, please let the maintainer know and he'll try to correct the\ndistro identification failure. Post on the script forums: http://techpatterns.com/forums/forum-33.html\nwith your system information, including the contents of these files, if present:\n/etc/issue\n/etc/debian_version\n/etc/lsb-release"
			;;
		251)
			errorData="You must be logged in as root to run this script."
			;;
		250)
			errorData="You must be out of X/Desktop (like KDE, Gnome, Flux, LXDE etc) to run this feature."
			;;
		249)
			errorData="Your system does not have the correct version of X, $EXXC"
			;;
		248)
			errorData="Sorry, Ubuntu isn't supported by this script"
			;;
		247)
			errorData="You can't use the composite option with this driver: $DRIVER_DEFAULT"
			;;
		246)
			errorData="The driver: $DRIVER_DEFAULT is not currently supported for kernel version $KERNEL_NUMBER"
			;;
		245)
			errorData2=''
			if [ "$CARD" == "$FGLRX" -a "$B_FGLRX_DIRECT" != 'true' ];then
				errorData2="\nYou might want to try installing without the -D (formerly -F) option instead, which will do a\ndirect (no debs) binary install from the FGLRX run package.\nThis works more reliably for some systems (especially 64 bit)."
			fi
			errorData="The $CARD installer exited with the error: $errorExtra$errorData2\nA copy of this driver installer error log is also here: $LOG_FILE"
			;;
		244)
			errorData="Xorg does not appear to be installed."
			;;
		243)
			errorData="Your kernel type $KERNEL_BASE is not supported for these drivers."
			;;
		242)
			errorData="This script requires X.org 7.1 or greater to be installed on your system."
			;;
		241)
			errorData="This script does not support the $CARD driver: $errorExtra\nPlease make sure to enter a supported driver when using the -o option."
			;;
		240)
			errorData="This script does not support the $CARD driver: $errorExtra"
			;;
		239)
			errorData="This script does not support installing $CARD drivers in livemode."
			;;
		238)
			errorData="There does not appear to be a live connection, or $SCRIPT_NAME script server is down.\nIf you are sure you have a connection, restart script with -Z option to cancel connection test."
			;;
		237)
			errorData="The native xorg driver you selected: $errorExtra is not supported."
			;;
		236)
			errorData="An ATI $CARD error makes them not support your Xorg version $errorExtra\n If you are using less than R500 type card, you can install native radeon drivers with this script.\nUse this syntax to install those and reconfigure xorg.conf: $SCRIPT_NAME -N radeon"
			;;
		235)
			errorData="The driver $DRIVER_DEFAULT requires the 2.6.$errorExtra kernel to run.\nYou are running the $KERNEL_NUMBER kernel. Please update your kernel now."
			;;
		234)
			errorData="The driver $DRIVER_DEFAULT does not support the $errorExtra kernel.\nYou are running the $KERNEL_FULL kernel. Unable to install your $DRIVER_DEFAULT driver.\nYou can override this test with -! 6 option. If install works, let maintainer know."
			;;
		233) errorData="Creating the fix: $errorExtra for your $DRIVER_DEFAULT and kernel $KERNEL_FULL failed."
			;;
		232)
			errorData="The kernel for -K option: $errorExtra does not appear to be installed in your system."
			;;
		231)
			errorData="The file: $errorExtra appears to be corrupted. Please try to update again."
			;;
		230)
			errorData="Could not detect gcc version: $errorExtra, or it is not installed.\nPlease let the script maintainer know, this may be a bug in the script."
			;;
		229)
			errorData="The driver: $DRIVER_DEFAULT does not work on aptosid/sidux kernels.\nYou are trying to install it to this kernel: $KERNEL_FULL\nCurrently $FGLRX only works on new non-aptosid kernels."
			;;
		228)
			errorData="The option you selected: $errorExtra is not supported."
			;;
		227)
			errorData="The newest $CARD drivers ( >= 177.167 ) no longer support your $CARD GeForce 5xxx card.\nYou must use the $NV_LEGACY_3 driver or lower.\nThat is the default driver when you run this script."
			;;
		226)
			errorData="The driver you selected: $DRIVER_DEFAULT does not support your current Xorg version: $X_VERSION\nIf this is wrong, please let the script maintainer know.\nYou can override this test with -! 6 option. If install works, let maintainer know."
			;;
		# this is only for nvidia latest kernel + beta errors
		225)
			errorData="The driver $DRIVER_DEFAULT does not support the 2.6.$errorExtra kernel.\nYou are installing the driver to kernel: $KERNEL_FULL\nPlease try the beta driver instead. Use this command to install beta drivers\nto either non-current kernel: $SCRIPT_NAME -cB -K $KERNEL_FULL\nor to current kernel: $SCRIPT_NAME -cB"
			;;
		224)
			errorData="Your system is missing the required kernel header package: $errorExtra\n and it is not currently available in your repos. Cannot continue.\nPlease either update your kernel and kernel headers,\nor find and install kernel headers for $KERNEL_FULL\nYou can override this test with -! 6 option. If install works, let maintainer know."
			;;
		223)
			errorData="The install of the missing deb from your $SM_KERNEL_DOWNLOADS directory:\n$extraData\nhas failed for unknown reasons. Sorry, we did our best."
			;;
		222)
			errorData="The Xorg driver $extraData you are trying to install is not available\nfor your version of $DISTRIB_ID: $DISTRIB_CODENAME"
			;;
		221)
			errorData="AMD/ATI had dropped fglrx non-free driver support for your card type as of driver release 9-4\nOnly cards x2000 or newer are now supported by AMD/ATI for this driver.\nIf you know your card is supported, please let the $SCRIPT_NAME maintainer know.\nYou can override this test with -! 6 option. If install works, let maintainer know."
			;;
		220)
			errorData="The Driver you are trying to install does not work with libdrm2 version 2.4.x less than 2.4.11.\nYour installed version of libdrm2 is: $errorExtra\n\nIf you are using Debian Sid, you must upgrade your libdrm2 to 2.4.11 or greater."
			;;
		219)
			errorData="Fglrx direct driver install method does not allow you to install the\ndriver to another kernel, using the -K option, sorry. You must be booted into\nthe kernel you are installing the driver to for this driver method to work."
			;;
		218)
			errorData="Something went wrong in the creation of your new $EXXC file\nPlease let the script maintainer know."
			;;
		217)
			errorData="No supported $CARD card found for the distro driver (-d - formerly -s) installer option!\nYou can use this script to install the native Xorg drivers: $SCRIPT_NAME -n"
			;;
		216)
			errorData="You are using Ubuntu but you do not appear to have the 'restricted' repos enabled.\nPlease enable them before continuing, thank you."
			;;
		215)
			errorData="Your new $EXXC is missing, or is not located where expected.\nPlease let the script maintainer know."
			;;
		214)
			errorData="Cannot create your new $EXXC because X cannot be killed.\nPlease let the script maintainer know."
			;;
		213)
			errorData="$SCRIPT_NAME cannot locate any /boot/grub/ config files. Unable to continue.\n$SCRIPT_NAME requires grub config files: /boot/grub/menu.lst or /boot/grub/grub.cfg\n$SCRIPT_NAME does not support lilo or unmounted /boot partitions.\nThe action: $errorExtra cannot be done without an active Grub on your system."
			;;
		212)
			errorData="AMD has dropped Catalyst/FGLRX support for HD2xxx-4xxx series cards as of 12-6.\nYou should have bought Nvidia if you wanted a long term working non free driver, sorry.\nIf you know your card is supported, please let the $SCRIPT_NAME maintainer know.\nYou can override this test with -! 6 option. If install works, let maintainer know."
			;;
		211)
			errorData="You cannot start $SCRIPT_NAME with sudo. Please start $SCRIPT_NAME \nproperly as root (use either 'sudo su -' (note the '-' at the end) \nto become root, or login as root directly). If 'sudo su -' does not \nwork, please let the $SCRIPT_NAME maintainer know, and if your system \nhas root locked (why would anyone do that?) then you will have to \nunlock root. \n\nSee your distro manuals or help pages to fix this issue in that \ncase, and also make sure to update any documentation or how-to's \nfor running $SCRIPT_NAME with your distro.  This means you, Ubuntu/Mint users!\n\nTypical signs of sudo failures are respawnings of your desktop while \n$SCRIPT_NAME is running, or failures to create directories.\n"
			;;
		# specific install issues
		200)
			errorData="The package: $errorExtra failed to install, please check apt for any problems."
			;;
		199) # replaced by 231
			errorData="The file: $errorExtra failed to download - wget reports success."
			;;
		198)
			errorData="The url/file: $errorExtra\nfailed to download - wget error."
			;;
		197)
			errorData="The graphics driver installer: $errorExtra failed to download - wget error."
			;;
		196)
			errorData="The driver package: $errorExtra failed to extract and has been deleted."
			;;
		195)
			errorData="dkpg -i failed for package: $errorExtra"
			;;
		194)
			errorData="m-a build failed for package: $errorExtra"
			;;
		193)
			errorData="m-a install failed for package: $errorExtra"
			;;
		192)
			errorData="The $CARD driver uninstaller exited with this error: $errorExtra"
			;;
		191)
			errorData="This script cannot proceed if you leave $errorExtra installed."
			;;
		190)
			errorData="Removing package $errorExtra failed."
			;;
		189)
			errorData="Downloading the experimental driver $errorExtra failed."
			;;
		188)
			errorData="The experimental driver $errorExtra package is empty."
			;;
		187)
			errorData="The experimental driver package $errorExtra is not available currently, sorry."
			;;
		186)
			errorData="The package $errorExtra was not created. Cannot continue with install."
			;;
		185)
			errorData="m-a prepare failed for package: $errorExtra"
			;;
		184)
			errorData="m-a update failed for package: $errorExtra"
			;;
		183)
			errorData="depmod -a failed for package: $errorExtra"
			;;
		182)
			errorData="m-a clean failed for package: $errorExtra"
			;;
		181)
			errorData="Patch file: $errorExtra failed to download."
			;;
		180)
			errorData="wget error: Patch file: $errorExtra failed to download."
			;;
		179)
			errorData="Patching error: file: $errorExtra failed."
			;;
		178)
			errorData="Unsupported testing option argument: -! $errorExtra"
			;;
		177)
			errorData="Used -z command but no X application is present in system."
			;;
		176)
			errorData="Whoops, how did this happen? It appears you are not running a supported Distro for distro driver install."
			;;
		175)
			errorData="You are using the -k (build kernel module only) option, but required file: $errorExtra\nis not found in $SCRIPT_WORKING_DIR\nNote: if your installed driver is NOT the default $SCRIPT_NAME offers, you have to\nuse either the -o <driver number> OR the -B option (if you are using current beta driver)\nplus the -! 40 option. EG: to install beta to all kernels: $SCRIPT_NAME -B -! 40"
			;;
		174)
			errorData="The -k option cannot be used if you are using distribution packaged nVidia drivers."
			;;
		173)
			errorData="The -k option only supports nVidia cards, sorry."
			;;
		172)
			errorData="The -k option can only be used to install to the same driver that is running.\nYour system is running $errorExtra but you are building the module for: $DRIVER_DEFAULT\nYou can use the -o <driver version> option to override the defaults."
			;;
		171)
			errorData="The kernel module build failed with error code: $errorExtra\nPlease check /var/log/nvidia-installer.log for more information about the failure.\nA copy of this nvidia error log is also here: $LOG_FILE\nPlease try to reinstall the driver using: sgfxi -f (force override module build)\nbecause sometimes modules cannot be built to new kernels without the source\nbeing patched first, which requires a driver reinstall."
			;;
		170)
			errorData="An nvidia module already exists for $KERNEL_FULL at path:\n/lib/modules/$KERNEL_FULL/kernel/drivers/video/nvidia.ko\nYou must either remove this manually, or install a new driver with $SCRIPT_NAME.\nInstalling a driver will remove all previous modules, then you can\nrebuild them with the -! 40 option (see $SCRIPT_NAME -h for more information on that method)."
			;;
		169)
			errorData="No previous $NVIDIA $SCRIPT_NAME run package install detected for -k option module build."
			;;
		168)
			errorData="An Xorg update overwrote $NVIDIA run package files. You must reinstall $NVIDIA driver.\nUnable to build -k option module."
			;;
		167)
			errorData="You have used the -! 33 override option but the $errorExtra module action reports as failed\n.$SCRIPT_NAME is unable to continue in this scenario.\nPlease blacklist/unblacklist your $errorExtra manually then run $SCRIPT_NAME again."
			;;
		166)
			errorData="The options ($errorExtra) you used are not compatible, and create internal $SCRIPT_NAME conflicts.\nPlease correct this error and start again."
			;;
		165)
			errorData="Extraction of zip file: $errorExtra failed."
			;;
		100)
			errorData="The function: $errorExtra exited through user action."
			;;
		*)
			errorData="Unexpected Error !"
			;;
	esac
	ErrorMessage="ERROR: ($errorCode) $errorData"
	echo -e ${E}$ErrorMessage${N}
	if [ -f $LOG_FILE -a "$B_LOGGING_STARTED" == 'true' ];then
		log_function_data "$ErrorMessage"
		echo
		echo "${S}Log file is located here: $LOG_FILE"
	fi
	echo "${M}Exiting script now.${N}"

	exit $errorCode
}

### -------------------------------------------------------------------
### card type/version detections
### -------------------------------------------------------------------

# this only runs if card count > 1
select_card()
{
#cardData=$(echo "00:0d.0 VGA compatible controller [0300]: nVidia Corporation GeForce 6100 nForce 405 [10de:03d1] (rev a2)
#02:00.0 VGA compatible controller [0300]: nVidia Corporation G71 [GeForce 7300 G S] [10de:01df] (rev a1)"  | grep -E 'VGA' | cut -d ':' -f 3-4 | cut -d ' ' -f 2-50 | tr ' ' '-' )
#tester="00:0d.0 0300: 10de:03d1 (rev a2)
#02:00.0 0300: 10de:01df (rev a1) "
	# not using: |3D[[:space:]]controller ]|Display[[:space:]]controller - may cause dual id of same device 
	# NOTE: we have to confirm it's a real card, we do that by checking: xx:xx.0 structure on pcibus id string.
	local cardData=$( lspci -nn | \
	grep -iE '(VGA compatible controller|3D controller|Display controller)' | \
	grep -E '(^[^:]+:[^:\.]+[:\.]0)[[:space:]]' | \
	cut -d ':' -f 3-4 | cut -d ' ' -f 2-50 | tr ' ' '-' )
	local cards='' card='' singleCardId=''
	local options='' opt='' bFound='false'
	local timeStampXorg=$EXXC-bu-$( date +%Y-%m-%d-%H:%M:%S )

	echo $MLINE
	echo "${S}The script detected more than one video card in your system:"
	echo "${C}$cardData"
	echo
	if [ "$B_SKIP_CONFIG" != 'true' ];then
		echo "${M}If you want to preserve your current ${C}xorg.conf${M}, for example if you use dual"
		echo "card setup, and your system is working fine with the driver you are installing,"
		echo "please restart ${C}$SCRIPT_NAME${M} with extra ${C}-C${M} option and it will not change xorg.conf."
		echo
		echo "${C}$SCRIPT_NAME${S} will adjust your xorg.conf busID. For typical, single monitor/dual card setups, this is desirable,"
		echo "but for rare cases of dual card, dual monitor setups, you may want to start with ${C}-C${S} (exit here to do so) "
		echo
		
		echo "If you proceed without ${C}-C${S}, a copy of your current ${C}xorg.conf${S} will be made here: ${C}$timeStampXorg"
	else
		echo "${S}Because you started with ${C}-C${S} option, ${C}$SCRIPT_NAME${S} will NOT change your ${C}xorg.conf${S} here"
		echo "but will simply set which card to use for the automatic driver selection. Just pick the card"
		echo "you want ${C}$SCRIPT_NAME${S} to use as the main card and ${C}$SCRIPT_NAME${S} will continue to installing the proper driver."
	fi
	echo
	echo "${S}Please select which card you want to install a driver for now to proceed:"
	echo $MLINE

	options="$cardData exit"
	select opt in $options
	do
		for card in $options
		do
			if [ "$opt" == "$card" ];then
				if [ "$card" == 'exit' ];then
					echo "${S}Exiting script now.${N}"
					exit 0
				else
					singleCardId=$( echo $card | grep -Eo -i '[a-z0-9]{4}:[a-z0-9]{4}' )
					echo "${S}You have elected to install drivers for this video card:"
					echo "${C}$card${N}"
					# override the global values and handle this explicitly
					# note that we need to do this whether or not -C is used
					CARD_DATA=$singleCardId

					if [ "$B_SKIP_CONFIG" != 'true' ];then
						if [ ! -e $timeStampXorg ];then
							cp $EXXC $timeStampXorg
						fi
						log_function_data "xorg.conf was backed up to: $timeStampXorg"
						B_XORG_BACKED_UP='true'
						# set correct bus id as last step, note you have to check for . in PCI string:
						# like this: O1:00.0 and change it to O1:00:0
						BUS_ID=$( lspci -n | grep "$CARD_DATA" | grep -Eio '^[0-9]{1,2}:[0-9a-z]{1,2}(\.|:)[0-9]' | sed 's/\./:/')

						# handle explicit assignment of busid to avoid errors
						echo "${S}Updating ${C}xorg.conf${S} to use the card with this BusID: ${C}$BUS_ID${N}"
						if [ -n "$BUS_ID" ];then
							# create a dummy in case it's needed by new xorg system
							create_section_device
							pcibusid_hex_to_dec # need to get rid of hex due to xorg error
							# this is redundant if set above but easier to do for all cases
							sed -i -r 's/\s*#*\s*BusID.*/\tBusID\t"PCI:'$BUS_ID'"/' $EXXC
						fi
					fi
				fi
				bFound='true'
				break
			else
				bFound='false'
			fi
		done
		break
	done
	if [ "$bFound" != "true" ];then
		echo "${E}Please select one of the numbers for your choices!${N}"
		select_card
	fi
}
#select_card;exit

# this is separated from detect card because it will be used for nv/ati basic card tests
set_card()
{
	local bCardFound='false' card=''

	# note: select_card has already handled multiple cards on box, so no need to loop it
	CARD_BRAND=$( echo $CARD_DATA | cut -d ':' -f1 )
	case $CARD_BRAND in
		10de|12d2)
			CARD=$NVIDIA
			bCardFound='true'
			B_DEFAULT_NATIVE_DRIVER='true'
			;;
		1002)
			CARD=$FGLRX
			bCardFound='true'
			B_DEFAULT_NATIVE_DRIVER='true'
			;;
		8086)
			CARD=$INTEL
			bCardFound='true'
			B_DEFAULT_NATIVE_DRIVER='true'
			;;
		10c8)
			CARD=$NEOMAGIC
			bCardFound='true'
			B_DEFAULT_NATIVE_DRIVER='true'
			;;
		121a)
			CARD=$TDFX
			bCardFound='true'
			B_DEFAULT_NATIVE_DRIVER='true'
			;;
		*)
			# this is required to handle unknown card types when forced override is used
			if [ -n "$NATIVE_OVERRIDE" ];then
				bCardFound='true'
			fi
			;;
	esac
	if [ "$bCardFound" != 'true' ];then
		error_handler 254
	fi
}
## card support information:
#  nvidia: http://us.download.nvidia.com/XFree86/Linux-x86/1.0-9755/README/appendix-a.html
## pick out the id string for nvidia/fglrx, set all the master variables for nv/fg
detect_card_version()
{
	local foundVersion='' version='' card='' cardBrand='' cardNumber=''
	local isQuad='' is8xxx=''

	# note: select_card has already handled multiple cards on box, so no need to loop it
	cardBrand=$( echo $CARD_DATA | cut -d ':' -f1 )
	cardNumber=$( echo $CARD_DATA | cut -d ':' -f2 )
	case $cardBrand in
		10de|12d2)
			# these will also assign dynamic betas to $NV_BETA prior to sending it
			# to the master DRIVER_BETA for support tests right after
			DRIVER_DEFAULT=$( assign_standard_or_beta_driver 'default' 'driver' )
			B_BETA_EXISTS=$( assign_standard_or_beta_driver 'default' 'set-exists' )
			DRIVER_BETA=$NV_BETA
			VERSIONS=$NV_VERSIONS
			OTHER_VERSIONS=$NV_OTHERS
			CARD_NUMBER=$cardNumber
			# do some card specific tests to determine generic classes
			# |3D[[:space:]]controller |Display[[:space:]]controller
			isQuad=$( lspci | \
			grep -E '([[:space:]]VGA[[:space:]])' | \
			grep -i -o 'quadro' )
			is8xxx=$( lspci | \
			grep -E '[[:space:]]VGA[[:space:]]' | \
			grep -Eo '8[0-9]{3}' )
			case $cardNumber in
				# http://listing.driveragent.com/pci/10de/?q=94c3 # later series
				# http://listing.driveragent.com/pci/12d2/?q=94c3 # full legacy
				# http://www.nvidia.com/object/linux-amd64-display-archive.html
				0008|0009|0010|0018|0019)
					error_handler 253 # if card in this list exit
					LEGACY_LEVEL=0
					;;
				0020|0028|0029|002c|002d|00a0|0100|0101|0103|0150|0151|0152|0153|0170)
					DRIVER_INSTALL=$( assign_standard_or_beta_driver 'legacy-1' 'driver' )
					B_BETA_EXISTS=$( assign_standard_or_beta_driver 'legacy-1' 'set-exists' )
					# B_RENDER_ACCEL='' # set default to false
					LEGACY_LEVEL=1
					# buntu doesn't have 71xxx drivers in package pool since they don't support
					# new xorg
					case $SYSTEM_BASE in
						ubuntu)
							if [ "$B_USE_DISTRO_DRIVER" == 'true' ];then
								error_handler 217 # if card in this list exit
							fi
							;;
					esac
					;;
				0110|0111|0112|0113|0170|0171|0172|0173|0174|0175|0176|0177|0178|0179|017a|017c|017d|0180|0181|0182|0183|0185|0186|0187|0188|018a|018b|018c|01a0|01f0|0200|0201|0202|0203|0250|0251|0253|0258|0259|025b|0280|0281|0282|0286|0288|0289|028c)
					DRIVER_INSTALL=$( assign_standard_or_beta_driver 'legacy-2' 'driver' )
					B_BETA_EXISTS=$( assign_standard_or_beta_driver 'legacy-2' 'set-exists' )
					LEGACY_LEVEL=2
					# B_RENDER_ACCEL='' # set default to false
					if [ "$B_FORCE_NO_COMPOSITE" != 'true' ];then
						B_COMPOSITE='true'
					fi
					;;
				# This is for the GeForce FX 5xxx series. Not sure about the quadro fx series:
				# 004d 004e 09d0 009d 00cd 00ce 00fe 019d 019e
				# http://www.nvidia.com/object/IO_32667.html
				# gawk '{t=t tolower($NF) "|"}END{gsub(/0x/,"",t);print t}'
				00fa|00fb|00fc|00fd|00fe|0301|0302|0308|0309|0311|0312|0314|031a|031b|031c|0320|0321|0322|0323|0324|0325|0326|0327|0328|032a|032b|032c|032d|0330|0331|0332|0333|0334|0338|033f|0341|0342|0343|0344|0347|0348|034c|034e)
					DRIVER_INSTALL=$( assign_standard_or_beta_driver 'legacy-3' 'driver' )
					B_BETA_EXISTS=$( assign_standard_or_beta_driver 'legacy-3' 'set-exists' )
					LEGACY_LEVEL=3
					if [ "$B_FORCE_NO_COMPOSITE" != 'true' ];then
						B_COMPOSITE='true'
					fi
					;;
				# list of 6/7xxx devices: http://nvidia.custhelp.com/app/answers/detail/a_id/3142
				# http://www.nvidia.com/object/IO_32667.html
				# gawk '{t=t tolower($NF) "|"}END{gsub(/0x/,"",t);print t}'
				0040|0041|0042|0043|0044|0045|0046|0047|0048|004e|0090|0091|0092|0093|0095|0098|0099|009d|00c0|00c1|00c2|00c3|00c8|00c9|00cc|00cd|00ce|00f1|00f2|00f3|00f4|00f5|00f6|00f8|00f9|0140|0141|0142|0143|0144|0145|0146|0147|0148|0149|014a|014c|014d|014e|014f|0160|0161|0162|0163|0164|0165|0166|0167|0168|0169|016a|01d0|01d1|01d2|01d3|01d6|01d7|01d8|01da|01db|01dc|01dd|01de|01df|0211|0212|0215|0218|0221|0222|0240|0241|0242|0244|0245|0247|0290|0291|0292|0293|0294|0295|0297|0298|0299|029a|029b|029c|029d|029e|029f|02e0|02e1|02e2|02e3|02e4|038b|0390|0391|0392|0393|0394|0395|0397|0398|0399|039c|039e|03d0|03d1|03d2|03d5|03d6|0531|0533|053a|053b|053e|07e0|07e1|07e2|07e3|07e5)
					DRIVER_INSTALL=$( assign_standard_or_beta_driver 'legacy-4' 'driver' )
					B_BETA_EXISTS=$( assign_standard_or_beta_driver 'legacy-4' 'set-exists' )
					LEGACY_LEVEL=4
					if [ "$B_FORCE_NO_COMPOSITE" != 'true' ];then
						B_COMPOSITE='true'
					fi
					;;
				# 8/9xxx gt100-300 series
				# http://www.nvidia.com/object/IO_32667.html
				# gawk '{t=t tolower($NF) "|"}END{gsub(/0x/,"",t);print t}'
				0191|0193|0194|0197|019d|019e|0400|0401|0402|0403|0404|0405|0406|0407|0408|0409|040a|040b|040c|040d|040e|040f|0410|0420|0421|0422|0423|0424|0425|0426|0427|0428|0429|042a|042b|042c|042d|042e|042f|05e0|05e1|05e2|05e3|05e6|05e7|0595|068f|0697|0714|0743|05ea|05eb|05ed|05f8|05f9|05fd|05fe|05ff|0600|0601|0602|0603|0604|0605|0606|0607|0608|0609|00a7|060a|060b|060c|060d|060f|0610|0611|0612|0613|0614|0615|0617|0618|0619|061a|061b|061c|061d|061e|061f|0621|0622|0623|0625|0626|0627|0628|062a|062b|062c|062d|062e|0605|0630|0631|0632|0635|0637|0638|063a|0640|0641|0643|0644|0645|0646|0647|0648|0649|202d|064a|064b|064c|0651|0652|0850|0653|0654|14a2|14d2|0633|0693|0658|0659|065a|065b|065c|06e0|06e1|06e2|06e3|06e4|06e5|06e6|06e7|06e8|360b|06e9|06ea|06eb|06ec|06ef|06f1|06f8|06f9|060d|06fa|06fb|06fd|06ff|0711|0840|0844|0845|0846|0847|0848|0849|084a|084b|084c|084d|084f|0860|0861|0862|0863|0864|0865|0866|00b1|0867|0868|0869|086a|086c|086d|086e|086f|0870|0871|0872|1c42|0873|1c52|0874|0876|087a|087d|087e|087f|08a0|08a2|08a3|08a4|08a5|0a20|0a22|0a23|0a26|0a27|0a28|0a29|0a2a|0a2b|0a2c|0a2d|0a32|0a34|0a35|0a38|0a3c|0a60|0a62|0a63|0a64|0a65|0a66|0a67|0a68|0a69|0a6a|0a6c|0a6e|3607|0a6f|0a70|3605|3617|0a71|0a72|0a73|3607|3610|0a74|903a|0a75|3605|0a76|0a78|0a7a|0003|3950|397d|3980|8006|90b4|aa51|aa58|ac71|ac82|0a7c|0ca0|0ca2|0ca3|0ca4|0ca5|0ca7|0ca8|0ca9|0cac|0caf|0cb0|0cb1|0cbc|10c0|10c3|10c5|10d8)
					DRIVER_INSTALL=$( assign_standard_or_beta_driver 'legacy-5' 'driver' )
					B_BETA_EXISTS=$( assign_standard_or_beta_driver 'legacy-5' 'set-exists' )
					LEGACY_LEVEL=5
					if [ "$B_FORCE_NO_COMPOSITE" != 'true' ];then
						B_COMPOSITE='true'
					fi
					;;
				*)
					# set flags for fully supported non-legacy cards
					B_USE_XVMC='true'
					LEGACY_LEVEL=100
					if [ "$B_FORCE_NO_COMPOSITE" != 'true' ];then
						B_COMPOSITE='true'
					fi
					;;
			esac
			# this handles 8xxx xvmc issue
			if [ -n "$is8xxx" ];then
				B_USE_XVMC='false'
			fi
			# this handles quad cards, whose driver supports both nv legacy and standard cards
			if [ -n "$isQuad" ];then
				: # now quad driver is just latest
				#DRIVER_QUAD=$NV_QUAD
				#DRIVER_INSTALL=$NV_QUAD
			fi
			;;
		1002)
			DRIVER_DEFAULT=$FG_DEFAULT
			# if a hack / driver change is required, this will trigger it
			driver_version_hacks "$DRIVER_DEFAULT"
			DRIVER_BETA=$FG_BETA
			VERSIONS=$FG_VERSIONS
			OTHER_VERSIONS=$FG_OTHERS
			CARD_NUMBER=$cardNumber
			case $cardNumber in
				# fireGL cards, temp no support in fglrx
				# http://wiki.cchtml.com/index.php/Hardware
				# note: 4e50 should work with 8.4 driver
				3154|3e54|4147|4154|4a4d|4e47|4e4b|4e54|5464|5550|5551|564a|564b|5b64|5d49|5e48|5e49|71C4)
					LEGACY_LEVEL=0
					error_handler 253
					;;
				# http://listing.driveragent.com/pci/1002/?q=94c3
				0544)
					LEGACY_LEVEL=0
					error_handler 253
					;;
				# removed from list: 4337 - laptop chip
				4136|4137|4237|4242|4243|4336|4337|4354|4358|4437|4554|4654|4742|4744|4747|4749|474c|474d|474e|474f|4750|4751|4752|4753|4754|4755|4756|4757|4758|4759|475a|4964|4965|4966|4967|496e|496f|4c42|4c44|4c45|4c46|4c47|4c49|4c4d|4c4e|4c50|4c51|4c52|4c53|4c54|4c57|4c58|4c59|4c5a|4c64|4c65|4c66|4c67|4c6e|4c6f|4d46|4d4c|4f72|4f73)
					LEGACY_LEVEL=0
					error_handler 253
					;;
				5041|5042|5043|5044|5045|5046|5047|5048|5049|504a|504b|504c|504d|504e|504f|5050|5051|5052|5053|5054|5055|5056|5057|5058|5144|5145|5146|5147|5148|5149|514a|514b|514c|514d|514e|514f|5154|5155|5157|5158|5159|515a|515e|515f|5168|5169|516a|516b|516c|516d|516f|5245|5246|5247|524b|524c|5345|5346|5347|5348|534b|534c|534d|534e|5354|5446|544c|5452|5453|5454|5455|5654|5655|5656|5833|5834|5835|5838|5854|5874|5940|5941|5942|5944|5960|5961|5962|5964|5965|5969|5c41|5c43|5c61|5c63|5d44)
					LEGACY_LEVEL=0
					error_handler 253
					;;
				7c37|728c|7834|7835)
					LEGACY_LEVEL=0
					error_handler 253
					;;
				# a few cards of the 7xxx numbering are actuall x2xxx cards
				# sadly, this doesn't build the module, so leaving it commented out, x series fail
# 				718a|7188|7210|7211)
# 					LEGACY_LEVEL=100
# 					if [ "$B_DISTRO_FLAG" == 'true' ];then
# 						B_USE_DISTRO_DRIVER='true'
# 					fi
# 					;;
				# this is going to handle all pre hd/x2000 cards, any exceptions will be added
				# to an explicit whitelist above this if required
				3*|4*|5*|7*)
					LEGACY_LEVEL=1
					# error should occur but on off chance that legacy smxi users are running very old install
					# I'll leave it for now. Otherwise sgfxi will handle this itself later on.
					# 2014-03-02: turned on, no point in leaving support
					error_handler 253
					# going to leave this in for now until debian kernels and
					# xorgs catch up, but will permit by default for non legacy 0 cards
					if [ "$B_DISTRO_FLAG" == 'true' ];then
						B_USE_DISTRO_DRIVER='true'
					fi
					;;
				# these should cover most of the hd2xxx-hd4xxx series with discontinued support
				94*|95*|97*)
					LEGACY_LEVEL=2
					;;
				*)
					# if no working driver via standard ati installer. Here we're also handling
					# the monthly releases, so users can do an experimental test if needed
					# if [ "$B_DISTRO_FLAG" == 'true' -a "$B_TESTING_1" != 'true' ]
					LEGACY_LEVEL=100
					# this will reset the globals for betas/default drivers. Must not run in subshell
					assign_standard_or_beta_driver 'default' 'driver'
					
					# echo 'dd: ' $DRIVER_DEFAULT
					B_BETA_EXISTS=$( assign_standard_or_beta_driver 'default' 'set-exists' )
					# echo 'be: ' $B_BETA_EXISTS
					if [ "$B_DISTRO_FLAG" == 'true' ];then
						B_USE_DISTRO_DRIVER='true'
					fi
					if [ "$B_FORCE_NO_COMPOSITE" != 'true' ];then
						B_COMPOSITE='true'
					fi
					;;
			esac
			;;
		 # set B_NATIVE_DRIVER so script fires correctly
		 # intel | neomagic | 3dfx
		8086|10c8|121a)
			CARD_NUMBER=$cardNumber
			B_NATIVE_DRIVER='true'
			;;
	esac
	#echo $cardNumber
}

# note that for fglrx we need to just change the global values, not run this as subshell for driver tests
# args: $1 - default/legacy-[1-4]; $2 - set-exists/driver
assign_standard_or_beta_driver()
{
	local betaDriver='' stableDriver='' liveBetas='' betaVersion='' 
	local betaCurrent='' beta340='' beta304='' beta173='' beta96='' beta71='' 
	
	case $CARD in
		$NVIDIA)
			# only run this the first time it's called
			if [ "$B_USE_BETA" == 'true' -a "$1" == 'default' -a "$2" == 'driver' ];then
				liveBetas=$( get_live_beta_drivers )
				betaCurrent=$( cut -d ':' -f 1 <<< "$liveBetas" )
				beta340=$( cut -d ':' -f 2 <<< "$liveBetas" )
				beta304=$( cut -d ':' -f 3 <<< "$liveBetas" )
				beta173=$( cut -d ':' -f 4 <<< "$liveBetas" )
				beta96=$( cut -d ':' -f 5 <<< "$liveBetas" )
				beta71=$( cut -d ':' -f 6 <<< "$liveBetas" )
				## assign live defaults if required
				if [ -n "$betaCurrent" ];then
					if [ -z "$NV_DEFAULT_BETA" -o "$( compare_numbers $betaCurrent $NV_DEFAULT_BETA )" -eq 0 ];then
						NV_DEFAULT_BETA=$betaCurrent
						NV_BETA="$NV_BETA:$betaCurrent"
					fi
				fi
				if [ -n "$beta340" ];then
					if [ -z "$NV_LEGACY_BETA_5" -o "$( compare_numbers $beta340 $NV_LEGACY_BETA_5 )" -eq 0 ];then
						NV_LEGACY_BETA_5=$beta340
						NV_BETA="$NV_BETA:$beta340"
					fi
				fi
				if [ -n "$beta304" ];then
					if [ -z "$NV_LEGACY_BETA_4" -o "$( compare_numbers $beta304 $NV_LEGACY_BETA_4 )" -eq 0 ];then
						NV_LEGACY_BETA_4=$beta304
						NV_BETA="$NV_BETA:$beta304"
					fi
				fi
				if [ -n "$beta173" ];then
					if [ -z "$NV_LEGACY_BETA_3" -o "$( compare_numbers $beta173 $NV_LEGACY_BETA_3 )" -eq 0 ];then
						NV_LEGACY_BETA_3=$beta173
						NV_BETA="$NV_BETA:$beta173"
					fi
				fi
				if [ -n "$beta96" ];then
					if [ -z "$NV_LEGACY_BETA_2" -o "$( compare_numbers $beta96 $NV_LEGACY_BETA_2 )" -eq 0 ];then
						NV_LEGACY_BETA_2=$beta96
						NV_BETA="$NV_BETA:$beta96"
					fi
				fi
				if [ -n "$beta71" ];then
					if [ -z "$NV_LEGACY_BETA_1" -o "$( compare_numbers $beta71 $NV_LEGACY_BETA_1 )" -eq 0 ];then
						NV_LEGACY_BETA_1=$beta71
						NV_BETA="$NV_BETA:$beta71"
					fi
				fi
			fi

			case $1 in
				default)
					betaDriver=$NV_DEFAULT_BETA
					stableDriver=$NV_DEFAULT
					;;
				legacy-1)
					betaDriver=$NV_LEGACY_BETA_1
					stableDriver=$NV_LEGACY_1
					;;
				legacy-2)
					betaDriver=$NV_LEGACY_BETA_2
					stableDriver=$NV_LEGACY_2
					;;
				legacy-3)
					betaDriver=$NV_LEGACY_BETA_3
					stableDriver=$NV_LEGACY_3
					;;
				legacy-4)
					betaDriver=$NV_LEGACY_BETA_4
					stableDriver=$NV_LEGACY_4
					;;
				legacy-5)
					betaDriver=$NV_LEGACY_BETA_5
					stableDriver=$NV_LEGACY_5
					;;
			esac
			;;
		$FGLRX)
			local defaultBetaWorking='' defaultBetaVersion='' betaCurrentWorking='' betaCurrentVersionWorking=''
			local bDebugger='false'
			
			if [ "$B_USE_BETA" == 'true' -a "$1" == 'default' -a "$2" == 'driver' ];then
				### NOTE: not used anymore
				# liveBetas=$( get_live_beta_drivers )
				if [ "$bDebugger" == 'true' ];then
					echo
					echo "Start assign_standard_or_beta_driver"
					echo "lb:$liveBetas:"
				fi
				
				if [ -n "$liveBetas" ];then
					# check for spastic amd version numbering here, 13-6 vs 13.4
					# note, make sure to use [[ for null cases here
					if [[ -n $( grep -E '^[0-9]+-[0-9]+' <<< "$liveBetas" ) ]];then
						betaCurrent=$( cut -d '-' -f 1,2 <<< "$liveBetas" )
						betaVersion=$( cut -d '-' -f 3 <<< "$liveBetas" )
					elif [[ -n $( grep -E '^[0-9]+\.[0-9]+' <<< "$liveBetas" ) ]];then
						betaCurrent=$( cut -d '-' -f 1 <<< "$liveBetas" )
						betaVersion=$( cut -d '-' -f 2 <<< "$liveBetas" )
					fi
					# http://www2.ati.com/drivers/beta/amd-catalyst-13.11-betav1-linux-x86.x86_64.zip
					# now convert to numbered
					betaCurrentWorking=$( sed 's/-/./g' <<< "$betaCurrent"  )
					if [ -n "$( grep -E 'beta[v]?[0-9]' <<< "$liveBetas" )" ];then
						betaCurrentVersionWorking=$( sed -r 's/.*-beta[v]?([0-9\.]+)/\1/' <<< "$liveBetas" )
					fi
					defaultBetaWorking=$( sed 's/-/./g' <<< $FG_DEFAULT_BETA )
					if [ -n "$( grep -E 'beta[v]?[0-9]' <<< "$FG_BETA_VERSION" )" ];then
						defaultBetaVersion=$( sed -r 's/beta[v]?([0-9\.]+)/\1/' <<< "$FG_BETA_VERSION" )
					fi
					if [ "$bDebugger" == 'true' ];then
						echo ""
						echo "bc:$betaCurrent:"
						echo "bv:$betaVersion:"
						echo "bcw:$betaCurrentWorking:"
						echo "bcvw:$betaCurrentVersionWorking:"
						echo "dbw:$defaultBetaWorking:"
						echo "dbv:$defaultBetaVersion:"
					fi
					# echo $FG_DEFAULT_BETA  $defaultBetaWorking 
					if [ -z "$FG_DEFAULT_BETA" \
					-o "$( compare_numbers $betaCurrent $defaultBetaWorking )" -eq 0 ] || \
					[ -n "$betaCurrentVersionWorking" \
					-a -n "$defaultBetaVersion" -a "$( compare_numbers $betaCurrentVersionWorking $defaultBetaVersion )" -eq 0  ];then
						FG_DEFAULT_BETA=$betaCurrent
						FG_BETA_VERSION=$betaVersion
						# echo yest1
					fi
				fi
			fi
			# two cases, if the remote beta version is greater than default driver, or if local version is graater than default
			if [ -n "$defaultBetaWorking" -a "$( compare_numbers $defaultBetaWorking $FG_DEFAULT )" -eq 0 ] || \
			[ -n "$FG_DEFAULT_BETA" -a "$( compare_numbers $FG_DEFAULT_BETA $FG_DEFAULT )" -eq 0 ];then
				betaDriver=$FG_DEFAULT_BETA
				# echo yest2
			fi
			if [ "$bDebugger" == 'true' ];then
				echo "dbw > fd: $( compare_numbers $defaultBetaWorking $FG_DEFAULT )"
				echo "fdb > fd: $( compare_numbers $FG_DEFAULT_BETA $FG_DEFAULT )"
				echo "FDB:$FG_DEFAULT_BETA:"
				echo "FBV:$FG_BETA_VERSION:"
				echo "FD:$FG_DEFAULT:"
				echo "bd:$betaDriver:"
				echo "End assign_standard_or_beta_driver"
			fi
			stableDriver=$FG_DEFAULT
			;;
	esac

	if [ "$2" == 'driver' ];then
		if [ -n "$betaDriver" -a "$B_USE_BETA" == 'true' ];then
			case $CARD in
				$NVIDIA)
					echo $betaDriver
					;;
				$FGLRX)
					DRIVER_DEFAULT=$betaDriver
					;;
			esac
		elif [ -z "$betaDriver" -o "$B_USE_BETA" != 'true' ];then
			case $CARD in
				$NVIDIA)
					echo $stableDriver
					;;
				$FGLRX)
					DRIVER_DEFAULT=$stableDriver
					# explicitly unset these to clear out any sgfxi attempt to use beta stuff internally
					FG_BETA_VERSION=''
					### NOTE: legacy, not used as of 14.x
					# B_USE_BETA='false'
					;;
			esac
		fi
	else
		if [ -n "$betaDriver" -a "$B_USE_BETA" == 'true' ];then
			echo 'true'
		else
			echo 'false'
		fi
	fi
}

get_live_beta_drivers()
{
	local driverList='' betaCurrent='' beta340='' beta304='' beta173='' beta96='' beta71=''
	
	# get data
	if [ "$B_SKIP_WGET" != 'true' ];then
		case $CARD in
			$NVIDIA)
				driverList="$( wget -T 3 -t 2 -qO - $NV_LIVE_DRIVERS )"
				# get beta drivers
				betaCurrent=$( awk '/^curr.*beta/ {print $3}' <<< "$driverList" )
				beta340=$( awk '/^340.*beta/ {print $3}' <<< "$driverList" )
				beta304=$( awk '/^304.*beta/ {print $3}' <<< "$driverList" )
				beta173=$( awk '/^173.*beta/ {print $3}' <<< "$driverList" )
				beta96=$( awk '/^96.*beta/ {print $3}' <<< "$driverList" )
				beta71=$( awk '/^71.*beta/ {print $3}' <<< "$driverList" )
				driverList="$betaCurrent:$beta173:$beta96:$beta71"
				;;
			$FGLRX)
				driverList="$( wget -T 3 -t 2 -qO - $FG_LIVE_DRIVERS )"
				betaCurrent=$( grep 'beta' <<< "$driverList" )
				driverList=$betaCurrent
				# echo 'bc^'$betaCurrent'^'
				;;
		esac
	fi

	#return processed betas
	echo $driverList
}

# this is to get the live data for print out only, for apps that might use this
# this is only for -p script printout, and is triggered by: -p -! 121
reset_using_live_driver_data()
{
	if [ "$B_SKIP_WGET" != 'true' ];then
		local uaFull="-U s-tools/sgfxi-data.tool-data" 
		local driverList="$( wget $uaFull -T 3 -t 2 -qO - http://smxi.org/sg/data/sg-drivers-23 )"
		local nvidiaDefault=$( grep -iA 1 'NVidia Default Stable' <<< "$driverList" | grep 'DEFAULT' )
		local nvidiaBeta=$( grep -iA 1 'Nvidia Beta Drivers' <<< "$driverList" | grep 'DEFAULT' )
		local fglrxDefault=$( grep -iA 1 'Fglrx Main Drivers' <<< "$driverList" | grep 'DEFAULT' )
		
		# reset script locals with remote values, but only if wget succeeded, otherwise use script
		# local values as an acceptable failsafe default.
		if [ -n "$driverList" ];then
			# DEFAULT: 306.23 :: LEGACY 4: 304.23 ::  LEGACY 3: 173.14.27 :: LEGACY 2: 96.43.18 :: LEGACY 1: 71.86.14
			NV_DEFAULT=$( awk '{print $2}' <<< "$nvidiaDefault" )
			NV_LEGACY_1=$( awk '{print $6}' <<< "$nvidiaDefault" ) # old, tnt etc
			NV_LEGACY_2=$( awk '{print $10}' <<< "$nvidiaDefault" ) # ge4xx cards
			NV_LEGACY_3=$( awk '{print $14}' <<< "$nvidiaDefault" ) # 5xxx cards
			NV_LEGACY_4=$( awk '{print $18}' <<< "$nvidiaDefault" ) # 6/7xxx cards
			NV_LEGACY_5=$( awk '{print $22}' <<< "$nvidiaDefault" ) # 8/9xxx/21x cards
			NV_VERSIONS=$( awk '{print $2 ":" $6 ":" $10 ":" $14 ":" $18 ":" $22 }' <<< "$nvidiaDefault" )
			
			# DEFAULT: 260.19.06 :: LEGACY 3: N/A :: LEGACY 2: N/A  :: LEGACY 1: N/A
			## beta drivers 
			NV_DEFAULT_BETA=$( awk '{print $2}' <<< "$nvidiaBeta" ) # >= 6xxx
			NV_LEGACY_BETA_1=$( awk '{print $6}' <<< "$nvidiaBeta" ) # old, tnt etc
			NV_LEGACY_BETA_2=$( awk '{print $10}' <<< "$nvidiaBeta" ) # ge4xx cards
			NV_LEGACY_BETA_3=$( awk '{print $14}' <<< "$nvidiaBeta" ) # 5xxx cards
			NV_LEGACY_BETA_4=$( awk '{print $18}' <<< "$nvidiaBeta" ) # 5xxx cards
			NV_LEGACY_BETA_5=$( awk '{print $22}' <<< "$nvidiaBeta" ) # 5xxx cards
			
			# DEFAULT: 10-9 :: PREVIOUS 1: 10-8 :: PREVIOUS 2: 9-3
			# fglrx drivers
			FG_DEFAULT=$( awk '{print $2}' <<< "$fglrxDefault" )
			FG_VERSIONS=$( awk '{print $2 ":" $6 ":" $10 }' <<< "$fglrxDefault" )
		fi
	fi
}

### -------------------------------------------------------------------
### general script utilities
### -------------------------------------------------------------------

# args: $1 - get/set; $2 - prefname
get_set_prefs()
{
	eval $LOGUS
	local etcsm='/etc/smxi.conf' retValue='' name='' value=''

	case $1 in
		get)
			retValue=$( grep -s $2 $etcsm )
			echo $retValue
			log_function_data "Return value: $retValue"
			;;
		set)
			touch $etcsm
			# test = first, this will handle the base name and anything else
			name=$( cut -d '=' -f 1 <<< $2 )
			# check to see if it's there, if it is, it must be a = type thing
			if [ -z "$( grep -s $name $etcsm )" ];then
				echo $2 >> $etcsm
				log_function_data "Added $2 to $etcsm"
			else
				sed -i "s/$name.*/$2/" $etcsm
				log_function_data "Updated $name to $2 in $etcsm"
			fi
			;;
	esac
	eval $LOGUE
}

# handles bug in stub installer that leaves tempfiles uncleaned
cleanup_update_files()
{
	eval $LOGUS
	local all_files="" slxorg='sgfxi-lib-xorg'

	# Note: if  * is in "" the wildcard does not work
	# /dev/null handles case where no temp or original file exists
	all_files=$( ls "${SCRIPT_NAME}."* 2> /dev/null )
	# make sure stuff exists, rm files
	if [ -n "$all_files" ];then
		rm -f $all_files
	fi
	if [ -f $slxorg ];then
		rm -f $slxorg # clean up old xorg lib file
	fi
	if [ -d /usr/src/kernel-downloads -a ! -d $SM_KERNEL_DOWNLOADS  ];then
		mv -f /usr/src/kernel-downloads $SM_KERNEL_DOWNLOADS
	fi
	
	eval $LOGUE
}

# make the default locations for driver run package files
create_data_storage()
{
	local nvidiaPackages='' fglrxPackages='' bMoved='false'
	# don't run this in case of user set test paths
	if [ ! -d "$SCRIPT_WORKING_DIR" -a "$B_TESTING_1" != 'true' ];then
		echo $LINE
		echo "${S}Creating ${C}$SCRIPT_WORKING_DIR${S} to store driver downloads in...${N}"
		mkdir -p $SCRIPT_WORKING_DIR
		rm -f ${USRS}nohup.out &>/dev/null # sometimes these get left over...
		rm -rf /usr/src/nvidia-installer &>/dev/null # this can cause weirdness so dump it
		nvidiaPackages=$( ls ${USRS} 2>/dev/null | grep -Esi '^nvidia' )
		nvidiaPackages=$( echo $nvidiaPackages )
		fglrxPackages=$( ls ${USRS} 2>/dev/null | grep -Esi '^(amd-driver-|ati-driver-|fglrx)'  )
		fglrxPackages=$( echo $fglrxPackages )
		log_function_data "nvidiaPackages:\n$nvidiaPackages"
		log_function_data "fglrxPackages:\n$fglrxPackages"
		if [ -n "$nvidiaPackages" ];then
			echo "${S}Moving all existing ${C}nVidia${S} data files to ${C}$SCRIPT_WORKING_DIR${S}...${N}"
			for i in $nvidiaPackages
			do
				if [ -e "${USRS}$i" ];then
					mv -f ${USRS}$i $SCRIPT_WORKING_DIR 2>/dev/null
				fi
			done
			bMoved='true'
		fi
		if [ -n "$fglrxPackages" ];then
			echo "${S}Moving all existing ${C}ATI/fglrx${S} data files to ${C}$SCRIPT_WORKING_DIR${S}...${N}"
			for i in $fglrxPackages
			do
				if [ -e "${USRS}$i" ];then
					mv -f ${USRS}$i $SCRIPT_WORKING_DIR 2>/dev/null
				fi
			done
			bMoved='true'
		fi
		if [ "$bMoved" == 'true' ];then
			echo "${S}Please take note of the updated location for the downloaded drivers.${N}"
			print_hec
		fi
	fi
}

clean_script_data()
{
	check_root
	cd $SCRIPT_HOME

	local downloadDirectorySize='' backupFiles='' backupFilesCount=''
	local opt='' bRepeat='false'
	local options="remove-video-driver-downloads delete-xorg.conf-backup-files uninstall-$SCRIPT_NAME quit" 
	
	echo $MLINE
	echo "${M}$SCRIPT_NAME cleanup tool"
	echo $MLINE
	echo "${S}Calculating cleanup data....${N}"
	echo $LINE
	downloadDirectorySize=$( du -ch $SCRIPT_WORKING_DIR 2>/dev/null | grep 'total' )
	backupFiles=$( ls $EXXC-bu* $EXXC.1st* 2>/dev/null )
	backupFilesCount=$( wc -w <<< $backupFiles )
	echo "${S}The following ${C}$SCRIPT_NAME${S} data exists for possible cleanup in your system"
	echo "$SCRIPT_WORKING_DIR: ${C}$downloadDirectorySize${S}"
	echo "$EXXC-bu* backup files: ${C}$backupFilesCount${S}"
	echo $LINE
	echo "${C}1 - remove-video-driver-downloads${S} - Delete ALL video driver downloads."
	echo "${C}2 - delete-xorg.conf-backup-files${S} - Delete ALL xorg.conf backup files."
	echo "${C}3 - uninstall-$SCRIPT_NAME${S} - Removes ALL pieces of $SCRIPT_NAME. Cannot be undone."
	echo "   Will confirm your choice before proceeding."
	
	echo "${C}4 - quit${S} - Exit now."
	echo $LINE
	select opt in $options
	do
		case $opt in
			remove-video-driver-downloads)
				if [ -d $SCRIPT_WORKING_DIR ];then
					rm -rf $SCRIPT_WORKING_DIR
					echo "${C}$SCRIPT_WORKING_DIR${S} deleted. ${C}$downloadDirectorySize${S} cleaned up.${N}"
				else
					echo "${M}No ${C}$SCRIPT_WORKING_DIR${M} directory present so nothing deleted.${N}"
				fi
				bRepeat='true'
				;;
			delete-xorg.conf-backup-files)
				if [ -n "$backupFiles" ];then
					rm -f $backupFiles
					echo "${C}$backupFilesCount $EXXC-bu*${S} back-up files deleted.${N}"
				else
					echo "${M}No ${C}$EXXC-bu*${M} back-up files present so none deleted.${N}"
				fi
				bRepeat='true'
				;;
			uninstall-$SCRIPT_NAME)
				uninstall_script
				;;
			quit)
				echo "${S}Ok, quitting now.${N}"
				exit 0
				;;
			*)	print_error 'opt'
				bRepeat='true'
				;;
		esac
		break
	done
	
	if [ "$bRepeat" == 'true' ];then
		clean_script_data
	fi
}

uninstall_script()
{
	local opt=''
	local options="yes-uninstall-everything return-main-menu"
	echo $LINE
	echo "${S}Are you sure you want to totally uninstall ${C}$SCRIPT_NAME${S}"
	echo "This will remove $SCRIPT_NAME and all its components permanently!"
	echo $LINE
	echo "${S}Enter a number for your selection and hit enter"
	echo $LINE
	echo "${C}1 - yes-uninstall-everything${S} - Completely uninstall $SCRIPT_NAME and its related."
	echo "    components, logs, and configurations."
	echo "${C}2 - return-main-menu${S} - Go back to main menu, skip the uninstall."
	echo $LINE
	select opt in $options
		do
			case $opt in
				yes-uninstall-everything)
					echo "${S}Ok, removing all the pieces now...${N}"
					rm -rf /var/log/${SCRIPT_NAME}*
					rm -f $EXXC-bu* $EXXC.1st*
					rm -f /etc/logrotate.d/${SCRIPT_NAME}*
					rm -rf $SCRIPT_WORKING_DIR
					rm -f $SCRIPT_HOME/video_support_* $SCRIPT_HOME/sg-drivers*
					rm -f $SCRIPT_HOME/${SCRIPT_NAME}*
					rm -f /etc/modprobe.d/kms-sg-blacklist.conf
					echo "${S}Ok, everything is removed. Exiting since $SCRIPT_NAME is now gone.${N}"
					exit 0
					;;
				return-main-menu)
					echo "${S}Ok, going back to cleanup menu now.${N}"
					;;
			esac
			break
	done
	
	if [ "$bRepeat" == 'true' ];then
		uninstall_script
	fi
}
### -------------------------------------------------------------------
### kernel data and header testing
### -------------------------------------------------------------------

kernel_string_info()
{
	# The kernel variables stuff needs to be in a separate function to get data from
	# either the running kernel or the new installed kernel
	if [ -n "$INSTALL_TO_KERNEL" ];then
		KERNEL_FULL=$INSTALL_TO_KERNEL
	else
		KERNEL_FULL=$( uname -r ) # full kernel name
	fi

	if [ -n "$( echo $KERNEL_FULL | grep -sE "[\.|-]slh\(64\)\?[\.|-]" )" ];then
		B_IS_APTOSID_KERNEL='true'
	fi
	if [ -n "$( grep -si 'CONFIG_XEN=y' /boot/config-$KERNEL_FULL )" ];then
		B_IS_XEN='true'
	fi
	# note the extra cut -d '-' -f 1 test is to dump the doubled 2.6.24 in legacy kernel strings.
	# check for new single number syntax, like 3.19
	if [ -n "$( grep -Es '^[3-9]\.' <<< $KERNEL_FULL )" ];then
		KERNEL_BASE=$( echo $KERNEL_FULL | cut -d '.' -f 1 ) # like: 3
		KERNEL_NUMBER=$( echo $KERNEL_FULL | cut -d '-' -f 1 | cut -d '.' -f 1-2 ) # like: 3.19
		KERNEL_MATH=$( echo $KERNEL_FULL | cut -d '-' -f 1 | cut -d '.' -f 2 ) # like: 19
	# else check for old 2.6.19 style
	else
		KERNEL_BASE=$( echo $KERNEL_FULL | cut -d '.' -f 1-2 ) # like: 2.6
		KERNEL_NUMBER=$( echo $KERNEL_FULL | cut -d '-' -f 1 | cut -d '.' -f 1-3 ) # like: 2.6.19
		KERNEL_MATH=$( echo $KERNEL_FULL | cut -d '-' -f 1 | cut -d '.' -f 3 ) # like: 19
	fi
	if [ -n "$( grep -is "PAE" <<< $KERNEL_FULL )" ];then
		FED_KERNEL_PAE='-PAE'
	fi
}

# The best test I've found so far to check whether the kernel exists or not:
test_install_kernel_version()
{
	if [ ! -d /lib/modules/$INSTALL_TO_KERNEL ];then
		echo "${S}These are your currently installed kernels:${C}"
		ls /lib/modules
		echo ${N}
		error_handler 232 $INSTALL_TO_KERNEL
		#comment the line above to debug the kernel_string_info function - Also uncomment the debug lines in that function
	# it passed the test
	else
		kernel_string_info
	fi
}

# this handles a case where there's a kernel header mismatch or
# when they are simply missing, the former is strange, the latter normal
check_kernel_headers()
{
	eval $LOGUS
	local headerName=''
	local headerPresent=''
	local headerInstalled='' testKernel=''
	
	case $SYSTEM_BASE in
		debian|ubuntu)
			headerName="linux-headers-$KERNEL_FULL"
			headerPresent="$( ls ${USRS}$headerName/ 2>/dev/null )"
			headerInstalled=$( check_package_status "$headerName" 'i' )
			# want to make sure it's available, and not merely referenced
			local headerAvailable=$( check_package_status "$headerName" 'c' )
			local headerFile="$( ls ${SM_KERNEL_DOWNLOADS}/$KERNEL_FULL/$headerName*.deb 2>/dev/null )"
		
			log_function_data "headerPresent: $headerPresent\nheaderName: $headerName\nheaderInstalled: $headerInstalled\nheaderAvailable: $headerAvailable\nheaderFile: $headerFile"
		
			# first try direct apt install, then dpkg from smxi downloads, then give up
			if [ -n "$headerPresent" ];then
				: # do nothing, it's there
			elif [ -z "$headerInstalled" -a -n "$headerAvailable" ];then
				echo "${S}Installing missing kernel header package ${C}$headerName${S} before proceeding...${N}"
				install_package "$headerName"
			elif [ -z "$headerInstalled" -a -n "$headerFile" -a -f "$headerFile" ];then
				echo "${S}Installing missing kernel header package ${C}$headerName${S}"fse
				echo "using your archived header package: ${C}$headerFile${N}"
				dpkg -i $headerFile || error_handler 223 "$headerFile"
			elif [ -z "$headerInstalled" -a -z "$headerAvailable" -a "$B_TESTING_5" != 'true' ];then
				error_handler 224 "$headerName"
			fi
			;;
		fedora)
			# fedora 12 headers: /usr/src/kernels/$(uname -r)
			# kernel-PAE-devel-2.6.31.5-127.fc12.i686.rpm
			local kernelDevel='' develPresent='' kernelWorking=''
			# need to slice off .PAE from working kernel name/headers name
			kernelWorking=$( sed -r 's/\.PAE//' <<< $KERNEL_FULL )
			headerName="kernel-headers-$kernelWorking"
			headerPresent="$( ls ${USRS}kernels/$KERNEL_FULL/ 2>/dev/null )"
			# rpm is reporting two names here I think, we'll see, if it's got the
			# kernel name in it, we'll call it installed.
			headerInstalled=$( check_package_status "$headerName" 'i' | grep $kernelWorking )
			# if [ -z "$headerPresent" -a -z "$headerInstalled" ];then
			if [ -z "$headerInstalled" ];then
				install_package "$headerName"
			fi
			kernelDevel="kernel$FED_KERNEL_PAE-devel-$kernelWorking"
			develPresent=$( check_package_status "$kernelDevel" 'i' )
			if [ -z "$develPresent" ];then
				install_package "$kernelDevel"
			fi
			;;
		# fresh arch installs do not have the kernel header in /usr/src but this test
		# is highly erratic, arch is not using consistent methods, requires more testing
		arch)
			headerName="linux-headers"
			headerPresent="$( ls /lib/modules/$KERNEL_FULL/build/ 2>/dev/null )"
			testKernel=$( grep -Esi '^(2\.6|[3-9]\.[0-9]+)\.[0-9]+-ARCH$' <<< $KERNEL_FULL )
			# 2.6.32-ARCH
			if [ -z "$headerPresent" ];then
				# if it's a custom kernel, no package available so die
				if [ -n "$testKernel" ];then 
					error_handler 224 "$headerName"
				# otherwise let's test for the default, and install it if its missing
				else
					headerInstalled=$( check_package_status "$headerName" 'i' )
					if [ -n "$( check_package_status "$headerName" 'c' )" ];then
						install_package "$headerName"
					else
						error_handler 224 "$headerName"
					fi
				fi
			fi
			;;
	esac
	eval $LOGUE
}

# Nvidia requires for 64 bit ia32 libs installed for 64 bit
# This will satisfy the nVidia driver and also let the installer 
# place the 32-bit compatibility files in the correct location, 
# letting 32-bit applications run properly that depend on OpenGL acceleration.
# args: $1 - full/test
check_ia32_libs()
{
	eval $LOGUS
	
	local returnValue='false'

	if [ "$BITS" == '64' -a "$CARD" == "$NVIDIA" ];then
		local ia32Name='' ia32Path='' 
		local ia32Supported='' ia32Present='' ia32Available=''
		local ia32Installed='' testKernel=''
		local kernelDevel='' develPresent='' kernelWorking=''
		#  dpkg -l | grep -E '^ii  libc6:i386'
		case $SYSTEM_BASE in
			debian|ubuntu)
				ia32Name='ia32-libs-i386:i386'
				ia32Path='/emul/ia32-linux'
				
				if [ "$1" != 'test' ];then
					echo "${S}Checking for ${C}ia32-lib multiarch${S} support for ${C}nVidia 32-bit compatibility layer${S}...${N}"
				fi
				# first verify that we can do this, ie, that the base system supports architectures. Debian Lenny does not have this capability
				ia32Supported=$( dpkg --print-foreign-architectures 2>/dev/null || echo 'false' )
				
				if [ "$ia32Supported" != 'false' ];then
					ia32Present=$( dpkg --print-foreign-architectures | grep -o 'i386' )
					ia32Installed=$( check_package_status "$ia32Name" 'i' )
				fi

				if [ "$ia32Present" == 'i386' -a "$( readlink -f $ia32Path/usr/lib )" == '/usr/lib/i386-linux-gnu' \
				-a -n "$ia32Installed"  ];then
					if [ "$1" != 'test' ];then
						echo "${M}Your system is compatible with ${C}nVidia's${M} proprietary driver ${C}32-bit compatibility layer${M}.${N}"
					fi
					log_function_data "32 bit nvidia compat already present and configured"
				elif [ "$ia32Supported" != 'false' -a  "$1" == 'test' ];then
					returnValue='true'
					log_function_data "32 bit nvidia supported. Showing install option."
				elif [ "$ia32Supported" != 'false' -a  "$1" == 'full' ];then
					###############################
					# Check all the requirements for 32-bit support for nVidia drivers in 64-bit
					# one by one, correcting any discrepancies if found.
					###############################
					# add i386 multi-arch support if missing
					if [ "$ia32Present" != 'i386' ]; then
						echo "${S}Missing ${C}i386 multiarch${S} support, adding...${N}"
						dpkg --add-architecture i386
						# force reset to grab the new arch i386 repo data
						B_UPDATED='false'
						update_package_manager 'update'
						log_function_data "added i386 multiarch support and updated."
					fi
					# then check that i386 package exists
					ia32Available=$( check_package_status "$ia32Name" 'c' )
					
					# since ia23 has too many dependencies that can break in sid, and have, we need to confirm that
					# it is working for real even if apt-cache policy reports an install candidate
					if [ "$( apt-get -s install $ia32Name &>/dev/null || echo 'bad' )" != 'bad' ];then
						# install ia32-libs if missing
						if [ -z "$ia32Installed" -a -n "$ia32Available" ]; then
							echo "${S}Installing missing package ${C}$ia32Name${S}...${N}"
							install_package "$ia32Name"
						fi
						# confirm that package is installed, some weird system glitches made install fail
						ia32Installed=$( check_package_status "$ia32Name" 'i' )
						if [ -n "$ia32Installed" ];then
							# create required /emul directory if missing
							if [ ! -d "$ia32Path/usr" ]; then
								echo "${S}Missing ${C}$ia32Path${S}, creating...${N}"
								mkdir -p $ia32Path/usr
								log_function_data "Created missing $ia32Path/usr directory."
							fi
							# fix symlink to multiarch i386 folder if wrong
							if [ ! -L "$ia32Path/usr/lib" ] && \
							[ "$(readlink -f $ia32Path/usr/lib)" != '/usr/lib/i386-linux-gnu' ]; then
								if [ -e "$ia32Path/usr/lib" ]; then
									echo "${M}Not sure what ${C}${ia32Path}/usr/lib${M} is, removing it.${N}"
									rm -rf $ia32Path/usr/lib
									log_function_data "Removed mysterious $ia32Path/usr/lib directory."
								fi
								ln -s /usr/lib/i386-linux-gnu $ia32Path/usr/lib
								echo "${S}Created symlink at ${C}$ia32Path/usr/lib${S}.${N}"
								log_function_data "Created sym link $ia32Path/usr/lib"
							fi
							echo "${S}Your system is now compatible with ${C}nVidia's${S} proprietary driver ${C}32-bit compatibility layer${S}.${N}"
						else
							echo "${W}No ${C}$ia32Name${W} installed or present in ${C}APT${W}. Please let the ${C}$SCRIPT_NAME${W} maintainer know."
							echo "Unable to complete ${C}$NVIDIA 32 bit compatibility layer${W} setup. Continuing to driver install.${N}"
							log_function_data "Missing $ia32Name package, not installed."
						fi
					else
						echo "${M}There is a problem in ${C}APT${M} currently. Unable to install ${C}$ia32Name${M}. Continuing"
						echo "Try running ${C}$SCRIPT_NAME${M} again in a day or two and the issue should be resolved.${N}"
						log_function_data "APT reported error on attempt to -s install $ia32Name."
					fi
				else
					if [ "$1" != 'test' ];then
						echo "${M}Your system ${C}$SYSTEM_BASE $SYSTEM_CODENAME${M} is ${C}NOT${M} compatible with ${C}$ia32Name${M}. Continuing with driver install.${N}"
					fi
					log_function_data "No dpkg -add-architecture supported."
				fi
				;;
# 			fedora)
# 				# fedora 12 headers: /usr/src/kernels/$(uname -r)
# 				# kernel-PAE-devel-2.6.31.5-127.fc12.i686.rpm
# 				
# 				# need to slice off .PAE from working kernel name/headers name
# 				kernelWorking=$( sed -r 's/\.PAE//' <<< $KERNEL_FULL )
# 				ia32Name="kernel-headers-$kernelWorking"
# 				ia32Present="$( ls ${USRS}kernels/$KERNEL_FULL/ 2>/dev/null )"
# 				# rpm is reporting two names here I think, we'll see, if it's got the
# 				# kernel name in it, we'll call it installed.
# 				ia32Installed=$( check_package_status "$ia32Name" 'i' | grep $kernelWorking )
# 				# if [ -z "$ia32Present" -a -z "$ia32Installed" ];then
# 				if [ -z "$ia32Installed" ];then
# 					install_package "$ia32Name"
# 				fi
# 				kernelDevel="kernel$FED_KERNEL_PAE-devel-$kernelWorking"
# 				develPresent=$( check_package_status "$kernelDevel" 'i' )
# 				if [ -z "$develPresent" ];then
# 					install_package "$kernelDevel"
# 				fi
# 				;;
# 			# fresh arch installs do not have the kernel header in /usr/src but this test
# 			# is highly erratic, arch is not using consistent methods, requires more testing
# 			arch)
# 				ia32Name=""
# 				ia32Present=""
# 				testKernel=$( grep -Esi '^2\.6\.[0-9]{2}-ARCH$' <<< $KERNEL_FULL )
# 				# 2.6.32-ARCH
# 				if [ -z "$ia32Present" ];then
# 					# if it's a custom kernel, no package available so die
# 					if [ -n "$testKernel" ];then 
# 						error_handler 224 "$ia32Name"
# 					# otherwise let's test for the default, and install it if its missing
# 					else
# 						ia32Installed=$( check_package_status "$ia32Name" 'i' )
# 						if [ -n "$( check_package_status "$ia32Name" 'c' )" ];then
# 							install_package "$ia32Name"
# 						else
# 							error_handler 224 "$ia32Name"
# 						fi
# 					fi
# 				fi
# 				;;
		esac
	fi
	
	if [ "$1" == 'test' ];then
		echo $returnValue
	fi
	eval $LOGUE
}

### -------------------------------------------------------------------
### startup and tools testing
### -------------------------------------------------------------------

# note that we want this to print with no root error
check_root()
{
	if [ "$B_PRINT_VER" != 'true' ];then
		# if started with sudo, this will pass
		if [ "$( whoami )" != 'root' ];then
			error_handler 251
		fi
		#Check if started with sudo, not root
		if [ -n "$SUDO_USER" ] ; then
			error_handler 211
		fi
		# this can detect 'sudo su -' if required
		local startPPID=$( ps -j -fp $PPID 2>/dev/null | awk '/root/ {print $3}' )
		local startPPPID=$( ps -j -fp $startPPID 2>/dev/null | awk '/root/ {print $3}' )
		local sudoBase=$( ps -j -fp $startPPPID 2>/dev/null | grep -Eos 'sudo su.*' )
		# log_function_data "startPPID: $startPPID\nstartPPPID: $startPPPID\nsudoBase: $sudoBase"
		if [ -n "$sudoBase" ];then
			echo "${M}Information: Starting $SCRIPT_NAME with: ${C}$sudoBase${N}"
			SUDO_START=$sudoBase
		fi
	fi
}

basic_startup_tests()
{
	## basic execute requirements
	cd $SCRIPT_HOME
	check_root
	# this allows users to update in x, for example, to see latest drivers
	if [ "$B_FORCE_UPDATE" == 'true' ];then
		check_update_script "$SCRIPT_NAME" "$SCRIPT_DOWNLOAD" 'default server'
	fi
	check_set_distro
	# initial systemd handling
	if [ -n "$( type -p systemctl )" ];then
		B_SYSTEMD='true'
		#systemdData="$( systemctl list-units --type=target 2>/dev/null)"
		#if [ -n "$( grep -sE '^sysinit.target.*[[:space:]]active' <<< "$systemdData" )" ];then
		# this is totally reliable, shows systemd or init
		systemdData="$( cat /proc/1/comm 2>/dev/null)"
		if [ -n "$( grep 'systemd' <<< "$systemdData" )" ];then
			B_SYSTEMD_SYSINIT='true'
		fi
		systemdData="$( systemctl status graphical.target 2>/dev/null )"
		if [ -n "$( grep -Eis '^[[:space:]]*Loaded:[[:space:]]*loaded' <<< "$systemdData" )" ];then
			B_SYSTEMD_GRAPHICAL='true'
		fi
	fi
	# not making this elif for now because who knows what ubuntu will actually do with upstart
	if [ -n "$( type -p initctl )" ];then
		B_UPSTART='true'
	fi
	# make sure Xorg is installed
	if [ -z "$( which Xorg )" ];then
		error_handler 244
	fi
	# make sure xorg.conf exists, with xorg > 1.4 exception to handle null xorg.conf
	if [ ! -f $EXXC -a -z "$( echo $X_VERSION | grep -E '[1-4]\.[0-9]+(\.[0-9]+)?' )" ];then
		error_handler 249
	fi
	# double check only 2.6 or newer series kernels, note double [[ and <
	if [[ "$KERNEL_BASE" < 2.6 ]];then
		error_handler 243
	fi
	
	cleanup_update_files
	check_script_depends

	# only support current systems, xorg >= 7.1/1.x
	if [ -z "$X_VERSION" ];then
		error_handler 242
	fi
	# this corrects a stupid mistake I made
	rm -f *-sgfxi.log # was creating log files in /usr/local/bin
	# test to see if any dm is running, we'll shutdown all wm later though
	if [ -n "$DISPLAY" -a "$B_SKIP_X_TEST" != 'true' -a "$B_KERNEL_MODULE_ONLY" != 'true' \
	     -a "$B_PRINT_VER" != 'true' -a "$B_LAUNCH_FROM_X" != 'true' ];then
		error_handler 250
	fi
	case $SYSTEM_BASE in
		ubuntu)
			# we need to confirm that restricted repos are enabled before continuing
			if [ "$B_USE_DISTRO_DRIVER" == 'true' ];then
				update_to_nonfree_sources
			fi
			;;
	esac
}

get_current_runlevel()
{
	local currentRunlevel=$( echo $(runlevel) | awk '{print $NF}' )
	echo $currentRunlevel
}

# this is a quick / dirty check so sgfxi can know if a user system
# has a live connection or not. This is mainly for logging/debugging
check_connection()
{
	local checkUrl=${SCRIPT_DOWNLOAD_DATA}connection-test result=0
	local ua='-U s-tools/sgfxi-data.connection-test'
	
	wget $ua -q -t 1 -T 2 --spider $checkUrl || result=$?
	echo $result
}

## basic system requirements for this script to run, first so user doesn't
## have to be root or out of x to get basic failure information
check_set_distro()
{
	local lsbOsrData='' workingId=''
	local isStable='' isTesting='' isUnstable=''
	local etcIssue=$( cat /etc/issue 2>/dev/null )
	
	# make sure that it's a debian/arch/ubuntu based system
	# note that mint/ubuntu have file /etc/debian_version so we need to be careful here
	if [ -n "$( grep -si 'buntu' <<< $etcIssue )" ];then
		workingId='ubuntu'
	# mint test, note that for new lmde we are treating it as pure debian
	elif [ -n "$( grep -si 'mint' <<< $etcIssue )" -a -z "$( grep -si 'Linux Mint Debian' <<< $etcIssue )" ];then
		workingId='linuxmint'
	# debian defaults, might miss other ubuntu derived distros but those will
	# be handled as we find them, empirically.
	elif [ -f "$EDV" -o -f "$EDVV" ];then # edvv is devuan
		# set files to ram first, no need to keep reading them
		local edvContent='' easContent='' eaaContent='' edvFile=''
		
		if [ -f "$EDV" ];then
			edvFile=$EDV
		elif [ -f "$EDVV" ];then
			edvFile=$EDVV
		fi
		
		workingId='debian'
		
		if [ -n "$( grep -si 'Linux Mint Debian' <<< $etcIssue )" ];then
			workingId='linuxmint-debian'
		fi
		
		if [ -f "$edvFile" ];then
			edvContent="$( cat $edvFile )"
		fi
		if [ -f "$EAS" -o -d "$EAS.d" ];then
			easContent="$( cat $EAS $EAS.d/*.list 2>/dev/null )"
		fi
		if [ -f "$EAA" ];then
			eaaContent="$( cat $EAA )"
		fi
		
		# these tests will be improved over time, but are ok for now
		local isEtch=$( grep -is '^4.' <<< "$edvContent" )
		local isLenny=$( grep -is '^5.' <<< "$edvContent" )
		local isSqueeze=$( grep -Eis '^(squeeze|6\.)' <<< "$edvContent" )
		local isWheezy=$( grep -Eis '^(wheezy|7\.)' <<< "$edvContent" )
		local isJessie=$( grep -Eis '^(jessie|8\.)' <<< "$edvContent" )
		local isStretch=$( grep -Eis '^(stretch|9\.)' <<< "$edvContent" )

		# first tests sources
		local isStable=$( grep -Esiw '^[[:space:]]*deb' <<< "$easContent" | grep -Eiv "$NON_DEBIAN_PATTERN" | grep -Eicw '(stable|wheezy|squeeze|lenny|etch|jessie)' )
		local isTesting=$( grep -Esiw '^[[:space:]]*deb' <<< "$easContent" | grep -Eiv "$NON_DEBIAN_PATTERN" | grep -Eicw '(stretch|testing)' )
		local isUnstable=$( grep -Esiw '^[[:space:]]*deb' <<< "$easContent" | grep -Eiv "$NON_DEBIAN_PATTERN" | grep -Eicw '(sid|unstable)' )
		
		# then test conf for default version
		local isStableDefault=$( grep -Esi 'APT::Default-Release[[:space:]]"(stable|etch|lenny|squeeze|wheezy|jessie)"' <<< "$eaaContent" )
		local isTestingDefault=$( grep -Esi 'APT::Default-Release[[:space:]]"(testing|stretch)"' <<< "$eaaContent" )
		local isUnstableDefault=$( grep -Esi 'APT::Default-Release[[:space:]]"(sid|unstable)"' <<< "$eaaContent" )
	# arch tests
	elif [ -f "$EAR" ] || [ -n "$( grep -si '^arch' <<< $etcIssue  )" ];then
		workingId='arch'
	elif [ -f "$EFR" ] || [ -n "$( grep -si '^fedora' <<< $etcIssue  )" ];then
		workingId='fedora'
	else
		error_handler 252
	fi
	
	# ideally all distros would use lsb/os-release, but sadly they don't. 
	if [ -s $ELR ];then
		lsbOsrData="$( cat $ELR )"
		DISTRIB_CODENAME=$( grep 'DISTRIB_CODENAME' <<< "$lsbOsrData" | cut -d '=' -f 2 | tr '[A-Z]' '[a-z]' )
		DISTRIB_ID=$( grep 'DISTRIB_ID' <<< "$lsbOsrData" | cut -d '=' -f 2 | tr '[A-Z]' '[a-z]' )
		DISTRIB_RELEASE=$( grep 'DISTRIB_RELEASE' <<< "$lsbOsrData" | cut -d '=' -f 2 | tr '[A-Z]' '[a-z]' )
# 	elif [ -s $EOR ];then
# 		lsbOsrData="$( cat $EOR )"
# 		# DISTRIB_CODENAME=$( grep 'DISTRIB_CODENAME' <<< "$lsbOsrData" | cut -d '=' -f 2 | tr '[A-Z]' '[a-z]' )
# 		DISTRIB_ID=$( grep '^ID' <<< "$lsbOsrData" | cut -d '=' -f 2 | tr '[A-Z]' '[a-z]' | tr '/' '-' )
		# DISTRIB_RELEASE=$( grep '^PRETTY_NAME' <<< "$lsbOsrData" | awk '{print $NF}' | tr '[A-Z]' '[a-z]' | tr '/' '-'  )
	fi
	
	case $workingId in
		arch)
			APT_TYPE='pacman'
			DISTRO_FGLRX=$ARCH_FGLRX
			DISTRO_NVIDIA=$ARCH_NVIDIA
			SYSTEM_BASE='arch'
			SYSTEM_CODENAME='arch'
			SCRIPT_HOME='/usr/bin'
			X_NAME='Xorg'
			;;
		debian|linuxmint-debian)
			DISTRO_FGLRX=$DEBIAN_FGLRX
			DISTRO_NVIDIA=$DEBIAN_NVIDIA
			FG_DISTRIB_ID='Debian'
			SYSTEM_BASE='debian' # debian not using elr file yet
			if [ "$workingId" == 'linuxmint-debian' ];then
				APT_TYPE='apt-get'
			fi
			# set system type. This test will never be perfect, but it's a good approximation
			if [ -n "$isEtch" -o -n "$isLenny" -o -n "$isSqueeze" -o -n "$isWheezy"  -o -n "$isJessie" -o -n "$isStableDefault" ] || [ "$isStable" -gt 0 -a "$isUnstable" -eq 0  -a "$isTesting" -eq 0 ];then
				if [ -n "$isEtch" ];then
					FG_DISTRIB_CODENAME='etch'
					SYSTEM_CODENAME='etch'
				elif [ -n "$isLenny" ];then
					FG_DISTRIB_CODENAME='lenny' # note: 'stable' breaks the installer
					SYSTEM_CODENAME='lenny'
				elif [ -n "$isSqueeze" ];then
					FG_DISTRIB_CODENAME='squeeze' # note: 'stable' breaks the installer
					SYSTEM_CODENAME='squeeze'
				elif [ -n "$isWheezy" ];then
					FG_DISTRIB_CODENAME='wheezy' # note: 'stable' breaks the installer
					SYSTEM_CODENAME='wheezy'
				elif [ -n "$isJessie" ];then
					FG_DISTRIB_CODENAME='jessie' # note: 'stable' breaks the installer
					SYSTEM_CODENAME='jessie'
				else
					FG_DISTRIB_CODENAME='stable'
					SYSTEM_CODENAME='stable'
				fi
			elif [ "$isUnstable" -eq 0 -o -n "$isTestingDefault" ] && [ -n "$isStretch" -o "$isTesting" -gt 0 ];then
				FG_DISTRIB_CODENAME='sid'
				SYSTEM_CODENAME='testing'
			else
				FG_DISTRIB_CODENAME='sid'
				SYSTEM_CODENAME='sid'
			fi
			X_NAME='X'
			# these will be used for various advanced tests in some components
			# commented out because debian  now uses os-release by default
# 			if [ -z "$DISTRIB_ID" ];then
				if [ -f /etc/siduction-version ];then
					DISTRIB_ID='siduction'
				elif [ -f /etc/aptosid-version ];then
					DISTRIB_ID='aptosid'
				elif [ -f /etc/sidux-version ];then
					DISTRIB_ID='sidux'
				elif [ -f /etc/antix-version ];then
					DISTRIB_ID='antix'
				elif [ -f /etc/lsb-release-crunchbang ];then
					DISTRIB_ID='crunchbang'
				fi
# 			fi
			;;
		fedora)
			APT_TYPE='yum'
			DISTRO_FGLRX=$FEDORA_FGLRX
			DISTRO_NVIDIA=$FEDORA_NVIDIA
			FG_DISTRIB_ID='Fedora'
			FG_DISTRIB_CODENAME=''
			SYSTEM_BASE='fedora'
			if [ -f "$EFR" ];then
				DISTRIB_CODENAME=$( grep '^DISTRIB_CODENAME' $EFR | cut -d '=' -f 2 | tr '[A-Z]' '[a-z]' | awk '{print $1}' )
				SYSTEM_CODENAME=$DISTRIB_CODENAME
# 				DISTRIB_CODENAME=$( grep -si 'Fedora' $EFR | sed -r 's/Fedora.*\((.*)\)/\1/i' )
# 				SYSTEM_CODENAME=$( grep -si 'Fedora' $EFR | sed -r 's/Fedora.*[[:space:]]([0-9]+)[[:space:]]\(.*\)/\1/i' )
			fi
			X_NAME='X'
			;;
		linuxmint)
			APT_TYPE='apt-get'
			DISTRO_FGLRX=$UBUNTU_FGLRX
			DISTRO_NVIDIA=$UBUNTU_NVIDIA
			FG_DISTRIB_ID='Ubuntu'
			SYSTEM_BASE='ubuntu'
			# need to double check here for fglrx deb builder
			case $DISTRIB_RELEASE in
				6)	FG_DISTRIB_CODENAME='intrepid'
					SYSTEM_CODENAME='intrepid'
					;;
				7)	FG_DISTRIB_CODENAME='jaunty'
					SYSTEM_CODENAME='jaunty'
					;;
				8)	FG_DISTRIB_CODENAME='karmic'
					SYSTEM_CODENAME='karmic'
					;;
				9)	FG_DISTRIB_CODENAME='lucid'
					SYSTEM_CODENAME='lucid'
					;;
				10)FG_DISTRIB_CODENAME='maverick'
					SYSTEM_CODENAME='maverick'
					;;
				11)FG_DISTRIB_CODENAME='natty'
					SYSTEM_CODENAME='natty'
					;;
			esac
			X_NAME='X'
			;;
		ubuntu)
			DISTRO_FGLRX=$UBUNTU_FGLRX
			DISTRO_NVIDIA=$UBUNTU_NVIDIA
			FG_DISTRIB_ID='Ubuntu'
			FG_DISTRIB_CODENAME=$DISTRIB_CODENAME
			SYSTEM_BASE='ubuntu'
			SYSTEM_CODENAME=$DISTRIB_CODENAME
			X_NAME='X'
			if [ -f /etc/lsb-release-crunchbang ];then
				DISTRIB_ID='crunchbang-ubuntu'
			fi
			;;
		*)
			## basic system requirements for this script to run, first so user doesn't
			## have to be root or out of x to get basic failure information
			# make sure that it's a debian based system
			error_handler 252
			;;
	esac
	if [ -z "$DISTRIB_ID" ];then
		DISTRIB_ID=$SYSTEM_BASE
	fi
	if [ -z "$DISTRIB_CODENAME" ];then
		DISTRIB_CODENAME=$SYSTEM_CODENAME
	fi
	SIS=$DISTRIB_ID-$DISTRIB_CODENAME-$BITS
}

check_run_package_tools()
{
	eval $LOGPS
	local makePath=$( type -p make )
	local patchPath=$( type -p patch )
	
	if [ -z "$makePath" ];then
		if [ -n "$( check_package_status 'make' 'c' )" ];then
			install_package 'make'
		fi
	fi
	if [ -z "$patchPath" ];then
		if [ -n "$( check_package_status 'patch' 'c' )" ];then
			install_package 'patch'
		fi
	fi
	
	eval $LOGPE
}

check_script_depends()
{
	eval $LOGPS
	local wgetPath=$( type -p wget )
	local logrotatePath=$( type -p logrotate )
	
	if [ -z "$wgetPath" ];then
		if [ -n "$( check_package_status 'wget' 'c' )" ];then
			install_package 'wget'
		fi
	fi
	if [ -z "$logrotatePath" ];then
		if [ -n "$( check_package_status 'logrotate' 'c' )" ];then
			install_package 'logrotate'
		fi
	fi
	eval $LOGPE
}

check_driver_install_tools()
{
	eval $LOGPS
	
	local fakerootPath=$( type -p fakeroot )
	
	# nvidia and fglrx tools check_package_status
	case $SYSTEM_BASE in
		debian|ubuntu)
			if [ -z "$( check_package_status 'module-assistant' 'i' )" ];then
				if [ -n "$( check_package_status 'module-assistant' 'c' )" ];then
					install_package 'module-assistant'
				fi
			fi
			if [ -z "$( check_package_status 'build-essential' 'i' )" ];then
				if [ -n "$( check_package_status 'build-essential' 'c' )" ];then
					install_package 'build-essential'
				fi
			fi
			
			;;
# 		arch)
# 			if [ -z "$( check_package_status 'gcc' 'i' )" ];then
# 				if [ -n "$( check_package_status 'gcc' 'c' )" ];then
# 					install_package 'gcc'
# 				fi
# 			fi
# 			;;
	esac
	
	if [ -z "$fakerootPath" ];then
		if [ -n "$( check_package_status 'fakeroot' 'c' )" ];then
			install_package 'fakeroot'
		fi
	fi
	# note wget test needs to be in first main test function

	if [ "$CARD" == $NVIDIA ];then
		:
	# fglrx tools and tests
	elif [ "$CARD" == $FGLRX ];then
		case $SYSTEM_BASE in
			debian|ubuntu)
				if [ -z "$( check_package_status 'debhelper' 'i' )" ];then
					if [ -n "$( check_package_status 'debhelper' 'c' )" ];then
						install_package 'debhelper'
					fi
				fi
				# presence of this package will break fglrx install
				if [ -n "$( check_package_status 'dpkg-cross' 'i' )" ];then
					remove_package 'dpkg-cross' "$CARD"
				fi
				if [ -z "$( check_package_status 'libstdc++5' 'i' )" ];then
					if [ -n "$( check_package_status 'libstdc++5' 'c' )" ];then
						install_package 'libstdc++5'
					fi
				fi
				if [ -z "$( check_package_status 'libstdc++6' 'i' )" ];then
					if [ -n "$( check_package_status 'libstdc++6' 'c' )" ];then
						install_package 'libstdc++6'
					fi
				fi
				if [ -z "$( check_package_status 'unzip' 'i' )" ];then
					if [ -n "$( check_package_status 'unzip' 'c' )" ];then
						install_package 'unzip'
					fi
				fi
				;;
			arch)
				if [ -z "$( check_package_status 'unzip' 'i' )" ];then
					if [ -n "$( check_package_status 'unzip' 'c' )" ];then
						install_package 'unzip'
					fi
				fi
				;;
		esac
	fi

	eval $LOGPE
}

# compare 2 dot [5.34.6] or 1/0 dot [3.45, 3] version numbers
# return codes: 0 - $1 > $2; 1 - $1 == $2; 2 - $1 < $2
# note: this also works for one dot, like 3.4, and for 0 dot, like 3
# note: this function will always be sent . type numbers, and it handles any
# localization re decimal indicators internally, otherwise it's too much of a pain.
# Handles cases like 13.10 > 13.9 as well, ie, 10>9
# Make sure all numbers passed to this function only contain numbers/dots, like: 195.23.23
# if any non numeric values are encountered the function will return 3, which means one of the
# numbers was not numeric almost certainly.
compare_numbers()
{
	eval $LOGUS

	# first we need to determine what the base system is using for decimal indicator
	local returnValue='' 
	local oneTwo=0 oneThree=0 twoTwo=0 twoThree=0
	local b_debug='false'
	# local decimalType=$( echo 1 | awk '{total = 1 / 2; print total}' | grep -Eo '(\.|,)' )

	# next we'll get the raw data and transate it into separate numbers, this also handles cases
	# like 13.10 is greater than 13.9 for versions
	local oneOne=$( cut -d '.' -f 1 <<< $1 )
	local twoOne=$( cut -d '.' -f 1 <<< $2 )
	if [ -z "$oneOne" ];then
		oneOne=0
	fi
	if [ -z "$twoOne" ];then
		twoOne=0
	fi
	
	returnValue=$( number_compare $oneOne $twoOne )
	# only do more tests if first numbers are equal
	if [ "$returnValue" -eq 1 ];then
		oneTwo=$( cut -d '.' -f 2 <<< $1 )
		twoTwo=$( cut -d '.' -f 2 <<< $2 )
		if [ -z "$oneTwo" ];then
			oneTwo=0
		fi
		if [ -z "$twoTwo" ];then
			twoTwo=0
		fi
		
		returnValue=$( number_compare $oneTwo $twoTwo )
		# only do more tests if second numbers are equal
		if [ "$returnValue" -eq 1 ];then
			oneThree=$( cut -d '.' -f 3 <<< $1 )
			twoThree=$( cut -d '.' -f 3 <<< $2 )
			if [ -z "$oneThree" ];then
				oneThree=0
			fi
			if [ -z "$twoThree" ];then
				twoThree=0
			fi
			returnValue=$( number_compare $oneThree $twoThree )
		fi
	fi

	if [ "$b_debug" == 'true' ];then
		echo "oneOne: $oneOne"
		echo "oneTwo: $oneTwo"
		echo "oneThree: $oneThree"
		echo "twoOne: $twoOne"
		echo "twoTwo: $twoTwo"
		echo "twoThree: $twoThree"
		echo "returnValue $returnValue"
	fi

	echo $returnValue
	log_function_data "returnValue: $returnValue"
	eval $LOGUE
}
# args: $1 first number; $2 -second number
number_compare()
{
	local compareValue=3 # 3 will be used for debugging of non numberic numbers etc
	
	if [ "$1" -gt "$2" ];then
		compareValue=0
	elif [ "$1" -eq "$2" ];then
		compareValue=1
	elif [ "$1" -lt "$2" ];then
		compareValue=2
	fi
	echo $compareValue
}
## DEBUGGER
# compare_numbers 13.101.233 13.101.222 ;exit

# for smxi launch in X
launch_from_X()
{
	if [ "$B_LAUNCH_FROM_X" == 'true' ];then
		if [ "$( tty | grep pts )" ];then
			#TERM=linux
			TERM=1
			exec openvt -s bash -c "$SCRIPT_NAME $@; bash"
		fi
	fi
}

### -------------------------------------------------------------------
### package manager tools
### -------------------------------------------------------------------

check_apt_aptitude()
{
	eval $LOGUS
	local opt='' managers='apt-get aptitude quit'
	local aptPref=$( get_set_prefs 'get' 'apt-type' | cut -d '=' -f 2 | grep -E '^(apt-get|aptitude)$' )
	
	# always override first of all
	if [ -n "$aptPref" ];then
		APT_TYPE=$aptPref
	else
		if [ -f /var/log/aptitude ];then
			case $SYSTEM_BASE in
				debian)
					# leave mint debian using apt-get
					if [ -z "$( type -P apt )" ];then
						echo $LINE
						echo "${S}It appears you are using aptitude. It is not good to mix apt-get and aptitude."
						echo "Please pick your preferred package manager before you continue, or exit now."
						echo
						echo "Your selection (for example: ${C}apt-type=apt-get${S}) will be stored in ${C}/etc/smxi.conf${S}"
						echo "${C}smxi${S} will also use this choice for its default package manager, so make sure it's correct."
						echo $LINE
			
						select opt in $managers
						do
							case $opt in
								apt-get|aptitude)
									APT_TYPE=$opt
									log_function_data "Selected package manager: $opt"
									get_set_prefs 'set' "apt-type=$opt"
									;;
								quit)
									echo "${S}Ok, figure it out and try again later...${N}"
									exit 0
									;;
								*)
									echo "${E}You have to pick one before you can continue!${N}"
									ask_apt_aptitude
									;;
							esac
							break
						done
					else
						log_function_data "Derived Mint Debian using apt wrapper - default to apt-get."
					fi
					;;
				ubuntu)
					# going to ignore linuxmint's apt wrapper method
					if [ -z "$( type -P apt )" ];then
						APT_TYPE='aptitude'
						log_function_data "Ubuntu hardset to aptitude. If not ubuntu then error."
					else
						log_function_data "Derived Ubuntu using apt wrapper - default to apt-get."
					fi
					;;
			esac
		fi
	fi
	
	case $APT_TYPE in
		aptitude)
			WITHOUT_RECOMMENDS='--without-recommends'
			;;
		apt-get)
			WITHOUT_RECOMMENDS='--no-install-recommends'
			;;
	esac
	
	eval $LOGUE
}

# Returns null if package is not available in user system apt.
# args: $1 - package to test; $2 c/i
check_package_status()
{
	eval $LOGUS
	local packageVersion='' statusType='' cacheData=''
	local poolPackageCount=0

	case $2 in
		c)	statusType='Candidate:'
			;;
		i)	statusType='Installed:'
			;;
	esac
	case $APT_TYPE in
		apt-get|aptitude)
			LC_ALL= LC_CTYPE= LC_MESSAGES= LANG= cacheData="$( apt-cache policy $1 2>/dev/null )"
	
			# we need to filter out all cases were the only instance in apt is the locally installed
			# version, ie:  *** 2.13 0 \ 100 /var/lib/dpkg/status is the only value returned
			poolPackageCount=$( grep -Es "^[[:space:]]*[0-9]{3}"  <<< "$cacheData" | grep -vcE "^[[:space:]]*100[[:space:]]" )
			
			packageVersion=$( awk '
			/'$statusType'/ && !/(\(None\)|\(none\))/ {print $2}' <<< "$cacheData" )
			
			# if either none found, or only a local apt version available, return null
			if [ "$statusType" == 'Candidate:' -a "$poolPackageCount" -eq 0 ];then
				packageVersion=''
			fi
			;;
		pacman)
			case $2 in
				c)
					LC_ALL= LC_CTYPE= LC_MESSAGES= LANG= packageVersion=$( pacman -Si "$1" 2>/dev/null | grep -i '^Version' | awk '{print $3}'  )
					;;
				i)
					LC_ALL= LC_CTYPE= LC_MESSAGES= LANG= packageVersion=$( pacman -Q "$1" 2>/dev/null | awk '{print $2}'  )
					;;
			esac
			;;
		yum)
			case $2 in
				c)
					LC_ALL= LC_CTYPE= LC_MESSAGES= LANG= packageVersion=$( yum list "$1" 2>/dev/null | grep -Esvi '(presto|packagekit|packages)'| awk '{print $2}' )
					;;
				i)
				LC_ALL= LC_CTYPE= LC_MESSAGES= LANG= packageVersion=$( rpm -qa 2>/dev/null | grep -Esvi '(presto|packagekit|packages)' | grep -is "$1"   )
					;;
			esac
			;;
	esac

	echo $packageVersion
	log_function_data "Package Version: $packageVersion"
	eval $LOGUE
}

# arg: $1 - package name; $2 - /experimental/unstable/testing/stable; $3 - reinstall
# optional args. Note that if you use 3, you have to set 2 by '' if blank.
install_package()
{
	eval $LOGUS
	local distroVersion='' optionalArgs='' 
	local useUntrusted='' install=''
	local packageInstalled=''
	local update='' install='' doYes='' useUntrusted=''
	
	case $APT_TYPE in
		aptitude)
			doYes=''
			install='install'
			update='update'
			if [ "$SYSTEM_CODENAME" == 'etch' ];then
				useUntrusted='' # etch aptitude doesn't support this
			else
				useUntrusted='--allow-untrusted'
			fi
			;;
		apt-get)
			doYes='-y'
			install='install'
			update='update'
			useUntrusted='--allow-unauthenticated'
			;;
		pacman)
			doYes=''
			update='-Sy'
			install='-S'
			useUntrusted=''
			;;
		yum)
			doYes='' # note: -y is used, but for debugging we'll wait to add that.
			update=''
			install='install'
			useUntrusted='' # check later
			;;
	esac
	if [ -n "$update" ];then # yum has no update repo data command, it does it automatically
		update_package_manager "$update"
	fi

	# this will force install of sid to get rid of experimental if required
	case $SYSTEM_BASE in
		debian)
			if [ -n "$2" ];then
				distroVersion="/$2" #  --force-yes requird to avoid apt downgrade error
			fi
			;;
	esac
	# only do reinstall if arg is set and package is installed
	case "$3" in
		reinstall)
			packageInstalled=$( check_package_status "$1" 'i' )
			if [ -n "$packageInstalled" ];then
				case $APT_TYPE in
					aptitude)
						optionalArgs=''
						install='reinstall'
						;;
					apt-get)
						optionalArgs=' --reinstall '
						;;
					pacman)
						optionalArgs=''
						;;
					yum)
						optionalArgs=''
						install='reinstall'
						;;
				esac
			fi
			;;
		*)
			case $APT_TYPE in
				pacman)
					optionalArgs=$3
					;;
			esac
			;;
	esac
	# then install the package with all options
	log_function_data "Install command for $APT_TYPE: $install;optionalArgs: $optionalArgs;UseUntrusted: $useUntrusted;WithoutRecommends: $WITHOUT_RECOMMENDS;doYes: $doYes; packages: $1$distroVersion"
	echo "${S}Updating required package ${C}$1${S} now...${N}"
	$APT_TYPE $install $useUntrusted $WITHOUT_RECOMMENDS $doYes $optionalArgs $1$distroVersion || error_handler 200 "$1"
	eval $LOGUE
}

# args: $1 - update type / name
update_package_manager()
{
	eval $LOGUS
	if [ "$B_UPDATED" != 'true' ];then
		$APT_TYPE $1
		# for now not going to exit with real error, just want failures logged
		if [ "$?" -eq 0 ];then
			echo "${C}$APT_TYPE $1 ${S}successful. Continuing...${N}"
			B_UPDATED='true'
			log_function_data "Update $APT_TYPE successful"
		else
			echo "${C}$APT_TYPE $1 ${E}Failed. Continuing anyway...${N}"
			log_function_data "Update $APT_TYPE error: $?"
		fi
	fi
	eval $LOGUE
}

# args: $1 - package to test for; $2 - excludes from list
list_installed_packages()
{
	eval $LOGUS
	local packageList='' excludes=$2
	if [ -z "$excludes" ];then
		excludes='blanketyblank'
	fi
	
	case $APT_TYPE in
		apt-get|aptitude)
			packageList=$( dpkg -l | awk '{print $2}' | grep -Ei "$1" | grep -Ev "$excludes" )
			;;
		pacman)
			packageList=$( pacman -Q | awk '{print $1}' | grep -Ei "$1" | grep -Ev "$excludes" )
			;;
		yum)
			packageList=$( rpm -qa | awk '{print $1}' | grep -Ei "$1" | grep -Ev "$excludes" )
			;;
	esac
	log_function_data "packageList: $packageList"
	echo $packageList
	eval $LOGUE
}

# $1 - package(s) to remove; $2 - extra information; $3 - no-loop: remove all at once
# $4 optional: extra args
remove_package()
{
	eval $LOGUS
	local response='' package='' purge='' extraInfo="$2" doYes=''
	case $APT_TYPE in
		aptitude|apt-get)
			purge='purge'
			case $4 in
				yes) doYes='-y'
					;;
			esac
			;;
		pacman)
			purge='-R'
			;;
		yum)
			purge='erase'
			;;
	esac
	
	if [ -n "$extraInfo" ];then
		extraInfo=" $extraInfo"
	fi

	echo $MLINE
	echo "${M}You will need to remove the following package(s): ${C}$1"
	echo "${M}in order to proceed with your${C}$extraInfo${M} driver install${N}"
	echo $MLINE
	if [ "$3" == 'no-loop' ];then
		echo "${S}Removing ${C}$1${S}...${N}"
		$APT_TYPE $purge $doYes $1 || error_handler 190 "$1"
	else
		for package in $1
		do
			if [ -n "$( check_package_status  "$package" 'i' )" ];then
				echo "${S}Removing ${C}$package${S}...${N}"
				$APT_TYPE $purge $doYes $package || error_handler 190 "$package"
			else
				echo "${S}The package ${C}$package${S} is not installed, continuing...${N}"
			fi
		done
	fi
 	echo "${S}Package(s) removed successfully, continuing with driver install.${N}"
 	eval $LOGUE
}

# args: $1 - package to hold. sets hold for apt-get/aptitude
hold_package()
{
	eval $LOGUS
	# first set for aptitude syntax
	case $APT_TYPE in
		aptitude|apt-get)
			if [ "$APT_TYPE" == 'aptitude' ];then
				$APT_TYPE hold $1
			fi
			# then set hold into dpkg
			echo $1 hold | dpkg --set-selections
			;;
		pacman)
			:
			;;
		yum)
			:
			;;
	esac
	eval $LOGUE
}

update_to_nonfree_sources()
{
	eval $LOGPS
	
	local isFree=0 i='' counter=0
	local eas='/etc/apt/sources.list'
	local easdl='/etc/apt/sources.list.d/debian.list'
	local eassl='/etc/apt/sources.list.d/aptosid.list'
	local aptProx='' 
	local ubRestricted='' ubMultiverse='' ubUniverse=''
	local yumFreeRepo='' yumNonFreeRepo='' yumList='' bRepoAdded='false'
	
	if [ "$B_USE_DISTRO_DRIVER" == 'true' ];then
		case $SYSTEM_BASE in
			debian)
				# loop through possible files to update
				for i in $eas $easdl $eassl
				do
					if [ -f "$i" ];then
						counter=$( grep -Ec 'deb.*(debian\.org|peer1\.net).*(contrib.*non-free|non-free.*contrib)' $i )
						isFree=$(( $counter + $isFree ))
					fi
				done
				log_function_data "Debian contrib non free listed: $counter\nisFree: $isFree"
				if [ "$isFree" -eq 0 ];then
					for i in $eas $easdl
					do
						if [ -f "$i" ];then
							# I'm going to assume if the user has proxy stuff set up, they know what
							# they are doing here.
							aptProx=$( grep -Esi '^[[:space:]]*deb.*:9999/' $i )
							if [ -z "$aptProx" ];then
								echo "${S}Updating your ${C}$i${S} to use non-free / contrib now...${N}"
								sed -i -r 's%(#?deb.*(debian\.org|peer1\.net|sidux\.com|sidux\.net|debian\.tu-bs\.de|mirrorservice\.org|heanet\.ie|spline\.de|sunsite\.utk\.edu|leg\.uct\.ac\.za|mirror\.aarnet\.edu\.au).*\s(main|fix\.main))(\s*)(non-free.*|contrib.*)*%\1 contrib non-free%' $i
								# the second test requires the results of the first to work
								# note that spaces are required for this to work more reliably for most patterns
								sed -i -r 's%(#?deb.*(sidux\.com|sidux\.net|debian\.tu-bs\.de|mirrorservice\.org|heanet\.ie|spline\.de|sunsite\.utk\.edu|ftp-mirror\.internap\.com|ftp\.tw.debian\.org|leg\.uct\.ac\.za|mirror\.aarnet\.edu\.au).*\snon-free)%\1 firmware fix.contrib fix.non-free %' $i
							fi
						fi
					done
					$APT_TYPE update && B_UPDATED='true' # need to refresh
				fi
				;;
			ubuntu)
				# just to make sure, want to get out fast
				ubRestricted=$( grep -siE '^[[:space:]]*deb[[:space:]].*ubuntu.*restricted' $eas $eas.d/*.list )
				if [ -z "$ubRestricted" ];then
					error_handler 216
				fi
				;;
			fedora)
				yumList="$( yum repolist )"
				yumFreeRepo=$( grep  -Eis '^rpmfusion-free.*enabled' <<< "$yumList" )
				yumNonFreeRepo=$( grep  -Eis '^rpmfusion-nonfree.*enabled' <<< "$yumList" )
				echo -n "${S}Checking for ${C}rpmfusion free${S} repos.... ${N}"
				if [ -z "$yumFreeRepo" ];then
					echo "${S}Adding${N}"
					rpm -Uvh http://download1.rpmfusion.org/free/fedora/rpmfusion-free-release-stable.noarch.rpm
					bRepoAdded='true'
				else
					echo "${S}Present${N}"
				fi
				echo -n "${S}Checking for ${C}rpmfusion non-free${S} repos.... ${N}"
				if [ -z "$yumNonFreeRepo" ];then
					echo "${S}Adding${N}"
					rpm -Uvh http://download1.rpmfusion.org/nonfree/fedora/rpmfusion-nonfree-release-stable.noarch.rpm
					bRepoAdded='true'
				else
					echo "${S}Present${N}"
				fi
				if [ "$bRepoAdded" == 'true' ];then
					echo "${S}Please note that you will be asked during the distro driver install to accept the"
					echo "repo ${C}GPG keys${S} for the repos you just added. Make sure to enter ${C}y${S} for this question.${N}"
					print_hec
				fi
				;;
		esac
	fi
	eval $LOGPE
}

# if null, this will trigger a first run update, maybe in the future can also
# add time of last update tests, we'll see. For now returns size in MB for tests
check_package_manager_updated()
{
	eval $LOGUS
	local dpkguf='/var/cache/apt/pkgcache.bin'
	local sizeWorking=0
	
	case $SYSTEM_BASE in
		debian|ubuntu)
			# this covers the case of first install, no apt update yet, which
			# makes the following  c tests all fail. This will never be true from
			# sm fired sessions since smxi always updates first. Or updates
			# if apt cache file is less than 5mB
			if [ -f $dpkguf ];then
				# dpkgUpdate=$( ls -l --time-style=+%Y-%m-%d-%H:%M $dpkguf | grep -Eo "20[0-9]{2}-[0-9]{2}-[0-9]{2}-[0-9]{2}:[0-9]{2}" )
				sizeWorking=$( du -B M $dpkguf | grep -Eo '^[0-9]+' )
			fi
			log_function_data "sizeWorking: $sizeWorking"
			if [ "$sizeWorking" -lt 4 ];then
				update_package_manager 'update'
			fi
			;;
	esac

	eval $LOGUE
}


### -------------------------------------------------------------------
### script updating / patch file install tools
### -------------------------------------------------------------------

# args: $1 script to get/check; $2 - which download source to use
# $3 - extra message; $4 - repeat, to only retest download failure once
check_update_script()
{
	local fileDataTemp='' isGood='' extraText='' bRunUpdate='false'
	local versionTest=0 versionData='' localVersion='' remoteVersion=''
	local downloadUrl=$2 uArgs='up' ua="-U s-tools/$SCRIPT_NAME"
	local origXorg='/etc/X11/xorg-conf-orig-sg'

	if [ -n "$( grep -E '(dev|svn|alt)' <<< $3 )" ];then
		extraText="${C}$3:\n$2${S}"
	else
		extraText="${C}$3${S}"
	fi
	cd $SCRIPT_HOME # make sure we're in the right place
	# download / replace requested file
	case $1 in
		$SCRIPT_NAME)
			if [ "$B_FORCE_UPDATE" == 'true' ];then
				uArgs='ufr'
				bRunUpdate='true'
			elif [ "$4" == 'repeat' ];then
				uArgs='rep'
				bRunUpdate='true'
			# uncomment if you need this to not trigger for dev purposes
# 			elif [ "$B_TESTING_5" == 'true' ];then
# 				uArgs='dev'
# 				bRunUpdate='true'
			else
				echo -n "${S}Checking ${C}$SCRIPT_NAME${S} versions.... ${N}"
				# 0: same versionp; 1 - different version; 2 - download error
				versionData=$( check_script_version )
				versionTest="$?"
				localVersion=$( cut -d ':' -f 1 <<< "$versionData" )
				remoteVersion=$( cut -d ':' -f 2 <<< "$versionData" )
				if [ "$versionTest" -eq 0 ];then
					echo "${S}local and remote versions match. Continuing...${N}"
					bRunUpdate='false'
				elif [ "$versionTest" -eq 1 ];then
					echo "${M}update required:${S} local: ${C}$localVersion${S} - remote: ${C}$remoteVersion${N}"
					bRunUpdate='true'
				else
					echo "${E}Failed to aquire remote version data. ${S}Will try direct download instead.${N}"
					bRunUpdate='true'
				fi
			fi
			# this will try to download again, the version tester itself isn't going to do any
			# kind of error handling
			if [ "$bRunUpdate" == 'true' ];then
				ua="$ua.$uArgs.$SIS"
				echo -e "${S}Updating ${C}$SCRIPT_NAME${S} now using the $extraText${N}"
				fileDataTemp="$( wget $ua -q -O - $downloadUrl$1 )" || error_handler 198 $1
				# all smxi files have this string as last line, if there, the file should usually
				# run fine, except for weird fringe cases where the ascii file is corrupted partially
				isGood=$( grep -si '##\*\*EOF\*\*##' <<< "$fileDataTemp" )
				if [ -n "$isGood" ];then
					echo "$fileDataTemp" > $1
					chmod 705 $1
					if [ "$B_FORCE_UPDATE" != 'true' ];then
						exec ./$1 -R$START_OPTIONS
					else
						print_information
						echo "${C}$SCRIPT_NAME${S} was successfully updated. Please start the script again to access"
						echo "the latest features and drivers. Remember that ${C}$SCRIPT_NAME${S} always updates itself"
						echo "automatically when it starts so usually ${C}-U${S} is not required."
						echo
						echo "To see the latest drivers or support features, use the ${C}-L${S} option. You can"
						echo "run this option in X, and you don't need to be root to use it. Features:"
						echo "Show all currently supported drivers: ${C}$SCRIPT_NAME -L d${S}"
						echo "Show current nVidia support status: ${C}$SCRIPT_NAME -L n${S}"
						echo "Show current ATI/Fglrx support status: ${C}$SCRIPT_NAME -L f${S}"
						echo "Show current local/remote ${C}$SCRIPT_NAME${S} versions: ${C}$SCRIPT_NAME -L v${S}"
						print_hec
						echo "${S}Update completed. Exiting now.${N}"
					fi
					exit 0
				else
					if [ "$4" != 'repeat' ];then
						# let's try this once again to make sure it wasn't just a temp problem
						echo -e "${E}The file ${C}$1${E} did not download correctly from:\n$2\nRetrying download now...${N}"
						check_update_script "$1" "$2" "$3" 'repeat'
					else
						error_handler 231 $1
					fi
				fi
			fi
			;;
		# I'm only going to load this stuff one time per file so I won't
		# have to worry about rechecking and multi downloads etc
		*)
			if [ "$B_SKIP_WGET" != 'true' ];then
				fileDataTemp="$( wget -q -O - $downloadUrl$1 )" || error_handler 198 $2$1
			fi
			# run fine, except for weird fringe cases where the ascii file is corrupted partially
			isGood=$( grep '##\*\*EOF\*\*##' <<< "$fileDataTemp" )
			if [ -n "$isGood" ];then
				case $1 in
					*xorg-conf)
						echo "${S}Updating ${C}$EXXC${S} to new ${C}$1${S} version now...${N}"
						if [ ! -f $origXorg ];then
							echo "${S}Backing up your original ${C}$EXXC${S} to ${C}$origXorg${S}...${N}"
							mv -f $EXXC $origXorg
						else
							echo "${S}Your original ${C}$EXXC${S} has already been backed up to ${C}$origXorg${S}"
						fi
						echo "${S}Replacing your ${C}$EXXC${S} with ${C}$1${S} now...${N}"
						echo  "$fileDataTemp" > $EXXC
						chmod 604 $EXXC
						echo "${S}All done with the ${C}$EXXC${S} update."
						echo "Try running ${C}$SCRIPT_NAME${S} again and see if your driver install works this time.${N}"
						;;
					*)
						echo  "$fileDataTemp" > $1
						chmod 604 $EXXC
						source ./$1 # load the library file
						;;
				esac
			else
				error_handler 199 $1 # if corrupted file, exit with file name + error
			fi
			;;
	esac
}
# return values: # 0: same versionp; 1 - different version; 2 - download error
check_script_version()
{
	local returnValue=0 wgetError=0 validated='' versionData=''
	local ua="-U s-tools/$SCRIPT_NAME-updater.$SIS"
	local localVersion='' remoteVersion=''
	if [ "$B_SKIP_WGET" == 'true' ];then
		returnValue=2
	else
		versionData="$( wget $ua -qO - $SCRIPT_DOWNLOAD_VERSION )" || wgetError="$?"
		if [ "$wgetError" -eq 0  ];then
			validated=$( grep -Esi '#\*\*EOF\*\*#' <<< "$versionData" )
			if [ -n "$validated" ];then
				localVersion=$( awk '/^#.*[[:space:]]version:/ {print $3}' $SCRIPT_HOME/$SCRIPT_NAME )
				remoteVersion=$( grep 'sgfxi' <<< "$versionData" | cut -d '=' -f 2 | cut -d ':' -f 1 )
				if [ "$localVersion" == "$remoteVersion" ];then
					returnValue=0
				else
					returnValue=1
				fi
				echo "$localVersion:$remoteVersion"
			else
				returnValue=2
			fi
		else
			returnValue=2
		fi
	fi
	return $returnValue
}

# args: $1 patch file to apply; $2 - [optional] standard (implied)/test
apply_patch_file()
{
	eval $LOGUS
	# this is just for test, set the global to force build so it can get patched
	if [ "$2" == 'test' ];then
		B_FORCE_OPTION='true'
		return 0;
	fi
	local patchFile=$1
	## this can be changed to branches with -! 20 or -! 21
	local patchUrl="${PATCH_DOWNLOAD}patches/$patchFile" ua="-U s-tools/$SCRIPT_NAME-data.patches.$patchFile"
	local patchFileDataTemp=''

	cd $SCRIPT_WORKING_DIR/$INSTALL_DIRECTORY # first change to the correct directory
	log_function_data "Patch File Dir: $SCRIPT_WORKING_DIR/$INSTALL_DIRECTORY"
	log_function_data "Patch URL: $patchUrl"

	echo "${S}Retrieving patch ${C}$patchFile${S}...${N}"
	# get patch file, set to variable
	patchFileDataTemp="$( wget $ua -q -O - $patchUrl 2>/dev/null )" || error_handler 180 $patchFile
	if [ -n "$patchFileDataTemp" ];then
		echo "${S}Running patch ${C}$patchFile${S}...${N}"
		patch -p 0 <<< "$patchFileDataTemp" || error_handler 179 $patchFile
		echo "${S}Patching completed...${N}"
	else
		error_handler 181 $patchFile
	fi
	eval $LOGUE
}

### -------------------------------------------------------------------
### print data functions
### -------------------------------------------------------------------

print_information()
{
	local scriptVersion=$( grep -Eo -m 1 "(version:).*" $SCRIPT_HOME/$SCRIPT_NAME | cut -d ' ' -f 2 )
	local scriptDate=$( grep -Eo -m 1 '(Date:).*' $SCRIPT_HOME/$SCRIPT_NAME | cut -d ' ' -f 2-4 )
	#local cardInfo=$( lspci | awk -F': ' '/VGA compatible controller.*: / { print $NF }' | sed -r 's%(ATI\sTechnologies\sInc\s|nVidia\sCorporation\s)(.*)%\2%'  )
	# |3D controller|Display controller
	local cardInfo=$( lspci | \
	awk -F': ' '/VGA compatible controller.*: / { print $NF }' | \
	sed -r 's%(ATI\s|nVidia\s|Intel\s)(Technologies\sInc\s|Corporation\s|Unknown\sdevice){1,2}(.*)%\1\3%g' )
	local cardRam='' cardVendor='' busId=''

	# we need the real busid, not the xorg one
	busId=$( lspci -n | grep "$CARD_DATA" | grep -Eio '^[0-9]{1,2}:[0-9a-z]{1,2}(\.|:)[0-9]' )

	if [ -n "$busId" ];then
		cardRam=$( lspci -v -s $busId 2>/dev/null | grep -E '.*Memory[[:space:]].*[[:space:]]prefetchable.*\[size=([0-9\.]+[KMG])\]' | sed -r 's/.*Memory[[:space:]].*[[:space:]]prefetchable.*\[size=([0-9\.]+[KMG])\]/\1/' )
		cardVendor=$( lspci -v -s $busId 2>/dev/null | grep -E '.*Subsystem:[[:space:]]*(.*)' | sed -r 's/.*Subsystem:[[:space:]]*(.*)/\1/' | sed 's/[dD]evice.*$//g' | sed 's/[uU]nknown//g' )
	fi
	echo $MLINE
	echo " ${M}$SCRIPT_NAME${S} :: version: ${C}$scriptVersion${S} :: last updated: ${C}$scriptDate"
	echo $MLINE
	echo " ${S}graphics card information:"
	echo "   ${S}series: ${C}$cardInfo"
	if [ -n "$cardVendor" ];then
		echo "   ${S}vendor: ${C}$cardVendor"
	fi
	if [ -n "$cardRam" ];then
		echo "   ${S}ram:    ${C}$cardRam ${S}(note: not accurate for built in graphics)"
	fi
	echo $MLINE
}
#print_information

# args: $1 testing or standard; $2 function/feature name; $3 function name
print_information_continue()
{
	eval $LOGUS
	local response='' bShowIa32='false'

	case $1 in
		standard|info)
			echo -e "${S}$2"
			;;
	esac

	if [ "$1" == 'standard' ];then
		if [ "$B_AUTORUN" != 'true' ];then
			# this checks to see if it's a supported card/system, and that ia32 stuff is not already installed
			# only in case where it's supported and not installed / configured will user see this message
			bShowIa32=$( check_ia32_libs 'test' )
			echo "${M}Please select from the following options:${N}"
			echo "${C}<enter>${M}     - hit enter key to continue with ${C}$CARD${M} driver install (${C}default${M})"
			if [ "$bShowIa32" == 'true' ];then
				echo "${C}i + <enter>${M} - add/configure ${C}ia32-libs-i386${M} before doing the driver install. This lets things"
				echo "              like ${C}openGL 32 bit${M} apps and ${C}Steam${M} work smoothly with your ${C}64 bit $CARD${M} driver.${N}"
			fi
			echo "${C}x + <enter>${M} - exit now if there is an error.${N}"
			read response
			case $response in
				i|I)
					B_CHECK_IA32='true'
					;;
				x|X)
					error_handler 100 $FUNCNAME
					;;
			esac
		fi
	fi
	eval $LOGUE
}

# this is the hit enter to continue blurb...
print_hec()
{
	local response=''

	if [ "$AUTORUN" != 'true' ];then
		echo $MLINE
		# halt the script so people can read the advice
		echo "${Q}Please hit ${C}enter${Q} to continue${N}"
		echo $MLINE
		read response
	fi
}

### -------------------------------------------------------------------
### logging/debugging tools
### -------------------------------------------------------------------

create_log()
{
	local cardString=$( lspci | grep -i 'vga ' | cut -d ':' -f 3 )
	local sgfxiVersion=$( grep 'version:' $SCRIPT_NAME | grep -o "[0-9]*\.[0-9]*\.[0-9]*" )
	local installToKernel='' smValues=''
	
	if [ -n "$INSTALL_TO_KERNEL" ];then
		installToKernel="\nRunning install from Kernel: $(uname -r)\n"
	fi
	# it's important to log these in case there's some issue or bug in the values
	if [ -f $SM_VALUES ];then
		smValues="\nBegin User Set $SM_VALUES:\n$( cat $SM_VALUES)\nEnd User Set Values\n"
	fi

	# check and create log file:
	if [ ! -d $LOG_FILE_DIR ];then
		mkdir $LOG_FILE_DIR
	fi
	# cleanup legacy logs
	rm -f ${LOG_FILE_DIR}200*-sgfxi.log
	# check and create logfile:
	LOG_FILE=$LOG_FILE_DIR$LOG_FILE

	if [ ! -f $SCRIPT_ROTATE ];then
		echo "$LOG_FILE {
	rotate 8
	create
	size 10k
}
" > $SCRIPT_ROTATE
	else
		# update if needed
		if [ -n "$( grep ' 120k' $SCRIPT_ROTATE )" ];then
			sed -i 's/rotate[[:space:]]4/rotate 8/' $SCRIPT_ROTATE
			sed -i 's/size[[:space:]]120k/size 10k/' $SCRIPT_ROTATE
		fi
	fi
	touch $LOG_FILE # make sure there's one there for rotate to look at
	if [ -n "$( which logrotate )" ];then
		logrotate $SCRIPT_ROTATE
	fi

	touch $LOG_FILE # and if rotated, need a new one
	# sudo start will only show as information to check for 'sudo su -' starts, all others
# have exited with error
	echo -e "=========================================================
START $SCRIPT_NAME LOGGING:
=========================================================
Script started: $( date +%Y-%m-%d-%H:%M:%S )
Video Card Information:$cardString
Video Card Type: $CARD_BRAND
Video Card Number: $CARD_NUMBER
Xorg Version: $X_VERSION
Installing driver to kernel: $KERNEL_FULL$installToKernel
$SCRIPT_NAME script version: $sgfxiVersion
$SCRIPT_NAME start options: $START_OPTIONS
SYSTEM_BASE: $SYSTEM_BASE
SYSTEM_CODENAME: $SYSTEM_CODENAME
DISTRIB_CODENAME: $DISTRIB_CODENAME
DISTRIB_ID: $DISTRIB_ID
DISTRIB_RELEASE: $DISTRIB_RELEASE
SIS: $SIS
BITS: $BITS
FG_DISTRIB_CODENAME: $FG_DISTRIB_CODENAME
FG_DISTRIB_ID: $FG_DISTRIB_ID
APT_TYPE: $APT_TYPE
LOGIN_PID: $LOGIN_PID
SUDO_START: $SUDO_START
B_SYSTEMD: $B_SYSTEMD
B_SYSTEMD_GRAPHICAL: $B_SYSTEMD_GRAPHICAL
B_SYSTEMD_SYSINIT: $B_SYSTEMD_SYSINIT
B_UPSTART: $B_UPSTART
=========================================================
X is Running: $( x_is_running )
Current Runlevel: $( get_current_runlevel )
Connection is live (0=true): $( check_connection )
=========================================================$smValues
INSTALL_TO_KERNEL: $INSTALL_TO_KERNEL
KERNEL_FULL: $KERNEL_FULL
KERNEL_BASE: $KERNEL_BASE
KERNEL_NUMBER: $KERNEL_NUMBER
KERNEL_MATH: $KERNEL_MATH
B_IS_XEN: $B_IS_XEN" >> $LOG_FILE

	B_LOGGING_STARTED='true'
}

# $1 type or data; $2 is function; $3 - function args, optional
log_function_data()
{
	local funcInfo='' logSpacer='  '

	if [ "$B_PRINT_VER" != 'true' ];then
		case $1 in
			ps)
				funcInfo="Function: $2 - Primary: Start"
				;;
			pe)
				funcInfo="Function: $2 - Primary: End"
				;;
			us)
				funcInfo="Function: $2 - Utility: Start"
				;;
			ue)
				funcInfo="Function: $2 - Utility: End"
				;;
		esac

		if [ -n "$funcInfo" ];then
			log_writer "$funcInfo"
		else
			log_writer "${logSpacer}$1"
		fi

		if [ -n "$3" ];then
			log_writer "${logSpacer}Args: $3"
		fi
	fi
}

log_driver_installer_failure()
{
	local nvidiaLog='/var/log/nvidia-installer.log'
	local atiLog='/usr/share/ati/fglrx- install.log'
	local errorLog=''
	
	case $CARD in
		$FGLRX)
			errorLog=$atiLog
			;;
		$NVIDIA)
			errorLog=$nvidiaLog
			;;
	esac
	echo $PLINE  >> $LOG_FILE
	echo "Error logs from $CARD install: $errorFileData" >> $LOG_FILE
	echo $PLINE  >> $LOG_FILE
	if [ -f "$errorLog" ];then
		cat $errorLog >> $LOG_FILE
	else
		echo "No error logs found from the run package installer!" >> $LOG_FILE
	fi
	echo $PLINE  >> $LOG_FILE
}

# args: $1 - data to write to logfile. Note that the function is always logged
# via function_logging first, and other relevant globals are set there as well
log_writer()
{
	# this handles first line indents, all other indents must be set in message data
	# like so: message="some problem... \n${LOG_INDENT}more problem stuff..."
	if [ "$B_LOGGING_STARTED" == 'true' ];then
		# strip out escape color code, if any. Method by dzz, thanks ;-)
		echo -e "$1" | sed 's/\x1b\[[0-9]\{1,2\}\(;[0-9]\{1,2\}\)\{0,2\}m//g' >> $LOG_FILE
	fi
}

debugger_data_collector()
{
	local debug_data_home="$HOME/${SCRIPT_NAME}-data/" b_uploaded='false' xiin_download=''
	local xorg_d_files='' xorg_file='' data='' data2='' xiin_file='xiin.py'
	local ftp_upload='ftp.techpatterns.com/incoming' b_run_xiin='false' root_string=''
	local host=$( tr '[A-Z]' '[a-z]' <<< "$HOSTNAME" )
	if [[ -n $host ]];then
		host=${host// /-}
	else
		host="-no-host"
	fi
	if [[ $( whoami ) == 'root' ]];then
		root_string='-root'
	fi
	local debug_data_dir="$SCRIPT_NAME-$(date +%Y-%m-%d-%H%M%S)$host$root_string"
	local debug_gz_file="$debug_data_dir.tar.gz"
	echo "Starting $SCRIPT_NAME debugging data collection..."
	if [ ! -d $debug_data_home ];then
		mkdir $debug_data_home
		echo "Created data directory here: $debug_data_home"
	fi
	cd $debug_data_home
	if [ -d $debug_data_dir ];then
		rm -rf $debug_data_dir
	else
		mkdir $debug_data_dir
	fi
	if type -p shopt &>/dev/null;then
		shopt -s nullglob;a_distro_ids=(/etc/*[-_]{release,version});shopt -u nullglob;echo ${a_distro_ids[@]} &> $debug_data_dir/etc-distro-files.txt
		for distro_file in ${a_distro_ids[@]} /etc/issue
		do
			if [[ -f $distro_file ]];then
				cat $distro_file &> $debug_data_dir/distro-file${distro_file//\//-}
			fi
		done
	fi
	cat /etc/modules &> $debug_data_dir/etc-modules.txt
	readlink /usr/lib/libGL.so.1 &> $debug_data_dir/readlink-usr-lib-libgl.so.1.txt
	readlink /usr/lib/xorg/modules/extensions/libglx.so &> $debug_data_dir/readlink-lib-xorg-modules-extensions-libglx.so.txt
	ls -R /boot &> $debug_data_dir/boot-ls-files.txt
	echo $(get_active_grub_files) &> $debug_data_dir/grub-files-active.txt
	cat /boot/grub/grub.cfg &> $debug_data_dir/boot-grub-grub-cfg.txt
	ls /etc/modprobe.d/*.conf &> $debug_data_dir/ls-etc-modprobe-d.txt
	for item in $( ls /etc/modprobe.d/*.conf )
	do
		data=${item#/}
		cat $item &> $debug_data_dir/${data//\//-}
	done
	ls -R /var/lib/dkms/ &> $debug_data_dir/var-lib-dkms-ls-files.txt
	ls -R /etc/dkms/ &> $debug_data_dir/etc-dkms-ls-files.txt
	ls -R /usr/src/*/dkms.conf &> $debug_data_dir/usr-src-ls-dkms-files.txt
	ls -R /usr/src/*/dkms.conf | grep -iE '(catalyst|fglrx|nvidia)' &> $debug_data_dir/usr-src-ls-dkms-video-files.txt
	
	ps aux &> $debug_data_dir/ps-aux.txt
	ps -e &> $debug_data_dir/ps-e.txt
	ps -p 1 &> $debug_data_dir/ps-p-1.txt
	cat /proc/1/comm &> $debug_data_dir/proc-1-comm.txt
	runlevel &> $debug_data_dir/runlevel.txt
	
	if [ -f /etc/modprobe.d/dkms.conf ];then
		cat /etc/modprobe.d/dkms.conf &> $debug_data_dir/etc-modprobe-dkms.conf.txt
	else
		touch $debug_data_dir/etc-modprobe-dkms.conf-absent
	fi
	for item in $( ls -R /usr/src/*/dkms.conf | grep -iE '(catalyst|fglrx|nvidia)' )
	do
		data=${item#/}
		cat $item &> $debug_data_dir/${data//\//-}
	done
	if dpkg &>/dev/null;then
		dpkg -l | grep -iE '(nvidia|fglrx|catalyst)' &> $debug_data_dir/dpkg-l-grep-driver-files.txt
	else
		touch dpkg-absent
	fi
	glxinfo &> $debug_data_dir/glxinfo.txt
	xdpyinfo &> $debug_data_dir/xdpyinfo.txt
	xrandr &> $debug_data_dir/xrandr.txt
	X -version &> $debug_data_dir/x-version.txt
	Xorg -version &> $debug_data_dir/xorg-version.txt
	xprop -root &> $debug_data_dir/xprop-root.txt
	echo $GNOME_DESKTOP_SESSION_ID &> $debug_data_dir/gnome-desktop-session-id.txt
	# kde 3 id
	echo $KDE_FULL_SESSION &> $debug_data_dir/kde3-ful-session.txt
	echo $KDE_SESSION_VERSION &> $debug_data_dir/kde456-session-version.txt
	echo "$(kded$KDE_SESSION_VERSION --version )" &> $debug_data_dir/kde-version-data.txt
	echo $XDG_CURRENT_DESKTOP &> $debug_data_dir/xdg-current-desktop.txt
	lspci &> $debug_data_dir/lspci.txt
	lspci -k &> $debug_data_dir/lspci-k.txt
	lspci -knn &> $debug_data_dir/lspci-knn.txt
	lspci -n &> $debug_data_dir/lspci-n.txt
	lspci -nn &> $debug_data_dir/lspci-nn.txt
	lspci -mm &> $debug_data_dir/lspci-mm.txt
	lspci -mmnn &> $debug_data_dir/lspci-mmnn.txt
	lspci -mmnnv &> $debug_data_dir/lspci-mmnnv.txt
	lspci -v &> $debug_data_dir/lspci-v.txt
	sensors &> $debug_data_dir/sensors.txt
	if type -p inxi &>/dev/null;then
		inxi -rfv7 -c 0 &> $debug_data_dir/inxi-rfv7.txt
	else
		touch $debug_data_dir/inxi-absent
	fi
	cat /var/log/Xorg.0.log &> $debug_data_dir/xorg.0.log
	cat /var/log/Xorg.1.log &> $debug_data_dir/xorg.1.log
	cat /var/log/Xorg.2.log &> $debug_data_dir/xorg.2.log
	if [ -f /var/log/sgfxi/sgfxi.log ];then
		cat /var/log/sgfxi/sgfxi.log &> $debug_data_dir/sgfxi.log
	else
		touch $debug_data_dir/sgfxi.log-file-absent
	fi
	if [ -f /var/log/sgfxi/sgfxi.log.1 ];then
		cat /var/log/sgfxi/sgfxi.log.1 &> $debug_data_dir/sgfxi.1.log
	else
		touch $debug_data_dir/sgfxi.log.1-file-absent
	fi
	if [ -f /var/log/sgfxi/sgfxi.log.2 ];then
		cat /var/log/sgfxi/sgfxi.log.2 &> $debug_data_dir/sgfxi.2.log
	else
		touch $debug_data_dir/sgfxi.log.2-file-absent
	fi
	if [[ -e /etc/X11/xorg.conf ]];then
		cat /etc/X11/xorg.conf &> $debug_data_dir/xorg-conf.txt
	else
		touch $debug_data_dir/xorg-conf-file-absent
	fi
	if [[ -n $( ls /etc/X11/xorg.conf.d/ 2>/dev/null ) ]];then
		ls /etc/X11/xorg.conf.d &> $debug_data_dir/ls-etc-x11-xorg-conf-d.txt
		xorg_d_files=$(ls /etc/X11/xorg.conf.d)
		for xorg_file in $xorg_d_files
		do
			cat /etc/X11/xorg.conf.d/$xorg_file &> $debug_data_dir/xorg-conf-d-$xorg_file.txt
		done
	else
		touch $debug_data_dir/xorg-conf-d-files-absent
	fi
	if [[ -f /usr/share/ati/fglrx-install.log ]];then
		cat /usr/share/ati/fglrx-install.log  &> $debug_data_dir/usr-share-ati-fglrx-install.log
	else
		touch $debug_data_dir/usr-share-ati-fglrx-install-log-absent
	fi
	if [[ -f /var/log/catalyst-install.log ]];then
		cat /var/log/catalyst-install.log  &> $debug_data_dir/var/log/catalyst-install.log
	else
		touch $debug_data_dir/catalyst-install-log-absent
	fi
	# ubuntu tool
	if [[ -f /var/log/jockey.log ]];then
		cat /var/log/jockey.log  &> $debug_data_dir/var/log/jockey.log
	else
		touch $debug_data_dir/jockey-installer-log-absent
	fi
	if [[ -f /var/log/nvidia-installer.log ]];then
		cat /var/log/nvidia-installer.log  &> $debug_data_dir/nvidia-installer.log
	else
		touch $debug_data_dir/nvidia-installer-log-absent
	fi
	data=$( ls /etc/apt/sources.list /etc/apt/sources.list.d/*.list )
	if [[ -n $data ]];then
		for aptFile in $data
		do
			data2=${aptFile#/}
			cat $aptFile &> $debug_data_dir/${data2//\//-}
		done
	else
		touch $debug_data_dir/etc-apt-source-files-absent
	fi
	echo "Data collection completed."
	echo 'Creating tar.gz compressed file of this material now. Contents:'
	echo $LINE
	tar -cvzf $debug_gz_file $debug_data_dir
	echo $LINE
	echo 'Cleaning up leftovers...'
	rm -rf $debug_data_dir
	echo 'Testing gzip file integrity...'
	gzip -t $debug_gz_file
	if [[ $? -gt 0 ]];then
		rm -f $debug_gz_file
		echo 'Data in gz is corrupted, removed gzip file, try running data collector again.'
		exit 1
	else
		echo $LINE
		echo 'All done with debugger data collection.'
		echo "$SCRIPT_NAME will now try to upload this data to the script server..."
		echo $LINE
		# -Nc is creating really weird download anomolies, so using -O instead
		xiin_download="$( wget -q -O - https://github.com/smxi/inxi/raw/xiin/$xiin_file )"
		# if nothing got downloaded kick out error, otherwise we'll use an older version
		if [[ $? -gt 0 && ! -f $xiin_file ]];then
			echo -e "ERROR: Failed to download ftp uploader file: $xiin_file\nMaybe the remote site is down or your networking is broken?"
		elif [[ -n $( grep -s '# EOF' <<< "$xiin_download" ) || -f $xiin_file ]];then
			if [[ -n $( grep -s '# EOF' <<< "$xiin_download" ) ]];then
				echo "Updating $xiin_file from remote location"
				echo "$xiin_download" > $xiin_file
			else
				echo "Using local $xiin_file due to download failure"
			fi
			b_run_xiin='true'
		else
			echo -e "ERROR: $xiin_file downloaded but the program file data is corrupted. Unable to do ftp upload."
		fi
		if [[ $b_run_xiin == 'true' ]];then
			echo "Doing automatic upload of data to remote server $ftp_upload now..."
			python ./$xiin_file -u $debug_data_home$debug_gz_file $ftp_upload 1>/dev/null
			if [[ $? -gt 0 ]];then
				echo $Line
				echo "Error: looks like the automatic ftp upload failed. Error number: $?"
			else
				b_uploaded='true'
			fi
		else
			echo 'Unable to run the automoatic ftp upload because of an error with the xiin download.'
		fi
		if [ "$b_uploaded" != 'true' ];then
			echo "Please attach the gz file to a forum support thread, if the forum supports file attachments,"
			echo "OR simply copy it over to: ftp.techpatterns.com/incoming"
			echo "You can do this using a file manager like Dolphin, Konqueror, or any other one that lets"
			echo "you type in the ftp address in the location bar then connect to it."
			echo "After you do that, you can just drag in the gz file to the remote site."
		else 
			echo "The upload worked! You are done with the debugger process. Thank you."
		fi
		echo $LINE
		echo "It's all good apparently. You can find a copy of the data here:"
		echo "$debug_data_home$debug_gz_file"
		exit 0
	fi
}

########################################################################
#### FUNCTIONS: CORE GRAPHIC DRIVER INSTALLER TOOLS
########################################################################

### -------------------------------------------------------------------
### Native Driver installer section
### -------------------------------------------------------------------

# this bypasses core binary installers and just runs the required pieces
install_native_driver()
{
	eval $LOGPS
	local xorgBase='' xorgNv='nouveau' xorgAti='ati' xorgIntel='intel'
	local xorgDriver='' driver='' currentlyInstalled='' xorgCore=''
	local driverInstall='' experimentalText='' libMesaGlx=''
	local extraAtiPackage1='' bSkipInstall='false'
	
	# we're going to force this behavior for the default restore option by setting
	# explicit native override values, which will trigger the desired actions below
	if [ "$B_RESTORE_DEFAULTS" == 'true' ];then
		# need to do this for -! 5 flag testing, to set: SYSTEM_BASE etc
		if [ "$B_SKIP_FUNCTION" == 'true' ];then
			check_set_distro 
		fi
		case $CARD in
			$NVIDIA)
				NATIVE_OVERRIDE='nouveau'
				;;
			$FGLRX)
				NATIVE_OVERRIDE='radeon'
				;;
		esac
	fi
	
# 	xserver-xorg-video-intel
# 	libgl1-mesa-glx
# 	libgl1-mesa-dri
	case $SYSTEM_BASE in
		debian|ubuntu)
			xorgBase='xserver-xorg-video-'
			xorgCore='xserver-xorg-core'
			libMesaGlx='libgl1-mesa-glx'
			;;
		arch)
			extraAtiPackage1="install_package 'ati-dri' '' 'reinstall'"
			xorgBase='xf86-video-'
			xorgCore='xorg-server'
			libMesaGlx='libgl'
			if [ "$NATIVE_OVERRIDE" == 'radeon' ];then
				NATIVE_OVERRIDE=$xorgAti
			fi
			;;
		fedora)
			xorgBase='xorg-x11-drv-'
			xorgCore='xorg-x11-server-Xorg'
			libMesaGlx='libMesaGlx=' # I think, check this: yum list *mesa*
			;;
	esac

	if [ "$B_EXPERIMENTAL" == 'true' ];then
		experimentalText=' experimental'
	fi
	#
	if [ "$B_DEFAULT_NATIVE_DRIVER" == 'true' -o -n "$NATIVE_OVERRIDE" ];then
		eval $LOGPS
		# assign defaults from earlier CARD assignments in -n
		xorgDriver=$CARD
		# then do special case handling
		case $CARD in
			$NVIDIA)
				xorgDriver=$xorgNv
				;;
			# note: use default ati here and only override to radeon/radeonhd for native override
			$FGLRX)
				xorgDriver=$xorgAti
				;;
			$INTEL)
				xorgDriver=$xorgIntel
				;;
		esac

		# driverInstall is just for output text for user to know what driver script installs
		driverInstall=$xorgDriver
		# replace with override if it's been set
		if [ -n "$NATIVE_OVERRIDE" ];then
			xorgDriver=$NATIVE_OVERRIDE
			driverInstall=$NATIVE_OVERRIDE
		fi
		# this is mostly for cases where no default xorg driver is found
		# this will apply to -! 32 option mostly
		if [ -z "$xorgDriver" ];then
			bSkipInstall='true'
			driverInstall='no-driver-listed'
		fi
		# driver is the actual driver xorg will use
		driver=$xorgBase$xorgDriver

		if [ "$B_PRINT_VER" == 'true' ];then
			exit 0 # this is required for smxi native driver tests
		else
# 			if [ "$B_SM_INSTALL" != 'true' -a -n "$START_OPTIONS_PRINT" ];then
# 				print_information_continue 'info' "You are using the following options:\n$START_OPTIONS_PRINT"
# 			fi
			# make sure the driver is available for the user's debian version
			# is it true? nouveau pulled out of xorg? what the hell?
			if [ "$bSkipInstall" != 'true' -a -z "$( check_package_status $driver 'c' )" ];then
# 				if [ "$NATIVE_OVERRIDE" != 'nouveau' ];then
					error_handler 222 "$driver"
# 				else
# 					bSkipInstall='true'
# 				fi
			fi
			if [ "$B_RESTORE_DEFAULTS" == 'true' ];then
				print_information_continue 'standard' "The graphics installer will be cleaning out all previous drivers\nmoving ${C}$EXXC${S} to ${C}$EXXC-bu-$( date +%Y-%m-%d-%H:%M:%S )${S}\nIt will remove all $NATIVE_OVERRIDE nomodeset and blacklists in grub and /etc/modules,\nand will install Free xorg${S} driver: ${C}$driverInstall\n${S}This should more or less restore your system to the native, no xorg.conf state.${N}"
			else
				print_information_continue 'standard' "The graphics installer will be installing the${C}$experimentalText Free xorg${S} driver: ${C}$driverInstall${N}"
			fi
		fi
		x_start_stop_master stop

		## cleanup up old stuff
		pre_extract_clean_set_up
		preinstall_cleanup
		# this is required to do radeon xorg driver
		native_driver_install_keep
		if [ -n "$xorgCore" ];then
			# aptitude doesn't download missing package for reinstall
			case $SYSTEM_BASE in
				debian|ubuntu)
					install_package "$xorgCore" '' ''
					;;
			esac
			install_package "$xorgCore" '' 'reinstall'
		fi
		# need an override for this
		if [ "$CARD" == "$FGLRX" -a "$B_TESTING_5" != 'true' ];then
			install_package "$libMesaGlx" '' 'reinstall'
		fi
		
		if [ "$CARD" == "$FGLRX" -a "$B_EXPERIMENTAL" == 'true' ];then
			echo "${S}Installing experimental driver ${C}$driver${S} now...${N}"
			native_driver_experimental "$driver"
		else
			if [ "$bSkipInstall" != 'true' ];then
				# aptitude doesn't download missing package for reinstall
				case $SYSTEM_BASE in
					debian|ubuntu)
						install_package "$driver" '' ''
						;;
				esac
				install_package $driver '' 'reinstall'
			fi
			if [ "$CARD" == "$FGLRX" ];then
				eval $extraAtiPackage1
			fi
		fi
		# we'll need this to determine whether to do a reboot for radeon/nouveau
		NON_FREE_DRIVER=$( grep -Esi 'Driver[[:space:]]+"(fglrx|nvidia)"' $EXXC | grep -oEs "(nvidia|fglrx)" )
		## clean / update xorg, this is only to change driver to ati/nv, no full xorg conf yet.
		if [ "$B_RESTORE_DEFAULTS" == 'false' ];then
			update_xorg
		fi
		process_xvmc # this will restore xvmc defaults if nvidia stuff was being used
		
		case $NATIVE_OVERRIDE in
			nouveau|radeon)
				case $SYSTEM_BASE in
					arch|fedora|debian|ubuntu)
						add_module "$NATIVE_OVERRIDE"
						;;
				esac
				set_modesetting_on $NATIVE_OVERRIDE
				;;
		esac

		eval $LOGPE
		## and finish it up
		x_start_stop_master start
		exit 0 # just exit here in case something weird goes wrong with xorg start
	else
		error_handler 254 # this is redundant, but I'm leaving it as a fail safe
	fi
	eval $LOGPE
}

native_driver_install_keep()
{
	eval $LOGUS
	local lgmd='libgl1-mesa-dri'  ldrm='libdrm2'

	if [ "$NATIVE_OVERRIDE" == 'radeon' ];then
		if [ -z "$( check_package_status "$lgmd" 'i' )" ];then
			install_package $lgmd
		fi
		if [ -z "$( check_package_status "$ldrm" 'i' )" ];then
			install_package $ldrm
		fi
		if [ -n "$( type -P deborphan )" ];then
			# doing one at a time because if one is already on keep,
			# trying to add both will fail
			deborphan --add-keep $lgmd > /dev/null
			deborphan --add-keep $ldrm > /dev/null
		fi
	fi
	eval $LOGUE
}

# args: $1 $driver; $2 $currentlyInstalled
native_driver_experimental()
{
	eval $LOGPS
	if [ "$CARD" == $FGLRX ];then
		# step one, check and install basic drivers
		if [ -n "$EXPERIMENTAL_XORG_ATI" ];then
			echo "${S}Starting experimental driver ${C}$1${S} install now...${N}"
			download_install_package freedesktop-ati
			unset packageExists
		else
			error_handler 187 exp-xorg-ati
		fi
		# step 2, if required, check and install extra packages
		if [ "$B_EXTRA_EXPERIMENTAL" == 'true' -a -n "$EXPERIMENTAL_LIBDRM2" ];then
			echo "${S}Adding experimental components for ${C}$1${S} now...${N}"
			download_install_package freedesktop-ati-drm2
			download_install_package freedesktop-ati-drm-dev
			unset packageExists
		else
			error_handler 187 exp-drm2
		fi
	fi
	eval $LOGPE
}

# this is for non-standard debs, and other stuff, for experimental use primarily
download_install_package()
{
	eval $LOGUS
	local packageToInstall='' url='' systemType='_i386.deb' shortPackage=''
	if [ "$BITS" == '64' ];then
		systemType='_amd64.deb'
	fi

	case $1 in
		freedesktop-ati)
			packageToInstall=$EXPERIMENTAL_XORG_ATI$systemType
			;;
		freedesktop-ati-drm2)
			packageToInstall=$EXPERIMENTAL_LIBDRM2$systemType
			;;
		freedesktop-ati-drm-dev)
			packageToInstall=$EXPERIMENTAL_LIBDRM_DEV$systemType
			;;
	esac
	
	url=$SCRIPT_DOWNLOAD'ati-drivers/'$packageToInstall
	if [ -z "$packageToInstall" ];then
		error_handler 187 download-package
	fi
	# slice out first part of name for package display purposes
	shortPackage=$( echo $packageToInstall | cut -d '_' -f 1 )

	echo "${S}Downloading Experimental package ${C}$shortPackage${S} now...${N}"
	wget -Nc $url || error_handler 189 $packageToInstall

	if [ -s "$packageToInstall" ];then
		echo "${S}Experimental package ${C}$shortPackage${S} downloaded successfully, installing now.${N}"
		dpkg -i $packageToInstall
		rm -f $packageToInstall
	else
		#rm -f $packageToInstall
		error_handler 188 $packageToInstall
	fi
	eval $LOGUE
}

prep_native_driver()
{
	eval $LOGUS
	local xxva='xserver-xorg-video-ati' ldrmd='libdrm-dev'
	local packageList=''

	case $CARD in
		$FGLRX)
			packageList="$xxva $ldrmd"
			;;
	esac
	eval $LOGUE
	remove_package "$packageList" "$xxva"
}

### -------------------------------------------------------------------
### KMS Tools - Modesetting On/Off, Blacklist On/Off, Initramfs set
### -------------------------------------------------------------------

# $1 - module to be handled; $2 - optional: failed (triggers reboot requirement)
set_modesetting_off()
{
	eval $LOGPE
	local bShowMessage='false' retValue=1 # default false
	
	case $1 in
		nouveau|radeon)
			case $SYSTEM_BASE in
				# note that the nvidia installer now requires blacklisting a priori, so 
				# just treat arch like the other distros
# 				arch)
# 					if [ "$2" == 'failed' ];then
# 						echo $LINE
# 						echo "${S}Please note: Arch users: you can proceed with your driver install, but you must ${S}reboot${S}"
# 						echo "at the end of ${C}$SCRIPT_NAME${S} when the install is completed before the driver will work."
# 						echo "This is because its not possible to remove ${C}$1${S} from a running system.${N}"
# 						print_hec
# 					fi
# 					;;
				*)
					# only act if blacklist/nomodeset was added
					add_grub_nomodeset_blacklist_item $1
					retValue=$?
					if [ "$retValue" -eq 0 ];then
						bShowMessage='true'
					fi
					add_modprobe_d_blacklist_item $1
					retValue=$?
					if [ "$retValue" -eq 0 ];then
						bShowMessage='true'
					fi
					if [ "$bShowMessage" == 'true' ];then
						update_initramfs "remove-$1"
					fi
					
					if [ "$bShowMessage" == 'true' -a "$2" == 'failed' ];then
						# note: we don't want nouveau to try to restart on reboot, so we're changing
						# xorg.conf to use vesa here.
						NATIVE_OVERRIDE='vesa'
						B_NATIVE_DRIVER='true'
						echo "${S}Setting ${C}$EXXC${S} to use ${C}Xorg vesa driver${S} temporarily..... ${N}"
						update_xorgconf_driver_version
						reboot_now_question "$1" 'modeset-off'
					fi
					;;
			esac
			;;
	esac
	eval $LOGPS
}

# $1 - module to be handled; $2 - optional: failed (triggers reboot requirement)
set_modesetting_on()
{
	eval $LOGPS
	local bShowMessage='false'

	case $1 in
		modesetting|nouveau|radeon)
			# only act if blacklist/nomodeset was removed
			remove_grub_nomodeset_blacklist_item $1
			if [ "$?" -eq 0 ];then
				bShowMessage='true'
			fi
			remove_modprobe_d_blacklist_item $1
			if [ "$?" -eq 0 ];then
				bShowMessage='true'
			fi
			if [ "$bShowMessage" == 'true' ];then
				update_initramfs "add-$1"
			fi
			if [ "$bShowMessage" == 'true' -a "$2" == 'failed' ] || [ -n "$NON_FREE_DRIVER" ];then
				reboot_now_question "$1" 'modeset-on'
			fi
			;;
	esac
	eval $LOGPE
}

get_active_grub_files()
{
	eval $LOGUS
	local grubFiles=''
	
	if [ -f "$GRUB1_FED" ];then
		grubFiles="$GRUB1_FED"
	else
		if [ -f "$GRUB1" ];then
			grubFiles="$GRUB1"
		fi
		if [ -f "$GRUB2" ];then
			grubFiles="$grubFiles $GRUB2"
		fi
		if [ -f "$GRUBED" ];then
			grubFiles="$grubFiles $GRUBED"
		fi
	fi
	log_function_data "grub files: $grubFiles"
	
	if [ -z "$grubFiles" ];then
		error_handler 213 "modesetting-on-off"
	else
		echo $grubFiles
	fi
	eval $LOGUE
}

# args: $1 - radeon/nouveau
add_grub_nomodeset_blacklist_item()
{
	eval $LOGUS
	
	local returnValue=1 activeFile='No'
	local noModesetString='nomodeset'
	local noModesetString2="$1.modeset=0"
	local moduleSearch1="nomodeset|rdblacklist=nouveau|rdblacklist=radeon|nouveau.blacklist=1|radeon.blacklist=1"
	local moduleSearch2="nouveau.modeset=0|radeon.modeset=0"
	local grubFiles=$( get_active_grub_files )

	case $SYSTEM_BASE in
		fedora)
			noModesetString="rdblacklist=$1 nomodeset"
			;;
	esac
	
	if [ -n "$grubFiles" ];then
		if [ -z "$( grep -Eis '('$moduleSearch1')' $grubFiles )" -o -z "$( grep -Eis '('$moduleSearch2')' $grubFiles )" ];then
			echo -n "${S}Adding ${C}$grubFiles $noModesetString/$noModesetString2${S} for ${C}$1${S} blacklist${S} items..... ${N}"
			if [ -f "$GRUB1" ];then
				if [ -z "$( grep -Eis 'kernel.*root=.*('$moduleSearch1')' $GRUB1 )" ];then
					sed -i "/kernel.* root=/s|$| $noModesetString|" $GRUB1
					activeFile=$GRUB1
				fi
				if [ -z "$( grep -Eis 'kopt.*root=.*('$moduleSearch1')' $GRUB1 )" ];then
					sed -i "/kopt.*root=/s|$| $noModesetString|" $GRUB1
					activeFile=$GRUB1
				fi
				if [ -z "$( grep -Eis 'kernel.*root=.*('$moduleSearch2')' $GRUB1 )" ];then
					sed -i "/kernel.* root=/s|$| $noModesetString2|" $GRUB1
					activeFile=$GRUB1
				fi
				if [ -z "$( grep -Eis 'kopt.*root=.*('$moduleSearch2')' $GRUB1 )" ];then
					sed -i "/kopt.*root=/s|$| $noModesetString2|" $GRUB1
					activeFile=$GRUB1
				fi
			fi
			if [ -f "$GRUB2" ];then
				if [ -z "$( grep -Eis 'linux.*root=.*('$moduleSearch1')' $GRUB2 )" ];then
					sed -i "/linux.* root=/s|$| $noModesetString|" $GRUB2
					activeFile=$GRUB2
				fi
				if [ -z "$( grep -Eis 'linux.*root=.*('$moduleSearch2')' $GRUB2 )" ];then
					sed -i "/linux.* root=/s|$| $noModesetString2|" $GRUB2
					activeFile=$GRUB2
				fi
			fi
			if [ -f "$GRUB1_FED" -a ! -f "$GRUB2" ];then
				if [ -z "$( grep -Eis 'kernel.*root=.*('$moduleSearch1')' $GRUB1_FED )" ];then
					sed -i "/kernel.* root=/s|$| $noModesetString|" $GRUB1_FED
					activeFile=$GRUB1_FED
				fi
			fi
			
			log_function_data "$activeFile file updated to add $1 nomodeset: $grubFiles"
			echo "${S}Added${N}"
			returnValue=0
		fi
	fi
	if [ -f "$GRUBED" ];then
		if [ -z "$( grep -Eis "^GRUB_CMDLINE_LINUX_DEFAULT=.*$moduleSearch1" $GRUBED )" ];then
			echo -n "${S}Adding ${C}$GRUBED $noModesetString${S} for ${C}$1${S} blacklist${S} items..... ${N}"
			sed -r -i 's|GRUB_CMDLINE_LINUX_DEFAULT="(.*)"|GRUB_CMDLINE_LINUX_DEFAULT="\1 '$noModesetString'"|' $GRUBED
			echo "${S}Added${N}"
			log_function_data "File $GRUBED updated to add $1 $noModesetString: $GRUBED"
			returnValue=0
		fi
		if [ -z "$( grep -Eis "^GRUB_CMDLINE_LINUX_DEFAULT=.*$moduleSearch2" $GRUBED )" ];then
			echo -n "${S}Adding ${C}$GRUBED $noModesetString2${S} for ${C}$1${S} blacklist${S} items..... ${N}"
			sed -r -i 's|GRUB_CMDLINE_LINUX_DEFAULT="(.*)"|GRUB_CMDLINE_LINUX_DEFAULT="\1 '$noModesetString2'"|' $GRUBED
			echo "${S}Added${N}"
			log_function_data "File $GRUBED updated to add $1 $noModesetString2: $GRUBED"
			returnValue=0
		fi
	fi
	case $SYSTEM_BASE in
		fedora)
			if [ -f "$GRUB1_FED" -a ! -f "$GRUB2" ];then
				if [ -z "$( grep -si 'vmalloc=' $GRUB1_FED )" ];then
					echo -n "${S}Adding ${C}$GRUB1_FED vmalloc=256m${S} item..... ${N}"
					sed -i '/kernel.* root=/s|$| vmalloc=256m|' $GRUB1_FED
					log_function_data "File $GRUB1_FED updated to add vmalloc=256m: $GRUB1_FED"
					echo "${S}Added${N}"
				fi
				# also make system bootable to init 3 easily with grub, otherwise you can
				# literally not be able to access tty OR desktop in some cases
				if [ -n "$( grep -Eis '^[[:space:]]*(hiddenmenu|timeout=0)' $GRUB1_FED )" ];then
					echo -n "${S}Unhiding grub menu and adding ${C}timeout=3${S} to ${C}$GRUB1_FED${S}..... ${N}"
					sed -i 's|^[[:space:]]*hiddenmenu|#hiddenmenu|' $GRUB1_FED
					sed -i 's|^[[:space:]]*timeout=0|timeout=3|' $GRUB1_FED
					log_function_data "File $GRUB1_FED updated to restore grub timeout/unhide menu: $GRUB1_FED"
					echo "${S}Modified${N}"
				fi
			fi
			;;
	esac
	
	eval $LOGUE
	return $returnValue
}

# args: $1 - radeon/nouveau
remove_grub_nomodeset_blacklist_item()
{
	eval $LOGUS

	local returnValue=1
	local searchReplace1="nomodeset|$1.modeset=0|rdblacklist=$1|$1.blacklist=1"
	local grubFiles=$( get_active_grub_files )
	
	if [ -n "$grubFiles" ];then
		if [ -n "$( grep -Eis '('$searchReplace1')' $grubFiles )" ];then
			echo -n "${S}Removing ${C}$grubFiles $1 blacklist${S} items..... ${N}"
			sed -ri 's/[[:space:]]('$searchReplace1')//ig' $grubFiles
			log_function_data "file updated to remove $1 blacklist: $grubFiles"
			echo "${S}Removed${N}"
			returnValue=0
		fi
	elif [ "$B_SKIP_GRUB_FILE" == 'true' ];then
		echo "${M}Skipping grub file removal due to ${C}-! 33${M} option being used. Make sure to remove all blacklists"
		echo "and then reboot before you proceed!${N}"
		returnValue=0
	fi
	
	eval $LOGUE
	return $returnValue
}

# args: $1 - nouveau/radeon
add_modprobe_d_blacklist_item()
{
	eval $LOGUS
	local empksb='/etc/modprobe.d/kms-sg-blacklist.conf'
	local returnValue=1
	
	if [ -d /etc/modprobe.d ];then
		if [ -z "$( grep -Es "^[[:space:]]*blacklist[[:space:]]+$1" /etc/modprobe.d/*.conf )" ];then
			echo "${S}Creating ${C}$empksb $1 blacklist${S} item...${N}"
			if [ -f $empksb ];then
				echo -e "blacklist $1" >> $empksb
			else
				echo -e "blacklist $1" > $empksb
			fi
			returnValue=0
			log_function_data "file updated to add $1 blacklist: $empksb"
		fi
	fi
	eval $LOGUE
	return $returnValue
}

# args: $1 - nouveau/radeon
remove_modprobe_d_blacklist_item()
{
	eval $LOGUS
	local returnValue=1
	local empksb='/etc/modprobe.d/kms-sg-blacklist.conf'
	
	if [ -d /etc/modprobe.d ];then
		# first dump sgfxi created file if present, not going to use this for now
		if [ -f "$empksb" ];then
			rm -f $empksb
			log_function_data "$empksb deleted from /etc/modprobe.d/"
		fi
		# then edit anything that remains to get rid of that blacklist item
		if [ -n "$( grep -Es '^[[:space:]]*blacklist[[:space:]]+'$1'' /etc/modprobe.d/*.conf )" ];then
			echo "${S}Removed $1 blacklisting from /etc/modprobe.d/*.conf${N}"
			sed -i "s/^[[:space:]]*blacklist[[:space:]]\+$1//i" /etc/modprobe.d/*.conf 2>/dev/null
			returnValue=0
			log_function_data "$1 blacklist removed from /etc/modprobe.d/*.conf"
		fi
	fi
	eval $LOGUE
	return $returnValue
}

# 1 - add-nouveau|radeon/remove-nouveau|radeon; 
update_initramfs()
{
	eval $LOGPS
	local storedNouveau="/boot/initramfs-$KERNEL_FULL-nouveau.img"
	local storedRadeon="/boot/initramfs-$KERNEL_FULL-radeon.img"
	local startingInitram="/boot/initramfs-$KERNEL_FULL.img"
	case $SYSTEM_BASE in
		debian|ubuntu)
			case $1 in
				remove-nouveau|remove-radeon)
					if [ -n "$( type -p update-initramfs )" ];then
						echo "${S}Running ${C}update-initramfs -u${S} to remove Nouveau/Radeon from initrd... ${N}"
						update-initramfs -u -k $KERNEL_FULL
					fi
					;;
			esac
			;;
		fedora)
			case $1 in
				remove-nouveau)
					if [ -n "$( type -p dracut )" ];then
						echo "${S}Updating ${C}initramfs${S} to get rid of ${C}nouveau${S} now...${N}"
						mv -f $startingInitram $storedNouveau
						dracut $startingInitram $KERNEL_FULL
					fi
					;;
				remove-radeon)
					if [ -n "$( type -p dracut )" ];then
						echo "${S}Updating ${C}initramfs${S} to get rid of ${C}radeon${S} now...${N}"
						mv -f $startingInitram $storedRadeon
						dracut $startingInitram $KERNEL_FULL
					fi
					;;
				add-nouveau)
					if [ -f "$storedNouveau" ];then
						echo "${S}Restoring ${C}initramfs${S} with ${C}nouveau${S} now...${N}"
						mv -f $storedNouveau $startingInitram 
					elif [ -n "$( type -p dracut )" ];then
						echo "${S}Building ${C}initramfs${S} with ${C}nouveau${S} now...${N}"
						dracut $startingInitram $KERNEL_FULL
					fi
					;;
				add-radeon)
					if [ -f "$storedRadeon" ];then
						echo "${S}Restoring ${C}initramfs${S} with ${C}radeon${S} now...${N}"
						mv -f $storedRadeon $startingInitram 
					elif [ -n "$( type -p dracut )" ];then
						echo "${S}Building ${C}initramfs${S} with ${C}radeon${S} now...${N}"
						dracut $startingInitram $KERNEL_FULL
					fi
					;;
			esac
			;;
	esac
	eval $LOGPE
}

# args: $1 - module; $2 - modeset-on/modeset-off
reboot_now_question()
{
	eval $LOGPS
	local opt='' options='' initText='' initLevel=''
	
	case $DISTRIB_ID in
		fedora|aptosid|sidux|mepis|antix|siduction)
			initLevel=3
			;;
		*)
			initLevel='no-init'
			;;
	esac
	
	case $initLevel in
		2|3|4)
			initText="(use init ${C}$initLevel${M} to start, or use ${C}$initLevel${M} at grub)"
			;;
		*)
			initText="(use ctrl+alt+F1 to enter console after reboot)"
			;;
	esac
	
	echo $MLINE
	if [ "$2" == 'modeset-off' ];then
		echo "${M}Since ${C}$1${M} is running in the kernel, you will need to restart your computer before"
		echo "your ${C}$CARD${M} install is completed, and you may need to reboot again if it errors out,"
		echo "then you can run ${C}$SCRIPT_NAME${M} again and it should work."
		echo
		echo "${S}For best results, select the ${C}shutdown${S} option, let the computer sit for a minute, then restart it."
		
		echo $MLINE
		echo "${S}Not everyone's systems are having problems getting rid of ${C}$1${S}, but to make the process"
		echo "more consistently safe and reliable this step seems to be a good idea. Once you reboot,"
		echo "the ${C}$1${S} module will not be loaded, and no conflicts or issues should occur."
		echo "You only need to do this one time, since after that the ${C}$1${S} module will not load"
	elif [ "$2" == 'modeset-on' ];then
		echo "${M}To make your new ${C}$1 Xorg / Kernel modules${S} fully functional, you will need to reboot first"
		echo
		echo "${W}The ${C}$1${W} drivers have very unreliable support for newer ${C}nVidia/ATI${W} cards!"
		echo 
		echo "${S}If your desktop fails to start properly after you reboot, you may need to do one of two things:"
		echo "1 - move your xorg.conf file to a temporary new file name, like: "
		echo "    ${C}mv /etc/X11/xorg.conf /etc/X11/xorg.conf-holder${S}"
		echo "    then restart your desktop login manager (like gdm,xdm,kdm). If X then starts, you're fine."
		echo "2 - Add the grub kernel option: ${C}nomodeset${S}"
		echo "    at grub load, using the edit (e) method in grub, then boot with that. This will allow"
		echo "    you to at least run $SCRIPT_NAME to install the non-free driver."
	fi
	echo $MLINE
	echo "${M}Remember, to install ${C}$CARD${M} drivers, you'll need to run ${C}$SCRIPT_NAME${M} again."
	echo "after you have restarted $initText"
	echo $LINE
	echo "${C}1 - shutdown${S} - Shutdown, wait 30 seconds, then restart manually (${M}RECOMMENDED!${S}).${N}"
	echo "${C}2 - reboot${S} - Reboot. This may not let some data unload from your memory.${N}"
	echo "${C}3 - quit${S} - Exit script, do other things (then restart system to install nvidia).${N}"
	echo $LINE
	options="shutdown reboot quit"
	select opt in $options
	do
		case $opt in
			shutdown)
				echo "${S}Shutting down now...${N}"
				handle_shutdowns 'halt'
				exit 0
				;;
			reboot)
				echo "${S}Rebooting now...${N}"
				handle_shutdowns 'reboot'
				exit 0
				;;
			quit)
				echo "${S}Ok, remember you need to reboot before the $1 changes are live.${N}"
				exit 100 # need to exit with 100 to not trigger root pid kill in smxi
				;;
			*)
				echo "${W}Please select one of the options in the list, thank you.${N}"
				bRepeat='true'
				;;
		esac
		break
	done
	eval $LOGPE
	if [ "$bRepeat" == 'true' ];then
		reboot_now_question "$@"
	fi
}

# args: $1 - shutdown/reboot
handle_shutdowns()
{
	eval $LOGUS
	
	local command='' realCommand=$1
	
	if [ "$B_SYSTEMD_SYSINIT" == 'true' ];then
		case $realCommand in
			halt)
				realCommand='poweroff'
				;;
		esac
		# should handle case where mutant systemd systems fail because it is actually running sysvnit
		command="systemctl $realCommand 2>>$LOG_FILE || $1"
	else
		command=$1
	fi
	log_function_data "command: $command"
	
	eval $LOGUE
	eval $command
}

### -------------------------------------------------------------------
### Non-free Driver installer section
### -------------------------------------------------------------------

set_cpu_data()
{
	eval $LOGUS
	case $CARD in
		$NVIDIA)
			if [ "$BITS" == '64' ];then
				KERNEL_ARCH='_64'
				NV_64_ARCH='_64'
			fi
			;;
		$FGLRX)
			# this is legacy, no longer needed but in case ati changes again leave it
			KERNEL_ARCH='i386' # default value
			if [ "$BITS" == '64' ];then
				KERNEL_ARCH='amd64'
			fi
			;;
	esac

	if [ "$B_PRINT_VER" != 'true' ];then
		log_function_data "BITS: $BITS - arch: $KERNEL_ARCH"
	fi
	eval $LOGUE
}

## test if the driver to be installed is in the list of supported drivers
## advanced tests occur in driver_support_tests, patches set in check_patch_driver
check_supported_driver()
{
	eval $LOGUS
	local isGood='' pattern='[0-9]{4}'
	local drivers="$DRIVER_DEFAULT:$VERSIONS:$DRIVER_BETA:$OTHER_VERSIONS:$DRIVER_QUAD"

	if [ -n "$DRIVER_OVERRIDE" ];then
		isGood=$( echo $drivers | grep "$DRIVER_OVERRIDE" )
		if [ -z "$isGood" ];then
			error_handler 241 $DRIVER_OVERRIDE
		fi
	fi
	if [ "$1" == 'last-check' ];then
		isGood=$( echo $drivers | grep "$DRIVER_DEFAULT" )
		if [ -z "$isGood" ];then
			error_handler 240 $DRIVER_DEFAULT
		fi
	fi
	eval $LOGUE
}

set_driver_install_version()
{
	eval $LOGPS
	local response='' printDriver='' newKernelText='' betaDriverText=''
	local moduleOrInstall='installing' extraBetaInfo=''
	local bDebugger='false'

	# I'm forcing special cases to override the defaults so the data
	# printed out will show what drivers are supported
	if [ -n "$DRIVER_INSTALL" ];then
		DRIVER_DEFAULT=$DRIVER_INSTALL
	fi

	# this is only for du output :: this has to go before assigning -o version number
	if [ "$B_PRINT_VER" == 'true' ];then
		# echo the basic list:
		if [ "$B_USE_DISTRO_DRIVER" != 'true' ];then
			echo $DRIVER_DEFAULT':'$VERSIONS
		else
			# note: because sometimes I'm turning off fglrx run install due to failure
			# that leaves only debian fglrx to install
			echo $DISTRO_FGLRX
		fi
		exit 0
	fi
	# need to puke and die here, not earlier because of print out 
	if [ -n "$INSTALL_TO_KERNEL" -a "$B_FGLRX_DIRECT" == 'true' -a "$CARD" == $FGLRX -a "$( uname -r )" != "$INSTALL_TO_KERNEL" ];then
		error_handler 219
	fi

	if [ -n "$DRIVER_OVERRIDE" ];then
		DRIVER_DEFAULT=$DRIVER_OVERRIDE
	fi
	# error_handler 246 $DRIVER_DEFAULT # for unsupported cards
	if [ "$B_USE_DISTRO_DRIVER" != 'true' ];then
		check_supported_driver last-check
	else
		case $CARD in
			$FGLRX)
				DRIVER_DEFAULT=$DISTRO_FGLRX
				;;
			$NVIDIA)
				DRIVER_DEFAULT=$DISTRO_NVIDIA
				;;
		esac
	fi

	if [ "$B_SM_INSTALL" != 'true' -a -n "$START_OPTIONS_PRINT" ];then
		print_information_continue 'info' "You are using the following options:\n$START_OPTIONS_PRINT"
	elif [ "$B_SM_INSTALL" == 'true' -a -n "$INSTALL_TO_KERNEL" ];then
		newKernelText="\n${S}onto the kernel: ${C}$INSTALL_TO_KERNEL${N}"
	fi
	# this is only true if use beta flag true and beta driver exists
	if [ "$B_USE_BETA" == 'true' ];then
		case $CARD in
			$NVIDIA|$FGLRX)
				if [ "$B_BETA_EXISTS" == 'true' ];then
					if [ "$bDebugger" == 'true' ];then
						echo "FDB:$FG_DEFAULT_BETA:"
						echo "FBV:$FG_BETA_VERSION:"
						echo "bd:$betaDriver:"
						echo "End assign_standard_or_beta_driver"
					fi
					betaDriverText="\n${M}This is the latest ${C}$CARD Beta driver${M} for your card type.${N}\n"
					if [ "$CARD" == $FGLRX -a -n "$FG_BETA_VERSION" ];then
						extraBetaInfo=" ($FG_BETA_VERSION) "
					fi
				else
					betaDriverText="\n${M}There is ${C}no current beta driver${M} for your ${C}$CARD${M} card type.\n${S}Using the current ${C}stable driver${S} instead.${N}\n"
				fi
				# echo bdt: $betaDriverText
				;;
			*)
				betaDriverText="\n${M}There is no ${C}beta driver${M} for your ${C}$CARD${M} card.\n${S}Using the current ${C}stable driver${S} instead.${N}\n"
				;;
		esac
	fi
	if [ "$B_KERNEL_MODULE_ONLY" == 'true' ];then
		moduleOrInstall='building a module for'
	fi
	print_information_continue 'standard' "The graphics installer will be $moduleOrInstall the ${C}$CARD${S} driver: ${C}$DRIVER_DEFAULT$extraBetaInfo${N}$betaDriverText$newKernelText"

	log_function_data "Installing this driver: $DRIVER_DEFAULT$extraBetaInfo"

	eval $LOGPE
	# test for support
	driver_support_tests supported-driver
}

# args: $1 - which fix. Holds miscellaneous highly specific fixes, created as needed
misc_fixes()
{
	eval $LOGUS
	local outcome=''
	case $1 in
		nvidia-24-link)
			local headersDir="${USRS}linux-headers-$KERNEL_FULL/include"
			# I don't know why the -e/f tests fail, I thought -e means exists at all...
			if [ -L "$headersDir/asm" -o -e "$headersDir/asm" ];then
				rm -f $headersDir/asm
			fi

			echo "${S}Creating symbolic link ${C}asm-x86 asm${S}...${N}"

			ln -sf $headersDir/asm-x86 $headersDir/asm || error_handler 233 "link -s asm-x86 asm"

			if [ ! -e $headersDir/asm-i386 -a "$BITS" == '32' ];then
				log_function_data "Creating soft link asm-x86 asm-i386 in $headersDir"
				echo "${S}Creating symbolic link ${C}asm-x86 asm-i386${S}...${N}"

				ln -s $headersDir/asm-x86 $headersDir/asm-i386 || error_handler 233 "link -s asm-x86 asm-i386"
				log_function_data "Link successfully created."
			else
				log_function_data "link asm-x86 asm-i386 in $headersDir already exists"
			fi
			;;
		linux-generated-patch)
			local generated1="${USRS}$KERNEL_FULL/include/generated/" 
			local generated2="/lib/modules/$KERNEL_FULL/build/include/generated/"
			outcome="$generated1 or $generated2 do not exist"
			if [ -d "$generated1" -o -d "$generated2" ];then
				echo 'true'
				outcome="$generated1 or $generated2 exist"
			fi
			log_function_data "outcome: $outcome"
			;;
		drm-2-x-test)
			local drmVersion=$( check_package_status 'libdrm2' 'i' )
			local isFixedVersion='' isLessThan=''
			# set to 0 if null to avoid math errors
			if [ -z "$drmVersion" ];then
				drmVersion=0
			fi
			# returns 0 for true/ 1 for false
			dpkg --compare-versions $drmVersion gt 2.4.10
			isFixedVersion=$?
			dpkg --compare-versions $drmVersion lt 2.4
			isLessThan=$?
			log_function_data "isFixedVersion: $isFixedVersion :: isLessThan: $isLessThan"
			if [ "$isFixedVersion" -ne 0 -a "$isLessThan" -ne 0 ];then
				error_handler '220' "$drmVersion"
			fi
			;;
	esac
	eval $LOGUE
}

set_download_info()
{
	eval $LOGPS
	local packageName='' downloadUrl='' response='' moduleTest=0 fgBetaVersion=''
	# http://us.download.nvidia.com/XFree86/Linux-x86/275.19/NVIDIA-Linux-x86-275.19.run
	case $CARD in
		$NVIDIA)
			# set the package name, .run is added to it when it's needed
			DRIVER_FILE="NVIDIA-Linux-x86$NV_64_ARCH-$DRIVER_DEFAULT$NV_PKG_NO"
			downloadUrl="$NVIDIA_DOWNLOAD_SITE/XFree86/Linux-x86$KERNEL_ARCH/$DRIVER_DEFAULT/"
			;;
		$FGLRX)
			# set driver package name
			# DRIVER_FILE="ati-driver-installer-$DRIVER_DEFAULT-$CPU"
			if [ "$B_USE_BETA" == 'true' ];then
				# note: need beta* because amd releases numbered betas within a month release
				# # http://www2.ati.com/drivers/beta/amd-driver-installer-catalyst-13.3-beta3-linux-x86.x86_64.zip
				# http://www2.ati.com/drivers/beta/amd-driver-installer-catalyst-13-6-beta-x86.x86_64.zip
				# amd-catalyst-13.6-beta-linux-x86.x86_64.run
				if [ -n "$FG_BETA_VERSION" ];then
					fgBetaVersion="-$FG_BETA_VERSION"
				fi
				if [ "$B_AMD" == 'true' ];then
					downloadUrl='http://www2.ati.com/drivers/beta/'
				else
					downloadUrl=$SCRIPT_DOWNLOAD_ALT
				fi
				# note, amd changed this AGAIN!!! for their damned betas
				# www2.ati.com/drivers/beta/amd-catalyst-13.8-beta1-linux-x86.x86_64.zip 
				# www2.ati.com/drivers/beta/amd-driver-installer-catalyst-13-6-beta-x86.x86_64.zip 
				# DO NOT BUY AMD CARDS if you want competent nonfree video driver support!!!
				if [ "$DRIVER_DEFAULT" == '13.6' ];then
					FG_POST=''
				fi
			else
				if [ "$B_AMD" == 'true' ];then
					downloadUrl='http://www2.ati.com/drivers/linux/'
				else
					downloadUrl=$SCRIPT_DOWNLOAD_ALT
				fi
			fi
			DRIVER_FILE="$FGLRX_PACKAGE_PREFIX-$DRIVER_DEFAULT$fgBetaVersion-${FG_POST}x86.x86_64"
			;;
	esac

	log_function_data "download url: $downloadUrl - driver file: $DRIVER_FILE"

	eval $LOGPE
	
	# absolute override
	if [ "$B_KERNEL_MODULE_ONLY" == 'true' ];then
		: # do nothing
	# otherwise if -f used, force install
	elif [ "$B_FORCE_OPTION" == 'true' ];then
		download_extract_driver $downloadUrl $DRIVER_FILE
	else
		case $CARD in
			$NVIDIA)
				# leaving in test flags in case something goes wrong in early tests
# 				if [ "$B_TESTING_5" == 'true' ];then
					test_module_build_ok 'return'
					moduleTest="$?"
					if [ "$moduleTest" -eq 0 ];then
						build_kernel_module_only 'build' 'silent'
					else
						echo $LINE
						echo "${S}Unable to rebuild module from previous driver install. Reinstalling driver instead.${N}"
						if [ -n "$DISPLAY" -a "$B_TESTING_2" != 'true' -a "$B_SKIP_X_TEST" != 'true'  -a "$B_LAUNCH_FROM_X" != 'true' ];then
							echo "${W}Sorry, installing the ${C}nVidia${W} driver can't be done in ${C}X${W}.${N}"
							error_handler 250
						fi
						download_extract_driver $downloadUrl $DRIVER_FILE
					fi
# 				else
# 					download_extract_driver $downloadUrl $DRIVER_FILE
# 				fi
				;;
			$FGLRX)
				download_extract_driver $downloadUrl $DRIVER_FILE
				;;
		esac
	fi
}

# arg: $1 install package to remove
pre_extract_clean_set_up()
{
	eval $LOGUS
	# this is only made for binary run packge installs
	if [ -d "$SCRIPT_WORKING_DIR" ];then
		cd $SCRIPT_WORKING_DIR
	fi
	if [ "$B_NATIVE_DRIVER" != 'true' ];then
		rm -rf $1 # this removes nvidia install dir if present
	fi

	# clean up any old stuff that might be left from last install, fglrx stuff
	# note: with 8.35.x ati switched to a randomly generated directory name
	# using the format fgrlx-install.FRGDXE
	rm -rf $FG_WORKING_DIR* /tmp/fglrx*
	rm -f /etc/fglrxrc /etc/fglrxprofiles.csv fglrx*
	eval $LOGUE
}

# args: $1 download url; $2 package name
download_extract_driver()
{
	eval $LOGPS
	local runPackage=$2'.run' errorTemp='' atiRef='' downloadPackage=$2 extension=''
	local zipPackage=$2'.zip' runZipPackage=$2'.run.zip' extractError=0 
	local uA='Mozilla/5.0 (X11; Ubuntu; Linux x86_64; rv:24.0) Gecko/20100101 Firefox/24.0'
	local downloadFrom=" from ${C}$1${S}"

	pre_extract_clean_set_up $2 ## $2 will only apply to nvidia install dir removal
	
	# test for existing downloaded version, then download, error if download fails
	# have to keep it in a clean if to avoid error
	if [ ! -f $runPackage -a ! -f $zipPackage -a ! -f $runZipPackage ];then
		case $CARD in
			$NVIDIA)
				downloadPackage=$runPackage
				;;
			$FGLRX)
				# this was needed to avoid some test from ati... still needed due to inconsistent amd site
				atiRef='--referer=support.ati.com '
				# atiRef='' $uA 
				# 12-8 was released, maybe on purpose, who knows, with a zipped .run file, why? who knows
# 				if wget -q --spider $uA $atiRef $1$runZipPackage;then
# 					echo "${S}Run package using .run.zip format. Preparing for zip/unzip procedure...${N}"
# 					downloadPackage=$runZipPackage
# 					extension='zip'
				if [ "$B_AMD" == 'true' ];then
					if wget -q --spider -U "$uA" $atiRef $1$zipPackage;then
						echo "${S}Run package using .zip format. Preparing for zip/unzip procedure...${N}"
						downloadPackage=$zipPackage
						extension='zip'
					else
						downloadPackage=$runPackage
					fi
				else
					downloadPackage=$zipPackage
					atiRef=''
					extension='zip'
					uA="s-tools/sgfxi-data.driver-$DRIVER_DEFAULT$fgBetaVersion" 
					downloadFrom=' This can sometimes take a while'
				fi
				;;
		esac
		echo "${S}Downloading ${C}$downloadPackage${S}$downloadFrom...${N}"
		wget -Nc -U "$uA" $atiRef $1$downloadPackage || error_handler 197 $downloadPackage
	else
		case $CARD in
			$FGLRX)
				if [ -f $zipPackage ];then
					extension='zip'
					downloadPackage=$zipPackage
				elif [ -f $runZipPackage ];then
					extension='zip'
					downloadPackage=$runZipPackage
				elif [ -f $runPackage ];then
					downloadPackage=$runPackage
				fi
		esac
		echo "${S}Using the previously downloaded installer package: ${C}$downloadPackage${N}"
	fi

	echo "${S}Extracting ${C}$downloadPackage${S}...${N}"
	case $CARD in
		$NVIDIA)
			# extract it, on error delete and call error handling
			bash ./$runPackage --extract-only 1>> $LOG_FILE 2>> $LOG_FILE
			errorTemp="$?"
			;;
		$FGLRX)
			# here we want to end up with a directory name like: fglrx-install-9-6 
			if [ "$extension" == 'zip' ];then
				# note, contents of zip file are not named the same as say version 12-8, rather: 8.982
				# typical amd inconsistentencies force further testing to make sure the thing that downloaded actually
				# is a real zip file.
				# rm this so we always have the new one
				if [ "$B_AMD" != 'true' ];then
					rm -f amdLICENSE.txt 2>/dev/null
				fi
				unzip -l ./$downloadPackage &>>$LOG_FILE || extractError="$?"
				# note, amd is clearly being run by total incompetents at this stage, the -v9.4 beta has this file name:
				# "amd-catalyst-13.11-beta V9.4-linux-x86.x86_64.run" clearly amd is using either budget outsourced labor
				# or they have no adults in charge (note the space, the upper case V, etc, total lack of any attempt
				# at basic discipline, really pathetic, sell your amd stock is my advice).
				if [ "$extractError" -eq 0 ];then
					runPackage=$( unzip -l ./$downloadPackage | grep -E 'amd-(catalyst|driver-installer)?.*.run$' | sed 's/beta[[:space:]]V/beta-v/' | awk '{print $NF}' )
				else
					log_function_data "fglrx zip extraction -l action failed."
				fi
				# echo $runPackage run
				if [ ! -f $runPackage ];then
					if [ "$extractError" -eq 0 ];then
						unzip ./$downloadPackage 2>>$LOG_FILE || extractError="$?"
						if [ "$extractError" -eq 0 ];then
							echo "${S}Run package ${C}$runPackage${S} extracted from: ${C}$downloadPackage${N}"
							log_function_data "fglrx zip extraction of run file succeeded."
						fi
					fi
				else
					echo "${S}Run package already extracted, using: ${C}$runPackage${N}"
				fi
				if [ "$extractError" -gt 0 ];then
					echo "${M}Removing bad zip package:${C}$downloadPackage${N}"
					rm -f $downloadPackage
					error_handler 165 "$downloadPackage"
				else
					log_function_data "fglrx zip extraction of run file successful."
				fi
# 				rm -f ./$downloadPackage
			fi
			LC_ALL= LC_CTYPE= LC_MESSAGES= LANG= bash ./$runPackage --extract $FG_WORKING_DIR-$DRIVER_DEFAULT 1>> $LOG_FILE 2>> $LOG_FILE
			errorTemp="$?"
			if [ -f $zipPackage -o -f $runZipPackage ];then
				rm -f $runPackage
			fi
			;;
	esac

	if [ "$errorTemp" -gt 0 -a "$B_TESTING_2" != 'true' ];then
		rm -f $runPackage
		error_handler 196 $runPackage
	fi

	eval $LOGPE
}

prep_install()
{
	eval $LOGPS
	local gccVersion=$( grep -Eio 'gcc[[:space:]]*version[[:space:]]*[4-7]\.[0-9]{1,2}' /proc/version | grep -Eo '[4-7]\.[0-9]{1,2}' )
	local gccPackage="gcc-$gccVersion"  
	local libMesaGlx='' ubgv='' bUpdateGcc='false'

	case $SYSTEM_BASE in
		arch)
			gccPackage='gcc'
			libMesaGlx='libgl'
			# -n "$gccVersion" -a 
			if [ -n "$gccVersion" -a -z "$( check_package_status "$gccPackage" 'i' | grep "$gccVersion" )" ];then
				bUpdateGcc='true'
			fi
			;;
		debian)
			libMesaGlx='libgl1-mesa-glx'
			# it looks like maybe as of gcc 5 debian dropped the decimal
			if [ -n "$gccVersion" -a -n "$( grep -E '^[5-9]' <<< $gccVersion)" ];then
				gccVersion=$(grep -Eo '^[5-9]' <<< $gccVersion )
				gccPackage="gcc-$gccVersion"
			fi
			;;
		ubuntu)
			libMesaGlx='libgl1-mesa-glx'
			if [ -n "$gccVersion" -a -n "$( grep -E '^[5-9]' <<< $gccVersion)" ];then
				gccVersion=$(grep -Eo '^[5-9]' <<< $gccVersion )
				gccPackage="gcc-$gccVersion"
			fi
			;;
		fedora)
			gccPackage='gcc'
			if [ -n "$gccVersion" -a -z "$( check_package_status "$gccPackage" 'i' | grep "$gccVersion" )" ];then
				bUpdateGcc='true'
			fi
			;;
	esac
	ubgv="/usr/bin/$gccPackage"
	
	case $CARD in
		$FGLRX)
			if [ "$B_TESTING_5" != 'true' ];then
				install_package "$libMesaGlx" '' 'reinstall'
			fi
			;;
	esac
	
	# We now need to do active detection of fglrx-install directory name due to
	# silly random directory naming schema ati just started with 8.35.5
	# Note: you can set --extract $FG_WORKING_DIR to hard code this name

	echo "${S}Preparing driver install...${N}"
	# this is causing aptitude to queue some signals that then make aptitude
	# try to reinstall all of the debian packages next time: aptitude install 
	# is run, for example, on smxi kernel install. So turning that off for now.
# 	if [ "$B_TESTING_6" != 'true' ];then
# 		if [ -f $EDV -a ! -f /etc/sidux-version -a ! -f /etc/aptosid-version ];then
# 			m-a -i prepare
# 		fi
# 	fi

	if [ -x "$ubgv" -a "$bUpdateGcc" != 'true' ];then
		export CC=$ubgv
	else
		# going to try to update gcc to kernel version first before error exit.
		if [ -n "$( check_package_status "$gccPackage" 'c' )" ];then
			install_package "$gccPackage"
			# this may not be needed, we'll see how it goes.
# 			if [ "$( check_package_status "g++-$gccVersion" 'c' )" ];then
# 				install_package "g++-$gccVersion"
# 			fi
			export CC=$ubgv
		else
			if [ "$SYSTEM_BASE" != 'fedora' ];then #for fedora dev only
				error_handler 230 "$ubgv"
			fi
		fi
	fi
	eval $LOGPE
}

set_install_directory()
{
	case $CARD in
		$NVIDIA)
			INSTALL_DIRECTORY=$DRIVER_FILE
			;;
		$FGLRX)
			INSTALL_DIRECTORY=$( ls | grep "$FG_WORKING_DIR" )
			;;
	esac
	cd $SCRIPT_WORKING_DIR/$INSTALL_DIRECTORY
	log_function_data "Function: set_install_directory - set to: $SCRIPT_WORKING_DIR/$INSTALL_DIRECTORY"
}

preinstall_cleanup()
{
	eval $LOGPS
	local oldNvidia='' divertedPackages='' installer='nvidia-installer' oldFglrx=''
	local fglrxUninstaller='/usr/share/ati/fglrx-uninstall.sh' useForce=''
	local bNvidiaError='false' bFglrxError='false' nvidiaGlxExtras='' extraPackageBan=''
	
	# yep, you guessed it, another stupid pointless amd/ati change. Discipline guys....
	if [ -e /usr/share/ati/amd-uninstall.sh ];then
		fglrxUninstaller='/usr/share/ati/amd-uninstall.sh'
		useForce='--force'
	fi
	
	echo "${S}Running preinstall cleanup...${N}"

	# this is not set as a path if native driver install
	if [ "$B_NATIVE_DRIVER" != 'true' ];then
		cd $SCRIPT_WORKING_DIR/$INSTALL_DIRECTORY
	fi
	# some legacy cleanup gunk, this can probably be dumped
	if [ -f /etc/modutils/1alsa ];then
		mv /lib/modules/extra/alsa /lib/modules/$KERNEL_FULL/
		rm -f /etc/modutils/1alsa
		if [ -n "$( type -p depmod )" ];then
			depmod $KERNEL_FULL -a
		fi
	fi

	## nvidia uninstallers, for systems where nvidia has been installed once at least
	# both files should be present in case of previous nvidia install
	if [ -x /usr/bin/$installer ];then
		log_function_data 'Using nvidia uninstaller: /usr/bin/'$installer
		/usr/bin/$installer --uninstall -s -N 1>> $LOG_FILE 2>> $LOG_FILE || installError="$?"
	elif [ -f /usr/lib/libnvidia-tls.so.1 ];then
		log_function_data 'Using local nvidia uninstaller'
		# some cases this will not be present, like to native ati/nv conversion
		if [ -f ./$installer ];then
			./$installer --uninstall -s -N 1>> $LOG_FILE 2>> $LOG_FILE || installError="$?"
		fi
	fi
	## NVIDIA removal...
	log_function_data "Pre Remove: nvidia.ko files: \n$( ls /lib/modules/*/kernel/drivers/video/nvidia.ko 2>/dev/null )"
	
	if [ -n "$installError" ];then
		error_handler 192 $installError
	fi
	# ubuntu-desktop depends on nvidia-common
	case $SYSTEM_BASE in
		ubuntu)
			extraPackageBan='|nvidia-common'
			;;
	esac
	## this is just to check after the above un-installer runs, this must be here or the
	## above packages won't be present, better to let nvidia handle uninstalling itself
	# also can clean out install-binary-gfx packages or nvidia-glx if present
	
	oldNvidia=$( list_installed_packages 'nvidia' "(libkwinnvidiahack|libgl1-nvidia-glx-ia32|libgl1-nvidia-glx:386|modalias|libvdpau|nvidia-bl-dkms|nvidia-cg-toolkit${extraPackageBan})" )
	# messy, aptitude at least fails to remove these, which makes the uninstall fail
	if [ -n "$( grep 'nvidia-installer-cleanup' <<< $oldNvidia )" ];then
		nvidiaGlxExtras=$( list_installed_packages '(glx-alternative-mesa|glx-diversions)' )
	fi
	
	if [ -n "$oldNvidia" ];then
		if [ -n "$nvidiaGlxExtras" ];then
			oldNvidia="$oldNvidia $nvidiaGlxExtras"
		fi
# 		if [ "$B_TESTING_6" == 'true' ];then
			# this is present in some installs, debian squeeze for example
			# this is also a bug in debian: 
			# http://bugs.debian.org/cgi-bin/bugreport.cgi?bug=594737
			# http://forums.debian.net/viewtopic.php?f=10&t=55518
			# http://bugs.debian.org/cgi-bin/bugreport.cgi?bug=597443
			case $SYSTEM_BASE in
				debian)
					if [ "$SYSTEM_CODENAME" != 'testing' -a "$SYSTEM_CODENAME" != 'sid' ];then
						GL='/usr/lib/xorg/modules/extensions/libglx.so'
						for package in $( dpkg-divert --list | grep "diversion of $GL" | awk '{print $7}' | grep -v -e fglrx-driver -e xorg-driver-fglrx )
						do
							echo "${S}Running diversion removal for: ${C}$package${N}"
							dpkg-divert --package $package --remove $GL  1>> $LOG_FILE 2>> $LOG_FILE
						done
					fi
					;;
			esac
# 		fi
		case $SYSTEM_BASE in
			# libgl will break the removal of nvidia, odd packaging decision, so need to reinstall it.
			# this is a weird way to handle the nvidia/libgl dependency, it's almost a loop if you
			# dont' use the --nodeps flag..
			arch)
				# "$B_USE_DISTRO_DRIVER" != 'true' -a 
				if [ -z "$( check_package_status 'libgl' 'i' )" ];then
					if [ -n "$( check_package_status 'libgl' 'c' )" ];then
						install_package 'libgl' '' '--nodeps'
						# redo list because nvidia-utils is removed
						oldNvidia=$( list_installed_packages 'nvidia' '(modalias|libvdpau)' )
					fi
				fi
				;;
		esac
		case $APT_TYPE in
			apt-get|aptitude)
				# note: aptitude fails to note the removal of these packages if dpkg is used
				# this is a new behavior, relatively, but it means that the same tool that
				# installs package must remove it.
# 				if [ "$B_TESTING_6" == 'true' ];then
# 					dpkg --purge $oldNvidia  1>> $LOG_FILE 2>> $LOG_FILE || bNvidiaError='true'
# 				else
					remove_package "$oldNvidia" '' 'no-loop' 'yes'
# 				fi
				;;
			pacman|yum)
				remove_package "$oldNvidia" '' 'no-loop'
				;;
		esac
	fi
	if [ "$bNvidiaError" == 'true' ];then
		error_handler 190 "$oldNvidia" 
	fi
# 	if [ "$B_TESTING_6" != 'true' ];then
		log_function_data "Post Purge/Remove: nvidia.ko files: \n$( ls /lib/modules/*/kernel/drivers/video/nvidia.ko 2>/dev/null )"
		#rm -f /lib/modules/$KERNEL_FULL/kernel/drivers/video/nvidia.ko 1>> $LOG_FILE 2>> $LOG_FILE
		# for real driver installs, we need to remove ALL the existing nvidia driver .ko files
		rm -f /lib/modules/*/kernel/drivers/video/nvidia.ko 1>> $LOG_FILE 2>> $LOG_FILE
		# this is legacy stuff, not currently present
		rm -f /lib/modules/*/volatile/nvidia.ko >/dev/null 1>> $LOG_FILE 2>> $LOG_FILE
		rm -f /usr/local/bin/nvidia-settings /usr/local/bin/nvidia-xconfig 1>> $LOG_FILE 2>> $LOG_FILE
		rm -f /tmp/.X0-lock
		# double check, clean up anything left after uninstaller runs
		rm -rf ${USRS}nvidia* 1>> $LOG_FILE 2>> $LOG_FILE
		rm -rf ${SCRIPT_WORKING_DIR}/nvidia* 1>> $LOG_FILE 2>> $LOG_FILE
		rm -rf ${USRS}modules/nvidia* 1>> $LOG_FILE 2>> $LOG_FILE
# 	fi
	# this might need more work to not remove if X failed to stop
	remove_module 'nvidia'
	if [ "$B_NATIVE_DRIVER" != 'true' -a "$CARD" == "$NVIDIA" ];then
		remove_module 'nouveau'
	fi
	## FGLRX removal...
	# this is for manually installed amdccle removal
	if [ -f /usr/local/bin/amdccle ];then
		rm -f /usr/local/bin/amdccle
	fi

	oldFglrx=$( list_installed_packages 'fglrx' 'modalias' )
	if [ -n "$oldFglrx" ];then
		case $APT_TYPE in
			apt-get|aptitude)
# 				if [ "$B_TESTING_6" != 'true' ];then
# 					dpkg --purge $oldFglrx 1>> $LOG_FILE 2>> $LOG_FILE || bFglrxError='true'
# 				else
					remove_package "$oldFglrx" '' 'no-loop' 'yes'
# 				fi
				;;
			pacman|yum)
				remove_package "$oldFglrx" '' 'no-loop'
				;;
		esac
	fi
	if [ "$bFglrxError" == 'true' ];then
		error_handler 190 "$oldFglrx"
	fi
	# this is present in some installs, debian etch default for instance
	case $SYSTEM_BASE in
		debian|ubuntu)
			GL='/usr/X11R6/lib/libGL.so.1.2'
			for package in $( dpkg-divert --list | grep "diversion of $GL" | awk '{print $7}' | grep -v -e fglrx-driver -e xorg-driver-fglrx )
			do
				dpkg-divert --package $package --remove $GL  1>> $LOG_FILE 2>> $LOG_FILE
			done
			;;
	esac
	# then confirm that it's truly not installed in case of manual direct install
	if [ -f "$fglrxUninstaller" ];then
		log_function_data "Using fglrx uninstaller: $fglrxUninstaller force: $useForce"
		bash $fglrxUninstaller $useForce
	fi
	remove_module 'fglrx'
	# this should no longer be required with new dkms, which removes itself fine above,
	# but leaving this here for now for legacy dkms
# 	if [ "$B_TESTING_6" != 'true' ];then
		clean_dkms
# 	fi
	eval $LOGPE
}

## run patch module, then install
run_driver_installer()
{
	eval $LOGPS
	local installError=0 installerArgs='' nothing=''
	local xModPath='/usr/lib/xorg/modules'
	local xLibPath='/usr/lib'
	local installer='nvidia-installer'
	local distroId='' fglrxNumber='1'
	local distroCodeName=''

	# this was set in prep_install()
	cd $SCRIPT_WORKING_DIR/$INSTALL_DIRECTORY
	echo "${S}Running driver installer for ${C}$DRIVER_DEFAULT${S} (this might take a while)...${N}"

	log_function_data "driver: $DRIVER_DEFAULT"

	# run the card installers
	case $CARD in
		$NVIDIA)
			if [ -d $xModPath -a -d $xLibPath ];then
				# --x-library-path=$xLibPath
				installerArgs="-s -N --x-module-path=$xModPath --x-library-path=$xLibPath"
				
			else
				installerArgs="-s -N"
			fi
			if [ "$B_GUI_MODE" == 'true' ];then
				installerArgs="$installerArgs --no-x-check"
			fi
			# note: handles change from older /emul libs in Debian
			# http://www.nvnews.net/vbulletin/showthread.php?t=135332
			# note that lenny can be assumed to not need, this, so wait til squeeze stable
			if [ "$BITS" == '64' ];then
				# note: it appears that 256.xx changed something here for 64 bit paths, and
				# this is an attempt to fix that, not sure if it will work
				# http://forum.xbmc.org/showthread.php?t=57885
				## Update: 2010-11-27, apparently this was reverted by nvidia in 260.xx
				# further: --compat32-prefix= with no data seems to cause nvidia installer error
				# and --compat32-chroot=/usr/lib32 seems to also cause undesired location
				case $SYSTEM_BASE in
					debian)
						if [ "$SYSTEM_CODENAME" == 'sid' -o "$SYSTEM_CODENAME" == 'testing' ];then
							# installerArgs="$installerArgs --compat32-prefix= --compat32-libdir=  --compat32-chroot=/usr/lib32"
							# installerArgs="$installerArgs --compat32-prefix=/usr --compat32-libdir=lib32  --compat32-chroot=/usr/lib32"
							: # nothing happening now
						fi
						;;
					ubuntu)
						# installerArgs="$installerArgs --compat32-prefix= --compat32-libdir=  --compat32-chroot=/usr/lib32"
						# installerArgs="$installerArgs --compat32-prefix=/usr --compat32-libdir=lib32  --compat32-chroot=/usr/lib32"
						: # nothing happening now
						;;
				esac
			fi
			
			installerArgs="$installerArgs -k $KERNEL_FULL $EXTRA_ARGS "
			# fresh arch installs may have the single file but no headers in /usr/src
			# note that this didn't work even though the target file existed
# 			if [ "$B_USE_DIRECT_KERNEL_HEADER" == 'true' ];then
# 				installerArgs="$installerArgs --kernel-source-path=$KERNEL_HEADER_DIRECT"
# 			fi
			./$installer $installerArgs 1>> $LOG_FILE 2>> $LOG_FILE || installError="$?"
			install_libvdpau
			# only do a final removal of nouveau if the install succeeded
# 			remove_module 'nouveau' 
			;;
		$FGLRX)
			distroId=$FG_DISTRIB_ID
			distroCodeName=$FG_DISTRIB_CODENAME
			installer='ati-installer.sh'
			if [ "$B_FGLRX_DIRECT" != 'true' ];then
				installerArgs="$DRIVER_DEFAULT --buildpkg $distroId/$distroCodeName"
				log_function_data "dist-id/dist-codename: $distroId/$distroCodeName"
				fglrxNumber='2'
			else
				echo $MLINE
				echo "${M}NOTE: When the ${C}FGLRX${M} direct installer runs, it will ask you a series of questions."
				echo "Simply hit ${C}<enter>${M} for each question the installer asks you, the defaults are good."
				echo "${M}If the first question asks you which driver method, type the number ${C}$fglrxNumber${M}"
				echo "and then hit ${C}<enter>${M}, then continue to the other questions."
				echo
				echo "${S}Hit ${C}<enter>${S} now to start the direct installer."
				echo $MLINE
				read nothing
				installerArgs="$DRIVER_DEFAULT --install"
				log_function_data "direct fglrx install - no debs: options: $installerArgs"
			fi

			# tell fglrx installer correct x version
	# 		if [ -n "$( echo $X_VERSION | grep -E '[1-2]\.[4-9]' )" ]
	# 		then
	# 			export XVERSION=$X_VERSION
	# 			export XTYPE='X.Org'
	# 		fi
			# note: there's a bug in fglrx that apparently will show no error return on failure
# 			LC_ALL= LC_CTYPE= LC_MESSAGES= LANG= bash ./$installer $installerArgs 1>> $LOG_FILE 2>> $LOG_FILE
			# ati just made the installer interactive, so can't log the data for now...
			LC_ALL= LC_CTYPE= LC_MESSAGES= LANG= bash ./$installer $installerArgs 
			installError="$?"
			;;
	esac

	if [ "$installError" -gt 0 ];then
		log_driver_installer_failure
		error_handler 245 $installError
	fi
	case $CARD in
		$FGLRX)
			:
			;;
	esac
	eval $LOGPE
}

# nvidia new only
install_libvdpau()
{
	local libVdPau=''
	
	case $SYSTEM_BASE in
		arch)
# 			libVdPau='libvdpau'
			libVdPau=''
			;;
		# http://bugs.debian.org/cgi-bin/bugreport.cgi?bug=558369
		# note: until the sid break for nvidia-libvdpau1/nvidia-libvdpau1-driver is fixed...
# 		debian)
# 			libVdPau='nvidia-libvdpau1-driver'
# 			;;
	esac
	
	if [ "$B_TESTING_5" != 'true' -a -n "$libVdPau" -a "$LEGACY_LEVEL" -gt 3 ];then
		if [ -z "$( check_package_status "$libVdPau" 'i' )" ];then
			if [ -n "$( check_package_status "$libVdPau" 'c' )" ];then
				install_package "$libVdPau"
			fi
		fi
	fi
}

post_installer_steps()
{
	eval $LOGPS
	local ema='/etc/modutils/aliases' oldFglrx=''

	echo "${S}Running post installer steps...${N}"

	cd $SCRIPT_WORKING_DIR

	rm -rf $INSTALL_DIRECTORY # remove the extracted driver install directory in /usr/src

	## this I think I will combine into one, just cleanup everything, that will handle
	## card brand changes more robustly, and leave less cruft in the system
	case $CARD in
		$NVIDIA)
			rm -f /etc/modutils/nvidia
			if [ -f $ema ];then
				perl -pi -e 's|.*char-major-195.*[\n]?||' $ema
				perl -pi -e 's|[\n]?$|\n|' $ema
				echo "alias char-major-195 nvidia" >> $ema
			fi
			;;
		$FGLRX)
			clean_up_fglrx_junk
			rm -f fglrx-installer_*.changes
			case $SYSTEM_BASE in
				arch)
					if [ -z "$( check_package_status 'mesa' 'i' )" ];then
						if [ -n "$( check_package_status 'mesa' 'c' )" ];then
							install_package 'mesa'
						fi
					fi
					;;
			esac
			;;
	esac
	eval $LOGPE
}

### -------------------------------------------------------------------
### module tools
### -------------------------------------------------------------------

# $1 - direct/build; $2 - silent [optional]
build_kernel_module_only()
{
	eval $LOGPS
	local installedDriver='' moduleResult=0 driverModule='' silent=' '
	local runPackage="$DRIVER_FILE.run"
	
	# double check that target kernel, or current one, has stuff in /lib/modules
	case $CARD in
		$NVIDIA)
			B_SKIP_INSTALL='true'
			remove_module 'nouveau'
			if [ "$1" == 'direct' ];then
				test_install_kernel_version
				test_module_build_ok 'error'
			fi
			if [ -z "$DISPLAY" -a "$B_KERNEL_MODULE_ONLY" != 'true' ];then
				x_start_stop_master stop
			fi
			echo $LINE
			echo "${S}Building kernel module ${C}$DRIVER_DEFAULT${S} for kernel ${C}$KERNEL_FULL${S} now (can take a while)...${N}"
			if [ "$2" != 'silent' ];then
				bash $SCRIPT_WORKING_DIR/$runPackage $silent -N --kernel-name=$KERNEL_FULL --kernel-module-only -a || moduleResult=$?
			else
				silent=' -s'
				bash $SCRIPT_WORKING_DIR/$runPackage $silent -N --kernel-name=$KERNEL_FULL --kernel-module-only -a 1>> $LOG_FILE 2>> $LOG_FILE || moduleResult=$?
			fi
			if [ "$moduleResult" -ne 0 ];then
				log_driver_installer_failure
				error_handler 171 "$moduleResult"
			else
				echo "${S}Build of module ${C}$DRIVER_DEFAULT${S} for kernel ${C}$KERNEL_FULL${S} was a success!"
				if [ "$B_KERNEL_MODULE_ONLY" == 'true' ];then
					echo "Script will exit now and you can do what you want, the module is working for that kernel.${N}"
					exit 0
				else
					x_start_stop_master start
				fi
			fi
			;;
		*)
			error_handler 173 
			;;
	esac
	
	eval $LOGPE
}

# $1 - error/return
test_module_build_ok()
{
	eval $LOGPS
	local runPackage="$DRIVER_FILE.run" returnValue=0 nvidiaPackages=''
	local libGlNvidia='' xorgNvidia='' logData=''
	echo $LINE
	echo "${S}Starting ${C}$NVIDIA module${S} build process checks for kernel: ${C}$KERNEL_FULL${N}"
	echo -n "  ${S}Checking for driver run package ${C}$DRIVER_FILE${S}.... ${N}"
	if [ ! -f "$SCRIPT_WORKING_DIR/$runPackage" ];then
		echo "${W}NOT FOUND${N}"
		returnValue=1
		logData="No Driver Run Package: "
		if [ "$1" == 'error' ];then
			error_handler 175 "$runPackage"
		fi
	else
		echo "${S}File Exists${N}"
	fi
	if [ "$returnValue" -eq 0 ];then
		echo -n "  ${S}Checking for distribution ${C}nVidia${S} driver packages.... ${N}"
		nvidiaPackages=$( list_installed_packages 'nvidia' '(libkwinnvidiahack|libgl1-nvidia-glx-ia32|libgl1-nvidia-glx:386|modalias|libvdpau)' )
		if [ -n "$nvidiaPackages" ];then
			echo "${W}PRESENT${N}"
			returnValue=2
			logData="${logData}Distro Nvidia Package: "
			if [ "$1" == 'error' ];then
				error_handler 174
			fi
		else
			echo "${S}None Detected${N}"
		fi
	fi
	if [ "$returnValue" -eq 0 ];then
		# really readlink /usr/lib/$( readlink /usr/lib/libGL.so )
		libGlNvidia=$( readlink /usr/lib/libGL.so.1 | grep -Eois '[0-9]{2,3}\.[0-9]{2,3}(\.[0-9]+)?' )
		echo -n "  ${S}Checking for installed ${C}nVidia${S} driver.... ${N}" 
		if [ -z "$libGlNvidia" ];then
			echo "${W}No $SCRIPT_NAME ${C}nVidia${W} Driver Detected${N}"
			returnValue=3
			logData="${logData}No Installed Nvidia: "
			if [ "$1" == 'error' ];then
				error_handler 169
			fi
		else
			echo "${S}Driver Installed${N}"
		fi
	fi
	if [ "$returnValue" -eq 0 ];then
		echo -n "  ${S}Checking installed driver ${C}$libGlNvidia${S} matches requested driver ${C}$DRIVER_DEFAULT${S}.... ${N}" 
		if [ "$libGlNvidia" != "$DRIVER_DEFAULT" ];then
			echo "${W}MISMATCH${N}"
			returnValue=4
			logData="${logData}Driver Mismatch $libGlNvidia/$DRIVER_DEFAULT: "
			if [ "$1" == 'error' ];then
				error_handler 172 "$installedDriver"
			fi
		else
			echo "${S}Drivers Match${N}"
		fi
	fi
	if [ "$returnValue" -eq 0 ];then
		echo -n "  ${S}Checking to make sure ${C}Xorg${S} has not been updated since last ${C}nVidia${S} install.... ${N}" 
		# this file belongs to xserver-xorg but is overwritten by nvidia, so if above test
		# is true and this is null, then xorg has been renewed
		xorgNvidia=$( readlink /usr/lib/xorg/modules/extensions/libglx.so | grep -Eois '[0-9]{2,3}\.[0-9]{2,3}(\.[0-9]+)?' )
		# installedDriver=$( bash $SCRIPT_WORKING_DIR/$runPackage -N --driver-info | grep -Eio 'version:[[:space:]]*[0-9\.]+' | grep -oE '[0-9\.]+' )
		if [ -z "$xorgNvidia" ];then
			echo "${C}Xorg${W} Updated${N}"
			returnValue=5
			logData="${logData}Xorg updated: "
			if [ "$1" == 'error' ];then
				error_handler 168
			fi
		else
			echo "${S}Xorg Not Updated${N}"
		fi
	fi
# 	echo "${S}Checking that installed driver is the same as the driver you are having" 
# 	echo -n "${C}$SCRIPT_NAME${S} build a kernel module for: ${C}$DRIVER_DEFAULT${S}.... ${N}"
# 	installedDriver=$( bash $SCRIPT_WORKING_DIR/$runPackage -N --driver-info | grep -Eio 'version:[[:space:]]*[0-9\.]+' | grep -oE '[0-9\.]+' )
# 	if [ "$installedDriver" != "$DRIVER_DEFAULT" ];then
# 		echo "${W}MISMATCH${N}"
# 		returnValue=1
# 		if [ "$1" == 'error' ];then
# 			error_handler 172 "$installedDriver"
# 		fi
# 	else
# 		echo "${S}Drivers Match${N}"
# 	fi
	if [ "$returnValue" -eq 0 ];then
		echo -n "  ${S}Checking for previous ${C}nVidia${S} driver module for ${C}$KERNEL_FULL${S}.... ${N}"
		if [ -f "/lib/modules/$KERNEL_FULL/kernel/drivers/video/nvidia.ko" ];then
			echo "${W}PRESENT${N}"
			returnValue=6
			logData="${logData}Nvidia module exists: "
			if [ "$1" == 'error' ];then
				error_handler 170
			fi
		else
			echo "${S}None Detected${N}"
		fi
	fi
	log_function_data "returnValue: $returnValue\nError Data: $logData"
	return "$returnValue"
	eval $LOGPE
}

install_modules_to_all_kernels()
{
	check_root
	local kernels=$(ls /lib/modules | grep -v "$( uname -r )" )
	local otherDriver='' kernel='' grubFile='' kernelInGrub='' kernelsConfirmed=''
	if [ -f "$GRUB2" ];then
		grubFile=$GRUB2
	elif [ -f "$GRUB1_FED" ];then
		grubFile=$GRUB1_FED
	elif  [ -f "$GRUB1" ];then
		grubFile=$GRUB1
	fi
	if [ -z "$grubFile" ];then
		error_handler 213 "kernel-module-installer"
	fi
	# this isn't a great test, but it's better than no test, and should avoid a lot of false
	# kernel ids
	case $SYSTEM_BASE in
		debian|ubuntu|fedora)
			echo $LINE
			echo "${S}Confirming full kernel list from ${C}/lib/modules${S}...${N}"
			# make sure the kernels are real, not fake as found in /lib/modules vmware added...
			for kernel in $kernels
			do
				echo -n "${S}Checking ${C}$kernel${S} in ${C}$grubFile${S}.... ${N}"
				kernelInGrub=$( grep -Eis "^[[:space:]]*(kernel|linux).*$kernel" $grubFile )
				if [ -n "$kernelInGrub" ];then
					echo "${M}Confirmed${N}"
					kernelsConfirmed="$kernelsConfirmed $kernel"
				else
					echo "${W}Invalid${N}"
				fi
			done
			;;
		arch)
			# arch has unreliable kernel naming, not following uname -r, ie: kernel26.img
			kernelsConfirmed=$kernels 
			;;
	esac
	if [ -n "$kernelsConfirmed" ];then
		# support other drivers being used if desired
		if [ -n "$DRIVER_OVERRIDE" ];then
			otherDriver=" -o $DRIVER_OVERRIDE"
		fi
		if [ "$B_USE_BETA" == 'true' ];then
			otherDriver=" -B"
		fi
		echo $LINE
		echo "${S}OK, installing modules to all confirmed kernels now...${N}"
		for i in $kernelsConfirmed
		do 
			sgfxi $otherDriver -R -A -k -K $i
		done
		echo $LINE
		echo "${S}Hey, did it work? Great! Bye for now.${N}"
	else
		echo "${S}No kernels found to create modules for. Exiting script now.${N}"
	fi
	exit 0
}

# note: for 
# args: $1 - which module; for nouveau used, post nvidia install with no errors
# use: $2 - nvidia-post - clean grub/module files of nouveau blacklists
remove_module()
{
	eval $LOGPS

	local outcome='unset' 

	if [ -n "$( lsmod | grep "^$1" )" ];then
		echo -n "${S}Removing module${C} $1${S}...... ${N}"
		modprobe -r $1 1>> $LOG_FILE 2>> $LOG_FILE 
		if [ "$?" -ne 0 ];then
			echo "${W}FAILED${N}"
			echo "${M}Error removing ${C}$1${M} module for pre-install cleanup operation."
			echo "Please investigate this further since it may make your $CARD driver install fail.${N}"
			outcome='failed' 
		else
			# working that if removal fails, module should not be removed, this might not be
			# correct though. Especially not for future nouveau, radeonhd, 
			if [ -f /etc/modules ];then
				perl -pi -e "s/^[[:space:]]*$1.*\n?//" /etc/modules
			fi
			echo "${S}Removed${N}"
			outcome='removed'
		fi
	fi
	log_function_data "operation outcome: $outcome"
	# going to run this for all cases, not just failure, maybe that will work better
	# also, there is an override to skip grub tests, but user has to have handled nouveau/
	# kms blacklisting manually
	if [ "$B_SKIP_GRUB_TEST" == 'true' ];then
		if [ "$outcome" == 'failed' ];then
			error_handler 167 "remove-$1"
		else
			echo "${M}Skipping modesetting section because of user requested ${C}-! 33${M} case.${N}"
		fi
	else
		case $1 in
			nouveau|radeon)
				set_modesetting_off "$1" "$outcome"
				;;
		esac
	fi
# 	if [ "$outcome" == 'failed' ];then
# 		set_modesetting_off "$1"
# 	fi
	
	eval $LOGPE
}

# args: $1 - module to add or process
# do some extra processing here for nouveau
add_module()
{
	eval $LOGPS

	local outcome='unset' 
	
	echo -n "${S}Adding module${C} $1${S}...... ${N}"
	modprobe $1 1>> $LOG_FILE 2>> $LOG_FILE
	if [ "$?" -ne 0 ];then
		echo "${W}FAILED${N}"
		echo "${M}Error adding ${C}$1${M} module after installation."
		echo "Please investigate this further since it may make your $CARD driver install fail.${N}"
		outcome='failed'
	else
		if [ -z "$( grep "^$1" /etc/modules )" ];then
			echo "$1" >> /etc/modules
		fi
		echo "${S}Added${N}"
		outcome='added'
	fi
	log_function_data "operation outcome: $outcome"
	# going to run this for all cases, not just failure, maybe that will work better
	# handle the no grub file explicitly in this one
	case $1 in
		nouveau|radeon)
			set_modesetting_on "$1" "$outcome"
			;;
	esac

# 	if [ "$outcome" == 'failed' ];then
# 		set_modesetting_on "$1"
# 	fi
	
	eval $LOGPE
}

# this should in theory all be gone but not necessarily in fact
# note that fglrx isn't working well here at all... 
# further: 2014-05-05: --debugger dkms data shows individual driver directories top level in dkms
# this is a change from previous /dkms/nvidia/ style. Update may resolve the lingering failures.
clean_dkms()
{
	eval $LOGPS
	local eddma='/etc/default/dmakms'
	if [ -n "$( ls /var/lib/dkms/ | grep -i fglrx )" ];then
		log_function_data "fglrx dkms directories found and deleted:\n$(ls /var/lib/dkms/ | grep -i fglrx)"
		echo "${M}Found and deleted ${C}fglrx dkms${M} material${N}"
		rm -rf /var/lib/dkms/fglrx* 1>> $LOG_FILE 2>> $LOG_FILE
	fi
	if [ -n "$( ls /var/lib/dkms/ | grep -i catalyst )" ];then
		log_function_data "amd-catalyst dkms directories found and deleted:\n$(ls /var/lib/dkms/ | grep -i catalyst)"
		echo "${M}Found and deleted ${C}catalyst dkms${M} material${N}"
		rm -rf /var/lib/dkms/catalyst* 1>> $LOG_FILE 2>> $LOG_FILE
	fi
	if [ -n "$( ls /var/lib/dkms/ | grep -i nvidia )" ];then
		echo "${M}Found and deleted ${C}nvidia dkms${M} material${N}"
		log_function_data "nvidia dkms directories found and deleted:\n$(ls /var/lib/dkms/ | grep -i nvidia)"
		rm -rf /var/lib/dkms/nvidia* 1>> $LOG_FILE 2>> $LOG_FILE
	fi
	# handle the dmakms stuff too if present
	if [ -f "$eddma" ];then
		if [ -n "$( grep -Esi '^[[:space:]]*nvidia-kernel-source' $eddma )" ];then
			log_function_data "nvidia dmakms entry found and commented out"
			sed -i 's/nvidia-kernel-source/#nvidia-kernel-source/' $eddma
		fi
		if [ -n "$( grep -Esi '^[[:space:]]*fglrx-kernel-source' $eddma )" ];then
			log_function_data "fglrx dmakms entry found and commented out"
			sed -i 's/fglrx-kernel-source/#fglrx-kernel-source/' $eddma
		fi
	fi
	eval $LOGPE
}

### -------------------------------------------------------------------
### distro fglrx/nvidia driver installer
### -------------------------------------------------------------------

install_distro_drivers()
{
	eval $LOGPS
	local nvidiaGlx='' nvidiaSource='' nvidiaModal='' nvidiaUtils=''
	local akmodNvidia='' nvidiaDriver='' nvidiaDriver2='' ubGlx='-glx' nvidiaSettings=''
	local fglrxSettings='' fglrxDriver='' fglrxSource=''

	clean_up_fglrx_junk

	case $CARD in
		$NVIDIA)
			case $SYSTEM_BASE in
				arch)
					# dependencies handle the rest of this. 
					# nvidia driver package includes nvidia settings
					case $LEGACY_LEVEL in
						1)	:
							# this has already been error handled.
							;;
						2)	nvidiaDriver="nvidia-$NV_AR_LEGACY_2"
							nvidiaUtils="nvidia-$NV_AR_LEGACY_2-utils"
							;;
						3)	nvidiaDriver="nvidia-$NV_AR_LEGACY_3"
							nvidiaUtils="nvidia-$NV_AR_LEGACY_3-utils"
							;;
						4)	nvidiaDriver="nvidia-$NV_AR_LEGACY_4"
							nvidiaUtils="nvidia-$NV_AR_LEGACY_4-utils"
							;;
						5)	nvidiaDriver="nvidia-$NV_AR_LEGACY_5"
							nvidiaUtils="nvidia-$NV_AR_LEGACY_5-utils"
							;;
						*)	nvidiaDriver="nvidia"
							nvidiaUtils="nvidia-utils"
							;;
					esac
					echo "${S}Installing ${C}$DISTRO_NVIDIA${S} components...${N}"
					install_package "$nvidiaDriver"
					# conflicts with libgl and removes it
# 					install_package "$nvidiaUtils"
					;;
				debian)
					case $LEGACY_LEVEL in
						# note, changed position of '-kernel' string in package name, not sure which debian stable
						# this happened in, I'll double check. nvidia-glx is not in debian anymore.
						1)	# nvidiaGlx='nvidia-glx-legacy'
							# nvidiaSource='nvidia-kernel-legacy-source'
							# if the two lines below don't work, comment them and uncomment the ones above
							nvidiaDriver="nvidia-legacy-$NV_DEBIAN_LEGACY_1-driver"
							nvidiaGlx="nvidia-glx-legacy-$NV_DEBIAN_LEGACY_1"
							nvidiaSettings="nvidia-settings-legacy-$NV_DEBIAN_LEGACY_1"
							nvidiaSource="nvidia-legacy-$NV_DEBIAN_LEGACY_1-kernel-source"
							;;
						2)	nvidiaDriver="nvidia-legacy-$NV_DEBIAN_LEGACY_2-driver"
							nvidiaGlx="nvidia-glx-legacy-$NV_DEBIAN_LEGACY_2"
							nvidiaSettings="nvidia-settings-legacy-$NV_DEBIAN_LEGACY_2"
							nvidiaSource="nvidia-legacy-$NV_DEBIAN_LEGACY_2-kernel-source"
							;;
						3)	nvidiaDriver="nvidia-legacy-$NV_DEBIAN_LEGACY_3-driver"
							nvidiaGlx="nvidia-glx-legacy-$NV_DEBIAN_LEGACY_3"
							nvidiaSettings="nvidia-settings-legacy-$NV_DEBIAN_LEGACY_3"
							nvidiaSource="nvidia-legacy-$NV_DEBIAN_LEGACY_3-kernel-source"
							;;
						4)	nvidiaDriver="nvidia-legacy-$NV_DEBIAN_LEGACY_4-driver"
							nvidiaGlx="nvidia-glx-legacy-$NV_DEBIAN_LEGACY_4"
							nvidiaSettings="nvidia-settings-legacy-$NV_DEBIAN_LEGACY_4"
							nvidiaSource="nvidia-legacy-$NV_DEBIAN_LEGACY_4-kernel-source"
							;;
						5)	nvidiaDriver="nvidia-legacy-$NV_DEBIAN_LEGACY_5-driver"
							nvidiaGlx="nvidia-glx-legacy-$NV_DEBIAN_LEGACY_5"
							nvidiaSettings="nvidia-settings-legacy-$NV_DEBIAN_LEGACY_5"
							nvidiaSource="nvidia-legacy-$NV_DEBIAN_LEGACY_5-kernel-source"
							;;
						*)	nvidiaDriver="nvidia-driver"
							nvidiaGlx='nvidia-glx'
							nvidiaSettings="nvidia-settings"
							nvidiaSource='nvidia-kernel-source'
							;;
					esac
					# start the install/73xx not supported for a while now. Note that this is actually set
					# in the card/xorg version handling, so I don't really need this legacy level test
					if [ "$LEGACY_LEVEL" -gt 2 ];then
						if [ "$B_USE_DISTRO_MODULE_MA" == 'true' ];then
							echo "${S}Installing ${C}$DISTRO_NVIDIA${S} components for ${C}m-a module build${S}...${N}"
							install_package 'nvidia-kernel-common'
							install_package "$nvidiaSettings"
							install_package "$nvidiaSource"
							echo "${S}Creating  ${C}$DISTRO_NVIDIA${S} kernel module for kernel ${C}$KERNEL_FULL${S}...${N}"
							# m-a --text-mode --non-inter -f -l ${KERNEL_FULL} a-i $nvidiaSource
							m-a update 1>> $LOG_FILE 2>> $LOG_FILE || error_handler 184 $DISTRO_NVIDIA
							m-a prepare $nvidiaSource 1>> $LOG_FILE 2>> $LOG_FILE || error_handler 185 $DISTRO_NVIDIA
							m-a clean $nvidiaSource 1>> $LOG_FILE 2>> $LOG_FILE || error_handler 182 $DISTRO_NVIDIA
							m-a build -t -f -l $KERNEL_FULL $nvidiaSource 1>> $LOG_FILE 2>> $LOG_FILE || error_handler 194 $DISTRO_NVIDIA
							m-a install -t -f -l $KERNEL_FULL $nvidiaSource 1>> $LOG_FILE 2>> $LOG_FILE || error_handler 193 $DISTRO_NVIDIA
			
							#m-a prepare && m-a qa-i nvidia
							#nvidiaGlx has dependences problems. Workaround is to build-install the driver before install nvidiaglx
							# echo "${S}Installing ${C}$nvidiaGlx${S} now...${N}"
							# install_package "$nvidiaGlx"
							echo "${M}Please report failure to $SCRIPT_NAME maintainer, I'm not sure this feature works.${N}"
							add_module 'nvidia'
						else
							echo "${S}Installing ${C}$DISTRO_NVIDIA dkms driver${S} components...${N}"
							install_package "$nvidiaSettings $nvidiaDriver" 
							add_module 'nvidia'
						fi
					fi
					;;
				fedora)
					# dependencies handle the rest of this
					# kmod-nvidia xorg-x11-drv-nvidia-libs.i586 xorg-x11-drv-nvidia-libs.x86_64
					# kmod-nvidia-PAE xorg-x11-drv-nvidia-libs.i586 xorg-x11-drv-nvidia-libs.x86_64
					# akmod-nvidia-173xx xorg-x11-drv-nvidia-173xx-libs.i586 xorg-x11-drv-nvidia-173xx-libs.x86_64
					# akmod-nvidia-96xx xorg-x11-drv-nvidia-96xx-libs
					local archExt='i686' archExt64='x86_64' 
					if [ "$BITS" == '64' ];then
						archExt=$archExt64
					fi
					case $LEGACY_LEVEL in
						1)	:
							# this has already been error handled.
							;;
						2)	akmodNvidia="akmod-nvidia$NV_FED_LEGACY_2"
							nvidiaDriver="xorg-x11-drv-nvidia$NV_FED_LEGACY_2-libs.$archExt"
							if [ "$BITS" == '64' ];then
								nvidiaDriver2="xorg-x11-drv-nvidia$NV_FED_LEGACY_2-libs.$archExt64"
							fi
							;;
						3)	akmodNvidia="akmod-nvidia$NV_FED_LEGACY_3"
							nvidiaDriver="xorg-x11-drv-nvidia$NV_FED_LEGACY_3-libs.$archExt"
							if [ "$BITS" == '64' ];then
								nvidiaDriver2="xorg-x11-drv-nvidia$NV_FED_LEGACY_3-libs.$archExt64"
							fi
							;;
						4)	akmodNvidia="akmod-nvidia$NV_FED_LEGACY_4"
							nvidiaDriver="xorg-x11-drv-nvidia$NV_FED_LEGACY_4-libs.$archExt"
							if [ "$BITS" == '64' ];then
								nvidiaDriver2="xorg-x11-drv-nvidia$NV_FED_LEGACY_4-libs.$archExt64"
							fi
							;;
						5)	akmodNvidia="akmod-nvidia$NV_FED_LEGACY_5"
							nvidiaDriver="xorg-x11-drv-nvidia$NV_FED_LEGACY_5-libs.$archExt"
							if [ "$BITS" == '64' ];then
								nvidiaDriver2="xorg-x11-drv-nvidia$NV_FED_LEGACY_5-libs.$archExt64"
							fi
							;;
						*)	akmodNvidia="akmod-nvidia"
							nvidiaDriver="xorg-x11-drv-nvidia-libs.$archExt"
							if [ "$BITS" == '64' ];then
								nvidiaDriver2="xorg-x11-drv-nvidia-libs.$archExt64"
							fi
							;;
					esac
					
					echo "${S}Installing ${C}$DISTRO_NVIDIA${S} components...${N}"
					install_package "$akmodNvidia $nvidiaDriver $nvidiaDriver2"
					# only do a final removal of nouveau if the install succeeded
# 					remove_module 'nouveau'
					
					if [ -x /usr/sbin/akmods ];then
						echo "${S}Forcing initial module build of ${C}$akmodNvidia${S} kernel module...${N}"
						/usr/sbin/akmods --force
					fi
					;;
				ubuntu)
					# note: new ubuntus dropped the -glx string, and current nvidia is
					# just called 'current'
					if [ -n "$( check_package_status 'nvidia-current' 'c' )" ];then
						ubGlx=''
						NV_UB_CURRENT='current'
					fi
					# dependencies handle the rest of this
					case $LEGACY_LEVEL in
						1)	:
							# this has already been error handled.
							;;
						2)	nvidiaDriver="nvidia${ubGlx}-$NV_UB_LEGACY_2"
							nvidiaSettings="nvidia-settings-$NV_UB_LEGACY_2"
							nvidiaModal="nvidia-$NV_UB_LEGACY_2-modaliases"
							;;
						3)	nvidiaDriver="nvidia${ubGlx}-$NV_UB_LEGACY_3"
							nvidiaModal="nvidia-$NV_UB_LEGACY_3-modaliases"
							nvidiaSettings="nvidia-settings-$NV_UB_LEGACY_3"
							;;
						4)	nvidiaDriver="nvidia${ubGlx}-$NV_UB_LEGACY_4"
							nvidiaModal="nvidia-$NV_UB_LEGACY_4-modaliases"
							nvidiaSettings="nvidia-settings-$NV_UB_LEGACY_4"
							;;
						5)	nvidiaDriver="nvidia${ubGlx}-$NV_UB_LEGACY_5"
							nvidiaModal="nvidia-$NV_UB_LEGACY_5-modaliases"
							nvidiaSettings="nvidia-settings-$NV_UB_LEGACY_5"
							;;
						*)	nvidiaDriver="nvidia${ubGlx}-$NV_UB_CURRENT"
							nvidiaModal="nvidia-$NV_UB_CURRENT-modaliases"
							nvidiaSettings="nvidia-settings"
							;;
					esac
					echo "${S}Installing ${C}$DISTRO_NVIDIA${S} components...${N}"
					# handle legacy ubuntus
					if [ -n "$ubGlx" ];then
						install_package "$nvidiaModal"
					fi
					install_package "$nvidiaSettings"
					install_package "$nvidiaDriver"
					;;
				*)
					error_handler 176
					;;
			esac 
			;;
		$FGLRX)
			case $SYSTEM_BASE in
				arch)
					echo "${S}Installing ${C}$DISTRO_FGLRX${S} components...${N}"
					install_package "catalyst"
					install_package "catalyst-utils"
					;;
				debian)
					case $LEGACY_LEVEL in
						# fglrx-glx is not in debian anymore.
						0|1)
							:
							;;
						2)	fglrxDriver="fglrx-legacy-driver"
							fglrxGlx="fglrx-glx-legacy-glx"
							fglrxSettings="fglrx-legacy-control"
							fglrxSource='fglrx-legacy-source'
							;;
						*)	fglrxDriver="fglrx-driver"
							fglrxGlx='fglrx-glx'
							fglrxSettings="fglrx-control"
							fglrxSource='fglrx-source'
							;;
					esac
					# start the install/hd2000-4000 not supported; check main legacy level to update this
					if [ "$LEGACY_LEVEL" -gt 1 ];then
						if [ "$B_USE_DISTRO_MODULE_MA" == 'true' ];then
							echo "${S}Installing ${C}$DISTRO_FGLRX m-a module${S} components...${N}"
							# install_package "$fglrxDriver"
							install_package "$fglrxSettings"
							# install_package 'fglrx-amdcccle'
							install_package "$fglrxSource"
							echo "${S}Creating  ${C}$DISTRO_FGLRX${S} kernel module for kernel ${C}$KERNEL_FULL${S}...${N}"
				
							# damentz suggestion to make sure old module is used
							# m-a a-i -f fglrx-kernel-src
							# kelmo:  m-a --text-mode --non-inter -f -l ${KERNEL_FULL} a-i fglrx
							m-a update 1>> $LOG_FILE 2>> $LOG_FILE || error_handler 184 $DISTRO_FGLRX
							m-a prepare fglrx 1>> $LOG_FILE 2>> $LOG_FILE || error_handler 185 $DISTRO_FGLRX
							m-a clean fglrx 1>> $LOG_FILE 2>> $LOG_FILE || error_handler 182 $DISTRO_FGLRX
							m-a build -f -l $KERNEL_FULL fglrx 1>> $LOG_FILE 2>> $LOG_FILE || error_handler 194 $DISTRO_FGLRX
							m-a install -f -l $KERNEL_FULL fglrx 1>> $LOG_FILE 2>> $LOG_FILE || error_handler 193 $DISTRO_FGLRX
						else
							echo "${S}Installing ${C}$DISTRO_FGLRX dkms driver${S} components...${N}"
							install_package "$fglrxSettings $fglrxDriver" 
							add_module 'fglrx'
						fi
					fi
					;;
				fedora)
					echo "${S}Installing ${C}$DISTRO_FGLRX${S} components...${N}"
					install_package "akmod-catalyst" # installs both driver and amdcccle
					;;
				ubuntu)
					echo "${S}Installing ${C}$UBUNTU_FGLRX${S} components...${N}"
					# legacy stuff
					if [ -n "$( check_package_status 'fglrx-modaliases' 'c' )" ];then
						install_package 'fglrx-modaliases'
					fi
					if [ -n "$( check_package_status 'xorg-driver-fglrx' 'c' )" ];then
						install_package 'xorg-driver-fglrx'
					fi
					if [ -n "$( check_package_status 'fglrx-driver' 'c' )" ];then
						install_package 'fglrx-driver'
					fi
					# current, as of T release, 2014
					if [ -n "$( check_package_status 'fglrx' 'c' )" ];then
						install_package 'fglrx'
					fi
					if [ -n "$( check_package_status 'fglrx-amdcccle' 'c' )" ];then
						install_package 'fglrx-amdcccle'
					fi
					;;
				*)
					error_handler 176
					;;
			esac
			;;
	esac
	eval $LOGPE
}

### -------------------------------------------------------------------
### ATI fglrx specific stuff
### -------------------------------------------------------------------

clean_up_fglrx_junk()
{
	eval $LOGUS
	# note that these can't be removed or 3d dies in direct -f install
	if [ "$B_FGLRX_DIRECT" != 'true' ];then
		rm -f /lib/modules/$KERNEL_FULL/kernel/drivers/char/drm/fglrx.*o
		rm -f /lib/modules/$KERNEL_FULL/volatile/fglrx.*o
		# this removes some config stuff that might cause watermarking issues
		# but this breaks direct install systems so don't remove it in direct install
		rm -rf /etc/ati
	fi

	if [ -d /usr/lib/opengl ];then
		rm -rf /usr/lib/opengl
		ldconfig
		log_function_data 'Note: cleanup usr/lib/opengl'
	fi

	eval $LOGUE
}

# this is only for fgrlx
install_fglrx_debs()
{
	# ati change this syntax too much... hope they stabilize
	# fglrx-amdcccle_8.443.1-1_i386.deb
	# fglrx-driver_8.443.1-1_i386.deb
	# fglrx-driver-dev_8.443.1-1_i386.deb
	# fglrx-installer_8.443.1-1_i386.changes
	# fglrx-kernel-src_8.443.1-1_i386.deb
	if [ "$CARD" == $FGLRX ];then
		eval $LOGPS
		local fgAmd='fglrx-amdcccle_' 
		local fgDri='fglrx-driver_' 
		local fgKsc='fglrx-kernel-src_'
		local fgDriver="$fgDri$DRIVER_DEFAULT-1_*.deb"
		local fgKsrc='fglrx-kernel-src'
		local fgAmdcccle="$fgAmd$DRIVER_DEFAULT-1_*.deb"
		local fgKernelSrc="$fgKsc$DRIVER_DEFAULT-1_*.deb"
		local fgAlias='' libAmdXv=''
		
		case $SYSTEM_BASE in
			ubuntu)
				fgDri='xorg-driver-fglrx_'
				fgKsc='fglrx-kernel-source_'
				fgKsrc='fglrx-kernel-source'
				fgDriver="$fgDri*.deb"
				fgAmdcccle="$fgAmd*.deb"
				fgKernelSrc="$fgKsc*.deb"
				libAmdXv='libamdxvb*.deb'
				fgAlias='fglrx-modaliases_*.deb'
				;;
		esac
		
		local availableDebs=$( ls *fglrx*.deb )
		local usunf='/usr/sbin/unfreeze-rc.d' 
		local frozen=0 forceIt=''
		
		case $SYSTEM_BASE in
			ubuntu)
				if [ -z "$( check_package_status 'dkms' 'i' )" ];then
					if [ -n "$( check_package_status 'dkms' 'c' )" ];then
						install_package 'dkms'
					fi
				fi
				;;
		esac

		# this is slightly excessive, but may handle a case where extra debs exist
		# due to weird user action. Also protects against new ati randomness.
		if [ -f $fgDriver ];then
			:
		elif [ -f $fgDri*.deb ];then
			fgDriver=$( ls $fgDri*.deb )
		else
			error_handler 186 $fgDri
		fi

		if [ -f $fgKernelSrc ];then
			:
		elif [ -f $fgKsc*.deb ];then
			fgKernelSrc=$( ls $fgKsc*.deb )
		else
			error_handler 186 $fgKsc
		fi

		if [ -f $fgAmdcccle ];then
			:
		elif [ -f $fgAmd*.deb ];then
			fgAmdcccle=$( ls $fgAmd*.deb )
		else
			error_handler 186 $fgAmd
		fi

# 		if [ "$SYSTEM_CODENAME" != 'unstable' ];then
# 			forceIt='--force-overwrite'
# 		fi
		if [ "$B_TESTING_5" == 'true' ];then
			forceIt='--force-all'
		fi

		log_function_data "These installation debs have been created: $availableDebs"

		echo "${S}Installing fglrx debs for kernel ${C}$KERNEL_FULL${S}...${N}"
		# unfreeze/freeze stuff may be required for some legacy type systems
		if [ -f /etc/frozen-rc.d ];then
			frozen=1
		fi
		if [ -x $usunf ];then
			$usunf
		fi

		log_function_data "Actual driver packages to install:\nfgDriver: $fgDriver\nfgAmdcccle: $fgAmdcccle\nfgKernelSrc: $fgKernelSrc"

		# due to problems with config file questions, trying no logging of 1>> now
		dpkg -i $forceIt $fgKernelSrc 2>> $LOG_FILE || error_handler 195 $fgKernelSrc
		dpkg -i $forceIt $fgDriver 2>> $LOG_FILE || error_handler 195 $fgDriver
 		dpkg -i $forceIt $fgAmdcccle 2>> $LOG_FILE || error_handler 195 $fgAmdcccle
 		
 		case $SYSTEM_BASE in
 			ubuntu)
				if [ -n "$libAmdXv" ];then
					dpkg -i $forceIt $libAmdXv 2>> $LOG_FILE || error_handler 195 $libAmdXv
				else
					echo "${E}ERROR: Missing ${C}$libAmdXv${E} but continuing...${N}"
				fi
				if [ -n "$fgAlias" ];then
					dpkg -i $forceIt $fgAlias 2>> $LOG_FILE || error_handler 195 $libAmdXv
				else
					echo "${E}ERROR: Missing ${C}$fgAlias${E} but continuing...${N}"
				fi
				;;
 			debian)
				log_function_data "Done installing debs created, now to: m-a build  -l $KERNEL_FULL -f $fgKsrc:"
				CC=$CC m-a build  -l $KERNEL_FULL -f $fgKsrc 1>> $LOG_FILE 2>> $LOG_FILE || error_handler 194 $fgKsrc
				log_function_data "Now to: m-a install  -l $KERNEL_FULL -f $fgKsrc:"
				m-a install -l $KERNEL_FULL -f $fgKsrc 1>> $LOG_FILE 2>> $LOG_FILE || error_handler 193 $fgKsrc
				
				# note: note with dkms
			:
# 			log_function_data "Done installing debs created, now to: m-a build fglrx:"
# 			CC=$CC m-a build fglrx-kernel 1>> $LOG_FILE 2>> $LOG_FILE || error_handler 194 fglrx-kernel
# 			log_function_data "Now to: m-a install fglrx:"
# 			m-a install fglrx-kernel 1>> $LOG_FILE 2>> $LOG_FILE || error_handler 193 fglrx-kernel
				;;
		esac

		# restore freeze state
		if [ "$frozen" -eq 1 -a -x $usunf ];then
			$usunf
		fi
		case $SYSTEM_BASE in
			debian)
				# put packages on hold fglrx-amdcccle, fglrx-driver, fglrx module
				echo "${S}Placing ATI packages on hold to avoid dist-upgrade issues with Debian fglrx drivers...${N}"
				hold_package 'fglrx-control'
				hold_package 'fglrx-driver'
				;;
			ubuntu)
				echo "${S}Placing ATI packages on hold to avoid upgrade issues with $DISTRIB_ID fglrx drivers...${N}"
				hold_package 'fglrx-amdcccle'
				hold_package 'xorg-driver-fglrx'
				;;
		esac

		eval $LOGPE
	fi
}

### -------------------------------------------------------------------
### Finalizing steps
### -------------------------------------------------------------------

# this only runs for non free driver installs, so no need to check for xorg stuff
final_install_steps()
{
	eval $LOGPS
	local fgModules='' fgModule=''

	echo "${S}Finalizing install...${N}"
	process_xvmc
	depmod $KERNEL_FULL -a # Probe all modules

	case $CARD in
		$NVIDIA)
			# this needs to be cleaned up a bit
			if [ -e /etc/udev/nvidia.rules ];then
				rm -f /etc/udev/nvidia.rules
			fi
			if [ -e /etc/udev/rules.d/nvidia.rules ];then
				rm -f /etc/udev/rules.d/nvidia.rules
			fi
			ldconfig # Configure Dynamic Linker Run Time Bindings.
			# remove_module 'nouveau'
			;;
		$FGLRX)
			##  clean up install parts
			rm -rf ${USRS}modules/fglrx
			rm -rf /tmp/fglrx* fglrx*
			add_module 'fglrx'
			# note, since ubuntu uses dkms we don't want to purge the kernel source
			case $SYSTEM_BASE in
				arch)
					fgModules='radeon drm'
					;;
				debian)
					dpkg --purge fglrx-kernel-src 1>> $LOG_FILE 2>> $LOG_FILE
					fgModules='radeon drm'
					;;
				ubuntu)
					fgModules='radeon drm'
					;;
			esac
			# test for, then remove if present
			for fgModule in $fgModules
			do
				remove_module "$fgModule"
			done
			;;
	esac

	sync # Force changed blocks to disk, update the super block
	echo $MLINE
	echo "${S}Congratulations! It looks like your new ${C}$DRIVER_DEFAULT $CARD${S} driver installed successfully!${N}"
	eval $LOGPE
}

process_xvmc()
{
	eval $LOGUS
	local lxvmcN='libXvMCNVIDIA_dynamic.so.1' lxvmc='libXvMC.so.1' exxv='/etc/X11/XvMCConfig'

	# xvmc information here: http://www.mythtv.org/wiki/index.php/XvMC
	if [ "$B_USE_XVMC" == 'true' -a "$B_NO_XVMC" != 'true' -a -x /usr/lib/$lxvmcN ];then
		echo $lxvmcN > $exxv
	else
		echo $lxvmc > $exxv
	fi
	eval $LOGUE
}

########################################################################
#### FUNCTIONS: XORG TOOLS
########################################################################

### -------------------------------------------------------------------
### Stop / Start Xorg handling section
### -------------------------------------------------------------------

x_start_stop_master()
{
	eval $LOGPS
	case $1 in
		stop)
			if [ "$B_SKIP_FUNCTION" != 'true' -a "$B_SM_INSTALL" != 'true' -a "$B_SKIP_X_TEST" != 'true' -a "$B_AUTORUN" != 'true' ];then
				launch_from_X 
				start_stop_x stop
				# testing this, only with trigger option
				
			fi
			;;
		start)
			if [ "$B_AUTORUN" != 'true' ];then
				if [ "$B_SKIP_X_QUESTION" == 'true' ];then
					start_stop_x start
				else
					# no point in starting x unless required
					if [ -z "$DISPLAY" ];then
						start_x_question
					# handles case where sgfxi is run in X
					else
						# almost no cases will X be running except a module build to another
						# kernel, since driver install shuts down X. Maybe distro-driver can do this.
						if [ -n "$INSTALL_TO_KERNEL" -a "$INSTALL_TO_KERNEL" != "$( uname -r )" ];then
							echo "${S}All done with driver install. Remember, you have to reboot to kernel ${C}$INSTALL_TO_KERNEL${S}"
							echo "for the driver module you just updated to be active.${N}"
						else
							echo "${S}All done with driver install. Remember, you have to restart X (your desktop)"
							echo "before your new driver is active.${N}"
						fi
					fi
				fi
			fi
			;;
	esac
	eval $LOGPE
}

start_x_question()
{
	eval $LOGPS
	local opt='' options='' bRepeat='false' package=''
	local ia32libs='ia32-libs' iaOpt='install-ia32libs'
	local ia32Alert='echo -e "\n${M}You should probably (re)install ${C}$ia32libs${M} (even if already installed)\nif you use applications that depend on them in your ${C}64 bit${M} system,\nfor example ${C}Wine${M}.${N}"'
	local ia32Install='echo -e "${C}$iaOpt${M} - Install ${C}$ia32libs${M} libs."'
	local fgGlxOpt='' fgGlx='' fgGlxAlert='' fgGlxInstall=''
	local nvGlxOpt='' nvGlx='' nvGlxAlert='' nvGlxInstall=''
	local startXopt='' startXText='' rebootOpt='' rebootText=''

	case $BITS in
		32)
			ia32Alert=''
			ia32Install=''
			iaOpt=''
			;;
		64)
			case $CARD in
				$FGLRX)
					fgGlxOpt='install-fglrx-glx'
					fgGlx='fglrx-glx fglrx-glx-ia32'
					fgGlxAlert='echo -e "\n${M}You might want to (re)install ${C}$fgGlx${M} (even if already installed)\nif you have problems with your ${C}64 bit ATI/fglrx${M} driver/apps.${N}"'
					fgGlxInstall='echo -e "${C}$fgGlxOpt${M} - Install ${C}$fgGlx${M}."'
					;;
				$NVIDIA)
					# not using this now until issue is confirmed by user
					# note, as of 2013-07-05 this issue occurs on install of: libgl1-nvidia-glx:i386
					# when trying to install that package apt tries to install nvidia installer cleaner
					# or cleanup
# 					nvGlxOpt='install-nvidia-glx'
# 					# note, this was the old package name
# 					# nvGlx='libgl1-nvidia-glx-ia32'
# 					nvGlx='libgl1-nvidia-glx:i386'
# 					nvGlxAlert='echo -e "\n${M}You might want to (re)install ${C}$nvGlx${M} (even if already installed)\nif you have problems with your ${C}64 bit nVidia${M} driver/apps.${N}"'
# 					nvGlxInstall='echo -e "${C}$nvGlxOpt${M} - Install ${C}$nvGlx${M}."'
					:
					;;
			esac
			;;
	esac
	ia32Alert=''
	ia32Install=''
	iaOpt=''
	fgGlx=''
	fgGlxOpt=''
	fgGlxAlert=''
	fgGlxInstall=''
	
	if [ "$B_SKIP_INSTALL" == 'true' -o -z "$INSTALL_TO_KERNEL" -o "$INSTALL_TO_KERNEL" == "$( uname -r )" ];then
		startXopt='start-desktop' 
		startXText='echo -e "${C}$startXopt${M} - All finished, (re-)start desktop now."'
	fi
	if [ -n "$INSTALL_TO_KERNEL" -a "$INSTALL_TO_KERNEL" != "$( uname -r )" ];then
		rebootOpt='reboot-now'
		rebootText='echo -e "${C}$rebootOpt${M} - You must reboot to use the driver for ${C}$INSTALL_TO_KERNEL${M}."'
	fi

	echo $MLINE
	echo "${S}Your driver install is now finished. You have the following options:"
	eval $ia32Alert
	eval $fgGlxAlert
	eval $nvGlxAlert
	echo $LINE
	eval $ia32Install
	eval $fgGlxInstall
	eval $nvGlxInstall
	eval $startXText
	eval $rebootText
	echo "${C}quit${M} - Quit now, to do something else before starting your desktop.${N}"
	echo $LINE
	options="$iaOpt $fgGlxOpt $nvGlxOpt $startXopt $rebootOpt quit"
	select opt in $options
	do
		case $opt in
			install-ia32libs)
				if [ "$BITS" == '64' ];then
					echo "${S}Installing the package ${C}$ia32libs${S} now...${N}"
					install_package $ia32libs '' 'reinstall'
					log_function_data "Final Step: Installed: $ia32libs"
				else
					echo "${E}The package ${C}$ia32libs${E} is only available for ${C}64 bit${E} systems.${N}"
				fi

				# repeat the question for users so they can start x now if they want.
				bRepeat='true'
				;;
			install-fglrx-glx)
				if [ "$BITS" == '64' -a "$CARD" == $FGLRX ];then
					echo "${S}Installing packages ${C}$fgGlx${S} now...${N}"
					for package in $fgGlx
					do
						install_package $package '' 'reinstall'
					done

					log_function_data "Final Step: Installed: $fgGlx"
				else
					echo "${E}The packages ${C}$fgGlx${E} are only installable in ${C}64 bit + ATI fglrx${E} systems.${N}"
				fi
				# repeat the question for users so they can start x now if they want.
				bRepeat='true'
				;;
			install-nvidia-glx)
				if [ "$BITS" == '64' -a "$CARD" == $NVIDIA ];then
					echo "${S}Installing packages ${C}$nvGlx${S} now...${N}"
					for package in $nvGlx
					do
						install_package $package '' 'reinstall'
					done

					log_function_data "Final Step: Installed: $nvGlx"
				else
					echo "${E}The packages ${C}$nvGlx${E} are only installable in ${C}64 bit + nvidia${E} systems.${N}"
				fi
				# repeat the question for users so they can start x now if they want.
				bRepeat='true'
				;;
			start-desktop)
				echo "${S}Ok, starting your desktop now, thanks for using this script.${N}"
				log_function_data "Final Step: start-desktop"
				start_stop_x start
				;;
			reboot-now)
				echo "${S}Ok, rebooting into kernel ${C}$INSTALL_TO_KERNEL${S} and your"
				echo "${C}$DRIVER_DEFAULT${S} video driver. Thanks for using this script.${N}"
				log_function_data "Final Step: reboot to kernel: $INSTALL_TO_KERNEL"
				handle_shutdowns 'reboot'
				exit 100 # need to exit with 100 to not trigger root pid kill in smxi
				;;
			quit)
				echo "${S}Ok, exiting now, thanks for using this script.${N}"
				# this is to send calling script message that it should not do its success action
				log_function_data "Final Step: quit"
				exit 100 # need to exit with 100 to not trigger pid root kill in smxi
				;;
			*)
				echo "${W}Please select one of the options in the list, thank you.${N}"
				bRepeat='true'
				;;
		esac
		break
	done

	if [ "$bRepeat" == 'true' ];then
		start_x_question
	fi
	eval $LOGPE
}
# start_x_question

# takes one argument, stop or start
start_stop_x()
{
	eval $LOGUS
	local displayManagers='entrance gdm gdm3 kdm kdm-trinity lightdm lxdm mdm nodm sddm slim wdm xdm' dman='' success=''
	# setting the default will handle cases like default 2 while still handling 3/5
	# also note, future systems will probably not use inittab, ubuntu doesn't, but
	# they will read it, so we'll always use this as default to respect user changes
	local defaultRunlevel=''
	if [ -f $EIT ];then
		defaultRunlevel=$( grep -Es '^id.*:initdefault:' $EIT | grep -Eo '[0-5]' )
	fi
	# default, this prevents errors when these don't exist in for ex. fedora
	local serviceControl='/etc/init.d/' startPath='/etc/init.d/' bSkipXKill='false'
	local noHup='nohup' xActionString='' finalXKill='' dmanCommand=''
	local gdmCommand='' bSkipLoop='false' ttyKill=0
	local action=$1
	
	local defaultDM=$( get_default_display_manager )
	if [ -z "$defaultDM" ];then
		defaultDM=$( do_display_manager_pid_test )
	fi
	local currentRunlevel=$( get_current_runlevel )
	
	if [ -z "$DISPLAY" -a "$1" == 'stop' ];then
		noHup=''
	fi
	# note that init.d does not take a space, but service does,for the first parameter like kdm
	if [ -n "$( type -p service )" ];then
		serviceControl='service '
	fi
	# note, both fedora and arch have moved to systemd so most of this is only for legacy systems
	case $SYSTEM_BASE in
		arch)
			serviceControl='/etc/rc.d/'
			bSkipXKill='true' # STARTS X when you KILL X...
			startPath='/etc/rc.d/'
			;;
		fedora) 
			serviceControl='' # no /etc/init.d, it's in /usr/sbin
			bSkipLoop='true'
			bSkipXKill='true' # STARTS X when you KILL X...
			case $1 in
				start)
					success='true' # go straight to init 5 start up
					;;
				stop)
					gdmCommand='init 3'
					;;
			esac
			defaultDM='gdm'
			;;
	esac
	log_function_data "default runlevel: $defaultRunlevel\ncurrent runlevel: $currentRunlevel"
	## restart x if this is not being run by smxi
	if [ "$B_SYSTEMD_INIT" == 'true' ];then
		echo "${M}Using ${C}systemd/systemctl${M} to try to ${C}$action${M} your desktop.${N}"
	fi
	if [ "$B_UPSTART" == 'true' ];then
		echo "${M}Using ${C}upstart/initctl${M} to try to ${C}$action${M} your desktop.${N}"
	fi

	if [ -z "$defaultDM" -a "$bSkipLoop" != 'true' ];then
		for dman in $displayManagers
		do
			# upstart, systemd
			if [ -n "$( type -p $dman )" ];then
				if [ "$B_SYSTEMD_INIT" == 'true' ];then
					dmanCommand="systemctl $action $dman.service"
				elif [ "$B_UPSTART" == 'true' ];then
					dmanCommand="initctl $action $dman"
				elif [ -x "$startPath$dman"  ];then
					dmanCommand="$serviceControl$dman $action"
				fi
				defaultDM=$dman
				break
			# sysvinit
			elif [ -x $startPath$dman  ];then
				if [ "$B_SYSTEMD_INIT" == 'true' ];then
					dmanCommand="systemctl $action $dman.service"
				elif [ "$B_UPSTART" == 'true' ];then
					dmanCommand="initctl $action $dman"
				else
					dmanCommand="$serviceControl$dman $action"
				fi
				defaultDM=$dman
				break
			fi
		done
	else
		# have to retest dm for null for fedora here
		# upstart in ubuntu, commands like: start gdm; stop gdm; restart gdm
		if [ -n "$defaultDM" ];then
			if [ "$B_SYSTEMD_INIT" == 'true' ];then
				dmanCommand="systemctl $action $defaultDM.service"
			elif [ "$B_UPSTART" == 'true' ];then
				dmanCommand="initctl $action $defaultDM"
			elif [ -x "$startPath$defaultDM" ];then
				dmanCommand="$serviceControl$defaultDM $action"
			fi
		elif [ -n "$gdmCommand" ];then
			dmanCommand=$gdmCommand # init 3 for fedora
			defaultDM=$gdmCommand
		else
			dmanCommand=''
		fi
	fi
	# testing for systemd and graphical loaded, fallback if dm was not found
	if [ -z "$dmanCommand" -a "$B_SYSTEMD_GRAPHICAL" == 'true' ];then
		case $action in
		  stop)
				dmanCommand="systemctl isolate multi-user.target"
				;;
			start)
				dmanCommand="systemctl isolate graphical.target"
				;;
		esac
	fi
	log_function_data "dmanCommand: $dmanCommand"
	if [ -n "$dmanCommand" ];then
		# nohup is required to make sure dm is fully stopped, and pids removed
		echo "${S}Attempting to ${C}$action${S} display manager ${C}$defaultDM${S} now... ${N}"
		dmanCommand="$noHup $dmanCommand 2>>$LOG_FILE && success='true'"
		eval $dmanCommand
		if [ -z "$noHup" ];then
			if [ "$success" == 'true' ];then
				echo "${S}Display manager ${C}$action${S} sucessful.${N}"
			else
				echo "${W}Display manager ${C}$action${S} failed${N}"
			fi
			log_function_data "Display manager $action status: $success"
		fi
	fi
	log_function_data "Reached post dmancommand: $dmanCommand"
	# this handles cases where somehow X is still running
	# startx x starts can for example bypass kdm tests, etc
	if [ "$1" == 'stop' ];then
		if [ "$( x_is_running )" == 'true' -a "$bSkipXKill" != 'true' ];then
			echo "${M}Note: display manager shutdown failed... shutting down X directly instead... ${N}"
			xActionString="$noHup killall Xorg && finalXKill='true'"
			eval $xActionString
			log_function_data "Final X kill reports worked: $finalXKill"
			if [ -z "$noHup" ];then
				if [ "$finalXKill" == 'true' ];then
					echo "${S}X shutdown successful.${N}"
				else
					echo "${W}X shutdown failed.${N}"
				fi
			fi
			# log the result
			if [ "$( x_is_running )" == 'true' ];then
				log_function_data "The final X kill has failed."
			fi
		fi
	fi
	# this will exit the root shell on successful run of start x
	if [ "$1" == 'start' -a "$success" == 'true' ];then
		# trying to bypass this because smxi is failing to restart x after driver install, so
		# I will make smxi exit after running sgfxi
		# if [ "$B_SM_INSTALL" != 'true' ];then
			# the failure case handels a weird thing when kill gives error
			if [ -n "$LOGIN_PID" ];then
				log_function_data "Kill login PID for dm start: $LOGIN_PID"
				# too many oddities with systemd kill root/tty, so not doing anything for now
				if [ "$B_SYSTEMD" == 'true' ];then
					#kill_systemd_tty || ttyKill=$?
					#if [ "$ttyKill" -gt 0 ];then
						kill $LOGIN_PID && exit 0 || exit 1
						exit 0
					#fi
				elif [ -n "$defaultRunlevel" ];then
					init $INIT_LEVEL && kill $LOGIN_PID && exit 0 || exit 1
				else
					kill $LOGIN_PID && exit 0 || exit 1
				fi
			else
				log_function_data "No login PID found, trying default runlevel: $defaultRunlevel"
				if [ -n "$defaultRunlevel" ];then
					echo "${E}No login Pid found to kill, starting init $defaultRunlevel and leaving root logged in.${N}"
					init $defaultRunlevel && exit 0 || exit 1
				else
					echo "${E}No login Pid found to kill, leaving root logged in.${N}"
					exit 0
				fi
			fi
		#else
		#	exit 0 # smxi will handle the pid root kill
		# fi
	fi
	eval $LOGUE
}

# this has weird consequences, not a good thing to use possibly, but I'll check it out
kill_systemd_tty()
{
	eval $LOGUS
	local returnValue=1 ttyStatus=''
	local scriptTTY=$(get_current_tty)
	
	# verify we have an actual tty valid type
	if [ -n "$scriptTTY" -a -n "$( grep -E '^tty[0-9]+$' <<< $scriptTTY )" ];then
		ttyStatus="$( systemctl status getty@$scriptTTY.service )"
		log_function_data "ttyStatus:\n$ttyStatus"
		# double check it's the tty running script, then make sure that tty is actually active
		if [ -n "$( grep "$SCRIPT_NAME" <<< "$ttyStatus" )" ];then
			if "$( grep -Esi 'Active:[[:space:]]*active' <<< "$ttyStatus" )" ];then
				echo "${M}Systemd being used to attempt to exit tty${N}"
				systemctl stop getty@$scriptTTY.service
				returnValue=$?
			fi
		fi
	fi
	# in theory this should not be running anymore so nothing to log, but we'll do it for errors
	log_function_data "returnValue: $returnValue"
	return $returnValue
	eval $LOGUE
}

get_current_tty()
{
	eval $LOGUS
	
	local term=$( tty )
	term=$( basename $term )
	
	log_function_data "term: $term"
	echo $term
	
	eval $LOGUE
}

x_is_running()
{
	eval $LOGUS
	local returnVal=''
	# we'll do one final X is running test here, note, handling a bunch of
	# different possible X detections in etch, lenny, and sid, then filtering out the grep
	local xIsRunning=$( ps aux | grep -E '/usr.*/X([[:space:]]|$)' | grep -v 'grep' )
	
	if [ -z "$xIsRunning" -a "$B_SYSTEMD" == 'true' ];then
		xIsRunning=$( systemd_dm_test )
	fi
	
	log_function_data "X ps aux: $xIsRunning"

	if [ -n "$xIsRunning" ];then
		returnVal='true'
	else
		returnVal='false'
	fi
	echo $returnVal
	log_function_data "returnVal: $returnVal"
	eval $LOGUE
}
# in some cases X will be off but dm is still on, which breaks restarts of desktop
systemd_dm_test()
{
	local dm=$( do_display_manager_pid_test )
	local unit=''
	if [ -n "$dm" ];then
		unit=$( systemctl list-units | grep -E "^[[:space:]]*$dm\.service[[:space:]]+(loaded|active|running)[[:space:]](loaded|active|running)" )
	fi
	echo $unit
}

# get active pid for dm. Note: for systemd, this doesn't matter since dm is loaded but not active (ACtive: inactive)
do_display_manager_pid_test()
{
	eval $LOGUS
	local dmIdList='entranced.pid gdm.pid gdm3.pid kdm.pid lightdm.pid lxdm.pid mdm.pid nodm.pid sddm.pid sddm slim.lock wdm.pid xdm.pid' dmId='' dmInstance=''
	
	for dmId in $dmIdList
	do
		# trim off extension of dm
		if [ -f /run/$dmId -o -f /run/${dmId%.*}/$dmId -o -f /var/run/$dmId -o -f /var/run/${dmId%.*}/$dmId  ];then
			dmInstance=${dmId%.*}
		fi
	done

	echo $dmInstance

	log_function_data "dmInstance: $dmInstance"
	echo $dmInstance
	eval $LOGUE
}

# just return the dm or null if missing
get_default_display_manager()
{
	eval $LOGUS
	local defaultDM=''
	
	# for systemd, if I read this right, this isn't necessarily set on the systemd system, but it can be
	# usually graphical.target will handle this automatically.
	if [ "$B_SYSTEMD" == 'true' ];then
		# slice out last part of link
		if [ -h /etc/systemd/system/display-manager.service ];then
			defaultDM=$( ls -l /etc/systemd/system/display-manager.service 2>/dev/null | awk '{print $NF}' | sed 's/\.service$//' )
		fi
	fi
	# whether or not it's systemd, let's check anyway for a default here
	if [ -z "$defaultDM" ];then
		defaultDM=$( cat /etc/X11/default-display-manager 2>/dev/null )
	fi
	if [ -n "$defaultDM" ];then
		defaultDM=$( basename $defaultDM 2>/dev/null )
	fi

	if [ "$defaultDM" == 'entranced' ];then
		defaultDM='entrance'
	fi

	echo $defaultDM
	log_function_data "defaultDM: $defaultDM"
	eval $LOGUE
}


### -------------------------------------------------------------------
### xorg configuration (previously in sgfxi-lib-xorg)
### -------------------------------------------------------------------

fix_xorg_device_id()
{
	eval $LOGUS
	if [ -n "$( grep -s 'Card0' $EXXC )" ];then
		echo "${S}Updating ${C}$EXXC${S} syntax. Changing ${C}Card[x]${S} to ${C}Device[x]${S}${N}"
		sed -r -i 's/Card([0-9]+)/Device\1/g' $EXXC
		#sed -i 's/Identifier[[:space:]]*"Card/Identifier "Device/' $EXXC
		#sed -i 's/Device[[:space:]]*"Card/Device "Device/' $EXXC
		log_function_data "$EXXC updated. CardX changed to DeviceX."
	else
		log_function_data "No CardX in $EXXC."
	fi
	eval $LOGUE
}

move_x_conf()
{
	eval $LOGUS
	local x_full_bu="$EXXC-bu-$( date +%Y-%m-%d-%H:%M:%S )"
	local message1="${S}Continuing to ${C}$EXXC${S} creation...${N}"
	
	if [ "$B_RESTORE_DEFAULTS" == 'true' ];then
		message1=''
	fi
	
	if [ -n "$( which $X_NAME )" ];then
		if [ "$B_RESTORE_DEFAULTS" != 'true' -a "$( x_is_running )" == 'true' ];then
			start_stop_x 'stop'
		fi
		if [ -f $EXXC ];then
			echo "${M}Moving ${C}$EXXC${M} to ${C}$x_full_bu${M}...${N}"
			mv -f $EXXC $x_full_bu
			echo "$message1"
		else
			if [ "$B_RESTORE_DEFAULTS" != 'true' ];then
				echo "${M}No ${C}$EXXC${M} file exists, continuing to ${C}$EXXC${M} creation...${N}"
			fi
		fi
	else
		if [ "$B_RESTORE_DEFAULTS" != 'true' ];then
			log_function_data "A rebuild of xorg.conf is requested, but there is no X application to rebuild it with."
			error_handler 177
		fi
	fi
	eval $LOGUE
}

# newest xorg will have no xorg.conf file
create_x_conf()
{
	eval $LOGPS
	
	local bRepeat='false' opt='' options=''
	
	if [ ! -f $EXXC -a -n "$( echo $X_VERSION | grep -E '[1-4]\.[0-9]+(\.[0-9]+)?' )" -a -n "$( which $X_NAME )" ];then
		log_function_data "xorg is present, no xorg.conf file"
		
		echo $LINE
		if [ "$B_MOVE_X_CONF" == 'true' ];then
			echo "${S}Now it's time to make your new replacement ${C}$EXXC${S} file. "
		else
			echo "${S}You are running a new version of X but you have no ${C}$EXXC${S} file. "
		fi
		echo "${M}Would you like to create it now (uses ${C}X -configure${M} command)?"
		echo $LINE
		echo "${C}1 - yes-create-xorg-conf-file${M} - Create file and proceed.${N}"
		echo "${C}2 - quit${M} - Quit now, not sure if I should do this.${N}"
		echo $LINE
		options="yes-create-xorg-conf-file quit"
		select opt in $options
		do
			case $opt in
				yes-create-xorg-conf-file)
					echo "${S}Ok, creating your new ${C}$EXXC${S} file now...${N}"
					# X has already been stopped in this case ideally from move, but 
					# checking again to make sure. X command cannot be run with X running
					if [ "$( x_is_running )" == 'true' ];then
						start_stop_x 'stop'
					fi
					# now double check and kill with precise errors to try to catch the cause
					# of failing xorg.conf generation
					if [ "$( x_is_running )" == 'true' ];then
						error_handler 214
					fi
					$X_NAME -configure 2>>$LOG_FILE
					
					# getting error reports of missing file or error on file creation
					if [ -f /root/xorg.conf.new ];then
						echo "${S}Moving newly created ${C}xorg.conf${S} to ${C}$EXXC${S} now...${N}"
						mv -f /root/xorg.conf.new $EXXC
						log_function_data "xorg.conf created and mv to /etc/X11/"
					else
						# temporary debugger logging
# 						ls /root/xorg* >> $LOG_FILE
# 						ls /usr/local/bin/xorg* >> $LOG_FILE
# 						ls $(pwd)/xorg* >> $LOG_FILE
# 						error_handler 215

						# this is a short term hack, only required until X/xserver-xorg package
						# is fixed to be able to create an xorg.conf file.. In theory this should
						# simply vanish as soon as the xorg.conf is generated again, since this
						# case would then never exist.
						if [ ! -f $EXXC ];then
							log_function_data "touch created xorg.conf file because it was missing, X -configure error."
							touch $EXXC
						fi
					fi

					# this handles the case where nouveau was running, sgfxi was started, 
					# no xorg.conf was found, and the X -configure command defaults to nv
					if [ "$B_TESTING_5" == 'true' -a -n "$( lsmod | grep '^nouveau' )" ];then
						NATIVE_OVERRIDE='nouveau'
						update_xorgconf_driver_version
					fi
					if [ -f $EXXC ];then
						echo "${S}Ok, all done, continuing...${N}"
						log_function_data "xorg xorg.conf file generated"
					else
						error_handler 218
					fi
					;;
				quit)
					echo "${S}Ok, you'll have to figure out what to do manually then if you want to run $SCRIPT_NAME.${N}"
					exit 100 # need to exit with 100 to not trigger pid root kill in smxi
					;;
				*)
					echo "${W}Please select one of the options in the list, thank you.${N}"
					bRepeat='true'
					;;
			esac
			break
		done
		
		if [ "$bRepeat" == 'true' ];then
			create_x_conf
		fi
	elif [ ! -f $EXXC -a -z "$( which X )" ];then
		log_function_data "There is no xorg.conf file, and no X command to build one with."
		error_handler 244
	else
		log_function_data "xorg is present with xorg.conf file"
	fi
	eval $LOGPE
}

# create required section device:
create_section_device()
{
	eval $LOGUS
	# if this section is not present, create it
	if [ "$( grep -Esic 'Section[ \t]*"Device"' $EXXC )" -eq 0 ];then
		echo  >> $EXXC
		echo -e 'Section "Device"' >> $EXXC
		echo -e '\tIdentifier "Device0"' >> $EXXC
		# the vesa is a just a failsafe, the actual driver will be set in driver version
# 		echo -e '\tDriver "vesa"' >> $EXXC
# 		echo -e '\tBusID "PCI:'$BUS_ID'"' >> $EXXC
		echo 'EndSection' >> $EXXC
		echo  >> $EXXC
	fi
	# now fill it if needed
	eval $LOGUE
	create_driver_entry
}

create_section_extensions()
{
	eval $LOGUS
	# if this section is not present, create it
	if [ "$( grep -Esc 'Section[ \t]*"Extensions"' $EXXC )" -eq 0 ];then
		echo  >> $EXXC
		echo -e '\nSection "Extensions"' >> $EXXC
		echo 'EndSection' >> $EXXC
	fi
	eval $LOGUE
}
 
create_section_serverflags()
{
	eval $LOGUS
	# if this section is not present, create it
	if [ "$( grep -Esic 'Section[ \t]*"ServerFlags"' $EXXC )" -eq 0 ];then
		echo  >> $EXXC
		echo -e 'Section "ServerFlags"' >> $EXXC
		echo 'EndSection' >> $EXXC
		echo  >> $EXXC
	fi
	eval $LOGUE
}

# args: $1 - the flag to set
set_server_flag()
{
	eval $LOGUS
	create_section_serverflags
	if [ -z "$( grep -Eis '^[[:space:]]*Option[[:space:]]+"'$1'"[[:space:]]+' $EXXC )" ];then
		perl -pi -e 's/^([\s]*Section\s*"ServerFlags")/\1\n\tOption      "'$1'"\t"true"\n/' $EXXC
	fi
	eval $LOGUE
}

# some rough code, will write driver / pciid if required,this is mainly for systems
# that are using the new xorg, and may not have a driver/busid entry.
# if all goes well, will only create a driver / busid entry if missing
create_driver_entry()
{
	eval $LOGUS
	# since this is set in the above function, it must exist, but I'll check to make sure
	local deviceLineNu=$( grep -Eisn 'Section[[:space:]]*"Device"' $EXXC | cut -d ':' -f 1 )

	# echo deviceLineNu: $deviceLineNu
	# make sure it's numeric, and that only one device section number was returned (space)
	if [ -n "$( grep -E '^[0-9]+$' <<< $deviceLineNu )" ];then
		# this is a trick to only grep within a block delimited by start/EndSection
		local isDriver=$( sed -n ''$deviceLineNu',/EndSection/ p' $EXXC | grep -Ei 'Driver[[:space:]]*".*"' )
		local isBusId=$( sed -n ''$deviceLineNu',/EndSection/ p' $EXXC | grep -Ei 'BusID[[:space:]]*".*"' )

		# echo isBusId: $isBusId
		# echo isDriver: $isDriver

		# the vesa is a just a failsafe, the actual driver will be set in driver version
		# this logic is complicated but seems to work, check the range in section device
		# line number to EndSection, then update the driver and busid if needed, as per
		# tests above already done
		# I'm not sure why -r didn't work, but it didn't in this case.
		if [ -z "$isDriver" ];then
			sed -i ''${deviceLineNu}',/EndSection/ s/Section[[:space:]]*"Device"/&\
\tDriver "vesa"/' $EXXC
		fi
		# only adding busid if driver is missing, otherwise mistakes will happen
		# xorg has a bug with bus id with hex, this is now handled in sgfxi
		# commented unless required by dual card presence, then uncommented
		if [ -z "$isBusId" ];then
			pcibusid_hex_to_dec
			sed -i ''${deviceLineNu}',/EndSection/ s/Driver[[:space:]]".*"/&\
\t#BusID "PCI:'${BUS_ID}'"/' $EXXC
		fi
	fi
	eval $LOGUE
}

# this will reset any hex in bus id string to avoid that new xorg failure to handle hex
pcibusid_hex_to_dec()
{
	eval $LOGUS

	local pt1=$( cut -d ':' -f 1 <<< $BUS_ID )
	local pt2=$( cut -d ':' -f 2 <<< $BUS_ID )
	local pt3=$( cut -d ':' -f 3 <<< $BUS_ID )
	local tempPt1='' tempPt2='' tempPt3=''

	let tempPt1=0x$pt1
	let tempPt2=0x$pt2
	let tempPt3=0x$pt3

	BUS_ID="$tempPt1:$tempPt2:$tempPt3"
	eval $LOGUE
}

# this will handle cases where user is changing from one card to another
update_xorgconf_driver_version()
{
	eval $LOGUS
	local driverName=$CARD

	if [ "$B_NATIVE_DRIVER" == 'true' ];then
		case $CARD in
			$FGLRX)
				driverName='radeon'
				;;
			$INTEL)
				driverName='intel'
				;;
			$NVIDIA)
				driverName='nouveau'
				;;
		esac

		# this handles hard overrides to specific driver
		if [ -n "$NATIVE_OVERRIDE" ];then
			driverName=$NATIVE_OVERRIDE
		fi
	fi

	# not converting: i810-modesetting i740 i128: note openchrome just released in sid
	# previous: (i810|nvidia|nv|fglrx|ati|radeon|apm|iftv|fbdev|vesa)
	# these are all known xserver-xorg-video-xxxx drivers, plus nvidia and fglrx
	sed -i -r 's%^\s*Driver\s*"(apm|ark|ati|chips|cirrus|cyrix|fbdev|fglrx|glint|iftv|ivtv|i128|i740|i810|imstt|intel|mach64|mesa|mga|modesetting|neomagic|newport|nouveau|nsc|nv|nvidia|openchrome|radeon|radeonhd|rendition|s3virge|s3|savage|siliconmotion|sis|sisusb|tdfx|tga|trident|tseng|v4l|vboxvideo|vesa|vga|via|vmware|voodoo)"%\tDriver\t"'$driverName'"%' $EXXC
	# confirm that it got written, if they add other driver names etc, like modesetting, it will fail until
	# sgfxi is updated with those new names.
	if [[ -z $( grep "\"$driverName\"" $EXXC ) ]];then
		echo "${M}Driver ${C}$driverName${M} failed to get written to ${C}$EXXC${M}."
		echo "Probable cause for failure loading desktop/X. Please alert $SCRIPT_NAME maintainer.${N}"
		log_function_data "Driver $driverName failed to get written to $EXXC. Probable cause for failure."
	else
		log_function_data "Driver $driverName written to $EXXC. This component worked."
	fi
	eval $LOGUE
}

# if required, create the Extensions section, then set it to what is needed for
# each specific argument/driver combination
check_extensions()
{
	eval $LOGUS
	local stateOn='enable' stateOff='disable' # default for nvidia
	local turnOff='' rendState=$stateOff compState=$stateOff aiglxString=''
	local compComment='#' rendComment='#'

	# for composite to be active, fglrx composite must be set to 0, not 1
	case $CARD in
		$FGLRX)
			#stateOn='Enable' # check into enable/disable syntax for fglrx/ati/radeon here
			#stateOff='Disable'
			rendState=$stateOff
			compState=$stateOff
			# this stuff needs to be Disabled explicitly, no comments for fglrx only.
			if [ "$B_NATIVE_DRIVER" != 'true' ];then
				rendComment='#'
				compComment=''
				#aiglxString='\n\tOption\t"AIGLX"\t"'$stateOff'"'
				if [ "$B_COMPOSITE" == 'true' ];then
					compState=$stateOn
				else
					compState=$stateOff
				fi
			fi
			;;
		$NVIDIA|$INTEL)
			if [ "$B_COMPOSITE" == 'true' ];then
				compState=$stateOn
				compComment=''
			else
				compState=$stateOff
			fi
			;;
	esac

	# clear out all previous extension stuff: note: fglrx composite, aiglx, render: off
	perl -pi -e 's/^[\s]*#*[\s]*Option\s*"Composite".*\n?//;
	s/^[\s]*#*[\s]*Option\s*"RENDER".*\n?//;
	s/^[\s]*#*[\s]*Option\s*"Render".*\n?//;
	s/^[\s]*#*[\s]*Option\s*"AIGLX".*\n?//;
	s/^[\s]*#*[\s]*Option\s*"Aiglx".*\n?//' $EXXC
	
	create_section_extensions
	
	# rebuild the extensions now
	perl -pi -e 's/^([\s]*Section\s*"Extensions")/\1\n'$compComment'\tOption      "Composite"\t"'$compState'"\n'$rendComment'\tOption      "RENDER"\t"'$rendState'"'$aiglxString'/' $EXXC
	eval $LOGUE
}

# resets xorg to basics, strips out all fglrx/nvidia specific stuff
clear_prep_xorg()
{
	eval $LOGUS
	perl -pi -e 's/^[\s]*Load\s*"GLcore"/#\tLoad\t"GLcore"/;
	s/^[\s]*Load\s*"dri"/#\tLoad\t"dri"/;
	s/^[\s]*#*[\s]*Load\s*"glx"/\tLoad\t"glx"/;
	s/^.*Load\s*"speedo".*\n?//;
	s/DefaultColorDepth.*/DefaultColorDepth 24/;
	s/^[\s]*Option\s*"sw_cursor"/\t#Option     "sw_cursor"/;
	s/^[\s]*#*[\s]*Option\s*"Composite".*/#\tOption\t"Composite"\t"1"/;
	s/^.*UseInternalAGPGART.*\n?//;
	s/^.*VideoOverlay.*\n?//;
	s/^.*OpenGLOverlay.*\n?//;
	s/^.*MonitorLayout.*\n?//;
	s/^.*IgnoreDisplayDevices.*\n?//;
	s/^.*Coolbits.*\n?//;
	s/^.*RenderAccel.*\n?//;
	s/^.*AllowGLXWithComposite.*\n?//;
	s/^.*RandRRotation.*\n?//;
	s/^.*AddARGBGLXVisuals.*\n?//;
	s/^.*DisableGLXRootClipping.*\n?//;
	s/^.*TripleBuffer.*\n?//;
	s/^.*OnDemandVBlankInterrupts.*\n?//;
	s/^.*UseEvents.*\n?//;
	s/^.*UseEDID.*\n?//;
	s/^.*UseEdidFreqs.*\n?//;
	s/^.*DynamicTwinView.*\n?//;
	s/^.*AGPFastWrite.*\n?//;
	s/^.*AGPMode.*\n?//;
	s/^.*DynamicClocks.*\n?//;
	s/^.*ColorTiling.*\n?//;
	s/^.*EnablePageFlip.*\n?//;
	s/^.*TexturedXrender.*\n?//;
	s/^.*ignoreABI.*\n?//;
	s/^.*AccelMethod.*\n?//' $EXXC

	# turn on dri again for fglrx/intel, it's off for nvidia
	case $CARD in
		$FGLRX|$INTEL)
			perl -pi -e 's/^[\s]*#*[\s]*Load\s*"dri"/\tLoad\t"dri"/' $EXXC
			;;
	esac
	eval $LOGUE
}

remove_modelines()
{
	eval $LOGUS
	local removeThem='false'

	## this handles standard cases, always for fglrx, never for native ati/nv
	#   and whenever required by argument. I'll see if native ever needs them removed
	if [ "$CARD" == $FGLRX  -o "$B_REMOVE_MODELINES" == 'true' ];then
		if [ "$B_NATIVE_DRIVER" == 'true' -a "$B_REMOVE_MODELINES" == 'true' ];then
			removeThem='true'
		elif [ "$B_NATIVE_DRIVER" != 'true' ];then
			removeThem='true'
		fi
	fi
	if [ "$removeThem" == 'true' ];then
		perl -pi -e 's/^.*Mode.ine.*\n?//g' $EXXC
	fi
	eval $LOGUE
}

update_xorg()
{
	eval $LOGPS
	# this to second time stamp should help fix that old repeated .1st bug
	local timeStampXorg=$EXXC-bu-$( date +%Y-%m-%d-%H:%M:%S )
	local stateOn='enable' stateOff='disable' stateTrue='true' stateFalse='false'
	# nvidia stuff
	local rend=$stateOn twin=$stateTrue triple=$stateFalse
	#  note: putting a space in these subsitution patterns breaks perl -e
	local ignoreDisplay='Option\t"IgnoreDisplayDevices"\t"TV"\n\t'
	# fglrx stuff, we're using default agpart 'on' now instead
	local agpart='on' layout='AUTO,AUTO' allowGlx='' useEvents=$stateFalse

	# this is set in rare cases of dual card early copy of xorg.conf
	if [ "$B_XORG_BACKED_UP" != 'true' ];then
		if [ ! -e $timeStampXorg ];then
			cp $EXXC $timeStampXorg
		fi
		log_function_data "xorg.conf was backed up to: $timeStampXorg"
		echo "${S}Backup copy of your previous version: ${C}$timeStampXorg${N}"
	fi
	echo "${S}Updating your ${C}$EXXC${S} file now...${N}"
	create_section_device # create section "device" if missing
	update_xorgconf_driver_version # will set to correct version
	clear_prep_xorg # bring xorg.conf to default condition
	check_extensions
	remove_modelines
	fix_xorg_device_id # fix the CardX change to DeviceX
	if [ "$B_SET_IGNOREABI" == 'true' ];then
		set_server_flag 'ignoreABI'
	fi

	if [ "$B_NATIVE_DRIVER" != 'true' ];then
		case $CARD in
			$NVIDIA)
				# set any custom stuff here
				#[ "$B_RENDER_ACCEL" != 'true' ] && rend=$stateOff
				# switching off this, making default always off, watch for user feedback
# 				if [ "$B_DISPLAY_DEVICES" == 'true' ];then
# 					ignoreDisplay=''
# 				fi
				# UseEvents can reduce the cpu usage of Xorg on nVidia cards at the cost
				# of instability on old versions of Xorg.  Since Xorg development has
				# stabilizied and all the big distributions run the latest Xserver, this
				# is safe to turn on.  
				if [ "$B_USE_EVENTS" ]; then
					useEvents=$stateTrue
				fi
				# this is legacy, new default is on
				#[ "$B_TWINVIEW" == 'true' ] && twin=$stateOn
				# triplebuffer can reduce 3d performance on cards with low graphics memory
				# 64 mb or less. Default is off/disable/0
				if [ "$B_TRIPLE_BUFFER" == 'true' ];then
					triple=$stateTrue
				fi
				# this should let 3D work again for older cards, 400 etc:
				# u
# 				if [ "$DRIVER_DEFAULT" == "$NV_LEGACY_1" ];then
# 					allowGlx='Option\t"AllowGLXWithComposite"\t"'$stateTrue'"\n\t'
# 				fi
				# note: coolbits requires an integer value
				# \n\tOption      "RandRRotation"\t"'$stateTrue'"
				# \n\tOption      "DynamicTwinView"\t"'$twin'"
				# perl -pi -e 's/^([\s]*Driver\s*"nvidia")/\1\n\t'$ignoreDisplay$allowGlx'Option      "Coolbits"\t"1"\n\tOption      "AddARGBGLXVisuals"\t"'$stateTrue'"\n\tOption      "TripleBuffer"\t"'$triple'"/' $EXXC
				## NOTE: ignoreDisplay makes 352 series fail to start x;
				## xorg reports: 15.059] (WW) NVIDIA(0): Option "UseEvents" is not used
				# perl -pi -e 's/^([\s]*Driver\s*"nvidia")/\1\n\t'$ignoreDisplay$allowGlx'Option      "Coolbits"\t"8"\n\tOption      "TripleBuffer"\t"'$triple'"\n\tOption      "UseEvents"\t"'$useEvents'"/' $EXXC
				perl -pi -e 's/^([\s]*Driver\s*"nvidia")/\1\n\t'$allowGlx'Option      "Coolbits"\t"8"\n\tOption      "TripleBuffer"\t"'$triple'"\n/' $EXXC
				;;
			$FGLRX)
				# set any custom stuff here
				# only use fglrx internal agpart if not in system and never for 64 bit
				#[ "$( lsmod | grep -c 'agpgart' )" -gt 0 -o "$BITS" == '64' ] && agpart='no'

				# this is only for laptops
# 				if [ -n "$(find /proc/acpi/battery/ -mindepth 1 -type d 2>/dev/null)" ]
# 				then
# 					layout='LVDS,AUTO' # no space in string
# 				fi

				# \n\tOption      "UseInternalAGPGART" "'$agpart'"
				# \n\tOption      "VideoOverlay" "on"
				# \n\tOption      "MonitorLayout" "'$layout'
				perl -pi -e 's/^([\s]*Load\s*"extmod")/#\1\n\tSubSection  "extmod"\n\t  Option  "omit xfree86-dga"\n\tEndSubSection/' $EXXC

				#s/^([\s]*Driver\s*"fglrx")/\1\n\tOption      "UseInternalAGPGART" "'$agpart'"\n\tOption "TexturedXrender"/
				;;
		esac
	## Native ati/nv specific stuff
	else
		if [ "$CARD" == $INTEL ];then
			:
		# note: changed XAA to EXA
		elif [ "$NATIVE_OVERRIDE" == 'radeon' ];then
			# removed: Option  "AGPFastWrite"    "off"\n\tOption  "AGPMode" "4"\n\tOption   "ColorTiling" "on"
			perl -pi -e 's/^([\s]*Driver\s*"radeon")/\1\n\t\n\tOption  "DynamicClocks"   "on"\n\tOption   "EnablePageFlip" "on"\n\tOption   "AccelMethod" "EXA"/' $EXXC
		fi
	fi
	eval $LOGPE
}

########################################################################
#### OPTION HANDLER
########################################################################

# args: $1 - d (driver); f (fglrx data); n (nvidia data)
show_extra_data()
{
	local fullUrl='' ua='-U s-tools/sgfxi-data' uaFull='' dataFull='' dataType=''
	local scriptVersion='' scriptDate='' scriptRemoteVersion='' scriptRemoteDate=''
	local dataWorking='' bSysInfo='false'
	
	case $1 in
		d)
			fullUrl='http://smxi.org/sg/data/sg-drivers-23'
			uaFull="$ua.driver-data"
			dataType='Supported Drivers List'
			;;
		f)
			fullUrl='http://smxi.org/sm/upgrade-data/video_support_fglrx'
			uaFull="$ua.fglrx-status"
			dataType='FGLRX Status'
			bSysInfo='true'
			;;
		n)
			fullUrl='http://smxi.org/sm/upgrade-data/video_support_nvidia'
			uaFull="$ua.nvidia-status"
			dataType='Nvidia Status'
			bSysInfo='true'
			;;
		v)
			fullUrl=$SCRIPT_DOWNLOAD_VERSION
			uaFull="$ua.version-data"
			dataType="(latest) $SCRIPT_NAME version information"
			;;
	esac
	if [ "$bSysInfo" == 'true' ];then
		echo "${S}System Information :: Xorg Version: ${N}$X_VERSION ${S}:: Kernel: ${N}$( uname -r )"
	fi
	echo -n "${S}Retrieving live data... ${N}"
	dataFull="$( wget -q  $uaFull -O - $fullUrl 2>/dev/null )"
	case $1 in
		v)
# 			# don't need to run this if distro maintainer has set path
# 			if [ "$B_ALLOW_AUTO_UPDATE" == 'true' ];then
# 				check_set_distro
# 			fi
			dataWorking=$( grep 'sgfxi=' <<< "$dataFull" | cut -d '=' -f 2 )
			
			if [ -f $SCRIPT_HOME/$SCRIPT_NAME ];then
				scriptVersion=$( grep -Eo -m 1 "(version:).*" $SCRIPT_HOME/$SCRIPT_NAME | cut -d ' '  -f 2-4 )
				scriptDate=$( grep -Eo -m 1 '(Date:).*' $SCRIPT_HOME/$SCRIPT_NAME | cut -d ' ' -f 2-4 )
			else
				scriptVersion="Error: wrong path for $SCRIPT_NAME"
				scriptDate="Error: wrong path for $SCRIPT_NAME"
			fi
			scriptRemoteVersion=$( cut -d ':' -f 1 <<< $dataWorking )
			scriptRemoteDate=$( cut -d ':' -f 2 <<< $dataWorking )
			if [ "$scriptVersion" == "$scriptRemoteVersion" ];then
				dataFull="Remote Version: $scriptRemoteVersion is the same as Local Version: $scriptVersion" 
			else
				dataFull="The remote and local script versions are different:\nRemote Version: $scriptRemoteVersion\nRemote Date:    $scriptRemoteDate\n\nLocal Version:  $scriptVersion\nLocal Date:     $scriptDate"
			fi
			;;
	esac
	if [ -n "$dataFull" ];then
		echo "${S}Success! Here is the current $dataType:${N}"
		echo $LINE
		echo -e "$dataFull"
	else
		echo "${W}Failed!!${N}"
		echo $WLINE
		echo "${W}Unable to access the remote data file, exiting now, sorry."
		echo "This feature requires a working internet connection.${N}"
	fi
}

# keep this above getopts to keep it readable
# args: $1 if err or not, $2 extra data
show_options()
{
	local xVersion=$X_VERSION
	if [ -z "$X_VERSION" ];then
		xVersion="${W}NO SUPPORTED XORG!${N}"
	fi
	#local pattern='(1\.0-)?([0-9]{4}|1[0-9]{2}\.[0-9]{2}\.?[0-9]{0,2}):?'
	#local nvDefault=$( echo $NV_DEFAULT | sed -r 's/'$pattern'/\2 /g')
	local nvDefaults=$( echo $NV_VERSIONS | tr ':' ' ' | sed 's/1.0-//g' )
	#local nvVersions=$( echo "$NV_VERSIONS:$NV_OTHERS" | sed -r 's/'$pattern'/\2 /g')
	local nvVersions=$( echo "$NV_OTHERS" | tr ':' ' ' | sed 's/1.0-//g')
	#local nvQuadText='' nvQuad=$( echo $NV_QUAD | sed -r 's/'$pattern'/\2 /g')
	local nvQuadText='' nvQuad=$( echo $NV_QUAD | tr ':' ' ' | sed 's/1.0-//g')
	local fgDefault=$FG_DEFAULT
	local fgVersions=$( echo "$FG_VERSIONS:$FG_OTHERS" | sed 's/:/ /g')
	local nativeVersions=$( echo $NATIVE_OVERRIDE_SUPPORTED | sed 's/|/ /g' )
	local fgBeta='' nvBeta='' betaText='' fgDebianSid=''
	local counter=0 driverCount=0 bSkipOutput=''
	driverCount=$( wc -w <<< $nativeVersions )

	if [ "$B_DISTRO_FLAG" == 'true' ];then
		fgDebianSid='echo -e "'${W}'ATI: installer package '$fgDefault' is currently broken in Debian (works in Ubuntu). Script will default to: '$DISTRO_FGLRX${N}'"'
	else
		fgDebianSid='echo -e "fglrx:  default: '$fgDefault'		supported-drivers: '$fgVersions'"'
	fi

	if [ -n "$NV_BETA" -a "$NV_BETA" != "$NV_DEFAULT" ];then
		nvBeta='echo -e "nvidia: '$( echo $NV_BETA | tr ':' ' ' | sed 's/[[:space:]][[:space:]]/ /g' )'"'
	fi
	if [ -n "$FG_DEFAULT_BETA" -a "$FG_DEFAULT_BETA" != "$FG_DEFAULT" ];then
		fgBeta='echo -e "fgrlx:\t'$FG_DEFAULT_BETA'"'
	fi
	if [ -n "$fgBeta" -o -n "$nvBeta" ];then
		betaText='echo "The following beta drivers are available:"'
	fi
	if [ -n "$NV_QUAD" -a "$NV_QUAD" != "$NV_DEFAULT" ];then
		nvQuadText='echo -e "Nvidia Quadroplex driver (automatically selected if you have a Quad card): '$nvQuad'"'
	fi

	if [ "$1" == 'err' ];then
		echo "${W}Sorry, one of your arguments is not a supported option.${N}"
		echo "Please check the following options and try again."
		echo $PLINE
	fi
	if [ -n "$DISPLAY" ];then
		echo "${W}While you can run this script in X, we recommend you run it in terminal.${N}"
		echo $PLINE
	fi
	echo "Script Requirements: Debian/Ubuntu/Arch/Fedora based systems."
	echo "Xorg version required: 7.1/1.1 or greater - Your X version: $xVersion"
	echo "Linux Kernel required: 2.6.18 or greater - Your kernel: $(uname -r)"
	echo $PLINE
	echo "'default(s):' - The driver installed automatically by $SCRIPT_NAME unless it is not supported by"
	echo "your card. Some older cards will force an override of this basic default. Script will"
	echo "print out what driver it will install when you start it up, with option to exit."
	echo
	echo "'supported-drivers:' choices require -o <see -o for correct syntax> to install>."
	echo "Fglrx:  default: $fgDefault"
	echo -n "Other supported-drivers: "
	counter=0
	driverCount=$( wc -w <<< $fgVersions )
	for i in $fgVersions
	do
		(( counter++ ))
		case $counter in
			12|28)
				echo "$i "
				echo -n ""
				;;
			$driverCount)
				echo "$i "
				;;
			*)
				echo -n "$i "
				;;
		esac
	done
	#echo "fglrx:  default: $fgDefault		supported-drivers: $fgVersions"
	echo "Nvidia: defaults (current + legacy - 3 2 1): $nvDefaults"
	echo -n "Other supported-drivers: "
	counter=0
	driverCount=$( wc -w <<< $nvVersions )
	for i in $nvVersions
	do
		(( counter++ ))
		case $counter in
			7|17)
				echo "$i "
				echo -n ""
				;;
			$driverCount)
				echo "$i "
				;;
			*)
				echo -n "$i "
				;;
		esac
	done
	eval $nvQuadText
	eval $betaText
	eval $nvBeta
	eval $fgBeta
	echo $PLINE
	echo "Script Options:"
	echo "-A Run the install non-interactively. Will not restart x at end. Expert users only! Requires testing."
	echo "-b Enable tripleBuffer (nvidia only). triplebuffer can reduce 3d performance on cards"
	echo "   with low graphics memory (64 mB or less). Default is disabled/off."
	echo "-B Use latest Beta Driver for your card type. Autodetects card type/beta driver (nVidia/AMD cards only)."
	echo "   If no beta driver is available, the current stable driver for your card type is used."
	echo "   (Also checks for live latest beta information, and replaces script defaults with newer if present)"
	echo "-c Force use of Xorg composite mode. Beryl/Compiz requires this for 3d. Old nvidia/ATI/Intel "
	echo "   cards not supported. Composite is default ON for newer nVidia/ATI cards (-c not required)."
	echo "-C Skip Xorg configuration. Only use this if your Xorg is already working with your driver."
	echo "   Main use is if you have dual card output and don't want xorg.conf changed."
	echo "-d Installs distro packaged nVidia/fglrx drivers. ATI/nVidia cards only (formerly -s)."
	echo "-D Build Distro (Debian/Ubuntu only) packages for fglrx with FGLRX binary run package,"
	echo "   then install them (formerly -F). Not recommended. Because of constant package"
	echo "   builder failures, the direct install method is now default."
# 	echo "-e Use experimental drivers (currently: xorg ati only)."
# 	echo "-E Adds extra experimental driver features. Currently libdrm2 things for ati."
	echo "-f Force option. Forces (re)install of your driver, bypasses default module check/build/rebuild (nVidia only)."
	echo "   Note; -f cannot be used with -k because they contradict each other!"
	echo "-h View this help menu."
	echo "-j Alternate text/output script colors. Requires this syntax: -j 0 (sets to monochrome )"
	echo "   -j 1 (default); -j 2 (pale); -j 3 (earthy); -j 4 (dark - for light console background)"
	echo "-k Build kernel module either for current kernel or another kernel (with -K <kernel version)"
	echo "   Can be run in X (if not in X and installing to current kernel). Simply builds the kernel"
	echo "   module for that kernel, and does not remove any other modules or drivers, or update $EXXC."
	echo "   Requires previous install with $SCRIPT_NAME of the same driver to work. This feature only"
	echo "   supports nVidia drivers.  $SCRIPT_NAME defaults to building modules for kernels automatically."
	echo "   The -f option overrides this default behavior and forces a full reinstall of the driver."
	echo "   Hint: sgfxi -! 40 will install modules to all your non-running kernels automatically!"
	echo "-K Installs nVidia/fglrx driver for another kernel. Syntax: $SCRIPT_NAME -K 2.6.25-2"
	echo "   $SCRIPT_NAME will double check that the kernel exists (Debian/Ubuntu only). "
	echo "-L List current live driver or status data then exit. Requires extra argument: d to show current drivers;"
	echo "   n to show current nvidia support status; f to show current fglrx support status;"
	echo "   v to show current latest local + remote $SCRIPT_NAME svn/server version information."
	echo "-m Overrides default (-d) dkms driver method, uses $SCRIPT_NAME's old method, kernel-source + m-a build"
	echo "   of module. Use only if you want to avoid dkms (fglrx/nvidia only). Triggers -d as well."
	echo "-n Automatically installs correct native xorg nvidia, intel, or ati/amd driver for your system."
	echo "   Cleans up old binary driver stuff, updates xorg.conf with new driver information,"
	echo "   and cleans nvidia and fgrlx stuff out of xorg.conf. For radeon/noveau, also preps."
	echo "-N Force install of specific xorg driver. Syntax: $SCRIPT_NAME -N <driver> Ex: $SCRIPT_NAME -N radeon"
	echo -n "   Supported Xorg drivers: "
	counter=0
	driverCount=$( wc -w <<< $nativeVersions )
	for i in $nativeVersions
	do
		(( counter++ ))
		case $counter in
			12|25)
				echo " $i"
				echo -n "  "
				;;
			$driverCount)
				echo " $i"
				;;
			*)
				echo -n " $i"
				;;
		esac
	done
	echo "   Also configures xorg.conf as required. Full radeon xorg 3d configuration automatically."
	echo "-o Override default: install a specific driver, this is an absolute override - syntax:"
	echo "   -o 177.68 (for nVidia) or: -o 8-6 (for fglrx)"
	echo "-q Turns off composite mode. Default is ON for newer nVidia/ATI cards."
	echo "-Q Skip start X Question, automatically start X post driver install."
	echo "-r Remove mode lines from xorg.conf"
# 	echo "-t Enables dynamic twinview (nVidia only) - LEGACY, unused now. Default is on, enabled."
	echo "-R Skips self updating feature. No restart."
	
# 	echo "-S Skips automatic logout and X startup when script is run in standalone mode."
	echo "-U Forces $SCRIPT_NAME to update itself, must be root, but can be in x. Exits after."
	echo "-v Prints $SCRIPT_NAME current version information. Exits after."
	echo "-W Skip all wget downloads. Expert Use Only! Only use this to (re)install a driver that has already "
	echo "   been downloaded using $SCRIPT_NAME previously. Because using this option can have unknown or unintended"
	echo "   consequences, only use it if you are following instructions to do so. $SCRIPT_NAME always saves its "
	echo "   driver downloads by default in all cases, so using -W will not change that behavior , but it may stop"
	echo "   other key downloads, like patches. The standard use for this is to download the driver file in X,"
	echo "   then exit, and install it out of X"
	echo "-x Reverts to default libXvMC.so.1 for system instead of nVidia package (nVidia only)"
	echo "-X Use to skip auto X start/stop. Do not use this unless you have a good reason to not "
	echo "   want X start/stop tests to run. Gives start X option on completion if not in X. Expert use only."
	echo "-Y Clean script download and backup files. Shows a list of cleanup actions to carry out, including script uninstaller."
	echo "   Can be run in X, as root."
	echo "-z Backup and recreate xorg.conf using the command: X -configure (requires X/Xorg command)"
	echo "   Only use if you know what you are doing! This creates a simple, basic xorg.conf file."
# 	echo "-Z Skips connection test. Use this if $SCRIPT_NAME gives you connection failed error but"
# 	echo "   you are sure your connection is fine."
	echo $PLINE
	echo "Advanced Options :: Only for Specialized Cases"
	echo "-! 32 Remove/Purge all drivers; remove all grub modeline blacklists; restore system to default"
	echo "      without redoing xorg.conf; moves xorg.conf to backup. Only use this on new Xorgs that do not"
	echo "      require xorg.conf file to operate. Using this command restores system to default."
	echo "-! 33 Skip Grub file tests. Important: Only use with nVidia/ATI if radeon/nouveau have been blacklisted."
	echo "-! 40 Create modules for all your kernels (nVidia only). Will loop through and test"
	echo "      each if can be made, then create the modules, excluding your running kernel."
	echo "      You must have already installed an nVidia driver with $SCRIPT_NAME to use -! 40"
	echo "      Note: if your installed driver is NOT the default $SCRIPT_NAME offers, you have to"
	echo "      use either the -o <driver number> OR the -B option (if you are using current beta driver)"
	echo "      as well as the -! 40 option. EG: to install beta to all kernels: $SCRIPT_NAME -B -! 40"
	echo "      -! 40 must be the LAST option in your list of options or errors will occur!"
	echo "--debugger Create debugger data file in $HOME/$SCRIPT_NAME-data - the file is a gz file that holds"
	echo "           whatever might be helpful to debugging $SCRIPT_NAME issues, like xorg.conf, lspci, inxi"
	echo "           output if present, etc. Upload file to: ftp.techpatterns.com/incoming OR use a service"
	echo "           like dropbox.com then give me the url to the uploaded file. If $SCRIPT_NAME has an internet"
	echo "           connection and python > 2.5, will also automatically upload the data to server for you."
	if [ "$1" == 'full' ];then
		echo $PLINE
		echo "Developer and Testing Options (Advanced):"
		echo "-! 1 - Sets flag B_TESTING_1='true' - sets testing function data active."
		echo "-! 2 - Sets flag B_TESTING_2='true' - triggers exit after run package download/extract."
		echo "-! 3 - Sets flag B_SKIP_FUNCTION='true' to turn off functions for script testing."
		echo "-! 4 - Sets flags B_TESTING_1='true' and B_TESTING_2='true'."
		echo "-! 5 - Sets flags B_TESTING_1, B_TESTING_2, and B_SKIP_FUNCTION ='true'."
		echo "-! 6 - Sets flag B_TESTING_3='true' - overrides initial driver xorg/kernel support tests."
		echo "-! 7 - Sets flag B_TESTING_4='true' - overrides patch controls."
		echo "-! 8 - Sets flag B_TESTING_5='true' - activates beta/advanced development features for debugging."
		echo "-! 9 - Sets flag B_TESTING_6='true' - triggers experimental new distro support methods."
		echo "-! 10 - Triggers an update from the primary dev download server."
		echo "-! 11 - Triggers an update from svn branch one - if present, of course."
		echo "-! 12 - Triggers an update from svn branch two - if present, of course."
		echo "-! <http://......> - Triggers an update from whatever server you list."
		echo "-! 20 - Uses patch from svn branch one server (must be in branch/one/patches)."
		echo "-! 21 - Uses patch from svn branch two server (must be in branch/two/patches)."
		echo "-! 30 - Backup, download, replace, xorg.conf with basic Debian xorg.conf version (legacy, don't use)."
		echo "        Use X -configure instead to redo your xorg, or -z option in $SCRIPT_NAME."
		echo "-! 31 - Backup, download, replace, xorg.conf with basic xorg.conf version (legacy, don't use)."
		
		echo "        Use X -configure instead to redo your xorg, or -z option in $SCRIPT_NAME."
		echo "-p Print currently supported drivers, <default>:<latest>:<legacy1>:<legacy2>"
		echo "   then exit the script without doing the driver download/install."
		echo "-! 121  - When used with -p, will use the live driver list from smxi.org"
		echo "          instead of the drivers taken from the local user $SCRIPT_NAME values."
	fi
	echo
	if [ "$1" == 'err' ];then
		exit 1
	else
		exit 0
	fi
}

# args: $1 - "$@"
get_options()
{
	local opt=''
	
	case $1 in
		--debugger)
			if tty > /dev/null ;then
				debugger_data_collector
			else
				echo "You cannot use the $SCRIPT_NAME debugger option in an IRC client!"
				exit 1
			fi
			;;
		--help|-h)
			if tty > /dev/null ;then
				show_options
			else
				echo "You cannot use the $SCRIPT_NAME help option in an IRC client!"
				exit 1
			fi
			;;
		--version|-v)
			# if showing in irc, kill the colors
			if ! tty > /dev/null ;then
				SCRIPT_COLORS=0
				set_script_colors
			fi
			print_information
			exit 0
			;;
	esac

	while getopts AbBcCdDeEfFGHj:kK:L:mnN:o:pP:QrRsStUWXxYzZ!: opt
	do
		case $opt in
			A) B_AUTORUN='true'
				START_OPTIONS=$START_OPTIONS' -A'
				START_OPTIONS_PRINT="$START_OPTIONS_PRINT  -A - Autorun is selected\n"
				;;
			b) B_TRIPLE_BUFFER='true'
				START_OPTIONS=$START_OPTIONS' -b'
				START_OPTIONS_PRINT="$START_OPTIONS_PRINT  -b - TripleBuffer is on (nVidia only)\n"
				;;
			B)	B_USE_BETA='true'
				START_OPTIONS=$START_OPTIONS' -B'
				START_OPTIONS_PRINT="$START_OPTIONS_PRINT  -B - Use Beta Driver (Only if available)\n"
				;;
			c) B_COMPOSITE='true'
				START_OPTIONS=$START_OPTIONS' -c'
				START_OPTIONS_PRINT="$START_OPTIONS_PRINT  -c - Force composite flag on. Does not work with legacy nVidia driver\n       Composite is default ON for newer nVidia cards (no -c required).\n       Switch composite OFF with: -q\n"
				;;
			C) B_SKIP_CONFIG='true'
				START_OPTIONS=$START_OPTIONS' -C'
				START_OPTIONS_PRINT="$START_OPTIONS_PRINT  -C - Xorg.conf will not be modified by this script.\n"
				;;
			d)	B_USE_DISTRO_DRIVER='true'
				B_FGLRX_DIRECT=''
				START_OPTIONS=$START_OPTIONS' -d'
				START_OPTIONS_PRINT="$START_OPTIONS_PRINT  -d - Install distro packaged driver.\n"
				;;
			D)	B_FGLRX_DEB_BUILDER='true'
				B_FGLRX_DIRECT=''
				START_OPTIONS=$START_OPTIONS' -D'
				START_OPTIONS_PRINT="$START_OPTIONS_PRINT  -D - Using FGLRX Distro package builder install. Not reliable, but try if you want.\n       Builds/Installs packages for distro from downloaded fglrx run file.\n"
				;;
	# 		e) B_EXPERIMENTAL='true'
	# 			START_OPTIONS=$START_OPTIONS' -e'
	# 			;;
	# 		E) B_EXTRA_EXPERIMENTAL='true'
	# 			START_OPTIONS=$START_OPTIONS' -E'
	# 			;;
			f)	B_FORCE_OPTION='true'
				START_OPTIONS=$START_OPTIONS' -f'
				START_OPTIONS_PRINT="$START_OPTIONS_PRINT  -f - You are using the forced override option. This will bypass kernel module\n       check/build and force reinstall of your driver (nVidia only).\n"
				;;
			F)	B_FGLRX_DEB_BUILDER='true'
				B_FGLRX_DIRECT=''
				START_OPTIONS=$START_OPTIONS' -F'
				START_OPTIONS_PRINT="$START_OPTIONS_PRINT  -F - Using FGLRX package builder install. Not reliable, but try if you want.\n       -F is deprecated, please use -D instead in the future.\n"
				;;
			G)	B_GUI_MODE='true'
				B_SKIP_X_TEST='true'
				START_OPTIONS=$START_OPTIONS' -G'
				START_OPTIONS_PRINT="$START_OPTIONS_PRINT  -G - Gui mode. Run in X. For nVidia, passes --no-x-check flag to nvidia installer\n       . Not reliable, but try if you want.\n"
				;;
			j)	if [ -n "$( grep -sE '^[0-4]$' <<< $OPTARG )" ];then
					SCRIPT_COLORS=$OPTARG
					START_OPTIONS=$START_OPTIONS" -j $OPTARG"
					# no reason to reset the colors if they are default
					if [ "$SCRIPT_COLORS" != 1 ];then
						START_OPTIONS=$START_OPTIONS" -j $SCRIPT_COLORS"
						set_script_colors
					fi
				else
					error_handler 228 $OPTARG
				fi
				;;
			k)	B_KERNEL_MODULE_ONLY='true'
				START_OPTIONS_PRINT="$START_OPTIONS_PRINT  -k - Building nvidia kernel module using previously installed driver\n      Permits building a module for an alternate kernel while in X.\n"
				START_OPTIONS=$START_OPTIONS" -k "
				;;
			K)	INSTALL_TO_KERNEL="$OPTARG"
				START_OPTIONS_PRINT="$START_OPTIONS_PRINT  -K - You are installing a graphic driver onto the kernel: ${C}$INSTALL_TO_KERNEL${S}\n"
				test_install_kernel_version
				START_OPTIONS=$START_OPTIONS" -K $OPTARG"
				;;
			L)	if [ -n "$( grep -sE '^[dfnv]$' <<< $OPTARG )" ];then
					show_extra_data "$OPTARG"
					exit 0
				else
					error_handler 228 $OPTARG
				fi
				;;
			m)	B_USE_DISTRO_MODULE_MA='true'
				B_USE_DISTRO_DRIVER='true'
				B_FGLRX_DIRECT=''
				START_OPTIONS=$START_OPTIONS' -m'
				START_OPTIONS_PRINT="$START_OPTIONS_PRINT  -m - Install distro packaged driver using kernel source + m-a.\n"
				;;
			n) B_NATIVE_DRIVER='true'
				START_OPTIONS=$START_OPTIONS' -n'
				START_OPTIONS_PRINT="$START_OPTIONS_PRINT  -n - Auto install of native xorg intel, nvidia, 3dfx, or ati drivers.\n"
				;;
			N)
				if [ -n $( grep -sE '('$NATIVE_OVERRIDE_SUPPORTED')' <<< $NATIVE_OVERRIDE ) ];then
					NATIVE_OVERRIDE="$OPTARG"
					B_NATIVE_DRIVER='true'
					START_OPTIONS_PRINT="$START_OPTIONS_PRINT  -N - Native driver custom install. You have requested to install the xorg driver: $NATIVE_OVERRIDE\n"
					START_OPTIONS=$START_OPTIONS" -N $OPTARG"
				else
					error_handler 237 $NATIVE_OVERRIDE
				fi
				;;
			o) DRIVER_OVERRIDE="$OPTARG"
				START_OPTIONS_PRINT="$START_OPTIONS_PRINT  -o - Driver override. Forces install of this driver: $DRIVER_OVERRIDE (nVidia|ATI fglrx only)\n"
				START_OPTIONS=$START_OPTIONS" -o $OPTARG"
				;;
			p) B_PRINT_VER='true'
				START_OPTIONS=$START_OPTIONS' -p'
				;;
			P)	if [ -n $( grep -sE '^(apt-get|aptitude)$' <<< $OPTARG ) ];then
					PACKAGE_MANAGER=$OPTARG
					APT_TYPE=$OPTARG
					START_OPTIONS=$START_OPTIONS" -P $OPTARG"
				else
					error_handler 228 $OPTARG
				fi
				;;
			q)	B_FORCE_NO_COMPOSITE='true'
				B_COMPOSITE='false'
				START_OPTIONS=$START_OPTIONS' -q'
				START_OPTIONS_PRINT="$START_OPTIONS_PRINT  -q - Turn off default ON composite flag (nVidia only).\n"
				;;
			Q)	B_SKIP_X_QUESTION='true'
				START_OPTIONS=$START_OPTIONS' -Q'
				START_OPTIONS_PRINT="$START_OPTIONS_PRINT  -Q - X will start automatically when the driver install is finished.\n"
				;;
			r) B_REMOVE_MODELINES='true'
				START_OPTIONS=$START_OPTIONS' -r'
				START_OPTIONS_PRINT="$START_OPTIONS_PRINT  -r - Remove modelines in xorg.conf (ATI only).\n"
				;;
			R) B_SKIP_RESTART='true'
				;;
			# deprecated but leaving to not break existing methods
			s)	B_USE_DISTRO_DRIVER='true'
				B_FGLRX_DIRECT=''
				START_OPTIONS=$START_OPTIONS' -s'
				START_OPTIONS_PRINT="$START_OPTIONS_PRINT  -s - Install distro packaged driver. Deprecated. Please use -d instead\n"
				;;
			S) B_SKIP_AUTOSTART='true'
				START_OPTIONS=$START_OPTIONS' -S'
				START_OPTIONS_PRINT="$START_OPTIONS_PRINT  -S - Deprecated, not used. Skip autostart of X/kde.\n"
				;;
			t) B_TWINVIEW='true'
				START_OPTIONS=$START_OPTIONS' -t'
				START_OPTIONS_PRINT="$START_OPTIONS_PRINT  -t - twinview on: this is deprecated. Always sets for twinview (nVidia only)\n"
				;;
			U) B_FORCE_UPDATE='true'
				;;
			W) B_SKIP_WGET='true'
				START_OPTIONS=$START_OPTIONS' -W'
				START_OPTIONS_PRINT="$START_OPTIONS_PRINT  -W - Skip wget downloads. Only use if you are having problems connecting\n    but you have the current driver downloaded already. Not recommended!\n"
				;;
			x) B_NO_XVMC='true' # because two flags are required to use nvidia xvmc, this is fine
				START_OPTIONS=$START_OPTIONS' -x'
				START_OPTIONS_PRINT="$START_OPTIONS_PRINT  -x - Skip nVidia xvmc setup. (nVidia only)\n"
				;;
			X) B_SKIP_X_TEST='true'
				START_OPTIONS=$START_OPTIONS' -X'
				START_OPTIONS_PRINT="$START_OPTIONS_PRINT  -X - Skip the test for X/KDE. Only use if you know what you are doing!\n"
				;;
			Y)	clean_script_data
				;;
			z)	if [ -z "$DISPLAY" ];then
					B_MOVE_X_CONF='true'
					START_OPTIONS=$START_OPTIONS' -z'
					START_OPTIONS_PRINT="$START_OPTIONS_PRINT  -z - Backup and recreate xorg.conf using the command: X -configure\nOnly use if you know what you are doing!\n"
				else
					error_handler 250
				fi
				;;
			Z) B_SKIP_CONNECT='true'
				START_OPTIONS=$START_OPTIONS' -ZW'
				START_OPTIONS_PRINT="$START_OPTIONS_PRINT  -Z - Deprecated, use -R to skip script update; use -W to skip all downloads.\n"
				;;
			H)	show_options 'full'
				;;
			## debuggers and testing options
			!)	# test for various supported methods
				bSkipOutput=''
				case $OPTARG in
					1)	B_TESTING_1='true'
						;;
					2)	B_TESTING_2='true'
						;;
					3)	B_SKIP_FUNCTION='true'
						;;
					4)	B_TESTING_1='true'
						B_TESTING_2='true'
						;;
					5)	B_TESTING_1='true'
						B_TESTING_2='true'
						B_SKIP_FUNCTION='true'
						;;
					6)	B_TESTING_3='true'
						;;
					7)	B_TESTING_4='true'
						;;
					8)	B_TESTING_5='true'
						;;
					9)	B_TESTING_6='true'
						;;
					10)
						cd $SCRIPT_HOME
						check_root
						check_set_distro
						check_update_script "$SCRIPT_NAME" "$SCRIPT_DOWNLOAD_DEV" 'dev server'
						;;
					11)
						cd $SCRIPT_HOME
						check_root
						check_set_distro
						check_update_script "$SCRIPT_NAME" "$SCRIPT_DOWNLOAD_BRANCH_1" 'svn: branch one server'
						;;
					12)
						cd $SCRIPT_HOME
						check_root
						check_set_distro
						check_update_script "$SCRIPT_NAME" "$SCRIPT_DOWNLOAD_BRANCH_2" 'svn: branch two server'
						;;
					http*)
						cd $SCRIPT_HOME
						check_root
						check_set_distro
						check_update_script "$SCRIPT_NAME" "$OPTARG" 'alt server'
						;;
					20)
						PATCH_DOWNLOAD="$SCRIPT_DOWNLOAD_BRANCH_1"
						;;
					21)
						PATCH_DOWNLOAD="$SCRIPT_DOWNLOAD_BRANCH_2"
						;;
					# let these run in X
					30)
						cd $SCRIPT_HOME
						check_root
						check_set_distro
						check_update_script "dm-1-xorg-conf" "$SCRIPT_DOWNLOAD_DATA" 'main server'
						exit 0
						;;
					31)
						cd $SCRIPT_HOME
						check_root
						check_set_distro
						check_update_script "sm-1-xorg-conf" "$SCRIPT_DOWNLOAD_DATA" 'main server'
						exit 0
						;;
					32)
						B_RESTORE_DEFAULTS='true'
						B_NATIVE_DRIVER='true'
						B_MOVE_X_CONF='true'
						;;
					33)
						B_SKIP_GRUB_TEST='true'
						;;
					40)
						B_BUILD_KERNEL_MODULES='true'
						;;
					120)
						B_SM_INSTALL='true'
						S=${CALLER_DEF} # change standard text color to caller standard text
						bSkipOutput='true'
						;;
					121)
						B_GET_LIVE_DRIVERS='true'
						;;
					122)
						B_LAUNCH_FROM_X='true'
						;;
					*)	
						error_handler 178 "$OPTARG"
						;;
				esac
				START_OPTIONS="$START_OPTIONS -! $OPTARG"
				if [ "$bSkipOutput" != 'true' ];then
					START_OPTIONS_PRINT="$START_OPTIONS_PRINT  -! $OPTARG - You are using an advanced Testing option. Only use this if you know what you are doing!\n"
				fi
				;;
			*) show_options err
				;;
		esac
	done
	if [ "$B_FORCE_OPTION" == 'true' -a "$B_KERNEL_MODULE_ONLY" == 'true' ];then
		error_handler 166 "-k and -f"
	fi
	#in case -n is used too - note: this will never be true, have to fix this one
	if [ "$B_NATIVE_DRIVER" == "true" -a -n "$INSTALL_TO_KERNEL" ];then
		echo "${W}WARNING: -n will uninstall binary drivers to all the kernels, not just $KERNEL_FULL${N}"
	fi
	
}

########################################################################
#### MAIN: EXECUTE
########################################################################

# this must be set before anything else runs in script, -j will reset to no colors
set_script_colors $COLOR_DEFAULT
# set all options
get_options "$@"
# this exits when it's done if triggered
if [ "$B_BUILD_KERNEL_MODULES" == 'true' ];then
	check_set_distro ## need to know what it is for some tests
	install_modules_to_all_kernels
fi
# Get kernel string stuff, no need to rerun this after it's been set in options
if [ -z "$INSTALL_TO_KERNEL" ];then
	kernel_string_info
fi

## if this exits with error, no lib files will be downloaded
if [ "$B_SKIP_FUNCTION" != 'true' ];then
	basic_startup_tests
fi

## update everything, restart if not run from smxi
if [ "$B_ALLOW_AUTO_UPDATE" == 'true' -a "$B_SKIP_RESTART" != 'true' -a "$B_SM_INSTALL" != 'true' -a "$B_SKIP_FUNCTION" != 'true' -a "$B_SKIP_WGET" != 'true' -a "$B_PRINT_VER" != 'true'  ];then
	check_update_script $SCRIPT_NAME "$SCRIPT_DOWNLOAD" 'default server'
fi

set_test_data # this will set other test data for debugging

if [ "$B_PRINT_VER" != 'true' ];then
	# test for multiple video cards and select only one
	if [ "$CARD_COUNT" -gt 1 -a "$B_RESTORE_DEFAULTS" != 'true' ];then
		# handle no xorg.conf with new X situation, only create xorg.conf
		# if > 2 cards prior to testing for supported cards
		if [ "$B_SKIP_FUNCTION" != 'true' ];then
			create_x_conf
		fi
		select_card
	fi
	print_information
fi

if [ "$B_GET_LIVE_DRIVERS" == 'true' -a "$B_PRINT_VER" == 'true' ];then
	reset_using_live_driver_data
fi

## this is separate so card can get set first for native installer
set_card

if [ "$B_NATIVE_DRIVER" != 'true' ];then
	detect_card_version
fi

# this needs to go before logging starts so we know what the package manager is
if [ "$B_PRINT_VER" != 'true' -a -z "$PACKAGE_MANAGER" -a "$B_SM_INSTALL" != 'true' -a "$B_AUTORUN" != 'true' ];then
	check_apt_aptitude
fi

## This has to run after card version detection to log that data
## don't log the first start if restart/print output happens
if [ "$B_PRINT_VER" != 'true' ];then
	create_log
fi
# need to handle new xorg no xorg.conf systems
# no need to create this if the card isn't supported, so this comes
# after print info and log start unless > 1 card detected
if [ "$B_PRINT_VER" != 'true' -a "$B_SKIP_FUNCTION" != 'true' ];then
	if [ "$B_MOVE_X_CONF" == 'true' ];then
		move_x_conf
	fi
	if [ "$B_RESTORE_DEFAULTS" != 'true' ];then
		create_x_conf
	fi
fi

# we'll need to force an initial update on fresh apt type installs for header
# checks and other package checks.
if [ "$B_SKIP_FUNCTION" != 'true' -a "$B_PRINT_VER" != 'true' -a "$B_SM_INSTALL" != 'true' ];then
	check_package_manager_updated
fi
# this exits when done
if [ "$B_NATIVE_DRIVER" == 'true' ];then
	install_native_driver
fi
## ready to set the data for version/system info
if [ "$B_USE_DISTRO_DRIVER" != 'true' ];then
	check_supported_driver # make sure user entered data is correct
	set_cpu_data
fi
# needs to be out to give print version, if print out driver data, exits after.
set_driver_install_version

if [ "$B_NATIVE_DRIVER" != 'true' ];then
	# make sure user has kernel headers, to avoid running unneeded clean up or prep
	check_kernel_headers
	if [ "$B_CHECK_IA32" == 'true' ];then
		check_ia32_libs 'full'
	fi
fi

if [ "$B_USE_DISTRO_DRIVER" != 'true' ];then
	create_data_storage
	check_run_package_tools
	set_download_info # also triggers the download / extract function
	# need to make sure this doesn't run for module build component
	if [ "$B_SKIP_INSTALL" != 'true' ];then
		if [ "$B_KERNEL_MODULE_ONLY" == 'true' ];then
			# this will run by itself because it's just some tests and a module rebuild
			# when it's done it will simply exit, no reboot or desktop start is required.
			build_kernel_module_only 'direct'
		else
			# this is going to run either the fglrx or nvidia patch library file function
			# must be after set_driver_install_version for output of data to smxi
			# note this must occur before binary driver install
			set_install_directory
			check_patch_driver
		fi
		if [ "$B_TESTING_2" == 'true' ];then
			exit 0 # this is just to test up to download/extract point
		fi
	fi
fi
# need to make sure this doesn't run for module build component
if [ "$B_SKIP_INSTALL" != 'true' ];then	
	x_start_stop_master stop
	
	if [ "$B_SKIP_FUNCTION" != 'true' -a "$B_PRINT_VER" != 'true' -a "$B_NATIVE_DRIVER" != 'true' ];then
		check_driver_install_tools
	fi
	prep_install
	# for testing/debugging and alt driver/card download testing,
	# I don't want to remove this stuff from system
	if [ "$B_SKIP_FUNCTION" != 'true' ];then
		preinstall_cleanup
	fi
	
	## both have same function name, so no detection is required, we did it already
	if [ "$B_USE_DISTRO_DRIVER" != 'true' ];then
		run_driver_installer
		post_installer_steps
		if [ "$B_FGLRX_DEB_BUILDER" == 'true' ];then
			install_fglrx_debs
		fi
	else
		update_to_nonfree_sources
		install_distro_drivers
	fi
	if [ "$B_SKIP_CONFIG" != 'true' ];then
		update_xorg
	fi
	final_install_steps
	
	x_start_stop_master start
fi

###**EOF**###


syntax highlighted by Code2HTML, v. 0.9.1