use subs qw( WriteInitializationFile yfiSOD WriteHomepage WriteCGIFile gamsxinst DOSify yfiSOD  );

use Cwd;
use Storable;
use Tk;
require Tk::ErrorDialog;
use Win32::Shortcut;
use Win32::Process;
use File::Basename;

$Courier = '-*-Courier-Medium-R-Normal--*-140-*-*-*-*-*-*';
$Medium = '-*-Helvetica-Medium-R-Normal--*-140-*-*-*-*-*-*';
$Bold = '-*-Helvetica-Bold-R-Normal--*-180-*-*-*-*-*-*';
$Large = '-*-Helvetica-Bold-R-Normal--*-220-*-*-*-*-*-*';

$top = new MainWindow;

$top->title("GAMS-X Installation");

$gamsinstHeader = $top->Label(
	-text => "GAMS-X Install Utility",
	-font => $Bold
)->pack(
	-expand => 1,
	-padx => 1,
	-pady => 1
);

$gamsinstInstructions = $top->Label(
	-text => "Please select the following files and directories and click on the OK button.  For more information, you can use the 'Help' buttons.",
)->pack(
	-expand => 1,
	-padx => 1,
	-pady => 1
);

$gamsinstFilesFrame = $top->Frame->pack(
	-expand => 1,
	-padx => 1,
	-pady => 1
);

$gamsinstUnzip = {};

@dirs = qw( PBin PLib GDir GXRoot GXDir GXLoc CGIRoot CGILoc Gnuplot );

@files = qw( Browser TextEditor );

@info = qw( Organization WebmasterEmail );

$descriptions = {

	'PBin' => 'The Perl executable directory:',
	'PLib' => 'The Perl library directory:',
	'GDir' => 'The GAMS root directory:',
	'GXRoot' => 'The GAMS-X root directory:',
	'GXDir' => 'The GAMS-CGI HTML directory (optional):',
	'Browser' => 'Your web browser of choice:',
	'TextEditor' => 'Your text editor of choice:',
	'Gnuplot' => 'The Gnuplot directory (optional):',
	'GXLoc' => 'The GAMS-CGI domain name (optional):',
	'CGIRoot' => 'Your CGI executable directory (optional):',
	'CGILoc' => 'The CGI virtual directory (optional):',
	'Organization' => 'The site affiliation (optional):',
	'WebmasterEmail' => "The webmaster's email address (optional):"

};

$help->{'PBin'} = <<"eop";
Select the directory that is your Perl executable directory.  This is where the Perl executable is found, and typically would be 

/usr/local/perl/bin

in Unix and 

C:\\Perl\\bin

in Windows, or, if you are using the Perl Developer's Kit or Perl Resource Kit for Windows,

C:\\Perl\\5.005\\bin\\MSWindows-x86-object

Note that the Unix directory divider '/' and the DOS directory divider '\\' are both recognized by Perl, so you can use either in the path name of the directory.

eop

$help->{'PLib'} = <<"eop";
Select the directory that is your Perl Library.  Typically this would be 

/usr/local/perl/lib

in Unix and 

c:\\Perl\\site\\lib

in Windows.

Note that the Unix directory divider '/' and the DOS directory divider '\\' are both recognized by Perl, so you can use either in the path name of the directory.

eop

$help->{'GDir'} = <<"eop";
Select the directory that is your GAMS root directory.  Typically this would be 

/usr/local/gams

in Unix and 

c:\\gams

in Windows.

Note that the Unix directory divider '/' and the DOS directory divider '\\' are both recognized by Perl, so you can use either in the path name of the directory.

eop

$help->{'GXRoot'} = <<"eop";
Select the directory that you would like GAMS-X to be installed in.  Typically this would be 

/usr/local/gams-x

in Unix and 

c:\\gams-x

in Windows.

If the directory you select does not exist, it will be created.  Its parent, however, must be an existing directory; e.g., if you want to install into c:\\mydir\\gams-x, c:\\mydir must exist.

Note that the Unix directory divider '/' and the DOS directory divider '\\' are both recognized by Perl, so you can use either in the path name of the directory.

eop

unless ($OS = $^O) {
	require Config;
	$OS = $Config::Config{'osname'};
}

$username = $OS =~ /Win/i ? 'username' : getpwuid ($>);

$help->{'GXDir'} = <<"eop";
Select the directory that you would like the web-accessible GAMS-X HTML files, such as model documentation and graphs, to be located in.  Typically you might use something like 

/home/$username/public_html/gams-cgi

in Unix.  In Windows, this directory depends on the web server that you are supporting.

With Apache, this would typically look like 

C:\\apache\\htdocs\\gams-cgi

Microsoft Internet Information Server (MIIS) might use

C:\\Inetpub\\wwwroot\\gams-cgi

ZBServer might use 

C:\\zbs\\html\\gams-cgi

Consult your web server documentation for more information.

If the directory you select does not exist, it will be created.  Its parent, however, must be an existing directory; e.g., if you want to install into c:\\apache\\htdocs\\gams-x, c:\\apache\\htdocs must exist.

If you do not intend to use GAMS-CGI, leave this selection blank.

Note that the Unix directory divider '/' and the DOS directory divider '\\' are both recognized by Perl, so you can use either in the path name of the directory.

eop

$help->{'Browser'} = <<"eop";
Select the executable file that corresponds to your favorite text editor; for example,

/usr/local/bin/netscape

in Unix or

C:\\Windows\\notepad.exe

in Windows.  Even if you are not using GAMS-CGI, the browser is used for viewing model documentation, and so should be identified.

To select the file from a file browser, choose the 'Browse' button to the right of the entry field.
eop

$help->{'TextEditor'} = <<"eop";
Select the executable file that is your web browser; e.g.,

/usr/local/bin/emacs

in Unix or

C:\\Windows\\notepad.exe

in Windows.

To select the file from a file browser, choose the 'Browse' button to the right of the entry field.
eop

$help->{'Gnuplot'} = <<"eop";
Select the Gnuplot directory; e.g.,

/usr/local/bin/gnuplot

in Unix or

C:\\Gnuplot

in Windows.  If you do not already have Gnuplot installed, GAMS-X will install it in the directory you specify.
eop

$help->{'GXLoc'} = <<"eop";
Enter the URL of the base domain name associated with this site.  This should be the URL used for the GAMS-CGI site.  For example,

http://economics.colorado.edu/gams-cgi

The URL should correspond to the virtual name of the directory given in the '$descriptions->{'GXDir'}' entry box.

eop

$help->{'CGIRoot'} = <<"eop";
Enter the path of the CGI executable directory associated with the GAMS-CGI site.  

In Windows, it might be something like

C:\\apache\\cgi-bin

if you are using Apache,

C:\\Inetpub\\scripts

if you are using Microsoft Internet Information Server (MIIS), or

C:\\Zbs\\cgi

if you are using ZBServer.  In Unix, it might be something like

/home/$username/public_html/cgi-bin

For more information, consult your web server documentation or the GAMS-X User's Guide and Owner's Manual.

eop

$help->{'CGILoc'} = <<"eop";
Enter the URL of the CGI executable directory associated with the GAMS-CGI site.  This URL will form the base of all CGI calls executed using GAMS-CGI.  

In Windows, it might be something like

http://economics.colorado.edu/cgi-bin

if you are using Apache, 

http://economics.colorado.edu/scripts

if you are using Microsoft Internet Information Server (MIIS), or

http://economics.colorado.edu/cgi

if you are using ZBServer.  On a Unix system with a C setuid wrapper called cgi-proxy, it might be something like

http://economics.colorado.edu/cgi-bin/cgi-proxy/$username/cgi-bin

With many servers, relative URLs may be given, such as 

/scripts

in Windows or

/cgi-bin/cgi-proxy/$username/cgi-bin

in Unix.

For more information, consult your web server documentation or the GAMS-X User's Guide and Owner's Manual.

eop

$help->{'Organization'} = <<"eop";
Enter the organization that will be affiliated with this website.  For example,

University of Colorado at Boulder Department of Economics

This information is used in a small blurb attached at the bottom of each GAMS-CGI page.

eop

$help->{'WebmasterEmail'} = <<"eop";
Enter the email of the webmaster who will be administering this site.  For example,

collin.starkweather\@colorado.edu

This information is used in a small blurb attached at the bottom of each GAMS-CGI page.

eop

$i = 0;

$gamsinstUnzip->{'Frame'} = $gamsinstFilesFrame->Frame->pack(
	-pady => 4,
	-padx => 4,
	-expand => 1
);

for my $dir (@dirs,@info) {

$gamsinstUnzip->{$dir}->{'Label'} = $gamsinstUnzip->{'Frame'}->Label(
	-justify => 'left',
	-anchor => 'w',
	-text => $descriptions->{$dir},
	-font => $Courier
)->grid(
	-row => $i,
	-column => 0,
	-pady => 4,
	-padx => 4,
	-sticky => 'nsew'
);

$gamsinstUnzip->{$dir}->{'Entry'} = $gamsinstUnzip->{'Frame'}->Entry(
	-width => 40,
)->grid(
	-row => $i,
	-column => 1,
	-pady => 4,
	-padx => 4,
	-sticky => 'nsew'
);

$gamsinstUnzip->{$dir}->{'Help'} = $gamsinstUnzip->{'Frame'}->Button(
	-text => 'Help',
	-command => sub {

	my $Dialog = $top->Dialog(
		-justify => 'left',
		-anchor => 'w',
		-title => "GAMS-X Install Help",
		-text => $help->{$dir},
		-bitmap         => 'info',
		-default_button => 'OK',
		-buttons        => ['OK'],
		-wraplength     => '7i'
	);

	my $answer = $Dialog->Show;		

	}
)->grid(
	-row => $i,
	-column => 3,
	-pady => 4,
	-padx => 4,
	-sticky => 'nsew'
);

$i++

}

for my $file (@files) {

$gamsinstUnzip->{$file}->{'Label'} = $gamsinstUnzip->{'Frame'}->Label(
	-justify => 'left',
	-anchor => 'w',
	-text => $descriptions->{$file},
	-font => $Courier
)->grid(
	-row => $i,
	-column => 0,
	-pady => 4,
	-padx => 4,
	-sticky => 'nsew'
);

$gamsinstUnzip->{$file}->{'Entry'} = $gamsinstUnzip->{'Frame'}->Entry(
	-width => 40,
)->grid(
	-row => $i,
	-column => 1,
	-pady => 4,
	-padx => 4,
	-sticky => 'nsew'
);

$gamsinstUnzip->{$file}->{'Browse'} = $gamsinstUnzip->{'Frame'}->Button(
	-text => 'Browse',
	-command => sub {

		my $myfile = $top->getOpenFile(
			-title => $file
		);

		$gamsinstUnzip->{$file}->{'Entry'}->delete(0,'end');
		$gamsinstUnzip->{$file}->{'Entry'}->insert(0,$myfile);

	}

)->grid(
	-row => $i,
	-column => 2,
	-pady => 4,
	-padx => 4,
	-sticky => 'nsew'
);

$gamsinstUnzip->{$file}->{'Help'} = $gamsinstUnzip->{'Frame'}->Button(
	-text => 'Help',
	-command => sub {

	my $Dialog = $top->Dialog(
		-justify => 'left',
		-anchor => 'w',
		-title => "GAMS-X Install Help",
		-text => $help->{$file},
		-bitmap         => 'info',
		-default_button => 'OK',
		-buttons        => ['OK'],
		-wraplength     => '7i'
	);

	my $answer = $Dialog->Show;		

	}
)->grid(
	-row => $i,
	-column => 3,
	-pady => 4,
	-padx => 4,
	-sticky => 'nsew'
);

$i++

}

$gamsxinstButtonsFrame = $top->Frame;

$gamsxinstButtonsFrame->pack;

$gamsxinstOKFrame = $gamsxinstButtonsFrame->Frame(
	-relief => 'sunken',
	-borderwidth => 1
);

$gamsxinstOKFrame->pack(
	-side => 'left', 
	-expand => 'yes', 
	-padx => '3m', 
	-pady => '2m'
);

$gamsxinstOK = $gamsxinstOKFrame->Button(
	-text => 'OK',
	-command => sub {

		#	Install GAMS-X here
		gamsxinst

		        }
)->pack(-padx => '2m', 
	-pady => '2m', 
	-side => 'left'
);

$gamsxinstCancel = $gamsxinstButtonsFrame->Button(
	-text => 'Cancel',
	-command => sub {

		$top->destroy

		        }
)->pack(-padx => '2m', 
	-pady => '2m', 
	-side => 'left'
);

$gamsxinstHelp = $gamsxinstButtonsFrame->Button(
	-text => 'Help',
	-command => sub {

	if (Exists($Announcement)) { $Announcement->destroy }

my $help = <<"eop";
Choose the directories and files as requested, then click on 'OK.'

If you have questions about an individual files or directories, click on the 'Help' button to the right of the appropriate entry box.

To choose a file, select the 'Browse' button to the right of the entry box.

For more information on installing GAMS-X, visit the GAMS-X User's Guide and Owner's Manual at

http://www.gams.com/gams-x
eop

	$Announcement = $top->Dialog(
		-title          => 'GAMS-X Install Help',
		-text           => $help,
		-bitmap         => 'info',
		-default_button => 'OK',
		-buttons        => ['OK'],
		-wraplength     => '4i'
	);

	$AnnouncementButton = $Announcement->Show;

	$Announcement->destroy

 		        }
)->pack(-padx => '2m', 
	-pady => '2m', 
	-side => 'left'
);

$top->bind(
	'<Escape>' => [
	                sub {  

		$top->destroy

			    }
		      ]
);

#	Now find some defaults
$default = {};

$default->{'GXRoot'} = $OS =~ /Win/i ? 'C:\gams-x' : "/home/$username/gams-x";

for (reverse grep !/^\./, grep /site[\/\\]lib$/, @INC) { $default->{'PLib'} = $_ }

if ( not ( $default->{'PBin'} = $^X ) =~ s/[\/\\]perl\.exe$//i ) {

	( $default->{'PBin'} = $default->{'PLib'} ) =~ s/site[\/\\]lib$/bin/;

}

@PATH = $OS =~ /Win/i ? split /;/, $ENV{PATH} : split /:/, $ENV{PATH};

$perl       = $OS =~ /Win/i ? 'perl.exe'     : 'perl';
$gams       = $OS =~ /Win/i ? 'gams.exe'     : 'gams';
$browser    = $OS =~ /Win/i ? 'netscape.exe' : 'netscape';
$texteditor = $OS =~ /Win/i ? 'notepad.exe'  : 'emacs';
$gnuplot    = $OS =~ /Win/i ? 'wgnuplot.exe' : 'gnuplot';

my @default_gxdirs = ( 'C:\apache\htdocs', 'C:\Inetpub\wwwroot', 'C:\zbs\html' );

my $default_gxdirs;

for $default_gxdirs (@default_gxdirs) {

	$default->{'GXDir'} = $default_gxdirs . '\gams-cgi' if -d $default_gxdirs

}

for $PATH (grep !/^[H-Z]\:/, @PATH) {

	if (-f $PATH . "/$gams") {

		$default->{'GDir'} = $PATH;

	} 

	if (basename ( $PATH ) =~ /html/i) {

		$default->{'GXDir'} = $PATH;

	} 

	if (basename ( $PATH ) =~ /cgi|scripts/i and not $PATH =~ /gams\-?cgi|gams\-x/i) {

		$default->{'CGIRoot'} = $PATH;
		$default->{'CGILoc'} = '/' . basename ( $PATH );

	} 

	if (-f $PATH . "/$browser") {

		$default->{'Browser'} = $OS =~ /Win/i ? $PATH . "\\$browser" : $PATH . "/$browser";

	} 

	if (-f $PATH . "/$texteditor") {

		$default->{'TextEditor'} = $OS =~ /Win/i ? $PATH . "\\$texteditor" : $PATH . "/$texteditor";

	}

	if (-f $PATH . "/$gnuplot") {

		$default->{'Gnuplot'} = $PATH;

	} 

}


if (not $default->{'CGIRoot'}) {

my @default_cgidirs = ( 'C:\apache\cgi-bin', 'C:\Inetpub\scripts', 'C:\zbs\cgi' );

my $default_cgidirs;

for $default_cgidirs (@default_cgidirs) {

	if (-d $default_cgidirs) {

		$default->{'CGIRoot'} = $default_cgidirs;
		$default->{'CGILoc'} = '/' . basename ( $default_cgidirs );

	} 

}

}

$default->{'Organization'} = "Your affiliation here";

$default->{'WebmasterEmail'} = "your\@email.here";

if (exists $default->{'GXDir'}) {

	$default->{'GXLoc'} = "http://your.site.here/gams-cgi"

}

for $key (sort keys %{$default}) {

	$gamsinstUnzip->{$key}->{'Entry'}->insert(0,$default->{$key})

}


MainLoop;

sub gamsxinst {

my @PATH = $OS =~ /Win/i ? split /;/, $ENV{PATH} : split /:/, $ENV{PATH};

unshift @PATH, '.';

my ($PATH,$unzip) = ('','');

for $PATH (grep !/^[H-Z]\:/, @PATH) {
	if ($OS =~ /Win/i) {
		$unzip = yfiSOD ( "$PATH/unzip.exe" ) if -f "$PATH/unzip.exe";
		$unzipdir = yfiSOD ( dirname ($unzip) ) if -f "$PATH/unzip.exe";
	} else {
		$unzip = yfiSOD ( "$PATH/unzip" ) if -f "$PATH/unzip";
		$unzipdir = yfiSOD ( dirname ($unzip) ) if -f "$PATH/unzip";
	}
}	

if (not $unzip) {
	print LOG "Error:  Unzip not found in path!\n";
	die "Cannot install GAMS-X:  The unzip utility cannot be found in your path!\n\nYou can obtain a copy of the unzip utility from the GAMS-X homepage at the same site as you download the GAMS-X installation files.\n\n"
}

$cwd = cwd();

$PBin = $gamsinstUnzip->{'PBin'}->{'Entry'}->get
	|| die "You must provide a directory name for the Perl binary directory!\n";
$PBin =~ s/[\\\/]$//;
chomp ( $PBin = yfiSOD( $PBin ) );

$PLib = $gamsinstUnzip->{'PLib'}->{'Entry'}->get
	|| die "You must provide a directory name for the Perl library directory!\n";
$PLib =~ s/[\\\/]$//;
chomp ( $PLib = yfiSOD( $PLib ) );

$GDir = $gamsinstUnzip->{'GDir'}->{'Entry'}->get
	|| die "You must provide a directory name for the GAMS root directory!\n";
$GDir =~ s/[\\\/]$//;
chomp ( $GDir = yfiSOD( $GDir ) );

$GXRoot = $gamsinstUnzip->{'GXRoot'}->{'Entry'}->get
	|| die "You must provide a directory name for the GAMS-X root directory!\n";
$GXRoot =~ s/[\\\/]$//;
chomp ( $GXRoot = yfiSOD( $GXRoot ) );

$GXLoc = $gamsinstUnzip->{'GXLoc'}->{'Entry'}->get;
$GXLoc =~ s/[\\\/]$//;
chomp ( $GXLoc = yfiSOD( $GXLoc ) );

$GXDir = $gamsinstUnzip->{'GXDir'}->{'Entry'}->get
	|| $GXRoot;
$GXDir =~ s/[\\\/]$//;
chomp ( $GXDir = yfiSOD( $GXDir ) );

$CGIRoot = $gamsinstUnzip->{'CGIRoot'}->{'Entry'}->get;
$CGIRoot =~ s/[\\\/]$//;
chomp ( $CGIRoot = yfiSOD( $CGIRoot ) );

$CGILoc = $gamsinstUnzip->{'CGILoc'}->{'Entry'}->get;
$CGILoc =~ s/[\\\/]$//;
chomp ( $CGILoc = yfiSOD( $CGILoc ) );

$Browser = $gamsinstUnzip->{'Browser'}->{'Entry'}->get;
$Browser =~ s/[\\\/]$//;
chomp ( $Browser = yfiSOD( $Browser ) );

$TextEditor = $gamsinstUnzip->{'TextEditor'}->{'Entry'}->get;
$TextEditor =~ s/[\\\/]$//;
chomp ( $TextEditor = yfiSOD( $TextEditor ) );

$Gnuplot = $gamsinstUnzip->{'Gnuplot'}->{'Entry'}->get;
$Gnuplot =~ s/[\\\/]$//;
chomp ( $Gnuplot = yfiSOD( $Gnuplot ) );

$Organization   = $gamsinstUnzip->{'Organization'}->{'Entry'}->get;
$WebmasterEmail = $gamsinstUnzip->{'WebmasterEmail'}->{'Entry'}->get;

if (not -f "$PBin/$perl") {
	die "The Perl executable was not detected in the Perl binary directory '$PBin'!\n"
}

if (not -d $PLib) {
	die "The Perl library cannot be found!  Are you sure that '$PLib' is the correct directory name?\n"
}

if (not -f "$GDir/$gams") {
	die "The GAMS executable was not detected in the GAMS root directory '$GDir'!\n"
}

if (not -d dirname($GXRoot)) {
	die "The directory '@{[dirname($GXRoot)]}' cannot be found!  Please select another name for your GAMS-X root directory.\n"
} 

if (not -d dirname($GXDir)) {
	die "The directory '@{[dirname($GXDir)]}' cannot be found!  Please select another name for your GAMS-X public HTML directory.\n"
}

$message = <<"eop";
GAMS-X will be installed with the following configuration:

The Perl Executable Directory:  $PBin
The Perl Library Directory:  $PLib
The GAMS Root Directory:  $GDir
The GAMS-X Root Directory:  $GXRoot
The GAMS-X public HTML directory:  $GXDir
The domain name of your GAMS-CGI site (optional):  $GXLoc
The path name of your CGI executable directory (optional):  $CGIRoot
The virtual name of your CGI executable directory (optional):  $CGILoc
The Gnuplot directory:  $Gnuplot
The organization Affiliated with this site (optional):  $Organization
The webmaster's email address (optional)  $WebmasterEmail
Your web browser:  $Browser
Your text editor:  $TextEditor

eop

$Announcement = $top->Dialog(
	-title          => 'GAMS-X Install Confirmation',
	-text           => $message,
	-bitmap         => 'info',
	-default_button => 'OK',
	-buttons        => ['OK','Cancel'],
	-wraplength     => '8i'
);

$AnnouncementButton = $Announcement->Show;

$Announcement->destroy; 

die "GAMS-X was not installed.\n" if $AnnouncementButton ne 'OK';

open (LOG, ">$cwd/gams-xinst.log") || die "Can't open log file $cwd/gams-xinst.log:  $!";

print LOG "GAMS-X installation beginning . . .\n\n";

print LOG <<"eop";
The following information was entered:

PBin:            $PBin
PLib:            $PLib
GDir:            $GDir
GXRoot:          $GXRoot
GXDir:           $GXDir
GXLoc:           $GXLoc
CGIRoot:         $CGIRoot
CGILoc:          $CGILoc
Gnuplot:         $Gnuplot
Organization:    $Organization
WebmasterEmail:  $WebmasterEmail
Browser:         $Browser
TextEditor:      $TextEditor

eop

$CWD = DOSify( $cwd );

$source = DOSify( $cwd . '/gams-xinst.zip' );
$target = DOSify( $cwd );

my ($status,$ProcessObj);

print LOG "Unzipping via unzip $source -d $target . . .\n\n";

if ($OS =~ /Win/i) {

	Win32::Process::Create(
		$ProcessObj,
		DOSify ( $unzip ), 
		DOSify ( "$unzip $source -d $target" ),
		0, 
		CREATE_NEW_CONSOLE, 
		DOSify ( $unzipdir )
	) || die "Couldn't start unzip utility:  " . Win32::FormatMessage(Win32::GetLastError());

	$ProcessObj->Wait(INFINITE);
	$ProcessObj->GetExitCode($status);

} else {

	print LOG `unzip $source -d $target`, "\n\n";

	$status = $? >> 8;

}

print LOG "Unzip exit code:  $status\n\n";

if (not -f $cwd . '/PLib.zip') {
	die "gams-xinst.zip did not unzip!  Please confirm that this file is in the same directory as the gams-x install utility.  You might also want to confirm that your browser did not rename the suffix (*.zip) when saving the file."
}

$source = DOSify($cwd . '/PLib.zip' );
$target = DOSify( $PLib );

print LOG "Unzipping via unzip $source -d $target . . .\n\n";

if ($OS =~ /Win/i) {

	Win32::Process::Create(
		$ProcessObj,
		DOSify ( $unzip ), 
		DOSify ( "$unzip $source -d $target" ),
		0, 
		CREATE_NEW_CONSOLE, 
		DOSify ( $unzipdir )
	) || die "Couldn't start unzip utility:  " . Win32::FormatMessage(Win32::GetLastError());

	$ProcessObj->Wait(INFINITE);
	$ProcessObj->GetExitCode($status);

} else {

	print LOG `unzip $source -d $target`, "\n\n";

	$status = $? >> 8;

}

print LOG "Unzip exit code:  $status\n\n";

$source = DOSify ($cwd . '/GDir.zip' );
$target = DOSify( $GDir );

print LOG "Unzipping via unzip $source -d $target . . .\n\n";

if ($OS =~ /Win/i) {

	Win32::Process::Create(
		$ProcessObj,
		DOSify ( $unzip ), 
		DOSify ( "$unzip $source -d $target" ),
		0, 
		CREATE_NEW_CONSOLE, 
		DOSify ( $unzipdir )
	) || die "Couldn't start unzip utility:  " . Win32::FormatMessage(Win32::GetLastError());

	$ProcessObj->Wait(INFINITE);
	$ProcessObj->GetExitCode($status);

} else {

	print LOG `unzip $source -d $target`, "\n\n";

	$status = $? >> 8;

}

print LOG "Unzip exit code:  $status\n\n";

$source = DOSify ($cwd . '/GXRoot.zip' );
$target = DOSify( $GXRoot );

if (not -d $GXRoot) {
	print LOG "Making GAMS-X root $GXRoot . . .\n";
	mkdir ($GXRoot, 0744) || die "Can't make GAMS-X root directory $GXRoot!"
}

print LOG "Unzipping via unzip $source -d $target . . .\n\n";

if ($OS =~ /Win/i) {

	Win32::Process::Create(
		$ProcessObj,
		DOSify ( $unzip ), 
		DOSify ( "$unzip $source -d $target" ),
		0, 
		CREATE_NEW_CONSOLE, 
		DOSify ( $unzipdir )
	) || die "Couldn't start unzip utility:  " . Win32::FormatMessage(Win32::GetLastError());

	$ProcessObj->Wait(INFINITE);
	$ProcessObj->GetExitCode($status);

} else {

	print LOG `unzip $source -d $target`, "\n\n";

	$status = $? >> 8;

}

print LOG "Unzip exit code:  $status\n\n";

if ($Gnuplot) {

	$source = $OS =~ /Win/i ? DOSify ($cwd . '/gp37w32.zip' ) : yfiSOD ($cwd . '/gnuplot.zip' ) ;
	$target = DOSify( $Gnuplot );

	if (not -d $Gnuplot) { 
		print LOG "Making Gnuplot directory $Gnuplot . . .\n";
		mkdir ($Gnuplot, 0744) || die "Can't make Gnuplot directory $Gnuplot:  $!"
	}

	my $file = $OS =~ /Win/i 
             ? yfiSOD ( "$Gnuplot/wgnuplot.exe" ) 
             : yfiSOD ( "$Gnuplot/gnuplot" );

	if (not -f $file) {

		print LOG "Unzipping via unzip $source -d $target . . .\n\n";

		if ($OS =~ /Win/i) {
	
			Win32::Process::Create(
				$ProcessObj,
				DOSify ( $unzip ), 
				DOSify ( "$unzip $source -d $target" ),
				0, 
				CREATE_NEW_CONSOLE, 
				DOSify ( $unzipdir )
			) || die "Couldn't start unzip utility:  " . Win32::FormatMessage(Win32::GetLastError());
	
			$ProcessObj->Wait(INFINITE);
			$ProcessObj->GetExitCode($status);
	
		} else {
	
			print LOG `unzip $source -d $target`, "\n\n";
	
			$status = $? >> 8;

		}

		print LOG "Unzip exit code:  $status\n\n";

	}

}

print LOG "Making default users.gx and models.gx files . . .\n\n";

store {}, $GXRoot . '/users/users.gx';
store {}, $GXRoot . '/models/models.gx';

$source = DOSify ($cwd . '/GXDir.zip' );
$target = DOSify( $GXDir );

if (not -d $GXDir) {
	print LOG "Making GAMS-X public HTML directory $GXDir . . .\n";
	mkdir ($GXDir, 0744) || die "Can't make GAMS-X public HTML directory $GXDir!"
}

print LOG "Unzipping via unzip $source -d $target . . .\n\n";

if ($OS =~ /Win/i) {

	Win32::Process::Create(
		$ProcessObj,
		DOSify ( $unzip ), 
		DOSify ( "$unzip $source -d $target" ),
		0, 
		CREATE_NEW_CONSOLE, 
		DOSify ( $unzipdir )
	) || die "Couldn't start unzip utility:  " . Win32::FormatMessage(Win32::GetLastError());

	$ProcessObj->Wait(INFINITE);
	$ProcessObj->GetExitCode($status);

} else {

	print LOG `unzip $source -d $target`, "\n\n";

	$status = $? >> 8;

}

print LOG "Unzip exit code:  $status\n\n";

$source = DOSify ($cwd . '/CGIRoot.zip' );
if ( $target = DOSify( $CGIRoot ) ) {

	&WriteCGIFile($CGIRoot) unless $GXDir eq $GXRoot

}

&WriteInitializationFile(

	$GXRoot, $GXDir, $GXLoc,
	$CGIRoot, $CGILoc,
	$PBin, $PLib,
	$GDir, $GIncDir,
	$Browser, $TextEditor, $Gnuplot,
	$Organization, $WebmasterEmail

);

my $HTML = $GXDir . '/index.html';

my $image = $GXLoc . '/images/gams-cgi.gif';

my $action = $CGILoc . '/gams-cgi.pl';

&WriteHomepage($HTML,$image,$action) unless $GXDir eq $GXRoot;

print LOG "Creating GAMS-X menu group and desktop icon . . .\n\n";

my $GAMSTk    = DOSify ( "$GXRoot\\gams-tk.pl" ) ;
my $Update    = DOSify ( "$GXRoot\\update.pl" ) ;
my $Uninstall = DOSify ( "$GXRoot\\gams-xuninst.pl" ) ;

my $XGroup = 1;

if (Win32::IsWinNT()) {

	if ($ENV{'SYSTEMROOT'} and $ENV{'USERNAME'}) {

		$dir = "$ENV{'SYSTEMROOT'}\\Profiles\\$ENV{'USERNAME'}";

	} else {

		$XGroup = 0;
		print LOG "Menu group and desktop not made:  Can't find either SYSTEMROOT or USERNAME.\n\n";
		print "Menu group and desktop shortcuts not made:  \n\nCan't find either SYSTEMROOT or USERNAME environment variables.\n\n"

	}

} else {

	if ($ENV{'WINDIR'}) {

		$dir = DOSify ( $ENV{'WINDIR'} );

	} else {

		$XGroup = 0;
		print LOG "Menu group and desktop not made:  Can't find WINDIR.\n\n";
		print "Menu group and desktop shortcuts not made:  \n\nCan't find WINDIR environment variable.\n\n"


	}

}		

if (-d $dir) {

	$start = "$dir\\Start Menu\\Programs\\GAMS-X";
	mkdir ($start ,0755) || print LOG "Can't make directory '$start'!  Installation continuing anyway . . .\n";

	print LOG "Making link '$start\\gams-tk.lnk' . . .\n";
	$GAMSTkStart = Win32::Shortcut->new;
	$GAMSTkStart->Description("GAMS-Tk");
	$GAMSTkStart->Path( DOSify ( $^X ) );
	$GAMSTkStart->Arguments($GAMSTk);
	$GAMSTkStart->WorkingDirectory( DOSify ( $GXRoot ) );
	$GAMSTkStart->IconLocation( DOSify ( "$GXRoot\\gams-tk.ico" ) );
	$GAMSTkStart->Save( "$start\\GAMS-Tk.lnk" );

	if ($Browser) {
		print LOG "Making link '$start\\GAMS-X.lnk' . . .\n";
		$GAMSTkShortcut = Win32::Shortcut->new;
		$GAMSTkShortcut->Description("GAMS-X Local Documentation");
		$GAMSTkShortcut->Path( DOSify ( $Browser ) );
		$GAMSTkShortcut->Arguments("$GXRoot\\html\\gams-x.html");
		$GAMSTkShortcut->WorkingDirectory( DOSify ( "$GXRoot\\html" ) );
		$GAMSTkShortcut->IconLocation( DOSify ( "$GXRoot\\gams-x.ico" ) );
		$GAMSTkShortcut->Save( "$start\\GAMS-X Documentation.lnk" );
	}

	$desktop = "$dir\\Desktop";
	print LOG "Making link '$desktop\\gams-tk.lnk' . . .\n";
	$GAMSTkDesktop = Win32::Shortcut->new;
	$GAMSTkDesktop->Description("GAMS-Tk");
	$GAMSTkDesktop->Path( DOSify ( $^X ) );
	$GAMSTkDesktop->Arguments($GAMSTk);
	$GAMSTkDesktop->WorkingDirectory( DOSify ( $GXRoot ) );
	$GAMSTkDesktop->IconLocation( DOSify ( "$GXRoot\\gams-tk.ico" ) );
	$GAMSTkDesktop->Save( "$desktop\\GAMS-Tk.lnk" );

	print LOG "Making link '$start\\update.lnk' . . .\n";
	$UpdateShortcut = Win32::Shortcut->new;
	$UpdateShortcut->Description("Update GAMS-X");
	$UpdateShortcut->Path( DOSify ( $^X ) );
	$UpdateShortcut->Arguments( $Update );
	$UpdateShortcut->WorkingDirectory( DOSify ( $GXRoot ) );
	$UpdateShortcut->IconLocation( DOSify ( "$GXRoot\\gams-x.ico" ) );
	$UpdateShortcut->Save( "$start\\Update GAMS-X.lnk" );

	print LOG "Making link '$start\\gams-xuninst.lnk' . . .\n";
	$UninstallShortcut = Win32::Shortcut->new;
	$UninstallShortcut->Description("Uninstall GAMS-X");
	$UninstallShortcut->Path( DOSify ( $^X ) );
	$UninstallShortcut->Arguments($Uninstall);
	$UninstallShortcut->WorkingDirectory( DOSify ( $GXRoot ) );
	$UninstallShortcut->IconLocation( DOSify ( "$GXRoot\\gams-x.ico" ) );
	$UninstallShortcut->Save( "$start\\Uninstall GAMS-X.lnk" );

	print LOG "\nMenu group desktop icon created for the following paths:\n\n$GAMSTk\n$Update\n$Uninstall\n\n";

} else {

	$XGroup = 0;
	print LOG "Menu group and desktop not made:  Can't find directory '$dir'.\n\n"

}

&Batchify( $GXRoot );

&Shebangify( $GXRoot );

close LOG;

my $message = <<"eop";
GAMS-CGI installation complete.

eop

if ($CGIRoot) {

$message .= <<"eop";
The file $HTML has been created as your GAMS-CGI homepage template.  By viewing this file in your favorite web browser and clicking on the GAMS-CGI logo, you can access your GAMS-CGI site.

eop

}

$gamstk = ( $OS =~ /Win/i and not Win32::IsWinNT() ) ? 'perl gams-tk.pl' : 'gams-tk.pl';

if ($XGroup) {

$message .= <<"eop";
To run GAMS-Tk, select GAMS-Tk from your GAMS-X program group in the Start.Programs menu on your Windows taskbar.

You may also type $gamstk from within the GAMS-X root directory $GXRoot.

eop

} else {

$message .= <<"eop";
To run GAMS-Tk, type $gamstk from within the GAMS-X root directory $GXRoot.

eop

}

$message .= <<"eop";
After you have started GAMS-Tk, you may enjoy installing the Ramsey model that comes with your GAMS-X installation.  Just select the Tools.Model.Install menu option in GAMS-Tk.  The Ramsey model is located in your GAMS-X working directory.

A log of this installation has been created in the file gams-xinst.log in the directory $cwd.

Before continuing, you may find it valuable to peruse the FAQ and known bugs sections of the GAMS-X User's Manual and Owner's Guide at http://www.gams.com/gams-x.

Also note that GAMS and Perl MUST be in your path for GAMS-X to function properly.

Enjoy!
eop

my $Announcement = $top->Dialog(
	-title          => 'GAMS-X Installation Complete',
	-text           => $message,
	-bitmap         => 'info',
	-default_button => 'OK',
	-buttons        => ['OK'],
	-wraplength     => '6i'
)->Show;

$top->destroy;

unlink 'GXRoot.zip' if -f 'GXRoot.zip';
unlink 'GDir.zip'   if -f 'GDir.zip';
unlink 'PLib.zip'   if -f 'PLib.zip';
unlink 'GXDir.zip'  if -f 'GXDir.zip';

} # end sub gamsxinst

sub WriteInitializationFile {

my (

	$GXRoot, $GXDir, $GXLoc,
	$CGIRoot, $CGILoc,
	$PBin, $PLib,
	$GDir, $GIncDir,
	$Browser, $TextEditor, $Gnuplot,
	$Organization, $WebmasterEmail

) = @_;

my $CGIEnabled = $GXDir eq $GXRoot ? 0 : 1;

my $dir;

if ( $OS =~ /Win/i ) {

	$dir = Win32::IsWinNT() ? $ENV{'SYSTEMROOT'} : $ENV{'WINDIR'};

	$INI = DOSify ( $dir . '/gams-x.ini' )

} elsif (exists $ENV{'HOME'}) {

	$dir = $ENV{'HOME'};

	$INI = $dir . '/gams-x.ini'

} else {

	print "Error:  Can't find SYSTEMROOT, WINDIR or HOME environment variables.\n\nInitialization file not written!\n\n";
	print LOG "Error:  Can't find WINDIR or HOME environment variables.  Initialization file not written!"

}

my $shebang = $^X;

$Gnuplot = $OS =~ /Win/i ? yfiSOD ( "$Gnuplot/wgnuplot.exe" ) :  yfiSOD ( "$Gnuplot/gnuplot" );

print LOG "Writing GAMS-X initialization file $INI . . .\n";

open (INI, ">$INI" ) || die "Can't open initialization file $INI:  $!\n\nGAMS-X installation aborted.\n\n";

print INI <<"eop";
#	The GAMS-X Initialization File
  
#	The directory structure

Shebang=#!$shebang
GXRoot=$GXRoot
GXDir=$GXDir
GXLoc=$GXLoc
CGIRoot=$CGIRoot
CGILoc=$CGILoc
PBin=$PBin
PLib=$PLib
GDir=$GDir
Browser=$Browser
TextEditor=$TextEditor
Gnuplot=$Gnuplot

#	GAMS-Tk configuration variables
TkOn=0
TkRows=20
TkColumns=10

#	GAMS-CGI configuration variables

Organization=$Organization
WebmasterEmail=$WebmasterEmail
Pause=0
Bypass=0
Restrict=0
Background=
BGColor=#D7CBBB
Logo=gams-cgi.gif
LogoHeight=95
LogoWidth=126
CGIEnabled=$CGIEnabled
Cookies=1
nph=1

#	Some useful URLs
GXHome=http://nash.colorado.edu/gams-x

#	Miscellaneous
MultiUser=1
MultiOwner=0
eop

close INI;

} # end sub WriteIninitializationFile

sub WriteCGIFile {

my ( $CGIRoot ) = @_;

my $dir;

my $shebang = $^X;

my $CGI = $CGIRoot . '/gams-cgi.pl';

print LOG "Writing GAMS-CGI file $CGI . . .\n";

open (CGI, ">$CGI" ) || warn "Can't open GAMS-CGI script $CGI:  $!\n\nGAMS-X installation continuing anyway . . .\n\n";

print CGI <<"eop";
#!$shebang

use GAMS::CGI;

my \$GAMS = new GAMS::CGI;

#	\$GAMS->Gripe("This site has been taken offline for maintenance.");

# Process the appropriate task:
if      (\$GAMS->Task eq "Greeting")                 {\$GAMS->Greeting
} elsif (\$GAMS->Task eq "Log In")                   {\$GAMS->Login
} elsif (\$GAMS->Task eq "New User")                 {\$GAMS->NewUser
} elsif (\$GAMS->Task eq "AddUser")                  {\$GAMS->AddUser; \$GAMS->WriteModelIndex
} elsif (\$GAMS->Task eq "Edit Account Information") {\$GAMS->EditAccountInformation
} elsif (\$GAMS->Task eq "EditUser")                 {\$GAMS->EditUser
} elsif (\$GAMS->Task eq "RemoveAccount")            {\$GAMS->RemoveAccount
} elsif (\$GAMS->Task eq "WriteModelIndex")          {\$GAMS->WriteModelIndex
} elsif (\$GAMS->Task eq "WriteCasebookIndex")       {\$GAMS->WriteCasebookIndex
} elsif (\$GAMS->Task eq "WriteCasebook")            {\$GAMS->WriteCasebook
} elsif (\$GAMS->Task eq "CopyHTML")                 {\$GAMS->CopyHTML
} elsif (\$GAMS->Task eq "CopyText")                 {\$GAMS->CopyText
} elsif (\$GAMS->Task eq "AddCasebook")              {\$GAMS->NewCasebook; \$GAMS->WriteCasebookIndex
} elsif (\$GAMS->Task eq "DeleteCase")               {\$GAMS->DeleteCase; \$GAMS->WriteCasebookIndex
} elsif (\$GAMS->Task eq "DeleteCasebook")           {\$GAMS->DeleteCasebook; \$GAMS->WriteCasebookIndex
} elsif (\$GAMS->Task eq "ImportCase")               {\$GAMS->ImportCase; \$GAMS->WriteCasebook
} elsif (\$GAMS->Task eq "RemoveCase")               {\$GAMS->RemoveCase; \$GAMS->WriteCasebook
} elsif (\$GAMS->Task eq "AddCase")                  {\$GAMS->AddCase; \$GAMS->WriteCasebook
} elsif (\$GAMS->Task eq "ReviseDescription")        {\$GAMS->ReviseDescription; \$GAMS->WriteCasebook
} else  {\$GAMS->Greeting
}

\$GAMS->Quit
eop

close CGI;

} # end sub WriteCGIFile

sub DOSify {

my $string = shift;

$string =~ s/\//\\/g;

$string

} # end sub DOSify

sub yfiSOD {

my $string = shift;

$string =~ s/\\/\//g;

$string

} # end sub yfiSOD

sub WriteHomepage {

my ($HTML,$image,$action) = @_;

print LOG "Writing GAMS-X homepage $HTML . . .\n";

open (HTML, ">$HTML") || warn "Can't open HTML index file $HTML:  $!\n\nGAMS-X installation continuing anyway . . .\n\n";;

print HTML <<"eop";
<HTML>

<HEAD>
<TITLE>GAMS-CGI Reference Page</TITLE>
</HEAD>

<BODY>

<CENTER>

<P>

<FORM ACTION="$action" METHOD="post">
<INPUT TYPE="hidden" NAME="task"          VALUE="index">
<INPUT TYPE="image"  NAME="GAMS-CGI Logo" IMG SRC="$image" HEIGHT=95 WIDTH=126 BORDER=0>
</FORM>

</P>

</CENTER>

</BODY>
</HTML>
eop

close HTML;

} # end sub WriteHomepage

sub Shebangify {

#	Adjusts the shebang in various Perl scripts to be consistent with
#	the local install

my $GXRoot = shift;
my $shebang = "#!$^X";

print LOG "Adjusting shebangification . . .\n";

my @files = (

	$GXRoot . '/gams-tk.pl',
	$GXRoot . '/update.pl',
	$GXRoot . '/gams-xuninst.pl',
	$GXRoot . '/gams-xscript.pl',
	$GXRoot . '/scripts/example.pl',
	$GXRoot . '/scripts/cgi2x.pl'

);

my ($file,@file);

for $file (@files) {

	print LOG "Adjusting shebang on $file . . .\n";

	if ( open (F, $file) ) {

		@file = <F>;

		$file[0] =~ s/^#!.*/$shebang/;

		if ( open (F, ">$file") ) {

			print F @file

		} else {

			print LOG "Can't open $file for shebangification:  $!\n";

		}

	} else {

		print LOG "Can't open $file for shebangification:  $!\n";

	}

}

} # end sub Shebangify

sub Batchify {

#	Adjusts the Perl call in the command-line utilities to be 
#	consistent with the local install

my $GXRoot = shift;

my $ScriptDir = DOSify( $GXRoot . '/scripts' );

print LOG "Adjusting batchification in directory $ScriptDir . . .\n";

my $cwd = cwd();

my (@lines,$line );

chdir $ScriptDir;

print LOG "Examining GAMS-X command-line utilities . . .\n";

print "\nExamining GAMS-X command-line utilities . . .\n\n";

for (<*.bat>) {

print LOG "Examining $_ . . .\n";

open(F,$_) || die;

@lines = <F>;

for $line (@lines) { 

if ($line =~ /^(perl \-x \-S )\"\%0\"/) { 

	print LOG "Adjusting path in $_ . . .\n";

	print "Adjusting path in $_ . . .\n";

}

$line =~ s/^(perl \-x \-S )\S+/\1$ScriptDir\\$_/ }

close F;

open(F, ">$_") || die;

print F @lines;

close F;

}

print "\n";

chdir $cwd;

}
