#!/bin/sh
#(c) Copyright Barry Kauler 2006,2007 www.puppylinux.com
#2007 Lesser GPL licence v2 (/usr/share/doc/legal/lgpl-2.1.txt)
## Abused by Dougal, Feb 2007
## Update: March 16th: fixed "OK" button when testing X
## Update: April 15th: fixed problem with MONTYPES format, added touchpad code
## Update: April 16th: removed MONTYPES, using a case-structure to set params
#v2.21 BK 9sept2007 bug fix: serial mouse setting was wrong.
#v3.93 BK 1dec2007: updated for dingo.
#v3.93 BK 2dec2007: bugfixes from Dougal and rerwin.
#v3.94 BK 24dec2007: recognise Classmate PC laptop.
#v3.95 BK 4jan2008: recognise eeepc laptop.
#v3.95 BK 8jan2008: bug that caused xorgwizard to run at every boot.
#v3.96 BK 22jan2008: special case submitted by rerwin.
#v3.97 BK 2feb2008: improved detection of Classmate laptop.
#v3.98 RE 7mar2008: added preferred mode parameter; corrected & added special cases submitted by rerwin.
#v3.99 BK 15apr2008: have restored the xrandrshell utility to the main GUI menu.
#v3.99 BK 15apr2008: workaround for xrandr and dual monitors.
#v3.99 RE 7apr2008: improve user interface for any Xvesa-hanging video adapters.
#v405 BK 22jul08: added support for 1024x600.
#v408 BK k2.6.25.16 serial mouse driver now a module 'sermouse'.
#v411 rerwin: mouse improvements.
#v411 moved choosemousefunc() to /etc/rc.d/functions4puppy4, want call from rc.sysinit.
#w000 path /usr/X11R7 no longer used.
#w002 no longer offering xvesa.
#w005 restored EXIT button in first dlg.
#w007 fix X if it is not a symlink.
#w019 april2009: restored Xvesa.
#w460 fixed X test screen, proper exit.
#w468 modify mouse detection message.
#w478 fix prevent 2 instances of xwin, do not 'exec xwin'.
#w480 bugfix, serial mouse choice lost if choose to tweak refresh.
#w482 allow switch between intel_drv.so and i810OLD_drv.so.
#091119 pizzasgood: patch for multiple monitors.
#091125 if no Xvesa, do not display dlg that offers to choose it.
#100109 fix yes/no labels in dlg, fix bug when switch to 'vesa' driver.
#100113 choose alternate video drivers.
#100215 now have xgamma-gui.
#100328 different xorg.conf0 for xorg 7.3.
#100329,100330 first window offer vesa.
#100401 offer alternate drivers in first window.
#100430 handle commercial nvidia driver. improve Choose button.
#100501 monitor probe returns random 'manufacture' data from one of my monitors.
#100510 fix column alignment.
#100516 TazOC: nvidia module loading fix.
#100603 Jemimah: support Elantech touchpads.
#100708 fix for when all three nv, nouveau, nvidia drivers present, choose just one.
#100820 Xvesa present, improve dialogs if choose Xorg.
#100820 for intel video, mplayer needs 'Option "LinearAlloc" "6144"' in xorg.conf.
#100902 fix switching between choosing 'intel' and 'i810' drivers.
#101224 added LANG=C in call to xinitrc_test.
#110505 support sudo for non-root user.
#110701 synaptics stuff seems to clash with xorg-server 1.10.1.
#110701 bugfix for '%' char in /root/xorg.conf.new.
#110806 correction, changed 1360x768 to 1366x768.
#110814 01micko: convert script from gtkdialog2 to gtkdialog3+.
#110910 BK: gtkdialog3 (patriot-e version) syntax error, bump to gtkdialog4.
#110911 'drivers-alternate' moved from /usr/lib/xorg/modules/ to /usr/lib/x/.
#110927 fix touchpad setup.
#111108 Karl Godt: fix for desktop drive icons getting drawn in wrong place after change resolution.
#120129 jemimah: add Option "SHMConfig" "on".
#120130 rodin.s: i18n internationalise script. BK: note, edited all changes manually, as script from rodin.s had some differences.
#120131 rodin.s: added a couple more translations.
#120213 /var/local/pup_event_icon_change_flag path changed from /tmp (see /sbin/clean_desk_icons)
#120213 rodin.s: removed LANG=C prefix when run xinitrc_test.
#120226 01micko: bugfix, call new script 'nouveau_unload'.
#120301 it seems have to reload console font after exit from X.
#120318 correctly set keyboard layout, model and variant.
#120323 partial replace 'xmessage' with 'pupmessage'.
#120723 BOOT_DISABLEXORGWIZARD variable in /etc/rc.d/BOOTCONSTRAINED. refer 3builddistro, also xwin.
#130201 01micko: support "modesetting_drv.so" xorg driver installed to /usr/lib/x/drivers-alternate/
#130427 new script xorgwizard-cli.
#130504 no longer using nouveau_unload.

[ "`whoami`" != "root" ] && exec sudo -A ${0} ${@} #110505

#130427 new script replaces this one...
if [ ! $DISPLAY ];then
 XORGVER="`Xorg -version 2>&1 | grep '^X Window System Version' | rev | cut -f 1 -d ' ' | rev`" #ex: 1.3.0
 [ ! "$XORGVER" ] && XORGVER="`Xorg -version 2>&1 | grep '^X\.Org X Server' | rev | cut -f 1 -d ' ' | rev`"
 if vercmp $XORGVER ge 1.11.0; then
  exec xorgwizard-cli
 fi
fi

export TEXTDOMAIN=xorgwizard
export OUTPUT_CHARSET=UTF-8
. gettext.sh

mkdir -p /usr/lib/x/drivers-backup
mkdir -p /var/local/xorg #100902

#130504 no longer using nouveau_unload...
##120226 unload nouveau
#[ $DISPLAY ] && CURRENTVIDEODRIVER="`grep -E -i " connected|card detect|primary dev" /var/log/Xorg.0.log|cut -d ':' -f1|rev|cut -d ' ' -f1|rev|cut -d '(' -f1|tr '[:upper:]' '[:lower:]'|head -n1`"
#[ "$CURRENTVIDEODRIVER" = "nouveau" ] && nouveau_unload
#[ -f /tmp/abort_xorgwizard ] && exit

. /etc/DISTRO_SPECS #120723
. /etc/rc.d/BOOTCONSTRAINED #120723

if [ ! $DISPLAY ];then #120723
 if [ "$BOOT_DISABLEXORGWIZARD" = "yes" ];then #120723 refer /etc/rc.d/BOOTCONSTRAINED and 3builddistro.
  echo
  echo "Sorry, the text-mode Xorg Wizard is disabled for this build of Puppy."
  exit
 fi
fi

alternate_driver_func() { #100401 100708
 REPLACEDDRV=""
 mv -f /usr/lib/x/drivers-backup/* /usr/lib/xorg/modules/drivers/ 2>/dev/null
 SUBSTDRV="$1" #alternative driver in /usr/lib/x/drivers-alternate
 case $SUBSTDRV in
  intel)
   REPLACEDDRV="i810"
   [ ! -h /usr/lib/xorg/modules/drivers/i810_drv.so ] && mv -f /usr/lib/xorg/modules/drivers/i810_drv.so /usr/lib/x/drivers-alternate/
   mv -f /usr/lib/x/drivers-alternate/intel_drv.so /usr/lib/xorg/modules/drivers/
   [ ! -e /usr/lib/xorg/modules/drivers/i810_drv.so ] && [ -h /var/local/xorg/i810_drv.so ] && mv -f /var/local/xorg/i810_drv.so /usr/lib/xorg/modules/drivers/ #100902
   #100330 restore, see i810 case below...
   if [ -d /usr/lib/x/drivers-alternate/intel ];then #100330 see my xf86-video-i810_xorg73 pet pkg.
    mkdir -p /usr/lib/x/drivers-alternate/i810
    for ONEXFILE in `find /usr/lib/x/drivers-alternate/intel -type f | sed -e 's%/usr/lib/x/drivers-alternate/intel/%%' | tr '\n' ' '`
    do
     ONEXDIR="`dirname $ONEXFILE`"
     [ "$ONEXDIR" = "." ] && ONEXDIR=""
     mkdir -p /usr/lib/x/drivers-alternate/i810/$ONEXDIR
     cp -a -f /$ONEXFILE /usr/lib/x/drivers-alternate/i810/$ONEXDIR #swap them
     cp -a -f /usr/lib/x/drivers-alternate/intel/$ONEXFILE /$ONEXDIR  # "
    done
   fi
  ;;
  i810)
   REPLACEDDRV="intel"
   [ -h /usr/lib/xorg/modules/drivers/i810_drv.so ] && mv -f /usr/lib/xorg/modules/drivers/i810_drv.so /var/local/xorg/ #move aside old symlink. 100902
   mv -f /usr/lib/xorg/modules/drivers/intel_drv.so /usr/lib/x/drivers-alternate/
   mv -f /usr/lib/x/drivers-alternate/i810_drv.so /usr/lib/xorg/modules/drivers/
   if [ -d /usr/lib/x/drivers-alternate/i810 ];then #100330 see my xf86-video-i810_xorg73 pet pkg.
    mkdir -p /usr/lib/x/drivers-alternate/intel #100330
    for ONEXFILE in `find /usr/lib/x/drivers-alternate/i810 -type f | sed -e 's%/usr/lib/x/drivers-alternate/i810/%%' | tr '\n' ' '`
    do
     ONEXDIR="`dirname $ONEXFILE`"
     [ "$ONEXDIR" = "." ] && ONEXDIR=""
     mkdir -p /usr/lib/x/drivers-alternate/intel/$ONEXDIR
     cp -a -f /$ONEXFILE /usr/lib/x/drivers-alternate/intel/$ONEXDIR #swap them
     cp -a -f /usr/lib/x/drivers-alternate/i810/$ONEXFILE /$ONEXDIR  # "
    done
   fi
  ;;
  nv)
   mv -f /usr/lib/x/drivers-alternate/nv_drv.so /usr/lib/xorg/modules/drivers/
   if [ -f /usr/lib/xorg/modules/drivers/nouveau_drv.so ];then
    REPLACEDDRV="nouvea"
    mv -f /usr/lib/xorg/modules/drivers/nouveau_drv.so /usr/lib/x/drivers-alternate/
   fi
   if [ -f /usr/lib/xorg/modules/drivers/nvidia_drv.so ];then #100430
    REPLACEDDRV2="nvidia"
    mv -f /usr/lib/xorg/modules/drivers/nvidia_drv.so /usr/lib/x/drivers-alternate/
    rmmod nvidia #100516
   fi
  ;;
  nouveau)
   mv -f /usr/lib/x/drivers-alternate/nouveau_drv.so /usr/lib/xorg/modules/drivers/
   if [ -f /usr/lib/xorg/modules/drivers/nv_drv.so ];then
    REPLACEDDRV="nv"
    mv -f /usr/lib/xorg/modules/drivers/nv_drv.so /usr/lib/x/drivers-alternate/
   fi
   if [ -f /usr/lib/xorg/modules/drivers/nvidia_drv.so ];then
    REPLACEDDRV2="nvidia"
    mv -f /usr/lib/xorg/modules/drivers/nvidia_drv.so /usr/lib/x/drivers-alternate/
    rmmod nvidia
   fi
  ;;
  nvidia)
   mv -f /usr/lib/x/drivers-alternate/nvidia_drv.so /usr/lib/xorg/modules/drivers/
   if [ -f /usr/lib/xorg/modules/drivers/nv_drv.so ];then
    REPLACEDDRV="nv"
    mv -f /usr/lib/xorg/modules/drivers/nv_drv.so /usr/lib/x/drivers-alternate/
   fi
   if [ -f /usr/lib/xorg/modules/drivers/nouveau_drv.so ];then
    REPLACEDDRV2="nouvea"
    mv -f /usr/lib/xorg/modules/drivers/nouveau_drv.so /usr/lib/x/drivers-alternate/
   fi
   modprobe nvidia
  ;;
  modesetting) #130201 01micko.
   REPLACEDDRV=""
   [ -f /usr/lib/x/drivers-alternate/modesetting_drv.so ] && mv -f /usr/lib/x/drivers-alternate/modesetting_drv.so /usr/lib/xorg/modules/drivers/
  ;;
  *) #100430 get rid of all drivers except chosen one.
   REPLACEDDRV=""
   mv -f /usr/lib/xorg/modules/drivers/* /usr/lib/x/drivers-backup/
   [ -h /usr/lib/x/drivers-backup/i810_drv.so ] && mv -f /usr/lib/x/drivers-backup/i810_drv.so /var/local/xorg/ #100902
   [ -f /usr/lib/x/drivers-backup/$SUBSTDRV ] && cp -f /usr/lib/x/drivers-backup/$SUBSTDRV /usr/lib/xorg/modules/drivers/
   [ -f /usr/lib/x/drivers-alternate/$SUBSTDRV ] && cp -f /usr/lib/x/drivers-alternate/$SUBSTDRV /usr/lib/xorg/modules/drivers/
  ;;
 esac
 if [ "$REPLACEDDRV" -o "$REPLACEDDRV2" ];then
  REPLACEDDRV0="${REPLACEDDRV}${REPLACEDDRV2}"
  XMSG1="`eval_gettext \"NOTICE: The '\\\${REPLACEDDRV0}' driver has been removed, so when Xorg probes the video hardware, it should instead use '\\\${SUBSTDRV}'. 

TECHNICAL NOTE: '\\\${REPLACEDDRV0}' has been moved to /usr/lib/x/drivers-alternate and if you ever want to manually get it back so that Xorg can use it, move it to /usr/lib/xorg/modules/drivers. Note that there may also be one or more directories inside /usr/lib/x/drivers-alternate with library files needed for the alternate drivers.

Press ENTER key to continue...\"`"
  if [ "$REPLACEDDRV" -a "$REPLACEDDRV2" ];then
   XMSG1="`eval_gettext \"NOTICE: The '\\\${REPLACEDDRV}' and '\\\${REPLACEDDRV2}' drivers have been removed, so when Xorg probes the video hardware, it should instead use '\\\${SUBSTDRV}'. 

TECHNICAL NOTE: '\\\${REPLACEDDRV}' and '\\\${REPLACEDDRV2}' have been moved to /usr/lib/x/drivers-alternate and if you ever want to manually get them back so that Xorg can use them, move them to /usr/lib/xorg/modules/drivers. Note that there may also be one or more directories inside /usr/lib/x/drivers-alternate with library files needed for the alternate drivers.

Press ENTER key to continue...\"`"
  fi
  dialog  --title "$(gettext 'Xorg Video Wizard')" --msgbox "${XMSG1}" 0 0
 fi
 #restart wizard after return.
} #end alternate_driver_func

# redirect errors to file (to help debug):
exec 2>/tmp/xorgwizard-errors.log

PSFND="`ps`"
CURRENTX="`readlink /usr/bin/X`"
if [ "$CURRENTX" = "" ];then #w007 fix if not a symlink.
 ln -snf Xorg /usr/bin/X
 CURRENTX='Xorg'
fi

#110701 improve logic...
XORGVER="`Xorg -version 2>&1 | grep '^X Window System Version' | rev | cut -f 1 -d ' ' | rev`" #ex: 1.3.0
[ ! "$XORGVER" ] && XORGVER="`Xorg -version 2>&1 | grep '^X\.Org X Server' | rev | cut -f 1 -d ' ' | rev`"

#100328 determine version of Xorg...
if [ -f /etc/X11/xorg.conf0XORG73 ];then
 #110701 remove test...
 #XORGBIN="`which Xorg`"
 #if [ "$XORGBIN" ];then
  #XVERSION=`Xorg -version 2>&1 | grep '^X Window System Version' | rev | cut -f 1 -d ' ' | rev | cut -c 3` #ex: 3 (as in 1.3.0)
  #[ ! $XVERSION ] && XVERSION=`Xorg -version 2>&1 | grep '^X.Org X Server' | rev | cut -f 1 -d ' ' | rev | cut -c 3`
  #if [ $XVERSION -lt 5 ];then
  if vercmp $XORGVER lt 1.5.0; then #110701
   if [ -f /etc/X11/xorg.conf0XORG73 ];then
    #xorg 7.3 needs a different file...
    mv -f /etc/X11/xorg.conf0XORG73 /etc/X11/xorg.conf0
   fi
  fi
 #fi
fi

. /etc/rc.d/functions4puppy4 #v411 has choosemousefunc().

#120318 broken, use shinobar's keymap-set...
##v2.0.0 read the console keymap (country layout), apply to xkb...
#CONSKEYMAP="`cat /etc/keymap | cut -c 1-2`"
#[ "$CONSKEYMAP" = "" ] && CONSKEYMAP="us"
#case $CONSKEYMAP in
#  az) XKEYMAP="fr" ;;     #azerty
#  wa) XKEYMAP="fr" ;;     #wangbe
#  dv) XKEYMAP="dvorak" ;; #dvorak
#  cr) XKEYMAP="cz" ;;     #croat
#  sl) XKEYMAP="si" ;;     #slovene v2.12 bugfix, changed from 'sk' to 'si' (sk is slovakia)
#  sv) XKEYMAP="se" ;;     #sweden
#  uk) XKEYMAP="gb" ;;     #united kingdom
#  *)  XKEYMAP="$CONSKEYMAP" ;;
#esac
#if [ -d /etc/X11/xkb/symbols/pc ];then #100127 fallback...
# if [ ! -f /etc/X11/xkb/symbols/pc/${XKEYMAP} ];then
#  if [ ! -f /etc/X11/xkb/symbols/${XKEYMAP} ];then
#   echo "ERROR: Console keyboard `cat /etc/keymap` no matching Xorg layout. PLEASE REPORT TO BK"
#   XKEYMAP='us'
#  fi
# fi
#fi
XKEYMAP='us'
RETVALS="`keymap-set --xopt`"
eval "$RETVALS" #ex: XKBMODEL="pc102", XKBLAYOUT="us", XKBVARIANT=""
[ "$XKBLAYOUT" = "" ] && XKBLAYOUT='us'
[ "$XKBMODEL" = "" ] && XKBMODEL='pc102'

if [ "$BOOT_DISABLEXORGWIZARD" = "yes" ];then #120723 refer /etc/rc.d/BOOTCONSTRAINED and 3builddistro.
 XORGPRELIM_XML="
  <text><label>\"$(gettext 'The behaviour of Xorg is controlled
by a configuration file, /etc/X11/
xorg.conf. This was generated auto-
matically at the first boot, but
you may now edit it manually.')\"</label></text>"
 XORGWIZ_XML=""
else
 XORGPRELIM_XML="
  <text><label>\"$(gettext 'The behaviour of Xorg is controlled
by a configuration file, /etc/X11/
xorg.conf. You have a choice here,
either to completely reconstruct
the /etc/X11/xorg.conf file, or
to modify the existing file.')\"</label></text>"
 XORGWIZ_XML="
 <frame $(gettext 'XorgWizard')>
  <hbox>
   <text><label>$(gettext 'XorgWizard completely reconstructs the /etc/X11/xorg.conf file, and X must not be running to do this. A reboot is required, and the Wizard will run in text mode, before X is launched.')</label></text>
   <vbox>
    <button>
     <input file>/usr/local/lib/X11/mini-icons/wizard16.xpm</input>
     <action>EXIT:11</action>
    </button>
   </vbox>
  </hbox>
  <text><label>$(gettext 'NOTE: You can also run XorgWizard manually, without rebooting, by exiting from X to the commandline (see Shutdown menu) then run xorgwizard.')</label></text>
 </frame>"
fi

MAIN1="
<window title=\"$(gettext 'Xorg Video Wizard')\">
<hbox>
 <vbox>
  <text><label>\"$(gettext 'Welcome to the Puppy Linux
Xorg Video Wizard!')\"</label></text>
  ${XORGPRELIM_XML}
 </vbox>
 <vbox>
  ${XORGWIZ_XML}
  <frame $(gettext 'Edit xorg.conf')>
   <hbox>
    <text><label>$(gettext 'You can manually edit /etc/X11/xorg.conf, but note that you will need to exit from X afterward then restart X (see Shutdown menu). Click button to edit:')</label></text>
    <vbox>
     <button>
      <input file>/usr/local/lib/X11/mini-icons/mini-x.xpm</input>
      <action>EXIT:15</action>
     </button>
    </vbox>
   </hbox>
  </frame>

  <frame xvidtune>
   <hbox>
    <text><label>$(gettext 'If the screen is displaced or the width/height are wrong, xvidtune can get it right. This will modify the existing xorg.conf file. Use with caution:')</label></text>
    <vbox>
     <button>
      <input file>/usr/local/lib/X11/mini-icons/mini-x.xpm</input>
      <action>EXIT:13</action>
     </button>
    </vbox>
   </hbox>
  </frame>

  <frame $(gettext 'Mouse/keyboard Wizard')>
   <hbox>
    <text><label>$(gettext '/etc/X11/xorg.conf has generic settings for mouse and keyboard and in most cases it is recommended to leave it as-is. Instead, use the MouseKeyboardWizard:')</label></text>
    <vbox>
     <button>
      <input file>/usr/local/lib/X11/mini-icons/wizard16.xpm</input>
      <action>EXIT:16</action>
     </button>
    </vbox>
   </hbox>
  </frame>

  <frame $(gettext 'Monitor gamma calibration')>
   <hbox>
    <text><label>$(gettext 'This will adjust the monitor colors, including screen brightness.')</label></text>
    <vbox>
     <button>
      <input file>/usr/local/lib/X11/mini-icons/mini-x.xpm</input>
      <action>EXIT:17</action>
     </button>
    </vbox>
   </hbox>
  </frame>

  <frame $(gettext 'Resolution changer')>
   <hbox>
    <text><label>$(gettext 'It is possible to change screen resolutions without exiting from X:')</label></text>
    <vbox>
     <button>
      <input file>/usr/local/lib/X11/mini-icons/mini-x.xpm</input>
      <action>EXIT:18</action>
     </button>
    </vbox>
   </hbox>
  </frame>

 </vbox>
</hbox>
</window>
"


#do this code block if X is running...
if [ ! "`echo -n "$PSFND" | grep "\\.xinitrc"`" = "" ];then

 RETSTR="`echo "$MAIN1" | gtkdialog4 --stdin`"
 RETVAL="`echo "$RETSTR" | grep '^EXIT=' | cut -f 2 -d '"'`" #'geany

 case $RETVAL in
  11) #XorgWizard.
   #rm /etc/mousedevice # Dougal: any reason for this?
   . /etc/DISTRO_SPECS #120226 01micko fix for boot to desktop
   [ "$DISTRO_XORG_AUTO" = "yes" ] && sed -i "s/^DISTRO_XORG_AUTO='yes'/DISTRO_XORG_AUTO='no'/" /etc/DISTRO_SPECS #120226 temporary, fixes xorgwizard gui bug
   mv -f /etc/X11/xorg.conf /etc/X11/xorg.conf.prev 2>/dev/null
   [ -e /usr/bin/Xvesa ] && ln -sf Xvesa /usr/bin/X
   NEXTWM="`cat /etc/windowmanager`"
   echo -n "$NEXTWM" > /etc/windowmanager #this makes change permanent.
   echo -n "$NEXTWM" > /tmp/wmexitmode.txt
   echo -n "ICONWIPE" >/var/local/pup_event_icon_change_flag #111108 Karl Godt: in case Xvesa selects different resolution.  120213 path changed from /tmp (see /sbin/clean_desk_icons)
   sync
   exec killall X
   ;;
  12) #xorgconfig
   xorgcfg
   pupmessage -bg "#ff8080" -center -title "xorgcfg" "$(gettext 'Changes to /etc/X11/xorg.conf will only take effect after X is restarted.')

$(gettext 'Click OK button to restart X...')"
   exec restartwm
   ;;
  13) #xvidtune
   pupmessage -bg violet -title "$(gettext 'Xvidtune IMPORTANT HELP')" "`gettext \"If you click the 'Show' button, the adjusted settings will be what
you want permanently. After hitting the 'Quit' button, you will be
given one last chance not to make the change permanent.\"`
$(gettext 'Thus:')
`gettext \"'Show' to record the settings (for later inclusion into xorg.conf)\"`
`gettext \"'Quit' to exit Xvidtune.\"`

$(gettext 'Please note that Xvidtune does not work with all video hardware, meaning
that changing the settings will cause no change on the screen.')" &
   XMSGPID=$!
   MODELINE0="`xvidtune | grep '^"[0-9]'`" #'geanyfix.
   pupkill $XMSGPID
   if [ ! "$MODELINE0" = "" ];then
    xmessage -bg orange -title "$(gettext 'Xvidtune: Modeline')" -buttons Write:10,Quit:11 "$(gettext 'The new modeline is:')
$MODELINE0

$(gettext 'Note, you will have to restart X for it to take effect. If it messes')
`gettext \"up X, edit from commandline 'mp /etc/X11/xorg.conf' and comment-out\"`
`gettext \"the 'UseModes' line (do not delete it) in the Monitor section.\"`

`gettext \"To insert this into /etc/X11/xorg.conf, click 'Write' button...\"`
`gettext \"To exit without changing xorg.conf, click 'Quit' button...\"`"
    if [ $? -eq 10 ];then
     PATTERNA="s/.*#modes0modeline0/ ModeLine $MODELINE0 #modes0modeline0/g"
     cat /etc/X11/xorg.conf | sed -e "$PATTERNA" > /tmp/xorg.conf.new
     sync
     cat /tmp/xorg.conf.new | sed -e 's/#.*UseModes/UseModes/g' > /etc/X11/xorg.conf
     sync
    fi
   fi
   exit
   ;;
  15) #edit xorg.conf
   exec defaulttexteditor /etc/X11/xorg.conf
   ;;
  16) #mouse/keyboard wizard
   exec input-wizard
   ;;
  17) #tkgamma
   exec tkgamma
   ;;
  18) #resolution changer
   exec xrandrshell
   ;;
 esac
 exit
fi

#come here when X is not running, completely rebuild xorg.conf...
if [ -f /etc/X11/xorg.conf ];then
# echo
# echo "/etc/X11/xorg.conf exists. XorgWizard rebuilds it from scratch."
# echo -e "Hit ENTER key to quit, or type \"y\" then ENTER keys to rename"
# echo -n "xorg.conf to xorg.conf.bak and continue XorgWizard: "
# read yeahman
# if [ "$yeahman" = "" ];then
#  exit
# else
  mv -f /etc/X11/xorg.conf /etc/X11/xorg.conf.bak
# fi
fi

#comes here first time boot puppy, or whenever bootup
#and xorg.conf has been removed.

#need to create xorg.conf so that at subsequent boots, xwin will not run xorgwizard...
cp /etc/X11/xorg.conf0 /etc/X11/xorg.conf

if [ ! $1 ];then #100430
 mv -f /usr/lib/x/drivers-backup/* /usr/lib/xorg/modules/drivers/ 2>/dev/null
fi

MSGwelcome="$(gettext 'Welcome to the Puppy Video Wizard!')
"
#100401 if xorgwizard started with any passed param, bypass initial window...
if [ ! $1 ];then
 if [ "`which Xvesa`" != "" ];then #091125
  MSGwelcome="" #100820
  #If video adapter would hang Xvesa, tell user and allow only Xorg.
  if [ -s /tmp/ddcprobeoem.txt ] || grep -q -f /etc/xorgoverrides /tmp/ddcprobe.txt 2>/dev/null;then    #Xvesa hanger encountered
   dialog --colors --title "$(gettext 'Puppy Video Wizard')" --yes-label "Xorg" --no-label "$(gettext 'Commandline')" --yesno "$(gettext 'Welcome to the Puppy Video Wizard!
Puppy has two X servers (to run Puppy in graphics mode):')
$(gettext 'Xvesa: A very small and simple "Kdrive" X server.')
$(gettext 'Xorg:  A very large and sophisticated X server, with many hardware-
       specific drivers for optimum performance (note: there is also
       a generic driver named "vesa", not the same as Xvesa!)')
\Z1$(gettext 'Your video hardware would cause Xvesa to freeze Puppy, so your options are to use Xorg or exit to the command prompt.')\Z0

$(gettext 'It is recommended that you choose the <Xorg> button now, but some
quirky video hardware does not work with Xorg, in which case you must operate from the command line.  Make sure you have at least 96 MB of RAM+swap, for Xorg to function.')

$(gettext 'Press ENTER for Xorg...')
$(gettext 'Press TAB (or right-arrow) key then ENTER key to use the command line...')\Zn" 0 0
   [ ! $? -eq 0 ] && exit
  else   #normal video adapter
   #offer to drop out to Xvesa...
   dialog --colors --title "$(gettext 'Puppy Video Wizard')" --yes-label "Xorg" --no-label "Xvesa" --yesno "$(gettext 'Welcome to the Puppy Video Wizard!
Puppy has two X servers (to run Puppy in graphics mode):')
$(gettext 'Xvesa: A very small and simple "Kdrive" generic X server.')
$(gettext 'Xorg:  A very large and sophisticated X server, with many hardware-
       specific drivers for optimum performance (note: there is also
       a generic driver named "vesa", not the same as Xvesa!)')
$(gettext 'Xvesa works flawlessly on most video hardware, simple to configure,
but one major disadvantage is that screen refresh rate is fixed.
Also, Xvesa has limited support for input devices, and lacks features
like hardware-acceleration (video may be jerky on slow PCs).')

$(gettext 'It is recommended that you choose the <Xorg> button now, but some
quirky video hardware does not work with Xorg, in which case you can
run this Wizard again and choose the <Xvesa> button.')

$(gettext 'Press ENTER for Xorg...')
$(gettext 'Press TAB (or right-arrow) key then ENTER key for Xvesa...')\Zn" 0 0
   STATUS=$?  #v3.99
   [ $STATUS -eq -1 ] && exit   #v3.99 ESC to exit, same as above dialogs
   if [ $STATUS -eq 1 ];then   #v3.99 Xvesa selected
    ln -sf Xvesa /usr/bin/X #Xvesa is now the default X server.
    #when start xorgwizard from commandline, it messes up xorg.conf...
    if [ -f /etc/X11/xorg.conf ];then
     if [ -f /etc/X11/xorg.conf.bak ];then
      #basic test to see that file has right stuff in it...
      if ! grep -F -q 'VertRefresh' /etc/X11/xorg.conf ;then
       cp -f /etc/X11/xorg.conf.bak /etc/X11/xorg.conf
      fi
     fi
    fi
    #....Xvesa Wizard will run automatically if no /etc/videomode.
    exit #w478
   fi
  fi   #v3.99
 fi
 #100820 did not choose Xvesa, or no Xvesa, now offer Xorg choices...
 FCHOOSE='nouveau'
 [ -f /usr/lib/xorg/modules/drivers/i810_drv.so ] && FCHOOSE='i810'
 [ -f /usr/lib/x/drivers-alternate/i810_drv.so ] && FCHOOSE='i810'
 case $FCHOOSE in #100820
  i810)
   MSGchoose="$(gettext 'EX: There are two drivers for Intel video, "intel" and "i810" and it may 
be necessary to choose one now as probe of the wrong one may hang the PC.')"
  ;;
  *)
   MSGchoose="$(gettext 'EX: There are two drivers for Nvidia video, "nv" and "nouveau" and it may
be necessary to choose one now as probe of the wrong one may hang the PC.')"
  ;;
 esac
 dialog --colors --extra-button --title "$(gettext 'Puppy Video Wizard')" --ok-label "$(gettext 'Probe')" --cancel-label "vesa" --extra-label "$(gettext 'Choose')" --yesno "${MSGwelcome}`gettext \"'Xorg' (or just 'X') is software that will run Puppy in graphics mode,
that is, display a desktop with windows, mouse, etc. Xorg has a dozen
or so drivers for specific video hardware, and if you choose the <Probe>
button then the Wizard will attempt to determine the correct driver for
your video hardware.\"`

`gettext \"With some hardware there is no specific driver, or maybe there is one
but it doesn't work (or doesn't work properly), in which case you can
fall back to the generic 'vesa' driver. The Wizard will offer to fall
back to the vesa driver later, but if you know already that you have
to use vesa, then you may choose it now...\"`

$(gettext 'If you know that some other driver works, <Choose> will select it now.')
${MSGchoose}

$(gettext 'Press ENTER key to probe for correct hardware-specific driver...')
$(gettext 'Or, TAB then ENTER to choose another driver...')
$(gettext 'Or, TAB, TAB then ENTER to select the generic vesa driver...')" 0 0
 STATUS=$?
 [ $STATUS -lt 0 ] && exit
 ALLDRIVERS="`ls -1 /usr/lib/xorg/modules/drivers | grep 'so$'`"
 if [ $STATUS -eq 0 ];then #Probe selected
  if [ "$ALLDRIVERS" = "vesa_drv.so" ];then
   cp -a -f --remove-destination /usr/lib/x/drivers-backup/* /usr/lib/xorg/modules/drivers/
   rm -f /usr/lib/x/drivers-backup/*
  fi
 else
  if [ $STATUS -eq 3 ];then #100401 choose. 100430 improved... 100820 improved...
#   ALLDRVLIST="`ls -1 /usr/lib/xorg/modules/drivers /usr/lib/x/drivers-alternate /usr/lib/x/drivers-backup 2>/dev/null | grep -E '^[a-zA-Z0-9].*_drv.so' | cut -f 1 -d '_' | tr '\n' ' '`"
#   dialog --title "Xorg Video Wizard" --inputbox "Here are all the Xorg drivers:
#${ALLDRVLIST}
#
#Type the name of the one you want to use and press ENTER:" 0 0 2>/tmp/tagchosendrv.txt
   ALLDRVLIST="`ls -1 /usr/lib/xorg/modules/drivers /usr/lib/x/drivers-alternate /usr/lib/x/drivers-backup 2>/dev/null | grep -E '^[a-zA-Z0-9].*_drv.so' | cut -f 1 -d '_' | sort -u | tr '\n' ' '`"
   drvLIST=""
   for ONEDRV in $ALLDRVLIST
   do
    if [ -h /usr/lib/xorg/modules/drivers/$ONEDRV_drv.so ];then #ignore hyperlinks
     #[ -h /usr/lib/xorg/modules/drivers/i810_drv.so ] && rm -f /usr/lib/xorg/modules/drivers/i810_drv.so #should not be there.
     continue
    fi
    case $ONEDRV in
     ati|radeon|radeonhd|r128|mach64)
      drvLIST="${drvLIST}
${ONEDRV} \"ATI\""
     ;;
     nv|nouveau|nvidia)
      drvLIST="${drvLIST}
${ONEDRV} \"Nvidia\""
     ;;
     intel|i810|i740)
      drvLIST="${drvLIST}
${ONEDRV} \"Intel\""
     ;;
     rendition)
      drvLIST="${drvLIST}
${ONEDRV} \"Rendition/Micron\""
     ;;
     amd)
      drvLIST="${drvLIST}
${ONEDRV} \"AMD\""
     ;;
     apm)
      drvLIST="${drvLIST}
${ONEDRV} \"Alliance ProMotion\""
     ;;
     ark)
      drvLIST="${drvLIST}
${ONEDRV} \"Ark Logic\""
     ;;
     ast)
      drvLIST="${drvLIST}
${ONEDRV} \"ASPEED Technology\""
     ;;
     chips)
      drvLIST="${drvLIST}
${ONEDRV} \"Chips and Technologies\""
     ;;
     cirrus)
      drvLIST="${drvLIST}
${ONEDRV} \"Cirrus Logic\""
     ;;
     cyrix)
      drvLIST="${drvLIST}
${ONEDRV} \"Cyrix MediaGX\""
     ;;
     geode)
      drvLIST="${drvLIST}
${ONEDRV} \"AMD Geode GX/LX\""
     ;;
     glide)
      drvLIST="${drvLIST}
${ONEDRV} \"Glide2x\""
     ;;
     glint)
      drvLIST="${drvLIST}
${ONEDRV} \"GLINT/Permedia/3Dlabs\""
     ;;
     i128)
      drvLIST="${drvLIST}
${ONEDRV} \"Number 9 I128\""
     ;;
     imstt)
      drvLIST="${drvLIST}
${ONEDRV} \"Integrated Micro Solutions\""
     ;;
     mga)
      drvLIST="${drvLIST}
${ONEDRV} \"Matrox\""
     ;;
     neomagic)
      drvLIST="${drvLIST}
${ONEDRV} \"Neomagic\""
     ;;
     newport)
      drvLIST="${drvLIST}
${ONEDRV} \"Newport\""
     ;;
     nsc)
      drvLIST="${drvLIST}
${ONEDRV} \"National Semiconductor\""
     ;;
     openchrome)
      drvLIST="${drvLIST}
${ONEDRV} \"VIA/S3G UniChrome/Chrome\""
     ;;
     rdc)
      drvLIST="${drvLIST}
${ONEDRV} \"RDC Vortex86mx\""
     ;;
     s3|s3virge|savage)
      drvLIST="${drvLIST}
${ONEDRV} \"S3\""
     ;;
     siliconmotion)
      drvLIST="${drvLIST}
${ONEDRV} \"Silicon Motion\""
     ;;
     sis|xgi|xgixp)
      drvLIST="${drvLIST}
${ONEDRV} \"SIS and XGI\""
     ;;
     tdfx)
      drvLIST="${drvLIST}
${ONEDRV} \"3Dfx\""
     ;;
     tga)
      drvLIST="${drvLIST}
${ONEDRV} \"TGA\""
     ;;
     trident)
      drvLIST="${drvLIST}
${ONEDRV} \"Trident\""
     ;;
     tseng)
      drvLIST="${drvLIST}
${ONEDRV} \"Tseng Labs\""
     ;;
     voodoo)
      drvLIST="${drvLIST}
${ONEDRV} \"Voodoo\""
     ;;
     vesa)
      drvLIST="${drvLIST}
${ONEDRV} \"VESA generic driver\""
     ;;
     ztv)
      drvLIST="${drvLIST}
${ONEDRV} \"AMD Geode\""
     ;;
     *)
      drvLIST="${drvLIST}
${ONEDRV} ${ONEDRV}"
     ;;
    esac
   done
   drvLIST="`echo "$drvLIST" | sort --key=2 --field-separator=" " | tr '\n' ' '`"
   drvDLG="dialog --title \"$(gettext 'Xorg Video Wizard')\" --menu \"$(gettext 'Choose an Xorg driver (down-arrow or up-arrow then ENTER):')\" 0 0 0 ${drvLIST}"
   eval $drvDLG 2>/tmp/tagchosendrv.txt

   if [ $? -eq 0 ];then
    CHOSENDRV="`cat /tmp/tagchosendrv.txt`"
    alternate_driver_func $CHOSENDRV
    exec xorgwizard $CHOSENDRV ###RESTART### note, passed param causes bypass of the initial window.
   else
    exec xorgwizard ###RESTART###
   fi
    
  else #Vesa selected
   mv -f /usr/lib/xorg/modules/drivers/* /usr/lib/x/drivers-backup/
   cp -f /usr/lib/x/drivers-backup/vesa_drv.so /usr/lib/xorg/modules/drivers/
  fi
 fi
fi

#resolution changer uses this. it must be removed here...
rm -f /etc/xrandrindex 2> /dev/null

ln -sf Xorg /usr/bin/X

# Dougal: moved echo to below xorg probing, since loop isn't slow anymore...
clear
echo -en "\\033[1;35m" #34=blue, 33=yellow, 32=green, 31=red, 35=purple, 36=aquablue, 38=black.
echo -n "$(gettext 'Probing video hardware, please wait...')"
echo -e "\\033[0;39m"
#autoprobe...
Xorg -configure > /tmp/xorgprobe.txt 2>&1
#... config in /root/xorg.conf.new


##### Below commented out by Dougal:

#echo '.' #progress indicator completion.
#CARD0DRIVER="`cat /tmp/CARD0DRIVER`"
#CARD0VENDOR="`cat /tmp/CARD0VENDOR`"
#CARD0BOARD="`cat /tmp/CARD0BOARD`"
#HORIZSYNC0="`cat /tmp/HORIZSYNC0`"
#VERTREFRESH0="`cat /tmp/VERTREFRESH0`"
##now have an almost-working xorg.conf, missing Screen section.
###############################END BIG ITERATION###########################


## My (Dougal) alternate code:
######################################################################
#  Rather than pipe data to "while read", I use "here document" (at bottom),
#+ so that the loop doesn't run in a subshell -- hence variables 
#+ (like HORIZSYNC0) are retained after the loop has ended...
while read ASECTION
do
 # this (outer) loop recieves a line containing **an entire section**
 # filter out entire sections we don't want
 case $ASECTION in
  *Section?\"Screen\"*)
   break #Screen section is created further down.
  ;;
  *Section?\"Files\"*|*Section?\"Module\"*|*Section?\"ServerFlags\"*)
   continue #these sections pre-created in /etc/X11/xorg.conf0
  ;;
 esac
 #  Params are retained for the entire ASECTION loop.
 #  I use TEMPSECTION since BASH is slow with file i/o -- so echo
 #+ only once for each section.
 #  Tabs at beginning of lines are lost when reading, so I add them
 #+ where appropriate (i.e. before every line except for Section borders).
 #+ ("\n"=newline ; "\t"=tab)
 IDENTIFIER="" ; XSECTION="" ; TEMPSECTION=""
 while read ALINE
 do
  case "$ALINE" in 
   EndSection*) #120318 improved...
    if [ "$XSECTION" = "InputDevice" -a "$IDENTIFIER" = "Keyboard0" ] ; then
     TEMPSECTION="$TEMPSECTION
	Option      \"XkbRules\" \"xorg\"
	Option      \"XkbModel\" \"${XKBMODEL}\"
	Option      \"XkbLayout\" \"${XKBLAYOUT}\" #xkeymap0"
	if [ "$XKBVARIANT" ];then
	 TEMPSECTION="$TEMPSECTION
	Option         \"XkbVariant\" \"$XKBVARIANT\""
	fi
    elif [ "$XSECTION" = "Monitor" -a "$IDENTIFIER" = "Monitor0" ] ; then
     TEMPSECTION="$TEMPSECTION
	HorizSync    HORIZSYNC0
	VertRefresh  VERTREFRESH0
	#UseModes     \"Modes0\" #monitor0usemodes
	Option      \"PreferredMode\" \"PREFERREDMODE0\"
	$ALINE
	
Section \"Modes\"
	Identifier \"Modes0\"
	#modes0modeline0
EndSection"
     #v3.98 rerwin - added preferredmode line, after usemodes line.
     continue # we added the line before the "Modes" section, so continue
    fi
    TEMPSECTION="$TEMPSECTION\n$ALINE"
    continue # just added line -- no need to get to bottom
    ;;
   Section?\"*) XSECTION=${ALINE%\"*} ; XSECTION=${XSECTION##*\"}
    TEMPSECTION="\n$ALINE" 
    continue # just added line -- no need to get to bottom
    ;;
   *Identifier*) IDENTIFIER=${ALINE%\"*} ; IDENTIFIER=${IDENTIFIER##*\"} 
    ;; 
   *\"ZAxisMapping\"*) continue 
    ;;
   *HorizSync*[0-9]*) set -- $ALINE ; HORIZSYNC0="$2$3$4" ; continue
    ;; 
   *VertRefresh*[0-9]*) set -- $ALINE ; VERTREFRESH0="$2$3$4" ; continue
    ;;
   *Option*\"Protocol\"?\"auto\"*) 
    case "`cat /etc/mousedevice 2>/dev/null`" in 
     input/mice) TEMPSECTION="$TEMPSECTION
	Option	    \"Protocol\" \"IMPS/2\" #mouse0protocol" 
	  continue
	  ;;
     *ttyS*) TEMPSECTION="$TEMPSECTION
	Option	    \"Protocol\" \"Microsoft\" #mouse0protocol"
	  continue
	  ;;
     *) TEMPSECTION="$TEMPSECTION
	Option	    \"Protocol\" \"auto\" #mouse0protocol"
	  continue
	  ;;
    esac
    ;;
   */dev/mouse*|*/dev/input/mice*) #v2.21
    TEMPSECTION="$TEMPSECTION\n\t$ALINE"
    case "`cat /etc/xextraoptions`" in 
     *2button*) BLA="" ;;
	 *) BLA="#" ;;
	esac
	TEMPSECTION="$TEMPSECTION
	${BLA}Option      \"Emulate3Buttons\"
	${BLA}Option      \"Emulate3Timeout\" \"50\""
	if [ "`cat /etc/mousebuttons`" = "5" ] ; then #scrollwheel
	 BLA=""
	else
	 BLA="#"
	fi
    TEMPSECTION="$TEMPSECTION
	${BLA}Option      \"ZAxisMapping\" \"4 5\" #scrollwheel"
	continue # we added the line at the beginning
    ;;	 
  esac
  
  if [ "$XSECTION" = "Device" -a "$IDENTIFIER" = "Card0" ] ; then
   FBODY=${ALINE%\"*} ; FBODY=${FBODY##*\"}
   case "$ALINE" in 
    *Driver*) CARD0DRIVER="$FBODY" ; ALINE="$ALINE #card0driver" ;;
    *VendorName*) CARD0VENDOR="$FBODY" ;;
    *BoardName*) CARD0BOARD="$FBODY" ;;
    *Screen1*Right?Of*Screen0*) ALINE="#$ALINE" ;;
   esac
  fi

  #091119 Comment out any lines for screens beside Screen0
  ALINE="$(echo "$ALINE" | sed 's/\s*Screen\s*[1-9]*\s*"Screen[1-9]"/#&/')"

  # add line to section (if we've come this far...)
  TEMPSECTION="$TEMPSECTION\n\t$ALINE"
 done <<_END2
$(echo "$ASECTION" | tr '%' '\n')
_END2
echo -e "$TEMPSECTION" | sed -e 's/_PERCENTCHAR_/%/g' >> /etc/X11/xorg.conf #110701
sync
done <<_END1
$(cat /root/xorg.conf.new | sed -e 's/%/_PERCENTCHAR_/g' | tr '\n' '%' | sed 's/EndSection/EndSection\n/g' )
_END1
###################################################################

#v2.21 quick hack...
sed -e 's%/dev/input/mice%/dev/mouse%'  /etc/X11/xorg.conf >/tmp/xorgconfmousefix
mv -f /tmp/xorgconfmousefix /etc/X11/xorg.conf

#echo "Probing the video card and monitor..."
#code below is not distinguishing multiple cards/monitors...
HORIZSYNC="$HORIZSYNC0"
VERTREFRESH="$VERTREFRESH0"

#want to choose a resolution and color-depth...
##sometimes get bogus '1x' or '0x' pixel horiz resolution...
#DDCPROBE="`ddcprobe | grep -v 'timing: [0123456789]x'`"
#DDCPROBE="`ddcprobe`"
ddcprobe >/tmp/ddcprobe.txt
#weird (ddcprobe is very weird), on some hardware, edid monitor probe fails
#every alternate run of ddcprobe...
case "`cat /tmp/ddcprobe.txt`" in *edidfail*)
 sleep 1
 ddcprobe >/tmp/ddcprobe.txt
 ;;
esac

#v3.93 rerwin: For some Tecra and Portege laptops, avoid an Xvesa hang by skipping "listmodes"
#v3.96 added trident line...
#v3.98 added more CYBER lines & corrected case
XVESALISTOK="yes"
TIMINGOK="yes"
if [ -s /tmp/ddcprobeoem.txt ];then   #v3.99 begin
 if [ ! -f /etc/xorgoverrides ] || ! grep -q -f /tmp/ddcprobeoem.txt /etc/xorgoverrides;then
  echo "`cat /tmp/ddcprobeoem.txt`" >> /etc/xorgoverrides  #append new signature if user canceled out from hung Xvesa
  sync
 fi
fi
if [ -f /etc/xorgoverrides ] && grep -q -f /etc/xorgoverrides /tmp/ddcprobe.txt;then   #v3.99 end
 #HORIZSYNC=""
 #VERTREFRESH=""
 XVESALISTOK="no" #'Xvesa -listmodes' hangs.
 TIMINGOK="no"    #ddcprobe returns incomplete 'timing:' info (res's missing).
 [ "`grep 'mode: 640x480x64k' /tmp/ddcprobe.txt`" = "" ] && echo 'mode: 640x480x64k' >> /tmp/ddcprobe.txt
 [ "`grep 'mode: 640x480x16m' /tmp/ddcprobe.txt`" = "" ] && echo 'mode: 640x480x16m' >> /tmp/ddcprobe.txt
 [ "`grep 'mode: 800x600x64k' /tmp/ddcprobe.txt`" = "" ] && echo 'mode: 800x600x64k' >> /tmp/ddcprobe.txt
 [ "`grep 'mode: 800x600x16m' /tmp/ddcprobe.txt`" = "" ] && echo 'mode: 800x600x16m' >> /tmp/ddcprobe.txt
 [ "`grep 'mode: 1024x768x64k' /tmp/ddcprobe.txt`" = "" ] && echo 'mode: 1024x768x64k' >> /tmp/ddcprobe.txt
 [ "`grep 'mode: 1024x768x16m' /tmp/ddcprobe.txt`" = "" ] && echo 'mode: 1024x768x16m' >> /tmp/ddcprobe.txt
fi   #v3.93 end

#v3.94 detect if a Classmate PC laptop with 800x480 screen...
#if [ "`grep 'edidfail' /tmp/ddcprobe.txt`" != "" ];then
# if [ "`cat /tmp/ddcprobe.txt | tr -s ' ' | grep 'oem: Intel(r)915GM/910ML/915MS Graphics'`" != "" ];then
#  if [ "`dmesg | grep 'CPU0: Intel(R) Celeron(R) M processor          900MHz'`" != "" ];then
#   if [ "`dmesg | grep 'uDiskOnChip'`" != "" ];then
#    #yep, looks like this is a Classmate model with 800x480...
#    echo 'timing: 800x480@60' >> /tmp/ddcprobe.txt
#   fi
#  fi
# fi
#fi
#v3.97 improved method: CM=Classmate, 915=chip 10=generation#...
[ "`dmidecode -s bios-version | grep '^CM91510'`" != "" ] && echo 'timing: 800x480@60' >> /tmp/ddcprobe.txt
#v3.95 recognise more special screens...
DMIDECODE="`dmidecode`"
#recognise EeePC Asus laptop...
[ "`echo "$DMIDECODE" | grep 'Product Name: 701'`" != "" ] && [ "`echo "$DMIDECODE" | grep 'Serial Number: EeePC'`" != "" ] && echo 'timing: 800x480@60' >> /tmp/ddcprobe.txt


#modes supported by card...
CARDCHOICES=""
if [ -e /usr/bin/Xvesa -a "$XVESALISTOK" = "yes" ];then #format of each line: 1024x768x16
 echo -e $(gettext '\nIf initialization freezes here, press ctrl-c and type "xorgwizard",\nselect "Xorg", choose monitor type and choose video mode.')   #v3.99
 grep '^oem:' /tmp/ddcprobe.txt > /tmp/ddcprobeoem.txt   #v3.99 current adapter signature
 Xvesa -listmodes 2>&1 | cut -f 2 -d ' ' | grep --extended-regexp 'x16$|x24$' | sort --field-separator=x --numeric-sort > /tmp/Xmodes.txt
 rm /tmp/ddcprobeoem.txt  #v3.99 didn't hang in Xvesa, so delete signature
else
 #the vesa 'mode:' lines returned by ddcprobe are very limited...
 grep '^mode:' /tmp/ddcprobe.txt | grep -E 'x64k|x16m'| cut -f 2 -d ' ' | sed -e 's/x64k/x16/g ; s/x16m/x24/g' > /tmp/Xmodes.txt
fi
sync
CARDCHOICES="`cat /tmp/Xmodes.txt`"

#frequencies supported by monitor...
#Xorg probe may already have got this information...
if [ "$HORIZSYNC" = "" -o "$VERTREFRESH" = "" ];then
 #one or both no good, so set both no good...
 HORIZSYNC=""
 VERTREFRESH=""
else
 #both have values, but are they 'valid'? Xorg probe sometimes returns bogus values...
 BOGUSVAL="no"
 for ONEVAL in `echo -n "$HORIZSYNC" | tr '\-' ' ' | tr ',' ' ' | tr -s ' '`
 do
  [ ${ONEVAL%.*} -lt 10 ] && BOGUSVAL="yes"
  [ ${ONEVAL%.*} -gt 200 ] && BOGUSVAL="yes"
 done
 for ONEVAL in `echo -n "$VERTREFRESH" | tr '\-' ' ' | tr ',' ' ' | tr -s ' '`
 do
  [ ${ONEVAL%.*} -lt 10 ] && BOGUSVAL="yes"
  [ ${ONEVAL%.*} -gt 200 ] && BOGUSVAL="yes"
 done
 if [ "$BOGUSVAL" = "yes" ];then
  #one or both no good, so set both no good...
  HORIZSYNC=""
  VERTREFRESH=""
 fi
fi

MONCHOICES=""
MONCUTXY=""
if [ "$TIMINGOK" = "yes" ];then #v3.93
 #modes supported by monitor... format of each line: 1024x768@75
 #MONCHOICES="`echo "$DDCPROBE" | grep 'timing:' | cut -f 2 -d ' ' | grep -v 'Apple' | grep -v '8514A' | grep -v '(XGA2)' | sort -u`"
 #get too many weird resolutions, maybe better just only allow these...
 MONCHOICES="`grep -F 'timing:' /tmp/ddcprobe.txt | grep -E -v 'Apple|8514A|Mac II|\(XGA2\)' | grep -E ' 640x480@| 800x480@| 800x600@| 1024x600@| 1024x768@| 1280x768@| 1280x800@| 1280x1024@| 1366x768@| 1400x1050@| 1440x900@| 1600x900@| 1600x1200@| 1680x1050@| 1920x1080@| 1920x1200@' | cut -f 2 -d ' ' | sort -u`"
 #no, better if reject known weird resolutions...
 #MONCHOICES="`echo "$DDCPROBE" | grep 'timing:' | cut -f 2 -d ' ' | grep -v --extended-regexp 'Apple|8514A|XGA2|720x400|832x624|256x256|248x248|632x632|280x280' | sort -u`"
 #...no, ddcprobe is buggy, returns random resolutions, cannot screen all out!
 MONCUTXY="`echo "$MONCHOICES" | cut -f 1 -d '@' | sort -u`" #each line: 1024x768
fi

#if Xorg probe failed to determine monitor freq, try ddcprobe...
if [ "$HORIZSYNC" = "" -o "$VERTREFRESH" = "" ];then
 MONFREQ="`grep -F 'monitorrange:' /tmp/ddcprobe.txt | cut -f 2-10 -d ' '`"
 HORIZSYNC="`echo -n "$MONFREQ" | cut -f 1 -d ','`"
 VERTREFRESH="`echo -n "$MONFREQ" | cut -f 2 -d ',' | tr -d ' '`"
fi

#ddcprobe on my laptop returns one 'timing:' line but no 'monitorrange:', so
#can fall back to calculating freqs...
if [ ! "$MONCHOICES" = "" ];then
 ##hmmm, maybe always use the freqs of the 'timing:' lines rather than the
 ##'monitorrange:' as it always seems to be too high...
 if [ "$HORIZSYNC" = "" -o "$VERTREFRESH" = "" ];then
  UHORIZSYNC=32    #start with mediocre values.
  UVERTREFRESH=60  # /
  LHORIZSYNC=30    # /
  LVERTREFRESH=56  # /
  for ONECH in $MONCHOICES #format: 1024x768@75
  do
   ONEVERT=${ONECH#*@}
   ONEX=${ONECH%x*}
   ONEY=${ONECH#*x} ; ONEY=${ONEY%@*}
   ONEHORIZ=`gtf $ONEX $ONEY $ONEVERT | grep -o 'hsync:.*' | cut -f 2 -d ' ' | cut -f 1 -d '.'`
   [ $ONEVERT -lt $LVERTREFRESH ] && LVERTREFRESH=$ONEVERT
   [ $ONEHORIZ -gt $UHORIZSYNC ] && UHORIZSYNC=$ONEHORIZ
   #it seems ddcprobe truncates any fractional part off vertrefresh...
   ONEVERT=`expr $ONEVERT + 1`
   ONEHORIZ=`gtf $ONEX $ONEY $ONEVERT | grep -o 'hsync:.*' | cut -f 2 -d ' ' | cut -f 1 -d '.'`
   [ $ONEVERT -gt $UVERTREFRESH ] && UVERTREFRESH=$ONEVERT
   [ $ONEHORIZ -lt $LHORIZSYNC ] && LHORIZSYNC=$ONEHORIZ
  done
  #v3.93 hmmm, above still can round down too much, add 2...
  UHORIZSYNC=`expr $UHORIZSYNC + 2`
  HORIZSYNC="${LHORIZSYNC}-${UHORIZSYNC}"
  VERTREFRESH="${LVERTREFRESH}-${UVERTREFRESH}"
 fi
fi

##091124 try another fallback...
#if [ "$HORIZSYNC" = "" -o "$VERTREFRESH" = "" ];then
# MONCHOICES="`grep '^dtiming: ' /tmp/ddcprobe.txt | cut -f 2 -d ' ' | grep '@' | tail -n 1`" #ex: 1280x800@59
# if [ "$MONCHOICES" ];then
#  ONEX="`echo -n "$MONCHOICES" | cut -f 1 -d 'x'`"
#  ONEY="`echo -n "$MONCHOICES" | cut -f 2 -d 'x' | cut -f 1 -d '@'`"
#  VERTREFRESH=`echo -n "$MONCHOICES" | cut -f 2 -d '@'`
#  HORIZSYNC=`gtf $ONEX $ONEY $VERTREFRESH | grep -o 'hsync:.*' | cut -f 2 -d ' ' | cut -f 1 -d '.'`
#  MONCUTXY="${ONEX}x${ONEY}"
# fi
#fi

RECMODE="800x600x16" #default recommended mode.

#if ddcprobe also failed, have to ask monitor type...
if [ "$HORIZSYNC" = "" -o "$VERTREFRESH" = "" ];then #"" if monitor not plug-n-play.
 ## Dougal: (v2.16??) removed MONTYPES param, added case-structure below
 ##  Dougal: modified formatting of list: old tag format used to give problems, 
 ##+ since we had the same tag for different options! (eg. "h31.5-90v60")
 MONCHOICES=""
 MONCUTXY=""
 while [ 1 ];do
  #need a dialog, ask generic monitor type... 100510 fix column alignment...
  dialog --no-collapse --no-cancel --title "$(gettext 'Puppy Video Wizard')" --menu "`gettext \"Automatic probing of your monitor was unsuccessful, so you now need\nto choose from a list of generic monitor types.\nChoose the highest specification that describes your monitor.\nLCD: Liquid Crystal Display.\nCRT: Cathode Ray Tube (normal monitor).\nChoose \"Z\" if you have the monitor user manual, and it has the\nhorizontal and vertical frequency specifications.\nDOWN-ARROW to highlight choice, ENTER key to finish...\"`"  0 0 0 \
 "A"  "h31.5v40-70      LCD Panel 640x480" \
 "B"  "h31.5-37v40-70   LCD Panel 800x600" \
 "B2" "h31.5-90v60      LCD Panel 1024x600" \
 "C"  "h31.5-48.5v40-70 LCD Panel 1024x768" \
 "D"  "h31.5-90v60      LCD Panel 1280x800" \
 "E"  "h31.5-67v50-75   LCD Panel 1280x1024" \
 "F"  "h31.5-90v60      LCD Panel 1366x768" \
 "G"  "h31.5-90v59-75   LCD Panel 1400x1050" \
 "H"  "h31.5-100v59-75  LCD Panel 1440x900" \
 "I"  "h31.5-90v60      LCD Panel 1600x1200" \
 "J"  "h31.5-90v60      LCD Panel 1680x1050" \
 "K"  "h30-68v67        LCD HDTV  1920x1080" \
 "L"  "h31.5-90v60      LCD Panel 1920x1200" \
 "M"  "h31.5v50-61      CRT 640x480" \
 "N"  "h31.5-35v50-61   CRT 800x600 (old 14inch monitor)" \
 "O"  "h31.5-48.5v56-72 CRT 1024x768 (basic 15inch monitor)" \
 "P"  "h31.5-79v50-90   CRT 1280x1024 (basic 17inch monitor)" \
 "Q"  "h31.5-90v50-90   CRT 1400x1050" \
 "R"  "h31.5-94v50-90   CRT 1600x1200" \
 "Z" "$(gettext 'SELECT THIS IF YOU KNOW MONITOR FREQUENCY SPECS')" \
  2>/tmp/taggen.txt
  CHOICE="`cat /tmp/taggen.txt 2>/dev/null`"
  [ "$CHOICE" = "" ] && continue
  ## Dougal: use case-structure for setting params -- safer than the old way
  ## (not sure why Barry only uses 16-bit, maybe worth improving?)
  case "$CHOICE" in
   A) # "h31.5v40-70		LCD Panel 640x480"
     RECMODE="640x480x16"
     HORIZSYNC="31.5"
     VERTREFRESH="40-70"
     ;;
   B) # "h31.5-37v40-70		LCD Panel 800x600"
     RECMODE="800x600x16"
     HORIZSYNC="31.5-37"
     VERTREFRESH="40-70"
     ;;
   B2) # "h31.5-90v60		LCD Panel 1024x600"
     RECMODE="1024x600x16"
     HORIZSYNC="31.5-90"
     VERTREFRESH="60"
     ;;
   C) # "h31.5-48.5v40-70	LCD Panel 1024x768"
     RECMODE="1024x768x16"
     HORIZSYNC="31.5-48.5"
     VERTREFRESH="40-70"
     ;;
   D) # "h31.5-90v60		LCD Panel 1280x800"
     RECMODE="1280x800x16"
     HORIZSYNC="31.5-90"
     VERTREFRESH="60"
     ;;
   E) # "h31.5-67v50-75		LCD Panel 1280x1024"
     RECMODE="1280x1024x16"
     HORIZSYNC="31.5-67"
     VERTREFRESH="50-75"
     ;;
   F) # "h31.5-90v60		LCD Panel 1366x768"
     RECMODE="1366x768x16"
     HORIZSYNC="31.5-90"
     VERTREFRESH="60"
     ;;
   G) # "h31.5-90v59-75		LCD Panel 1400x1050"
     RECMODE="1400x1050x16"
     HORIZSYNC="31.5-90"
     VERTREFRESH="59-75"
     ;;
   H) # "h31.5-100v59-75	LCD Panel 1440x900"
     RECMODE="1440x900x16"
     HORIZSYNC="31.5-100"
     VERTREFRESH="59-75"
     ;;
   I) # "h31.5-90v60		LCD Panel 1600x1200"
     RECMODE="1600x1200x16"
     HORIZSYNC="31.5-90"
     VERTREFRESH="60"
     ;;
   J) # "h31.5-90v60		LCD Panel 1680x1050"
     RECMODE="1680x1050x16"
     HORIZSYNC="31.5-90"
     VERTREFRESH="60"
     ;;
   K) # "h30-68v67		LCD HDTV  1920x1080"
     RECMODE="1920x1080x16"
     HORIZSYNC="30-68"
     VERTREFRESH="67"
     ;;
   L) # "h31.5-90v60		LCD Panel 1920x1200"
     RECMODE="1920x1200x16"
     HORIZSYNC="31.5-90"
     VERTREFRESH="60"
     ;;
   M) # "h31.5v50-61		CRT 640x480"
     RECMODE="640x480x16"
     HORIZSYNC="31.5"
     VERTREFRESH="50-61"
     ;;
   N) # "h31.5-35v50-61		CRT 800x600 (old 14inch monitor)"
     RECMODE="800x600x16"
     HORIZSYNC="31.5-35"
     VERTREFRESH="50-61"
     ;;
   O) # "h31.5-48.5v56-72	CRT 1024x768 (basic 15inch monitor)"
     RECMODE="1024x768x16"
     HORIZSYNC="31.5-48.5"
     VERTREFRESH="56-72"
     ;;
   P) # "h31.5-79v50-90		CRT 1280x1024 (basic 17inch monitor)"
     RECMODE="1280x1024x16"
     HORIZSYNC="31.5-79"
     VERTREFRESH="50-90"
     ;;
   Q) # "h31.5-90v50-90		CRT 1400x1050"
     RECMODE="1400x1050x16"
     HORIZSYNC="31.5-90"
     VERTREFRESH="50-90"
     ;;
   R) # "h31.5-94v50-90		CRT 1600x1200"
     RECMODE="1600x1200x16"
     HORIZSYNC="31.5-94"
     VERTREFRESH="50-90"
     ;;
   Z) # "SELECT THIS IF YOU KNOW MONITOR FREQUENCY SPECS"
     dialog --title "$(gettext 'Xorg Video Wizard')" --inputbox "$(gettext 'Please enter the horizontal frequency range of the monitor, in KHz. An example is given:')" 0 0 "31.5-48.5" 2>/tmp/taghoriz.txt
     dialog --title "$(gettext 'Xorg Video Wizard')" --inputbox "$(gettext 'Please enter the vertical frequency range of the monitor, in Hz. An example is given:')" 0 0 "56-72" 2>/tmp/tagvert.txt
     HORIZSYNC="`cat /tmp/taghoriz.txt 2>/dev/null`"
     VERTREFRESH="`cat /tmp/tagvert.txt 2>/dev/null`"
     [ "$HORIZSYNC" = "" ] && continue
     [ "$VERTREFRESH" = "" ] && continue
     # comment out -- it's the default from above
     #RECMODE="800x600x16"
     ;;
  esac
  break
 done
fi

#100406 loop back offer more modes if MONCHOICES inadequate...
while [ 1 ];do #more-monchoices-loop
 #if have MONCHOICES, that's all i want to display (with warning if not in card list).
 #if no MONCHOICES, then display card list only...
 echo -n "" > /tmp/finalchoices.txt
 if [ "$MONCHOICES" = "" ];then
  for ONECHOICE in $CARDCHOICES
  do
   if [ "$RECMODE" = "$ONECHOICE" ];then
    echo "$ONECHOICE \"$(gettext 'Unconfirmed MAXIMUM for monitor, OK for card')\" \\" >> /tmp/finalchoices.txt
   else
    echo "$ONECHOICE \"$(gettext 'Unconfirmed for monitor, OK for video card')\" \\" >> /tmp/finalchoices.txt
   fi
  done
  for ONECHOICE in 640x480x16 800x600x16 1024x600x16 1024x768x16 1280x800x16 1280x1024x16 1366x768x16 1400x1050x16 1440x900x16 1600x1200x16 1680x1050x16 1920x1080x16 1920x1200x16 640x480x24 800x600x24 1024x600x24 1024x768x24 1280x800x24 1280x1024x24 1366x768x24 1400x1050x24 1440x900x24 1600x1200x24 1680x1050x24 1920x1080x24 1920x1200x24
  do
   case "$CARDCHOICES" in *$ONECHOICE*) ;; *) # we've done CARDCHOICES above
    echo "$ONECHOICE \"$(gettext 'Unconfirmed for monitor, maybe NOT OK for card')\" \\" >> /tmp/finalchoices.txt ;;
   esac
  done
 else
  #decide on a default... (already 800x600x16 earlier) no, reset...
  RECMODE=""
  case "$MONCUTXY" in
   *1024x768*) RECMODE="1024x768x16" ;;
   *800x600*) RECMODE="800x600x16" ;;
  esac
  for ONECUTXY in $MONCUTXY #1024x768
  do
   for ONECHOICE in ${ONECUTXY}x16 ${ONECUTXY}x24
   do
    case "$CARDCHOICES" in
     *$ONECHOICE*) echo "$ONECHOICE \"$(gettext 'OK for monitor, OK for video card')\" \\" >> /tmp/finalchoices.txt ;;
     *) echo "$ONECHOICE \"$(gettext 'OK for monitor, maybe NOT OK for card')\" \\" >> /tmp/finalchoices.txt ;;
    esac 
   done
  done
 fi

 #FINALCHOICES="`cat /tmp/finalchoices.txt`"
 FINALCHOICES="`cat /tmp/finalchoices.txt | sort --field-separator=x --numeric-sort`" #v3.93 rerwin 

 if [ "$MONCHOICES" = "" ];then #100406
  echo '#!/bin/sh' > /tmp/choosexmodedlg
  echo -n "dialog --colors --extra-button --aspect 11 --default-item $RECMODE" >> /tmp/choosexmodedlg
  echo ' --no-collapse --title "'$(gettext 'Puppy Video Wizard')'" --ok-label "OK" --extra-label "'$(gettext 'TEST')'" --cancel-label "'$(gettext 'EXIT')'" --menu "'$(gettext 'Please use the UP/DOWN ARROW keys to select a video mode. Choices are
shown in the format WidthxHeightxBits, where Width and Height are
screen resolution in pixels, 16/24 bits = 65,536/16,777,216 colors.')'
' >> /tmp/choosexmodedlg
  [ ! "$RECMODE" = "" ] && echo "`eval_gettext \"CANNOT DECIDE? ...\\\${RECMODE} is suggested as a good choice.\"`"  >> /tmp/choosexmodedlg
  echo '\Z1'$(gettext 'RECOMMENDATION: Choose <TEST> button to verify it works!')'\Z0' >> /tmp/choosexmodedlg
  echo '
'$(gettext 'OK:     Just press ENTER key to immediately use the selected mode...')'
'$(gettext 'TEST: TAB key then ENTER to test and debug the mode before using it...')'
'$(gettext 'EXIT: Exit to text-mode console, do not start X...')'\Zn" 0 0 0 \' >> /tmp/choosexmodedlg #'geanyfix
  echo "$FINALCHOICES" >> /tmp/choosexmodedlg
  echo ' 2>/tmp/tag.txt' >> /tmp/choosexmodedlg
  echo 'exit $?' >> /tmp/choosexmodedlg
  chmod 755 /tmp/choosexmodedlg
  /tmp/choosexmodedlg
  XAUTO=$? #=0 for automatic.
  [ $XAUTO -ne 0 ] && [ $XAUTO -ne 3 ] && exit #drop out to console.
 else
  #offer more resolutions if MONCHOICES inadequate...
  echo '#!/bin/sh' > /tmp/choosexmodedlg
  echo -n "dialog --colors --extra-button --aspect 11 --default-item $RECMODE" >> /tmp/choosexmodedlg
  echo ' --no-collapse --title "'$(gettext 'Puppy Video Wizard')'" --ok-label "OK" --extra-label "'$(gettext 'TEST')'" --cancel-label "'$(gettext 'MORE')'" --menu "'$(gettext 'Please use the UP/DOWN ARROW keys to select a video mode. Choices are
shown in the format WidthxHeightxBits, where Width and Height are
screen resolution in pixels, 16/24 bits = 65,536/16,777,216 colors.')'
' >> /tmp/choosexmodedlg
  [ "$RECMODE" != "" ] && echo "`eval_gettext \"CANNOT DECIDE? ...\\\${RECMODE} is suggested as a good choice.\"`"  >> /tmp/choosexmodedlg
  echo '\Z1'$(gettext 'RECOMMENDATION: Choose <TEST> button to verify it works!')'\Z0' >> /tmp/choosexmodedlg
  echo '
'$(gettext 'NOTICE: If auto-probe has not detected a resolution that you know your monitor supports, click the <MORE> button to display more resolutions to choose from...')'' >> /tmp/choosexmodedlg
  echo '
'$(gettext 'OK:     Just press ENTER key to immediately use the selected mode...')'
'$(gettext 'TEST: TAB key then ENTER to test and debug the mode before using it...')'
'$(gettext 'MORE: Display more monitor resolutions to choose from...')'\Zn" 0 0 0 \' >> /tmp/choosexmodedlg #'geanyfix.
  echo "$FINALCHOICES" >> /tmp/choosexmodedlg
  echo ' 2>/tmp/tag.txt' >> /tmp/choosexmodedlg
  echo 'exit $?' >> /tmp/choosexmodedlg
  chmod 755 /tmp/choosexmodedlg
  /tmp/choosexmodedlg
  XAUTO=$? #=0 for automatic.
  if [ $XAUTO -eq 1 ];then #MORE
   MONCHOICES=""
   continue #more-monchoices-loop
  fi
  [ $XAUTO -ne 0 ] && [ $XAUTO -ne 3 ] && exit #drop out to console. maybe pressed ESC.
 fi
 
 break
done  #end more-monchoices-loop

CHOSENRES="`cat /tmp/tag.txt 2>/dev/null`"
[ "$CHOSENRES" = "" ] && CHOSENRES="800x600x16"
FINALDEPTH=${CHOSENRES##*x}
#CHOSENX=${CHOSENRES%%x*}
#CHOSENY=${CHOSENRES#*x} ; CHOSENY=${CHOSENY%x*}
#FINALXY="${CHOSENX}x${CHOSENY}"
FINALXY=${CHOSENRES%x*}

##lcd panels usually work at one freq only...
#if [ ! "$MONCHOICES" = "" ];then #format of each line: 1024x768@75
# FIXEDFREQS="`echo -n "$MONCHOICES" | grep "$FINALXY" | cut -f 2 -d '@' | tr '\n' ','' | sed -e 's/,$//g'`"
# [ ! "$FIXEDFREQS" = "" ] && VERTREFRESH="$FIXEDFREQS"
#fi

#some monitors have a very high vertrefresh, and Xorg uses it, but it is too high...
#v2.13b2 was 95, make it 85...
##  Dougal: note that old code (line below) didn't work in my case: 50.0-160.0
##+ seems like the ".0" gave it problems, so ended up with MAXVERT=""
#MAXVERT=`echo -n "$VERTREFRESH" | grep -o '[ -,][0-9]*$' | sed -e 's/^[ -,]//g'`
MAXVERT=${VERTREFRESH#*-} ; MAXVERT=${MAXVERT%.*}
if [ $MAXVERT -gt 85 ];then
 #VPATTERN="s/${MAXVERT}$/85/g"
 #VERTREFRESH="`echo -n "$VERTREFRESH" | sed -e "$VPATTERN"`"
 VERTREFRESH=${VERTREFRESH/$MAXVERT/85}
else
 #want to cut down rating on modern LCD panels also...
 if [ $MAXVERT -gt 74 ] && [ $MAXVERT -lt 86 ];then
   #and if manufactured in 2004 or later...
   #(so older CRTs in this range maxvert 75-85 will get rejected)
   if grep '^manufacture:' /tmp/ddcprobe.txt | grep -E -q ' 20[123][0-9]| 200[4-9]' ;then
    let LCDMAXVERT=MAXVERT-4
    #VPATTERN="s/${MAXVERT}$/${LCDMAXVERT}/g"
    #VERTREFRESH="`echo -n "$VERTREFRESH" | sed -e "$VPATTERN"`"
    VERTREFRESH=${VERTREFRESH/$MAXVERT/$LCDMAXVERT}
   fi
 fi
fi
#script also needs these max freqs later on...
#MAXHORIZ=`echo -n "$HORIZSYNC" | grep -o '[ -,][0-9]*$' | sed -e 's/^[ -,]//g'`
#MINVERT=`echo -n "$VERTREFRESH" | grep -o '^[0-9]*'`
#MINHORIZ=`echo -n "$HORIZSYNC" | grep -o '^[0-9]*'`
MAXHORIZ=${HORIZSYNC#*-} #; MAXHORIZ=${MAXHORIZ%.*}
MINVERT=${VERTREFRESH%-*} #; MINVERT=${MINVERT%.*}
MINHORIZ=${HORIZSYNC%-*} #; MINHORIZ=${MINHORIZ%.*}

#now write the Screen section...
#091119 handle multiple screens... 100430 add metamodes entry...
SCREEN_LIST=$(grep -o '^[^a-zA-Z]*Screen[^"]*"Screen[0-9]\+"' /etc/X11/xorg.conf | grep -o 'Screen[0-9]\+' | grep -o '[0-9]\+')
SCRNSECTION=""
for i in $SCREEN_LIST; do
SCRNSECTION="$SCRNSECTION
Section \"Screen\"
	Identifier \"Screen$i\"
	Device     \"Card$i\"
	Monitor    \"Monitor$i\"
	DefaultDepth $FINALDEPTH
	#Option         \"metamodes\" \"${FINALXY}_60 +0+0\" #METAMODES_${i}
	Subsection \"Display\"
		Depth       $FINALDEPTH
		Modes       \"${FINALXY}\"
	EndSubsection
EndSection
"
done
echo "$SCRNSECTION" >> /etc/X11/xorg.conf

PREFERREDMODE=$FINALXY   #v3.98 rerwin - set monitor preferred mode same as screen mode.
#horiz and vert sync ranges and preferred mode were found earlier but not written... v3.98
cp -f /etc/X11/xorg.conf /tmp/xorg.conf.tmp
#APATTERN="s/HORIZSYNC0/$HORIZSYNC/g"
sed -e "s/HORIZSYNC0/$HORIZSYNC/g ; s/VERTREFRESH0/$VERTREFRESH/g ; s/PREFERREDMODE0/$PREFERREDMODE/g" /tmp/xorg.conf.tmp >/etc/X11/xorg.conf   #v3.98 rerwin - added update of preferredmode.
#BPATTERN="s/VERTREFRESH0/$VERTREFRESH/g"
sync
#cat /tmp/xorg.conf.tmp2 | sed -e "$BPATTERN" > /etc/X11/xorg.conf
#sync
#rm -f /tmp/xorg.conf.tmp2

#110927 improved touchpad code...
if [ "`grep -E 'Elantech|Alps|Synaptics' /proc/bus/input/devices`" ];then
 cp -f /etc/X11/xorg.conf /etc/X11/xorg.conf-without-synaptic
 if [ "`lsmod | grep '^evdev'`" == "" ];then
  modprobe evdev
  [ "`grep '^modprobe evdev' /etc/rc.d/rc.local`" == "" ] && echo "modprobe evdev" >> /etc/rc.d/rc.local
 fi
 # Where we want to insert new lines...
 OLD1='Section "Module"'
 OLD2='Section "ServerLayout"'
 #110927 there may be two Monitor sections, need special once-only insertion...
 #format: sed '1,/wrong pattern/s/wrong pattern/good pattern/' wrong.file
 #see ref: http://www.suwald.com/linux-gnu/sed-howto.html
 sed -i '1,/Section "Monitor"/s/Section "Monitor"/Section "Monitor" #sectionmonitor0/' /etc/X11/xorg.conf-without-synaptic
 OLD3='Section "Monitor" #sectionmonitor0'
 NEW1='Section "Module"\
	Load "synaptics" #loadsynaptics'
 NEW2='Section "ServerLayout"\
	InputDevice "Synaptics Mouse" "AlwaysCore" #serverlayoutsynaptics'
 if vercmp $XORGVER lt 1.10.0;then #110701
  if grep -F -q 'Elantech' /proc/bus/input/devices ; then #100602 jemimah
   NEW3='Section "InputDevice"\
	Identifier "Synaptics Mouse"\
	Driver "synaptics"\
	Option "Device" "/dev/psaux"\
	Option "Protocol" "auto-dev"\
        Option "LeftEdge" "60"\
        Option "RightEdge" "1070"\
        Option "TopEdge" "90"\
        Option "BottomEdge" "680"\
        Option "Emulate3Buttons" "on"\
        Option "MaxTapTime" "180"\
        Option "MaxTapMove" "59"\
        Option "VertScrollDelta" "20"\
        Option "MinSpeed" "0.75"\
        Option "MaxSpeed" "1.00"\
        Option "AccelFactor" "0.16"\
        Option "SHMConfig" "on"\
        Option "VertEdgeScroll" "on"\
        Option "TapButton1" "1"\
EndSection\
\
Section "Monitor" #sectionmonitor0'
  fi
  if grep -F -q 'Alps' /proc/bus/input/devices ; then #Dougal
   NEW3='Section "InputDevice"\
	Identifier "Synaptics Mouse"\
	Driver "synaptics"\
	Option "Device" "/dev/psaux"\
	Option "Protocol" "auto-dev"\
	Option "LeftEdge" "120"\
	Option "RightEdge" "930"\
	Option "TopEdge" "120"\
	Option "BottomEdge" "650"\
	Option "FingerLow" "14"\
	Option "FingerHigh" "15"\
	Option "MaxTapTime" "0"\
	Option "MaxTapMove" "110"\
	Option "VertScrollDelta" "20"\
	Option "MinSpeed" "0.3"\
	Option "MaxSpeed" "0.75"\
	Option "AccelFactor" "0.030"\
	Option "EdgeMotionMinSpeed" "200"\
	Option "EdgeMotionMaxSpeed" "200"\
	Option "UpDownScrolling" "1"\
	Option "CircularScrolling" "1"\
	Option "CircScrollDelta" "0.1"\
	Option "CircScrollTrigger" "2"\
	Option "SHMConfig" "on"\
EndSection\
\
Section "Monitor" #sectionmonitor0'
  fi
  if grep -F -q 'Synaptics' /proc/bus/input/devices ; then #kirk
   NEW3='Section "InputDevice"\
	Identifier "Synaptics Mouse"\
	Driver "synaptics"\
	Option "Device" "/dev/psaux"\
	Option "Protocol" "auto-dev"\
	Option "LeftEdge" "1700"\
	Option "RightEdge" "5300"\
	Option "TopEdge" "1700"\
	Option "BottomEdge" "4200"\
	Option "FingerLow" "25"\
	Option "FingerHigh" "30"\
	Option "MaxTapTime" "0"\
	Option "MaxTapMove" "220"\
	Option "VertScrollDelta" "100"\
	Option "MinSpeed" "0.10"\
	Option "MaxSpeed" "0.30"\
	Option "AccelFactor" "0.0030"\
	Option "SHMConfig" "on"\
	#Option "Repeater" "/dev/ps2mouse"\
EndSection\
\
Section "Monitor" #sectionmonitor0'
  fi
 else #120129 jemimah: add Option "SHMConfig" "on"...
  NEW3='Section "InputDevice"\
	Identifier "Synaptics Mouse"\
	Driver "synaptics"\
	Option "SHMConfig" "on"\
EndSection\
\
Section "Monitor" #sectionmonitor0'
 fi
 sed "s%$OLD1%$NEW1% ; s%$OLD2%$NEW2% ;s%$OLD3%$NEW3%" /etc/X11/xorg.conf-without-synaptic >/etc/X11/xorg.conf
fi



#100820 for intel video, mplayer needs this...
zVIDEODRVR="`grep '#card0driver' /etc/X11/xorg.conf | cut -f 2 -d '"'`" #'geany
case $zVIDEODRVR in
 intel|i810)
  [ "`grep '"LinearAlloc" "6144"' /etc/X11/xorg.conf`" = "" ] && sed -i -e 's%#card0driver%#card0driver\n\tOption "LinearAlloc" "6144"%' /etc/X11/xorg.conf
 ;;
esac

#v2.13 want a hardware profile so can bootup on different PCs...
PROFILECHIP="`grep -m1 '^oem: ' /tmp/ddcprobe.txt | cut -f 2-4 -d ' ' | tr ' ' '_' | sed -e 's/[^0-9a-zA-Z]/_/g'`"
## Dougal: maybe add "^monitorname: "??
#PROFILEMONITOR="`grep -E -m1 '^monitorrange: |^monitorid: |^eisa: ' /tmp/ddcprobe.txt | cut -f 2 -d ':' | tr -d ' ' | sed -e 's/[^0-9a-zA-Z]/_/g'`"
#v3.95 'eisa:' and 'id:' return fluctuating values on some PCs, so search in this order...
PROFILEMONITOR="`grep '^monitorid: ' /tmp/ddcprobe.txt | head -n 1 | cut -f 2 -d ':' | tr -d ' ' | sed -e 's/[^0-9a-zA-Z]/_/g'`"
[ "$PROFILEMONITOR" = "" ] && PROFILEMONITOR="`grep '^monitorname: ' /tmp/ddcprobe.txt | head -n 1 | cut -f 2 -d ':' | tr -d ' ' | sed -e 's/[^0-9a-zA-Z]/_/g'`"
[ "$PROFILEMONITOR" = "" ] && PROFILEMONITOR="`grep '^monitorrange: ' /tmp/ddcprobe.txt | head -n 1 | cut -f 2 -d ':' | tr -d ' ' | sed -e 's/[^0-9a-zA-Z]/_/g'`"
#[ "$PROFILEMONITOR" = "" ] && PROFILEMONITOR="`grep '^dtiming: ' /tmp/ddcprobe.txt | tail -n 1 | cut -f 2 -d ':' | tr -d ' ' | sed -e 's/[^0-9a-zA-Z]/_/g'`"
#100501 remove, gives random data on one of my monitors...
#[ "$PROFILEMONITOR" = "" ] && PROFILEMONITOR="`grep '^manufacture: ' /tmp/ddcprobe.txt | tail -n 1 | cut -f 2 -d ':' | tr -d ' ' | sed -e 's/[^0-9a-zA-Z]/_/g'`"
#[ "$PROFILEMONITOR" = "" ] && PROFILEMONITOR="`grep '^eisa: ' /tmp/ddcprobe.txt | head -n 1 | cut -f 2 -d ':' | tr -d ' ' | sed -e 's/[^0-9a-zA-Z]/_/g'`"

echo "#PuppyHardwareProfile=${PROFILECHIP}${PROFILEMONITOR}" >> /etc/X11/xorg.conf
#create a copy of xorg.conf with the profile in the filename...
cp -af /etc/X11/xorg.conf /etc/X11/xorg.conf.${PROFILECHIP}${PROFILEMONITOR}
#also write profile to the backup (used for tweaking vertrefresh)...
echo "#PuppyHardwareProfile=${PROFILECHIP}${PROFILEMONITOR}" >> /tmp/xorg.conf.tmp

#v2.12
#note, this code will have to go into 'xwin' also.
#video bios may not offer the chosen resolution if it is widescreen.
#for intel video there is a way to patch the video bios, but this
#has to be run at every boot...
if grep -F 'oem:' /tmp/ddcprobe.txt | grep -F -q 'Intel' ;then
 #MYXYRES="`echo -n "$CHOSENRES" | cut -f 1-2 -d 'x'`" 
 MYXYRES=${CHOSENRES%x*}
 if ! grep -q "$MYXYRES" /tmp/Xmodes.txt ;then
  #MYXRES="`echo -n "$CHOSENRES" | cut -f 1 -d 'x'`" 
  #MYYRES="`echo -n "$CHOSENRES" | cut -f 2 -d 'x'`" 
  MYXRES=${CHOSENRES%%x*}
  MYYRES=${CHOSENRES%x*} ; MYYRES=${MYYRES#*x}
  #this is an app that patches video-bios, but in ram only...
  915resolution 38 $MYXRES $MYYRES
  #...replaces mode 38 (1024x768).
  #create something for xwin to eecute...
  echo "915resolution 38 $MYXRES $MYYRES" > /etc/resolutionfix
 fi
else
 #in case plug usb or multisession-cd into different pc...
 [ -f /etc/resolutionfix ] && rm -f /etc/resolutionfix
fi

[ $XAUTO -ne 0 ] && [ $XAUTO -ne 3 ] && exit #drop out to console.

#code here to test the video...
CHOSENVERT=""
while [ $XAUTO -ne 0 ];do #testloop
 case "`cat /etc/mousedevice 2>/dev/null`" in #w468
  #input/mice) MOUSETYPE="usb" ;;
  #psaux) MOUSETYPE="ps/2" ;;
  tty*) 
   #MOUSETYPE="serial"
   MOUSEMSG="
$(gettext 'Puppy thinks that you have a serial mouse. This type of mouse is
on ancient PCs. Most modern PCs use a usb or ps/2 mouse. If your
PC does not have a serial mouse, then you must choose the 
<Change_mouse> button now.')"
  ;;
  *)
   MOUSEMSG="
$(gettext 'Puppy thinks that you have a usb or ps/2 mouse. This is okay for
most cases, but some old computers have a serial mouse. If you have
an ancient PC that you know has a serial mouse, then you must choose
the <Change_mouse> button now.')"
  ;;
 esac
 
 dialog --title "$(gettext 'Xorg Video Wizard')" --yes-label "$(gettext 'TEST_X_NOW')" --no-label "$(gettext 'Change_mouse')" --yesno "$(gettext 'Okay, just about to take the plunge.')
${MOUSEMSG}

$(gettext 'After choosing <TEST_X_NOW> button, if the next screen shows a nice
dialog box, then X started okay. If the screen is blank or garbage,
then failure (In such a case, just press the ENTER key to terminate
the test, preferably within the 60 second test timeout).')

$(gettext 'IMPORTANT: If the ENTER key does not terminate the test, press the
combination CTRL-ALT-BACKSPACE (some odd old PCs may even require
you to press CTRL-ALT-BACKSPACE twice to terminate the test!)')

$(gettext 'Press ENTER key now to start X graphics mode (may take a few secs)...')
$(gettext 'TAB then ENTER to change the mouse (afterward will return here)...')" 0 0

 if [ ! $? -eq 0 ];then
  #change the mouse... (then go back up to above dialog)
  choosemousefunc
  #w480 bugfix, latter used if choose tweak refresh...
  cp -f /etc/X11/xorg.conf /tmp/xorg.conf.tmp
  continue
 fi

 #w460 test Xorg...
 export MONCHOICES
 xinit /usr/sbin/xinitrc_test -- /usr/bin/Xorg :0 #101224 added LANG=C. 120213 removed LANG=C prefix.

 eval "`cat /tmp/xorgwizard_initrc_test_results`" #results from xinitrc_test
#...XTEST, YTEST, HSTEST, VRTEST.
 
 load_consolefont #120301 it seems have to reload console font after exit from X.
 
 if [ -e /usr/bin/Xvesa ];then
  TWKMSG="$(gettext "Note: If you have tweaked away, to no avail, choose \"FINISHED\" and you
      will get one final chance to fall back to using Xvesa.
Note: If display has only minor displacement or proportions error, run
      (with care) Xvidtune module in Xorg Wizard within X (Setup menu). 

Press ENTER if test was okay (or to fall back to Xvesa)...") "
 else
  TWKMSG="$(gettext 'Press ENTER key if test was okay...')"
 fi

 dialog --no-collapse --title "$(gettext 'Xorg Video Wizard')" --yes-label "$(gettext 'FINISHED')" --no-label "$(gettext 'Tweak')" --yesno "$(gettext 'Report on X test:')
                  `eval_gettext \"Resolution:           \\\${XTEST}x\\\${YTEST} pixels\"`
                  `eval_gettext \"Horizontal frequency: \\\$HSTEST KHz\"`
                  `eval_gettext \"Refresh frequency:    \\\$VRTEST Hz\"`
                  `eval_gettext \"Video driver:         \\\$CARD0DRIVER\"`

$(gettext 'If you are reporting success, great, but if the display was not quite
right, say displaced or distorted, you now have the option of tweaking
various parameters, even choose a different video driver.
Ditto if testing X was an abysmal failure.')

${TWKMSG}
$(gettext 'TAB then ENTER to tweak parameters & retest X...')" 0 0

 if [ $? -eq 0 ];then
  break
 fi

 #100113 alternate drivers...
 #in quirky have 'drivers-alternate' folder but other builds may not, so create...
 mkdir -p /usr/lib/x/drivers-alternate
 [ -f /usr/lib/xorg/modules/drivers/i810OLD_drv.so ] && mv -f /usr/lib/xorg/modules/drivers/i810OLD_drv.so /usr/lib/x/drivers-alternate/i810_drv.so #puppy 431 has this.
 [ ! -h /usr/lib/xorg/modules/drivers/i810_drv.so ] && [ -f /usr/lib/xorg/modules/drivers/i810_drv.so ] && [ -f /usr/lib/xorg/modules/drivers/intel_drv.so ] && mv -f /usr/lib/xorg/modules/drivers/i810_drv.so /usr/lib/x/drivers-alternate/
 [ -f /usr/lib/xorg/modules/drivers/nv_drv.so ] && [ -f /usr/lib/xorg/modules/drivers/nouveau_drv.so ] && mv -f /usr/lib/xorg/modules/drivers/nouveau_drv.so /usr/lib/x/drivers-alternate/
 EXTRABUTTON=""
 EXTRALABEL=""
 EXTRADRVMSG=""
 case $CARD0DRIVER in
  intel)
   if [ -f /usr/lib/x/drivers-alternate/i810_drv.so ];then
    TRYDRV='i810'
    EXTRABUTTON='--extra-button'
    EXTRALABEL='--extra-label Old_i810_driver'
    EXTRADRVMSG="
$(gettext "ATTN: There is an older 'i810' Intel video driver that might work better...")"
   fi
  ;;
  i810)
   if [ -f /usr/lib/x/drivers-alternate/intel_drv.so ];then
    TRYDRV='intel'
    EXTRABUTTON='--extra-button'
    EXTRALABEL='--extra-label New_intel_driver'
    EXTRADRVMSG="
$(gettext "ATTN: There is an newer 'intel' Intel video driver that might work better...")"
   fi
  ;;
  nv)
   if [ -f /usr/lib/x/drivers-alternate/nvidia_drv.so ];then
    TRYDRV='nvidia'
    EXTRABUTTON='--extra-button'
    EXTRALABEL='--extra-label Alt_nvidia_driver'
    EXTRADRVMSG="
$(gettext "ATTN: There is an alternative 'nvidia' Nvidia video driver that might work better...")"
   else
    if [ -f /usr/lib/x/drivers-alternate/nouveau_drv.so ];then
     TRYDRV='nouveau'
     EXTRABUTTON='--extra-button'
     EXTRALABEL='--extra-label Alt_nouveau_driver'
     EXTRADRVMSG="
$(gettext "ATTN: There is an alternative 'nouveau' Nvidia video driver that might work better...")"
    fi
   fi
  ;;
  nouveau)
   if [ -f /usr/lib/x/drivers-alternate/nv_drv.so ];then
    TRYDRV='nv'
    EXTRABUTTON='--extra-button'
    EXTRALABEL='--extra-label Alternate_nv_driver'
    EXTRADRVMSG="
$(gettext "ATTN: There is an alternative 'nv' Nvidia video driver that might work better...")"
   fi
  ;;
  nvidia)
   if [ -f /usr/lib/x/drivers-alternate/nv_drv.so ];then
    TRYDRV='nv'
    EXTRABUTTON='--extra-button'
    EXTRALABEL='--extra-label Alternate_nv_driver'
    EXTRADRVMSG="
$(gettext "ATTN: There is an alternative 'nv' Nvidia video driver that might work better...")"
   fi
  ;;
 esac

 if [ "$CARD0DRIVER" != "vesa" ];then #v2.11 100109 fix yes/no labels...
  #current version of dialog in quirky has very annoying bug, --yes-label/no-label must be changed to --ok-label/cancel-label...
  if [ "$EXTRABUTTON" = "" ];then #100113
   dialog --no-collapse --title "$(gettext 'Xorg Video Wizard')" --yes-label "$(gettext 'Tweak_xorg.conf')" --no-label "Vesa_driver" --yesno "`eval_gettext \"Before continuing to tweaking xorg.conf, one other thing to consider.
Xorg has a dozen or so drivers for particular video hardware, which
optimises performance for the matching hardware, but sometimes a
driver does not work right or there is no exact driver to match the
hardware. The workaround for this is that Xorg has a generic driver
called 'vesa' (note, this is not the Xvesa X server!), that works with
most video hardware, but some performance may be lost.

The current driver being used by Xorg is '\\\${CARD0DRIVER}', and your video
vendor is:  '\\\${CARD0VENDOR}'
board info: '\\\${CARD0BOARD}'

So, if you have already tried 'tweaking' or you know that the Xorg
'\\\${CARD0DRIVER}' driver does not work on your hardware, consider the
generic driver. Click <Vesa_driver> to change Xorg to using the
generic driver, otherwise press ahead and try tweaking...\"`" 0 0
  else
   dialog --no-collapse ${EXTRABUTTON} --title "$(gettext 'Xorg Video Wizard')" --ok-label "$(gettext 'Tweak_xorg.conf')" --cancel-label "Vesa_driver" ${EXTRALABEL} --yesno "`eval_gettext \"Before continuing to tweaking xorg.conf, one other thing to consider.
Xorg has a dozen or so drivers for particular video hardware, which
optimises performance for the matching hardware, but sometimes a
driver does not work right or there is no exact driver to match the
hardware. The workaround for this is that Xorg has a generic driver
called 'vesa' (note, this is not the Xvesa X server!), that works with
most video hardware, but some performance may be lost.

The current driver being used by Xorg is '\\\${CARD0DRIVER}', and your video
vendor is:  '\\\${CARD0VENDOR}'
board info: '\\\${CARD0BOARD}'

So, if you have already tried 'tweaking' or you know that the Xorg
'\\\${CARD0DRIVER}' driver does not work on your hardware, consider the
generic driver. Click 'Vesa_driver' to change Xorg to using the
generic driver, otherwise press ahead and try tweaking...\\\${EXTRADRVMSG}\"`" 0 0
  fi
  RET2=$?
  SUBSTDRV='vesa'
  #[ $RET2 -eq 3 ] && SUBSTDRV="$TRYDRV" #w482 intel or i810
  #100113 if change driver, really should probe again...
  if [ $RET2 -eq 3 ];then
   SUBSTDRV="$TRYDRV"
   alternate_driver_func $SUBSTDRV #100401
   exec xorgwizard $SUBSTDRV ###RESTART###
  fi
  if [ $RET2 -ne 0 ];then
  
   #this is what a 'vesa' section in xorg.conf looks like:
   #Section "Device"
   #	### Available Driver options are:-
   #	### Values: <i>: integer, <f>: float, <bool>: "True"/"False",
   #	### <string>: "String", <freq>: "<f> Hz/kHz/MHz"
   #	### [arg]: arg optional
   #	#Option     "ShadowFB"           	# [<bool>]
   #	#Option     "DefaultRefresh"     	# [<bool>]
   #	#Option     "ModeSetClearScreen" 	# [<bool>]
   #	#Option     "NoDDC"              	# [<bool>]
   #	Identifier  "Card0"
   #	Driver      "vesa" #card0driver
   #	VendorName  "Unknown Vendor"
   #	BoardName   "Unknown Board"
   #	BusID       "PCI:0:2:0"
   #EndSection
  
   APATTERN="s/.*#card0driver/	Driver      \"${SUBSTDRV}\" #card0driver/"
   sed -e "$APATTERN" /etc/X11/xorg.conf > /tmp/xorg.conf.tmp2
   sync
   cp -f /tmp/xorg.conf.tmp2 /etc/X11/xorg.conf
   CARD0DRIVER="$SUBSTDRV" #100109
   continue
  fi
 else #using xorg 'vesa' driver...
  DRVSNUM="`ls -1 /usr/lib/xorg/modules/drivers | wc -l`"
#  if [ "$DRVRSNUM" = "1" ];then
#   dialog --no-collapse --title "Xorg Video Wizard" --msgbox "IMPORTANT INFORMATION
#Xorg currently only has the 'Generic driver' installed, called 'vesa'
#(remember: this is different from the simple Xvesa X server!).
#The Generic driver will work with most video hardware, however it lacks
#some features, in particular has a limited selection of screen refresh
#frequencies and is slow -- a factor if you wish to play DVD videos and
#graphical games. However, you can easily install a Xorg driver specific
#to your video hardware -- after Puppy is connected to the Internet, run
#the Puppy Package Manager and install the 'xorg_servers' package.
#After that, run the Xorg Video Wizard again and it will automatically
#choose the best driver for your PC's video hardware
#(PPM and Xorg Video Wizard are to be found in the 'Setup' menu).
#
#A further note: for extra video speed, Xorg has what is called the
#'Direct Rendering Interface' (DRI), which requires a special driver.
#Some games can benefit from this. Also, some applications and games
#need 'GLI', which is a special library for 3-dimensional rendering.
#Again, the PPM may offer extra packages to add these capabilities.
#
#For now, keep going with using the Generic driver
#(for general PC use, this is proably all that you need anyway)..." 0 0
#  fi

  #100330 offer to go back to probing all drivers...
  if [ "$DRVSNUM" = "1" ];then
   DRVSBKUP=`ls -1 /usr/lib/x/drivers-backup | wc -l`
   if [ $DRVSBKUP -gt 1 ];then
    dialog --no-collapse --title "$(gettext 'Xorg Video Wizard')" --yes-label "Vesa" --no-label "$(gettext 'Probe')" --yesno "
$(gettext 'Earlier you chose to use the Vesa driver and not probe for a hardware
-specific driver, but if you are not happy with that choice you can
now restart the Video Wizard and choose a full probe.

Choose <Vesa> if you are happy with the Vesa driver...
Choose <Probe> to go back and probe for a hardware-specific driver...')" 0 0
    if [ $? -ne 0 ];then
     cp -a -f --remove-destination /usr/lib/x/drivers-backup/* /usr/lib/xorg/modules/drivers/
     rm -f /usr/lib/x/drivers-backup/*
     exec xorgwizard ###EXIT###
    fi
   fi
  else
   #100113 offer to change to alternate drivers...
   ALTERNATEDRIVERS="`find /usr/lib/x/drivers-alternate -type f -name '*.so'  | rev | cut -f 2-9 -d '_' | cut -f 1 -d '/' | rev`"
   if [ "$ALTERNATEDRIVERS" != "" ];then
    xALTERNATEDRIVERS=""
    for ONEALT in $ALTERNATEDRIVERS
    do
     xONEALT="$ONEALT"
     case $ONEALT in
      i810) xONEALT='Intel' ;;
      intel) xONEALT='Intel' ;;
      nv) xONEALT='Nvidia' ;;
      nouveau) xONEALT='Nvidia' ;;
      nvidia) xONEALT='Nvidia' ;;
     esac
     xALTERNATEDRIVERS="$xALTERNATEDRIVERS $ONEALT $xONEALT"
    done
    rm -f /tmp/xorgwizard-altdrv 2>/dev/null
    dialog --title "$(gettext 'Xorg Video Wizard')" --menu "`gettext \"There are some alternative video drivers that Xorg is currently not using. If you think that your video hardware may need one of these, select it, otherwise stay with 'vesa'...

NOTICE: if you choose a driver other than 'vesa', then the Xorg Wizard will restart so that Xorg can probe the hardware with the chosen driver enabled.

TECHNICAL NOTE: Unused drivers are kept at /usr/lib/x/drivers-alternate. If you choose one (other than 'vesa'), it will be moved to /usr/lib/xorg/modules/drivers.\"`" 0 0 0 vesa Generic_driver $xALTERNATEDRIVERS 2> /tmp/xorgwizard-altdrv
    if [ -s /tmp/xorgwizard-altdrv ];then
     ALTDRV="`cat /tmp/xorgwizard-altdrv`"
     mv -f /usr/lib/x/drivers-alternate/${ALTDRV}_drv.so /usr/lib/xorg/modules/drivers/
     exec xorgwizard ${ALTDRV} ###RESTART###
    fi
   fi
  fi
 fi

 #tweak...
 dialog --no-collapse --title "$(gettext 'Xorg Video Wizard')" --yes-label "$(gettext 'Tweak_refresh')" --no-label "$(gettext 'Edit_xorg.conf')" --yesno "$(gettext 'If the graphics mode display was distorted, displaced, or a complete
mess, the simplest option now is to adjust the vertical screen refresh
frequency up or down slightly. 
However, if you are more experienced with Linux and X, you may prefer
to open xorg.conf in a text editor and change whatever you wish.

Press ENTER key for the easy option, tweak refresh frequency...
Press TAB then ENTER to open xorg.conf in a text editor...')" 0 0

 if [ $? -eq 0 ];then
  if [ "$MONCHOICES" = "" ];then
   #not plug-n-play.
   MSGPNP="$(gettext 'WARNING: Your monitor is not plug-and-play so this Wizard cannot
         determine its max allowable refresh frequency. A very cheap old
         CRT monitor may not handle more than 70Hz, better quality, 85Hz.')"
  else
   MSGPNP="`eval_gettext \"WARNING: the maximum screen refresh frequency is specified
         as \\\${MAXVERT}Hz (times per second). Do not choose any entry
         in the list below that exceeds this.\"`"
  fi
  MSGGEN="$(gettext 'Note1: It is unwise to push a monitor too hard. Just go high enough so
       that there is no flicker. 72Hz-85Hz for CRT, 60Hz for LCD.
Note2: Display displaced to right is often due to frequency too high.')"
  #just offer standard freqs...
  VERT0=56; MSGV0="$(gettext 'Very noticeable flicker on CRT screens')"
  VERT1=60; MSGV1="$(gettext 'Okay for most LCD screens, flicker on CRT')"
  VERT2=72; MSGV2="$(gettext 'Sensitive eyes may notice flicker on CRT')"
  VERT3=75; MSGV3="$(gettext 'Sensitive eyes may notice flicker on CRT')"
  VERT4=80; MSGV4="$(gettext 'Usually no flicker on CRT')"
  VERT5=85; MSGV5="$(gettext 'No flicker on CRT')"
  
  dialog --no-cancel --title "$(gettext 'Xorg Video Wizard')" --menu "`eval_gettext \"Xorg is currently set to refresh the screen \\\$VRTEST times per second. Taking this up or down may remove distortion etc., but note that the choices here are only suggested upper limits and Xorg may not use exactly the frequency chosen here.\"`

$MSGGEN

$MSGPNP" 0 0 0 \
 "$VERT0" "$MSGV0" \
 "$VERT1" "$MSGV1" \
 "$VERT2" "$MSGV2" \
 "$VERT3" "$MSGV3" \
 "$VERT4" "$MSGV4" \
 "$VERT5" "$MSGV5" \
 2>/tmp/tagvert.txt

  #FUTURE: use xrandr above, to determine alternative lower frequencies.

  CHOSENVERT="`cat /tmp/tagvert.txt 2>/dev/null`"
  NEEDHORIZ=`gtf $XTEST $YTEST $CHOSENVERT | grep -o 'hsync: .*' | cut -f 2 -d ' ' | cut -f 1 -d '.'`
  let NEEDHORIZ=NEEDHORIZ+1 #compensate for rounding off error.
  APATTERN="s/HORIZSYNC0/${HORIZSYNC}/g"
  if [ $NEEDHORIZ -gt ${MAXHORIZ%.*} ];then
   if [ "$MONCHOICES" = "" ];then
    #monitor not plug and play.
    APATTERN="s/HORIZSYNC0/${MINHORIZ}\\-${NEEDHORIZ}/g"
   fi
  fi
  sed -e "$APATTERN" /tmp/xorg.conf.tmp > /tmp/xorg.conf.tmp2
  BPATTERN="s/VERTREFRESH0/${MINVERT}\\-${CHOSENVERT}/g"
  sync
  sed -e "$BPATTERN" /tmp/xorg.conf.tmp2 > /etc/X11/xorg.conf
  sync
  
  #100430 nvidia driver needs to set metamodes entry in Screen section...
  #	#Option         \"metamodes\" \"${FINALXY}_60 +0+0\" #METAMODES_${i}
  mmPATTERN="s%.* #METAMODES%    Option         \"metamodes\" \"${XTEST}x${YTEST}_${CHOSENVERT} +0+0\" #METAMODES%"
  mm2PATTERN="s%.* #METAMODES%    #Option         \"metamodes\" \"${XTEST}x${YTEST}_${VRTEST} +0+0\" #METAMODES%"
  if [ "`grep 'Driver' /etc/X11/xorg.conf | grep '"nvidia"'`" != "" ];then
   sed -i -e "$mmPATTERN" /etc/X11/xorg.conf
  else
   sed -i -e "$mm2PATTERN" /etc/X11/xorg.conf
  fi
  
  rm -f /tmp/xorg.conf.tmp2
 else
  dialog --no-collapse --title "$(gettext 'Xorg Video Wizard')" --msgbox "`eval_gettext \"Before editing xorg.conf, consider this...

/etx/X11/xorg.conf has these lines in the Monitor section:
  HorizSync    \\\$HORIZSYNC
  VertRefresh  \\\$VERTREFRESH

For the resolution that you want to run at, you many want to narrow
-down the specs in xorg.conf. For example, say you want 1024x768@85,
but xorg.conf has VertRefresh 50-160. -- maybe narrow that to 50-85.

Press ENTER key to edit xorg.conf...\"`" 0 0
  #edit xorg.conf...
  mp /etc/X11/xorg.conf
 fi
done #testloop

if [ $XAUTO -ne 0 ];then #<FIX> (XAUTO=0 is <OK> button)
 if [ -e /usr/bin/Xvesa ];then
  dialog --title "$(gettext 'Xorg Video Wizard')" --yes-label "$(gettext 'DONE')" --no-label "Xvesa" --yesno "$(gettext "Just press ENTER key if all is fine and you are ready to run
Puppy with Xorg.

If you cannot get Xorg to work, press TAB then ENTER to choose
the \"Xvesa\" button. This will start Puppy with the simple Xvesa
graphics server that runs on most video hardware.")" 0 0

  if [ ! $? -eq 0 ];then
   ln -sf Xvesa /usr/bin/X
  else
   #prevent Xvesa video wizard from running after X has started...
   rm -f /tmp/videomode
  fi
 fi
else
 #prevent Xvesa video wizard from running after X has started...
 rm -f /tmp/videomode
fi

#move it so people ain't confused seeing it in /root...
mv -f /root/xorg.conf.new /tmp/xorg.conf.new

if [ $XAUTO -ne 0 ];then #<FIX> (XAUTO=0 is <OK> button)
 #need to do this here again in case of tweaking made some changes...
 #create a copy of xorg.conf with the profile in the filename...
 cp -af /etc/X11/xorg.conf /etc/X11/xorg.conf.${PROFILECHIP}${PROFILEMONITOR}
 clear
 echo "$(gettext "Xorg Video Wizard completed. Type 'xwin' to start X...")"
else
 clear
 #user chose the <OK> button, so going directly into X without testing.
 echo -en "\\033[1;31m" #34=blue, 33=yellow, 32=green, 31=red, 35=purple, 36=aquablue, 38=black.
 echo "$(gettext "If X did not work, type 'xorgwizard' to run the Video Wizard again.")"
 echo "$(gettext "After that, type 'xwin' to run X graphics mode.")"
 echo "$(gettext "Note, if X works but needs minor adjustment to the display, run the")"
 echo "$(gettext "Video Wizard from within X (in the Setup menu) -- module 'Xvidtune'")"
 echo -n "$(gettext "may be used, with caution, to finetune the display dimensions.")"
 echo -e "\\033[0;39m"
fi

#v3.99 begin
[ -z /tmp/ddcprobeoem.txt ] && rm /tmp/ddcprobeoem.txt  #empty
#If started from command line after hang, delete new Xvesa hanger indication and go to xwin - no need to have user type it in.
#[ -f /tmp/ddcprobeoem.txt ] && rm /tmp/ddcprobeoem.txt && exec xwin 
#3.99 end
[ -f /tmp/ddcprobeoem.txt ] && rm /tmp/ddcprobeoem.txt #w478

echo 'ICONWIPE' > /var/local/pup_event_icon_change_flag #111108 Karl Godt 120213 path changed from /tmp

###END###
