#! /usr/local/bin/xpwish
#    Copyright (C) 1997  Timothy M. Vanderhoek
#
#    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.
#
#    You should have received a copy of the GNU General Public License
#    along with this program; if not, write to the Free Software
#    Foundation, Inc., 675 Mass Ave, Cambridge, MA 02139, USA.
#
#    Tim Vanderhoek
#    ac199@hwcn.org
#

# We import the configure proc from the file xprez-proc-configure...
# This substitution is done by make...
#    Copyright (C) 1997  Timothy M. Vanderhoek
#
#    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.
#
#    You should have received a copy of the GNU General Public License
#    along with this program; if not, write to the Free Software
#    Foundation, Inc., 675 Mass Ave, Cambridge, MA 02139, USA.
#
#    Tim Vanderhoek
#    ac199@hwcn.org
#

# This proc gets copied from the file xprez-proc-configure, which is
# in turn generated from xprez-proc-configure.in

# Set-up all my important variables
proc Customize {} {
	global xprez namemap cset aimove_v

	# Directories where we may be able to find the card gifs
	set xprez(carddir1)	"/usr/local/share/games/tvp"
	set xprez(carddir2)	"./xprez/cards"
	set xprez(carddir3)	"./cards"
	set xprez(carddir4)	"."

	# Which cardback to use? (-01 through -04)
	set xprez(back)		01

	# delay before moving AIs in ms
	set xprez(aidelay)	180

	# Wait for clicks between rounds?
	set xprez(roundclick)	1

	# These names map into these types of players...
	# You may add new names, but be careful changing AI types...
	set namemap(Trixie)	RAND
	set namemap(Tiffany)	NOLAY
	set namemap(Tanya)	SIMPLE
	set namemap(Buster)	RAND
	set namemap(Billy)	NOLAY
	set namemap(Biff)	SIMPLE

	# Which players are playing
	set xprez(AI0)		{};  # Special case...  Don't change
	set xprez(AI1)		Human;  # Special case...  Don't change
	set xprez(AI2)		Buster
	set xprez(AI3)		Tiffany
	set xprez(AI4)		Biff

	# all measurements in centimetres
	# These point to the centre of the first card...
# Should allow these values to be set to 0, and then we auto-set them,
# based on the heights and widths of our images
	set xprez(topx)		4
	set xprez(topy)		2.55
	set xprez(bottomx)	4
	set xprez(bottomy)	11.55
	set xprez(leftx)	1.5
	set xprez(lefty)	3.55
	set xprez(rightx)	13
	set xprez(righty)	3.55
	set xprez(midx)		6;  # anchor nw
	set xprez(midy)		4.3;  # anchor nw
	set xprez(midlabdist)	.3;  # distance of labels from mid card
	set xprez(inc)		.5;  # amount to incr between cards
	set xprez(raise)	1.5;  # how much to raise selected cards by

	set xprez(version)	0.9.7.1
	set xprez(abouttvp)	{	This is TVP version 0.9.7.1, release August 19, 1997.  It is currently
being maintained by Tim Vanderhoek <ac199@hwcn.org>.  You can visit its homepage on the web at http://www3.sympatico.ca/john.vanderhoek/tim/src/president.
 	The preferred method of TVP distribution is by its source code, but exceptions exist.  The source is under the GNU GPL, whose conditions you can view from all of prez, aprez, and xprez by asking to see the license.
 	While TVP is free, you are requested to send a postcard to the author!  This will ensure that I (me, the author :) know that other people have an interest in TVP and that I continue to fix bugs, update, and improve it.  However, while most postcard-ware simply requests a postcard, TVP has a small twist!  On the postcard you are requested to write, in your native language (or, if that happens to be English, then in some funky foreign language that you happen to know, or, if English is the only language you know, then English is acceptable) the phrase "Hello!  How are you?".  Print the English name of the language (eg. French instead of Francais) somewhere on the postcard, too.  Then, send the postcard to Tim Vanderhoek / 3484 Ketelbey Crt. / Burlington, ON. / Canada. / L7M 3B4.
 	I assure you, your effort to send such a postcard will be greatly appreciated!  If you add your name and email address, I may even send you a nice thankyou note!  :)
 	TVP owes its genesis to a number of people, all of whom without TVP would not exist.
 	First, my grade 12 computer technology teacher, Harry Blyleven, for assigning an ISU and then giving his class the freedom to choose their own project for the ISU.  This would never have been started, otherwise.
 	Second, Dave Hagan, for convincing me that there might be at least one person interested in a finished version of the game.  :)
 	Sverre H. Huseby <s.h.huseby@usit.uio.no>, who wrote pixmaps for the playing cards which I use, and pointed out some fixes necessary to compile under Linux.  You can grab his library, shhcards-1.0.3, for manipulating cards from http://www.ifi.uio.no/~sverrehu/. 
 	And, finally, myself, for, well, writing everything, and, in general, doing all of the real work.  :)};  # substitution done by make
	set xprez(license)	{GNU GENERAL PUBLIC LICENSE
Version 2, June 1991
  Copyright (C) 1989, 1991 Free Software Foundation, Inc. 675 Mass Ave, Cambridge, MA 02139, USA  Everyone is permitted to copy and distribute verbatim copies  of this license document, but changing it is not allowed.
 Preamble
   The licenses for most software are designed to take away your freedom to share and change it.  By contrast, the GNU General Public License is intended to guarantee your freedom to share and change free software--to make sure the software is free for all its users.  This General Public License applies to most of the Free Software Foundation's software and to any other program whose authors commit to using it.  (Some other Free Software Foundation software is covered by the GNU Library General Public License instead.)  You can apply it to your programs, too.
   When we speak of free software, we are referring to freedom, not price.  Our General Public Licenses are designed to make sure that you have the freedom to distribute copies of free software (and charge for this service if you wish), that you receive source code or can get it if you want it, that you can change the software or use pieces of it in new free programs; and that you know you can do these things.
   To protect your rights, we need to make restrictions that forbid anyone to deny you these rights or to ask you to surrender the rights. These restrictions translate to certain responsibilities for you if you distribute copies of the software, or if you modify it.
   For example, if you distribute copies of such a program, whether gratis or for a fee, you must give the recipients all the rights that you have.  You must make sure that they, too, receive or can get the source code.  And you must show them these terms so they know their rights.
   We protect your rights with two steps: (1) copyright the software, and (2) offer you this license which gives you legal permission to copy, distribute and/or modify the software.
   Also, for each author's protection and ours, we want to make certain that everyone understands that there is no warranty for this free software.  If the software is modified by someone else and passed on, we want its recipients to know that what they have is not the original, so that any problems introduced by others will not reflect on the original authors' reputations.
   Finally, any free program is threatened constantly by software patents.  We wish to avoid the danger that redistributors of a free program will individually obtain patent licenses, in effect making the program proprietary.  To prevent this, we have made it clear that any patent must be licensed for everyone's free use or not licensed at all.
   The precise terms and conditions for copying, distribution and modification follow.

 GNU GENERAL PUBLIC 
 TERMS AND CONDITIONS FOR COPYING, DISTRIBUTION AND MODIFICATION
   0. This License applies to any program or other work which contains a notice placed by the copyright holder saying it may be distributed under the terms of this General Public License.  The "Program", below, refers to any such program or work, and a "work based on the Program" means either the Program or any derivative work under copyright law: that is to say, a work containing the Program or a portion of it, either verbatim or with modifications and/or translated into another language.  (Hereinafter, translation is included without limitation in the term "modification".)  Each licensee is addressed as "you".
 Activities other than copying, distribution and modification are not covered by this License; they are outside its scope.  The act of running the Program is not restricted, and the output from the Program is covered only if its contents constitute a work based on the Program (independent of having been made by running the Program). Whether that is true depends on what the Program does.
   1. You may copy and distribute verbatim copies of the Program's source code as you receive it, in any medium, provided that you conspicuously and appropriately publish on each copy an appropriate copyright notice and disclaimer of warranty; keep intact all the notices that refer to this License and to the absence of any warranty; and give any other recipients of the Program a copy of this License along with the Program.
 You may charge a fee for the physical act of transferring a copy, and you may at your option offer warranty protection in exchange for a fee.
   2. You may modify your copy or copies of the Program or any portion of it, thus forming a work based on the Program, and copy and distribute such modifications or work under the terms of Section 1 above, provided that you also meet all of these conditions:
 a) You must cause the modified files to carry prominent notices stating that you changed the files and the date of any change.
 b) You must cause any work that you distribute or publish, that in whole or in part contains or is derived from the Program or any part thereof, to be licensed as a whole at no charge to all third parties under the terms of this License.
 c) If the modified program normally reads commands interactively when run, you must cause it, when started running for such interactive use in the most ordinary way, to print or display an announcement including an appropriate copyright notice and a notice that there is no warranty (or else, saying that you provide a warranty) and that users may redistribute the program under these conditions, and telling the user how to view a copy of this License.  (Exception: if the Program itself is interactive but does not normally print such an announcement, your work based on the Program is not required to print an announcement.)

 These requirements apply to the modified work as a whole.  If identifiable sections of that work are not derived from the Program, and can be reasonably considered independent and separate works in themselves, then this License, and its terms, do not apply to those sections when you distribute them as separate works.  But when you distribute the same sections as part of a whole which is a work based on the Program, the distribution of the whole must be on the terms of this License, whose permissions for other licensees extend to the entire whole, and thus to each and every part regardless of who wrote it.
 Thus, it is not the intent of this section to claim rights or contest your rights to work written entirely by you; rather, the intent is to exercise the right to control the distribution of derivative or collective works based on the Program.
 In addition, mere aggregation of another work not based on the Program with the Program (or with a work based on the Program) on a volume of a storage or distribution medium does not bring the other work under the scope of this License.
   3. You may copy and distribute the Program (or a work based on it, under Section 2) in object code or executable form under the terms of Sections 1 and 2 above provided that you also do one of the following:
 a) Accompany it with the complete corresponding machine-readable source code, which must be distributed under the terms of Sections 1 and 2 above on a medium customarily used for software interchange; or,
 b) Accompany it with a written offer, valid for at least three years, to give any third party, for a charge no more than your cost of physically performing source distribution, a complete machine-readable copy of the corresponding source code, to be distributed under the terms of Sections 1 and 2 above on a medium customarily used for software interchange; or,
 c) Accompany it with the information you received as to the offer to distribute corresponding source code.  (This alternative is allowed only for noncommercial distribution and only if you received the program in object code or executable form with such an offer, in accord with Subsection b above.)
 The source code for a work means the preferred form of the work for making modifications to it.  For an executable work, complete source code means all the source code for all modules it contains, plus any associated interface definition files, plus the scripts used to control compilation and installation of the executable.  However, as a special exception, the source code distributed need not include anything that is normally distributed (in either source or binary form) with the major components (compiler, kernel, and so on) of the operating system on which the executable runs, unless that component itself accompanies the executable.
 If distribution of executable or object code is made by offering access to copy from a designated place, then offering equivalent access to copy the source code from the same place counts as distribution of the source code, even though third parties are not compelled to copy the source along with the object code.

   4. You may not copy, modify, sublicense, or distribute the Program except as expressly provided under this License.  Any attempt otherwise to copy, modify, sublicense or distribute the Program is void, and will automatically terminate your rights under this License. However, parties who have received copies, or rights, from you under this License will not have their licenses terminated so long as such parties remain in full compliance.
   5. You are not required to accept this License, since you have not signed it.  However, nothing else grants you permission to modify or distribute the Program or its derivative works.  These actions are prohibited by law if you do not accept this License.  Therefore, by modifying or distributing the Program (or any work based on the Program), you indicate your acceptance of this License to do so, and all its terms and conditions for copying, distributing or modifying the Program or works based on it.
   6. Each time you redistribute the Program (or any work based on the Program), the recipient automatically receives a license from the original licensor to copy, distribute or modify the Program subject to these terms and conditions.  You may not impose any further restrictions on the recipients' exercise of the rights granted herein. You are not responsible for enforcing compliance by third parties to this License.
   7. If, as a consequence of a court judgment or allegation of patent infringement or for any other reason (not limited to patent issues), conditions are imposed on you (whether by court order, agreement or otherwise) that contradict the conditions of this License, they do not excuse you from the conditions of this License.  If you cannot distribute so as to satisfy simultaneously your obligations under this License and any other pertinent obligations, then as a consequence you may not distribute the Program at all.  For example, if a patent license would not permit royalty-free redistribution of the Program by all those who receive copies directly or indirectly through you, then the only way you could satisfy both it and this License would be to refrain entirely from distribution of the Program.
 If any portion of this section is held invalid or unenforceable under any particular circumstance, the balance of the section is intended to apply and the section as a whole is intended to apply in other circumstances.
 It is not the purpose of this section to induce you to infringe any patents or other property right claims or to contest validity of any such claims; this section has the sole purpose of protecting the integrity of the free software distribution system, which is implemented by public license practices.  Many people have made generous contributions to the wide range of software distributed through that system in reliance on consistent application of that system; it is up to the author/donor to decide if he or she is willing to distribute software through any other system and a licensee cannot impose that choice.
 This section is intended to make thoroughly clear what is believed to be a consequence of the rest of this License.

   8. If the distribution and/or use of the Program is restricted in certain countries either by patents or by copyrighted interfaces, the original copyright holder who places the Program under this License may add an explicit geographical distribution limitation excluding those countries, so that distribution is permitted only in or among countries not thus excluded.  In such case, this License incorporates the limitation as if written in the body of this License.
   9. The Free Software Foundation may publish revised and/or new versions of the General Public License from time to time.  Such new versions will be similar in spirit to the present version, but may differ in detail to address new problems or concerns.
 Each version is given a distinguishing version number.  If the Program specifies a version number of this License which applies to it and "any later version", you have the option of following the terms and conditions either of that version or of any later version published by the Free Software Foundation.  If the Program does not specify a version number of this License, you may choose any version ever published by the Free Software Foundation.
   10. If you wish to incorporate parts of the Program into other free programs whose distribution conditions are different, write to the author to ask for permission.  For software which is copyrighted by the Free Software Foundation, write to the Free Software Foundation; we sometimes make exceptions for this.  Our decision will be guided by the two goals of preserving the free status of all derivatives of our free software and of promoting the sharing and reuse of software generally.
 NO WARRANTY
   11. BECAUSE THE PROGRAM IS LICENSED FREE OF CHARGE, THERE IS NO WARRANTY FOR THE PROGRAM, TO THE EXTENT PERMITTED BY APPLICABLE LAW.  EXCEPT WHEN OTHERWISE STATED IN WRITING THE COPYRIGHT HOLDERS AND/OR OTHER PARTIES PROVIDE THE PROGRAM "AS IS" WITHOUT WARRANTY OF ANY KIND, EITHER EXPRESSED OR IMPLIED, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE.  THE ENTIRE RISK AS TO THE QUALITY AND PERFORMANCE OF THE PROGRAM IS WITH YOU.  SHOULD THE PROGRAM PROVE DEFECTIVE, YOU ASSUME THE COST OF ALL NECESSARY SERVICING, REPAIR OR CORRECTION.
   12. IN NO EVENT UNLESS REQUIRED BY APPLICABLE LAW OR AGREED TO IN WRITING WILL ANY COPYRIGHT HOLDER, OR ANY OTHER PARTY WHO MAY MODIFY AND/OR REDISTRIBUTE THE PROGRAM AS PERMITTED ABOVE, BE LIABLE TO YOU FOR DAMAGES, INCLUDING ANY GENERAL, SPECIAL, INCIDENTAL OR CONSEQUENTIAL DAMAGES ARISING OUT OF THE USE OR INABILITY TO USE THE PROGRAM (INCLUDING BUT NOT LIMITED TO LOSS OF DATA OR DATA BEING RENDERED INACCURATE OR LOSSES SUSTAINED BY YOU OR THIRD PARTIES OR A FAILURE OF THE PROGRAM TO OPERATE WITH ANY OTHER PROGRAMS), EVEN IF SUCH HOLDER OR OTHER PARTY HAS BEEN ADVISED OF THE POSSIBILITY OF SUCH DAMAGES.
 END OF TERMS AND CONDITIONS

  Appendix: How to Apply These Terms to Your New Programs
   If you develop a new program, and you want it to be of the greatest possible use to the public, the best way to achieve this is to make it free software which everyone can redistribute and change under these terms.
   To do so, attach the following notices to the program.  It is safest to attach them to the start of each source file to most effectively convey the exclusion of warranty; and each file should have at least the "copyright" line and a pointer to where the full notice is found.
 <one line to give the program's name and a brief idea of what it does.> Copyright (C) 19yy  <name of author>
 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.
 You should have received a copy of the GNU General Public License along with this program; if not, write to the Free Software Foundation, Inc., 675 Mass Ave, Cambridge, MA 02139, USA.
 Also add information on how to contact you by electronic and paper mail.
 If the program is interactive, make it output a short notice like this when it starts in an interactive mode:
 Gnomovision version 69, Copyright (C) 19yy name of author Gnomovision comes with ABSOLUTELY NO WARRANTY; for details type `show w'. This is free software, and you are welcome to redistribute it under certain conditions; type `show c' for details.
 The hypothetical commands `show w' and `show c' should show the appropriate parts of the General Public License.  Of course, the commands you use may be called something other than `show w' and `show c'; they could even be mouse-clicks or menu items--whatever suits your program.
 You should also get your employer (if you work as a programmer) or your school, if any, to sign a "copyright disclaimer" for the program, if necessary.  Here is a sample; alter the names:
   Yoyodyne, Inc., hereby disclaims all copyright interest in the program   `Gnomovision' (which makes passes at compilers) written by James Hacker.
   <signature of Ty Coon>, 1 April 1989   Ty Coon, President of Vice
 This General Public License does not permit incorporating your program into proprietary programs.  If your program is a subroutine library, you may consider it more useful to permit linking proprietary applications with the library.  If this is what you want to do, use the GNU Library General Public License instead of this License.
};  # substitution done by make

	set cset(current)	{};  # don't touch this
	set cset(mystatus)	{};  # don't touch this
	set cset(stat1)		{Choose a set to lay}
	set cset(stat2)		{Click on set again to lay it!}
	set aimove_v(jm)	0;  # don't touch this
}


# About the program, in general...
# xprez		- Global configuration data
proc about {} {
	global xprez

	toplevel .about
	wm iconname .about "About TVP"
	wm title .about "All About TVP"
	frame .about.l

	text .about.l.text -relief raised -wrap word \
		-yscrollcommand ".about.l.sby set"
	.about.l.text insert 1.0 $xprez(abouttvp)

	button .about.done -text "Dismiss" -command "destroy .about"
	scrollbar .about.l.sby -command ".about.l.text yview"
	pack .about.done -side bottom
	pack .about.l -fill both -side top -expand true
	pack .about.l.sby -side left -fill y
	pack .about.l.text -side right -fill both -expand 1
}

# Show the license
# xprez		- Global configuration data
proc license {} {
	global xprez

	toplevel .license
	wm iconname .license "TVP License"
	wm title .license "GNU GPL License for Tim Vanderhoek's X-President"
	frame .license.l

	text .license.l.text -relief raised -wrap word \
		-yscrollcommand ".license.l.sby set"
	.license.l.text insert 1.0 $xprez(license)

	button .license.done -text "Dismiss" -command "destroy .license"
	scrollbar .license.l.sby -command ".license.l.text yview"
	label .license.title1 -justify center -foreground #F00 \
		-text "GNU General Public License"
	label .license.title2 -justify center -foreground #F00 \
		-text "Version 2, June 1991"
	pack .license.title1 .license.title2 -fill x -side top
	pack .license.done -side bottom
	pack .license.l -fill both -side top -expand true
	pack .license.l.sby -side left -fill y
	pack .license.l.text -side right -fill both -expand 1
}

# Enable a button named b if $var is true
proc enableButton {b var} {
	global enableButton_v

	set enableButton_v(var) $var
	set enableButton_v(b) $b
	uplevel #0 {

		set foo [eval set bar $$enableButton_v(var)]
		if {$foo} {
			$enableButton_v(b) configure -state normal
		}
	}
}

# This will allow the user to set most of the various configurable
# options...
# namemap	- The AIs we have available
# xprez		- Global configuration data
# mustrestart	- true == mustrestart... :)
proc options {} {
	global namemap xprez staticfoo mustrestart

	# The below doesn't seem to do what I want...  ie. eval to false
	# when .options exists...
	#if {![catch focus .options]} {}

	if {$staticfoo == 1} { return }
	set staticfoo 1

	toplevel .options
	wm iconname .options {Options}
	wm title .options {Configurable X-TVP Options!}

	focus .options

	frame .options.bt
	button .options.bt.dismiss \
		-text {Dismiss} \
		-command {restart .c; destroy .options; set staticfoo 0}
	button .options.bt.apply \
		-text {Apply} \
		-state disabled \
		-command { \
			.options.bt.apply configure -state disabled; \
			restart .c; \
			xp_call mustrestart "enableButton .options.bt.apply mustrestart"}
	pack .options.bt -side bottom
	pack .options.bt.dismiss .options.bt.apply -side left
	xp_call mustrestart "enableButton .options.bt.apply mustrestart"

	scale .options.scale \
		-digits 0 \
		-from 1 \
		-label "Delay between AI turns" \
		-length 8c \
		-showvalue true \
		-to 500 \
		-variable xprez(aidelay) \
		-orient horiz
	pack .options.scale -side top -fill x -expand yes -padx .5c

	checkbutton .options.cclick \
		-variable xprez(roundclick) \
		-text "Click on canvas between rounds"

	pack .options.cclick -side top

	frame .options.ais
	frame .options.ais.ai1

	pack .options.ais -side left -pady 1c
	pack .options.ais.ai1 -side top

	foreach n {2 3 4} {
		set ai xprez(AI$n)
		set frame .options.ais.ai$n
		frame $frame
		pack $frame -side top

		label .options.ais.ai$n.name -text "Player #$n: "
		pack .options.ais.ai$n.name -side left

		foreach {psn} [array names namemap] {
			label $frame.l$psn \
				-text $psn
			radiobutton $frame.r$psn \
				-value $psn \
				-variable $ai
			pack $frame.l$psn $frame.r$psn -side left
		}
	}
}

# This should always be called from the main stuff.  It will setup hooks
# so that everytime a variable is changed which forces the game to be
# started-over, it warns the user...
proc varwatch {} {
	global xprez

	set i 0
	# set-up a process to watch each of the following vars
	foreach var {xprez(AI2) xprez(AI3) xprez(AI4)} {
		set i [incr i]
		xp_call $var "varcatch $var [eval set foo $$var]"
	}
}

# This is called via varwatch.  If $var is going to change, it asks
# if the user really wants to change $var.
proc varcatch {var old} {
	global xprez mustrestart novarcatch

	set new [eval set foo $$var];

	if {$novarcatch} {
		xp_call $var "varcatch $var $new"
		return
	}

	if {[string compare $new $old] == 0 || $mustrestart} {
		xp_call $var "varcatch $var $new"
		return;
	}

	set r [tk_dialog .warning {Need to restart!} \
		"You are about to make a change which requires restarting!  Do you wish to make the change, or keep the old value?  ($old, $var, $new)" \
		warning 0 "Accept" "Revert"]
	if {$r != 0} {
		# We have to do this outside of this proc because trapping
		# of variable writes to $var are disabled while we are in
		# here...
		after 1 "uplevel #0 \" set novarcatch 1; set $var $old; \
			set novarcatch 0; \""
#		set $var $old
		set new $old
	} else {
		set old $new
		if {$mustrestart == 0} {
			set mustrestart 1
		}
	}

	xp_call $var "varcatch $var $new"
}

# This does all of the stuff that is necessary to Restart a game
# c		- The canvas
# lnam		- The ids of the AIs on the canvas
# xprez		- Global configuration data
# mustrestart	- Flag denoting wether or not its time to restart the game
# namemap	- Converts AI names into AI types
proc restart {c} {
	global lnam xprez mustrestart namemap

  if {$mustrestart} {

	set mustrestart 0

	xp_configure $namemap($xprez(AI2)) $namemap($xprez(AI3)) \
		$namemap($xprez(AI4))

	$c itemconfigure $lnam(2) -text $xprez(AI2)
	$c itemconfigure $lnam(3) -text $xprez(AI3)
	$c itemconfigure $lnam(4) -text $xprez(AI4)

	deal $c
  }
}

# Call this before calling any *Cards routines...
# Creates images c1, c2, ... d1, d2 ... back, blank
# globals
#         xprez  --  global configuration data
proc LoadCards {} {
	global xprez

	# find our little card directory
	foreach carddir "[array names xprez carddir*] nodir" {
		if "![catch {image create photo c14 \
		   -file $xprez($carddir)/joker.gif}]" {
			break
		}
	}
	if "![string compare $carddir nodir]" {
		puts {Couldn't open card directory!}
		exit 1
	}

	image create photo c14 -file $xprez($carddir)/joker.gif
	image create photo s14 -file $xprez($carddir)/joker.gif
	image create photo h14 -file $xprez($carddir)/joker.gif
	image create photo d14 -file $xprez($carddir)/joker.gif
	image create photo back -file $xprez($carddir)/backs-$xprez(back).gif
	image create photo blank
	blank blank

	# Create the clubs!
	for {set i 1} {$i <= 13} {incr i} {
		image create photo c$i \
			-file $xprez($carddir)/clubs-${i}.gif
	}
	# Create the spades!
	for {set i 1} {$i <= 13} {incr i} {
		image create photo s$i \
			-file $xprez($carddir)/spades-${i}.gif
	}
	# Create the hearts!
	for {set i 1} {$i <= 13} {incr i} {
		image create photo h$i \
			-file $xprez($carddir)/hearts-${i}.gif
	}
	# Create the diamonds!
	for {set i 1} {$i <= 13} {incr i} {
		image create photo d$i \
			-file $xprez($carddir)/diamonds-${i}.gif
	}
}

# Call this once before calling ShowCards
# c		- The canvas
# xprez		- Global configuration data
# lh		- Left Hand ids
# th		- Top Hand ids
# bh		- Bottom Hand ids
# rh		- Right Hand ids
# mh		- Middle Thingy ids
proc InitCards { c } {
	global xprez lh th bh rh mh

	set yy $xprez(midy)
	for {set j 0} {$j < 4} {incr j} {
		set xx $xprez(midx)
		set mh(label$j) [$c create text \
			[expr $xx - $xprez(midlabdist)]c ${yy}c \
			-justify center \
			-anchor ne \
			-text ""]
		for {set i 0} {$i < 4} {incr i} {
			# Heh.  Watch-out.  This isn't a multi-dimension array.
			set mh($j,$i) [$c create image ${xx}c ${yy}c \
				-anchor nw \
				-image blank]
			set xx [expr $xx + $xprez(inc)]
		}
		set yy [expr $yy + $xprez(inc)]
	}

	set xx $xprez(topx)
	for {set i 0} {$i < 14} {incr i} {
		set th($i) [$c create image ${xx}c $xprez(topy)c \
			-image blank]
		set xx [expr $xx + $xprez(inc)]
	}

	# This is the human's hand.  We'll enable the button-clicking
	# doo-hickey on them.
	set xx $xprez(bottomx)
	for {set i 0} {$i < 14} {incr i} {
		set bh($i) [$c create image ${xx}c $xprez(bottomy)c \
			-image blank]
		# Disable the Double-click, for now...
		#$c bind $bh($i) <Double-Button-1> "LaySet $i $c"
		$c bind $bh($i) <Button-3> "LaySet $i $c"
		$c bind $bh($i) <Button-1> "SelectSet $i $c"
		$c bind $bh($i) <Button-2> "AutoLay $i $c"
		set xx [expr $xx + $xprez(inc)]
	}

	set yy $xprez(lefty)
	for {set i 0} {$i < 14} {incr i} {
		set lh($i) [$c create image $xprez(leftx)c ${yy}c \
			-image blank]
		set yy [expr $yy + $xprez(inc)]
	}

	set yy $xprez(righty)
	for {set i 0} {$i < 14} {incr i} {
		set rh($i) [$c create image $xprez(rightx)c ${yy}c \
			-image blank]
		set yy [expr $yy + $xprez(inc)]
	}
}

# Draw the cards on the table
# c				- The canvas
# top, bottom, left, right	- The hands ("d2 c11 s1 ...")
proc ShowCards { c top bottom left right } {
	global xprez th lh rh bh mh

	set i 0;  # counter of cards shown
	foreach card $top {
		$c itemconfigure $th($i) \
			-image $card
		set i [expr $i + 1]
	}

	set i 0;  # counter of # cards shown
	foreach card $bottom {
		$c itemconfigure $bh($i) \
			-image $card
		set i [expr $i + 1]
	}

	set i 0;  # number of cards shown
	foreach card $left {
		$c itemconfigure $lh($i) \
			-imag $card
		set i [expr $i + 1]
	}

	set i 0;  # number of cards shown
	foreach card $right {
		$c itemconfigure $rh($i) \
			-image $card
		set i [expr $i + 1]
	}

	# j refers to the playnums...
	for {set j 0} {$j < 4} {incr j} {
		for {set i 0} {$i < 4} {incr i} {
			if {$i < [xp_laid $j num]} {
				$c itemconfigure $mh($j,$i) \
					-image [xp_laid $j card]
				$c itemconfigure $mh(label$j) \
					-text $xprez(AI[xp_laid $j player])
			} else {
				$c itemconfigure $mh($j,$i) \
					-image blank
				$c itemconfigure $mh(label$j) \
					-text $xprez(AI[xp_laid $j player])
			}
		}
	}
}

# Save
# xprez		- Global configuration data
proc save {} {
	global xprez

	if "![xp_havefile]" {
		tk_dialog .junk {Upgrade Time!} {You must upgrade to tk42 or better and recompile in order to use the save functions!  Sorry!} error 0 "Dismiss"
		return
	}

	set file [tk_getSaveFile \
		-filetypes {{"X-Prez files" {.xtvp} } {"All files" * }} \
		-initialfile Untitled -defaultextension .xtvp]

	if "![string length $file]" return

	xp_save $file $xprez(AI2) $xprez(AI3) $xprez(AI4)
}

# Load
# lnam		- Some label ids
# xprez		- Global configuration data
# novarcatch	- Prevent changes to xprez(AI?) from being trapped by 
#                 traps set-up by our Options menu
# pos		- ids for the position labels
proc load {} {
	global lnam xprez novarcatch pos

	if "![xp_havefile]" {
		tk_dialog .junk {Upgrade Time!} {You must upgrade to tk42 or better and recompile in order to use the load function!  Sorry!} error 0 "Dismiss"
		return
	}

	set file [tk_getOpenFile \
		-filetypes {{"X-Prez files" {.xtvp} } {"All files" * }} \
		-defaultextension .xtvp]

	if "![string length $file]" return

	set z [xp_load $file $xprez(AI2) $xprez(AI3) $xprez(AI4)]

	set novarcatch 1
	set xprez(AI2) [lindex $z 0]
	set xprez(AI3) [lindex $z 1]
	set xprez(AI4) [lindex $z 2]
	set novarcatch 0

	.f.scores.a1 configure -text "$xprez(AI1) [xp_scores 1]"
	.f.scores.a2 configure -text "$xprez(AI2) [xp_scores 2]"
	.f.scores.a3 configure -text "$xprez(AI3) [xp_scores 3]"
	.f.scores.a4 configure -text "$xprez(AI4) [xp_scores 4]"

	.c itemconfigure $pos(2) -text [xp_position 2]
	.c itemconfigure $pos(3) -text [xp_position 3]
	.c itemconfigure $pos(4) -text [xp_position 4]

	ShowCards .c [xp_cards 4] [xp_cards 1] [xp_cards 2] [xp_cards 3]

	.c itemconfigure $lnam(2) -text $xprez(AI2)
	.c itemconfigure $lnam(3) -text $xprez(AI3)
	.c itemconfigure $lnam(4) -text $xprez(AI4)

	ai_resched_loop .c
	unselectcurrentset .c

# ALSO need to adjust the .f.pass button...

}

# This will deal...
# c		- The canvas
# xprez		- Global configuration data
# pos		- ids for the position labels
proc deal {c} {
	global xprez pos aimove_v

	set xxx [xp_deal]
	if {[string length $xxx] != 0} {
		tk_dialog .junk {Cards Switched} $xxx info 0 "Dismiss"
	}

	.f.scores.a1 configure -text "$xprez(AI1) [xp_scores 1]"
	.f.scores.a2 configure -text "$xprez(AI2) [xp_scores 2]"
	.f.scores.a3 configure -text "$xprez(AI3) [xp_scores 3]"
	.f.scores.a4 configure -text "$xprez(AI4) [xp_scores 4]"

	$c itemconfigure $pos(2) -text [xp_position 2]
	$c itemconfigure $pos(3) -text [xp_position 3]
	$c itemconfigure $pos(4) -text [xp_position 4]

	ShowCards $c [xp_cards 4] [xp_cards 1] [xp_cards 2] [xp_cards 3]

	.f.pass flash
	.f.pass configure \
		-text "Pass" \
		-command "pass $c"

	unselectcurrentset $c
	ai_resched_loop $c
}

# This is called as an event-handler by the Tcl after command.
# It can be called at anytime and will not assume that it is one
# of the AI players' turns.
# c		- The canvas
# xprez		- Global configuration data
# aimove_v	- Variables used by aimove
# cset		- Information about the currently-selected set
proc aimove {c} {
	global xprez aimove_v cset

	# prevent some event-processor from starting another after aimove
	# while we are in tkwait...
	set aimove_v(ailoop) {running}

	# If everyone's gone, and if we've been instructed to wait
	# for a mouse-click after every round, then we'll wait for
	# said mouse-click...  Also, don't enter into this wait-mode
	# if there is only one player left...  Also, don't enter this
	# if I just moved...  Also don't enter this if the human's out...
	# Or don't enter this if it is the human's turn...
	if {[xp_all] && $xprez(roundclick) && [xp_left] > 1 && !$aimove_v(jm) \
	  && [xp_human] && [xp_turn] != 1} {

		set aimove_v(waiting_for_click) true
		.status configure -text {Click on centre-screen!}
		bind $c <Button-1> {+set aimove_v(waiting_for_click) false}
		vwait aimove_v(waiting_for_click)
		.status configure -text {}

		set aimove_v(i) 0
		after $xprez(aidelay) {set aimove_v(i) 1}
		vwait aimove_v(i)
	}

	if {[string length [xp_aimove]]} {
		unselectcurrentset $c
		set aimove_v(jm) 0
	}

	# if it is the human's turn and if there is no currently-selected set
	if {[xp_turn] == 1 && ![string length $cset(current)]} {
		set cset(mystatus) $cset(stat1)
		.status configure -text $cset(mystatus)
	} else {
		if {![string compare [.status cget -text] $cset(stat1)]} {
			.status configure -text {}
		}
	}

	ShowCards $c [xp_cards 4] [xp_cards 1] [xp_cards 2] [xp_cards 3]

	# If it's time to deal, then change the "pass" puppy to a
	# "deal" puppy, eh...
	if {![xp_turn]} {
		.f.pass configure \
			-text "Deal!!" \
			-command "deal $c"
		FlashDeal .f.pass
	}

	if {[xp_turn] != 1 && [xp_turn] != 0} {
		set aimove_v(ailoop) [after $xprez(aidelay) aimove $c]
	} else {
		set aimove_v(ailoop) {}
	}
}

# This will flash a button, and continue flashing said button until
# xp_turn returns non-zero
# b		- A button to flash
proc FlashDeal {b} {
	if {[xp_turn] == 0} {
		$b flash
		after 150 FlashDeal $b
	}
}

# This will move the ailoop scheduling to an even divisor of $xprez(aidelay)
# c		- The canvas
# aimove_v	- aimove variables
# xprez		- Global configuration
proc ai_resched_loop {c} {
	global aimove_v xprez

	# Schedule an ailoop only if there isn't one already running
	if {[string compare $aimove_v(ailoop) "running"]} {
		if {[string length $aimove_v(ailoop)]} {
			after cancel $aimove_v(ailoop)
		}
		set aimove_v(ailoop) [after $xprez(aidelay) aimove $c]
	}
}

# Select a set based on the card clicked-on, or, if a set is already
# selected and is about to be selected, AGAIN, then lay that set.
# card		- Index to $bh() for which card was clicked on
# c		- The canvas
# xprez		- Global configuration data
# bh		- The cards on the bottom hand
# aimove_v	- aimove variables
# cset		- Information about the currently-selected set
proc SelectSet {card c} {
	global xprez bh aimove_v cset

	if {[string length $cset(current)] && \
	  [string compare $cset(current) [xp_select $card]] == 0} {
		# There is a currently-selected set, and it is the
		# same as the newly-selected set.

		set foo2 0
		foreach i $cset(current) {
			incr foo2
		}
		if {[string length [set foo [xp_lay $cset(current) $foo2]]]} {
			tk_dialog .loser {Can't lay set!} \
				$foo error 0 "Ok"
		} else {
			ai_resched_loop $c

			# denote the fact that the human just moved
			set aimove_v(jm) 1
		}

		unselectcurrentset $c

		ShowCards $c [xp_cards 4] [xp_cards 1] [xp_cards 2] [xp_cards 3]
		return
	}

	unselectcurrentset $c

	# xp_select will select the proper cards, and return 
	# what numbers the cards are, ie. it will return indice into
	# the $bh() array (note that it also takes an index into the
	# $bh() array).  If it can't make the clicked-card into
	# a current set, it will return an empty string.

	set cset(current) [xp_select $card]

	# Highlight the current-set...
	foreach i $cset(current) {
		$c move $bh($i) 0 -$xprez(raise)c
	}

	set cset(mystatus) $cset(stat2)
	.status configure -text $cset(mystatus)
}

# Unselect any possibly selected set
# c		- The canvas
# bh		- The bottom-hand cards
# xprez		- Global configuration data
# cset		- Information related to the currently-selected set
proc unselectcurrentset {c} {
	global bh xprez cset

	# if there is a currently-selected set, de-select it...
	if {[string length $cset(current)]} {
		foreach i $cset(current) {
			$c move $bh($i) 0 $xprez(raise)c
		}
	}
	set cset(current) {}

	# If we own the current status-line...
	if {![string compare [.status cget -text] $cset(mystatus)]} {
		if {[xp_turn] == 1} {
			set cset(mystatus) $cset(stat1)
			.status configure -text $cset(mystatus)
		} else {
			.status configure -text {}
		}
	}
}

# Lay the selected set
# card		- index to $bh() for which card was clicked on
# c		- the canvas
# xprez		- Global configuaration data
proc LaySet {card c} {
	global xprez

	unselectcurrentset $c

	SelectSet $card $c
	SelectSet $card $c
}

# Make the move of passing
# c		- The canvas
# xprez		- Global configuration data
# bh		- Bottom hand ids
# aimove_v	- aimove variables
proc pass {c} {
	global xprez bh aimove_v

	unselectcurrentset $c

	if {[string length [set foo [xp_lay 0 0]]]} {
		tk_dialog .loser {Can't make move!} \
			$foo error 0 "Ok"
	} else {
		ai_resched_loop $c

		# denote the fact that the human just moved
		set aimove_v(jm) 1
	}
}

Customize 

wm title . "Tim Vanderhoek's X-President!"
wm resizable . 0 0
canvas .c \
	-closeenough 0 \
	-height [expr $xprez(bottomy) + 1.7]c \
	-width [expr $xprez(rightx) + 1.5]c
frame .f -relief sunken
frame .f.filler -height 2.5c
button .f.quit -text "Quit!" -command "destroy ."
button .f.license -text "See License" -command "license"
button .f.save -text "Save" -command "save"
button .f.load -text "Load" -command "load"
button .f.options -text "Options" -command "options"
button .f.about -text "About" -command "about"
button .f.pass -text "Pass" -command "pass .c"
button .f.standings -text "Standings" -command "standings"

frame .f.scores -relief raised -borderwidth 2m -height 4c
label .f.scores.a1 -text "$xprez(AI1) [xp_scores 1]"
label .f.scores.a2 -text "$xprez(AI2) [xp_scores 2]"
label .f.scores.a3 -text "$xprez(AI3) [xp_scores 3]"
label .f.scores.a4 -text "$xprez(AI4) [xp_scores 4]"

label .status

pack .status -side bottom
pack .f .c -side left -fill both
pack .f.scores -side bottom
pack .f.scores.a1 .f.scores.a2 .f.scores.a3 .f.scores.a4
pack .f.filler .f.options .f.save .f.load .f.about .f.license .f.quit .f.pass \
	-side top -fill x

# This will watch over all the variables that, when changed, force
# us to start over, again.
set novarcatch 0
set mustrestart 0
varwatch

# The global arrays rh, lh, bh, th hold the 14 ids, corresponding to
# the first, second, third, etc. card.  When a card is clicked on,
# if it is in the special-cased bh hand, it will first call 
# choosecard, which will select all the cards below it that are of
# the same type (eg. all fives), and colour their backgrounds yellow
# to show that they have been selected.  Then, the next time the card
# is clicked on and calls choosecard, choosecard will release that this
# is the second time this card is being clicked (it keeps a global
# variable denoting which card was last clicked on) and attempt to
# lay the cards.  If it can't, it will pop-up a warning dialog box.
# It will then switch temporarily into auto-pilot mode.  A button,
# "AI move" will become active, and if pressed, the AI will make its
# move.  Otherwise, the AI will move based on the expiration of a timer.

# Configure the libass and AI stuff...
# Do the defaults here.  If they change stuff through options, alert the
# user that they will lose this game that is already started.

set pos(2) [.c create text $xprez(leftx)c .4c \
	-anchor n \
	-text [xp_position 2] \
	-fill #A02]
set lnam(2) [.c create text $xprez(leftx)c 0 \
	-anchor n \
	-text $xprez(AI2)]; # left

set pos(4) [.c create text [expr $xprez(topx) + $xprez(inc) * 7]c .4c \
	-anchor n \
	-text [xp_position 4] \
	-fill #A02]
set lnam(4) [.c create text [expr $xprez(topx) + $xprez(inc) * 7]c 0 \
	-anchor n \
	-text $xprez(AI4)]; # top

set pos(3) [.c create text $xprez(rightx)c .4c \
	-anchor n \
	-text [xp_position 3] \
	-fill #A02]
set lnam(3) [.c create text $xprez(rightx)c 0 \
	-anchor n \
	-text $xprez(AI3)]; # right

LoadCards
InitCards .c

xp_configure $namemap($xprez(AI2)) $namemap($xprez(AI3)) $namemap($xprez(AI4))

# Initialization for ai_resched_loop
set aimove_v(ailoop) [after $xprez(aidelay) aimove .c]

# Initialization for proc options
set staticfoo 0

# So that any clicks on open canvas will unselect the current set
set underbelly [.c create rectangle 0 0 [.c cget -width] [.c cget -height] \
	-outline {}]
.c bind $underbelly <Button-1> "unselectcurrentset .c"
.c raise $underbelly $lnam(3)

deal .c
