#!/usr/bin/perl
#
# BNCweb: A user-friendly interface to the British National Corpus - Version 4.3
# Copyright (C) 2005-10 Hoffmann/Evert/Lehmann
#
# Updates and information available at http://www.bncweb.info
#
# This file is part of BNCweb.
# 
# BNCweb 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 3 of the License, or
# (at your option) any later version.
# 
# BNCweb 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, see <http://www.gnu.org/licenses/>.

#
# based on BNCweb Version 2.0:
# © 1996/2004 Lehmann/Hoffmann/Schneider
#

use lib "../lib_files";
use bncLibCQPXML;

use DBI;

# connect to mysql
$bncHandle = DBI->connect("DBI:mysql:$bwMYSQLtable:$bwMYSQLhost:$bwMysqlPort", "$bwMysqlUser", "$bwMysqlPwd") or bark("Can't connect to mysql on $bwMYSQLhost at port: $bwMysqlPort <BR>$bncHandle::errstr\n");

$username = $ENV{'REMOTE_USER'};
$thisProg='subcorpAdmin.pl';
$referer=$ENV{'HTTP_REFERER'};
$fileInfoCgi = "fileInfo.pl";
$speakerInfoCgi = "speakerInfo_new.pl";
	
unless (getParams($ENV{'QUERY_STRING'})) {
	barkFull("incomplete transmition of URL<BR>This problem is likely to occur in combination with proxy servers<BR>turn off your web-proxy and try again");
}

setParam("action", "choose") unless $params{action};

# Compile frequency list
# This is really quite different from other types of subcorpus administration - but I didn't want to 
# create a new mini-script for this...
if ($params{action} eq "compile") {

	&printHeader("Compiling frequency list...");
	
	print <<END;
		<TABLE BORDER="0" CELLPADDING=3 CELLSPACING=2 WIDTH="100%">
			<TR>
				<TD HEIGHT="30" BGCOLOR="#CCCCFF">
					<BIG><BIG><B>Compiling frequency list...</B></BIG></BIG>
				</TD>
			</TR>
			<TR>
				<TD BGCOLOR="#FFFFFF" HEIGHT="30">
END


	$time = int(time);
	$tempname = $username . "_" . $time;
	
	
	($fnumList, $textOrSpeaker) = &subCorporaList($params{username}, $params{subcorpus});

	&compileFlist($fnumList, $tempname, $params{username});
		
	&deleteCachedFreqlists($bwMaxFreqlistMySQL);
	$ButBefore = '/' . $bwCGIalias . '/BNCquery.pl?theQuery=subcorpus&info=' . $paramsEnc{info} . '&urlTest=yes';

	print <<END;
			<SCRIPT><!--
			location.replace("$ButBefore");
			//--></SCRIPT>
END

	exit(0);
	
}


# make sure only super-users can see (and delete!) all subcorpora - check this!!!!!!!!!!
if ($username ne $params{username}) {
	setParam("username", "$username") unless (($username=~m/\A($bwSuperuser)\Z/) || (&checkSuperUser2()));
} else {
	setParam("username", "$username");
}

if ($params{all}) { 
	# user checked "include all files"
	$allfiles = $params{all};
} elsif ($params{complete}) {
	# user wants all hits of a metatextual selection
	if ($params{spowri} eq "written") {
		$sqlQuery = "SELECT fnum FROM headerInfo WHERE $params{complete} ORDER BY fnum";
	} elsif ($params{spowri} eq "spoken") {
		$sqlQuery = "SELECT snum FROM speakers WHERE $params{complete}";
	} else {
		$sqlQuery = "SELECT snum FROM speakers, headerInfo WHERE headerInfo.fname = speakers.filename and $params{complete}";
	}
		
	$sth2 = $bncHandle->prepare($sqlQuery) or bark("Can't prepare $sqlQuery:" . $bncHandle::errstr);
	$sth2->execute or bark("Can't execute $sqlQuery:" . $sth::errstr);
	$resArrayResult=$sth2->fetchall_arrayref;
	
	for $k ( 0 .. ($#{$resArrayResult}) ) {
		$theItem=$resArrayResult->[$k][0];
		$allfiles .= "·$theItem";
	}
} else {
	# user checked a selection of files
	# input from multiple selections
	$theQuery= $ENV{'QUERY_STRING'};
	$theQuery = "&" . $theQuery . "&";
	$allfiles="";
	while ($theQuery=~m/&t=([^&]+)/g) {
		$file=$1;
		$allfiles .= "·$file";
	}
}

if ($params{theFiles}) {
	$theFiles = $params{theFiles};
	# user has manually entered a list of files
	$theFiles =~ s/\r+/ /g;
	$theFiles =~ s/\n+/ /g;
	$theFiles =~ s/\+/ /g;
	$theFiles =~ s/\s+/\,/g;
	$theFiles =~ s/\,+/·/g;
	if ($theFiles=~m/·/) {
		@theFiles = split (/·/, $theFiles);
	} else {
		$theFiles[0]=$theFiles;
	}
	$allfiles = "";
	$errorlist="";
	$error1=0;
	foreach $file (@theFiles) {
		# allow for lowercase input and convert letter O to zero
		$file = uc($file);
		$file =~ s/O/0/g;
		$fnum = &Filemapping($file);
		if (!$fnum) {
			$error1++;
			$errorlist .= "$file ";
		} else {
			$allfiles .= "·$fnum";
		}
	}
	$allfiles=~s/\A·//;
	
	# compile list of non-existing files for error feedback
	if ($error1 == 1) {
		$errormessage="<B>The file <I>$errorlist</I> doesn't exist!</B><BR>";
	} elsif ($error1 > 1) {
		$errormessage="<B>The files <I>$errorlist</I> don't exist!</B><BR>";
	}
}
if ($params{theSpids}) {
	$theFiles = $params{theSpids};
	# user has manually entered a list of files
	$theFiles =~ s/\r+/ /g;
	$theFiles =~ s/\n+/ /g;
	$theFiles =~ s/\+/ /g;
	$theFiles =~ s/\s+/\,/g;
	$theFiles =~ s/\,+/·/g;
	if ($theFiles=~m/·/) {
		@theFiles = split (/·/, $theFiles);
	} else {
		$theFiles[0]=$theFiles;
	}
	$allfiles = "";
	$errorlist="";
	$error1=0;

	foreach $file (@theFiles) {
		# allow for lowercase input and convert letter O to zero
		$file = uc($file);
		$file =~ s/O/0/g;

		$sqlQuery = "SELECT snum FROM speakers where spid = '$file'";
		$sth8 = $bncHandle->prepare($sqlQuery) or bark("Can't prepare $sqlQuery: $bncHandle::errstr");
		$sth8->execute or bark("Can't execute $sqlQuery: $sth8::errstr");
	
		if ($sth8->rows) {
			@rowArray=$sth8->fetchrow_array;
			$snum=$rowArray[0];
		}
		
		if (!$snum) {
			$error1++;
			$errorlist .= "$file ";
		} else {
			$allfiles .= "·$snum";
		}
	}
	$allfiles=~s/\A·//;
	
	# compile list of non-existing files for error feedback
	if ($error1 == 1) {
		$errormessage="<B>The speaker <I>$errorlist</I> doesn't exist!</B><BR>";
	} elsif ($error1 > 1) {
		$errormessage="<B>The speakers <I>$errorlist</I> don't exist!</B><BR>";
	}
}

$allfiles =~ s/\A·//;
setParam("all", "$allfiles");

# expand of the sanity checking procedures!!!

# sanity checking procedures 
if ($params{action} =~ m/\A(choose|enter|overwrite|deleteFiles)\Z/) {
	$error=0;
	if ((!$params{all}) && (!$params{theFiles}) && (!$params{duplicate})) {
		# user didn't choose any files
		$error++;
		$errormessage="<B>You haven't chosen any files for this action!</B><BR>";
	} 
	
	if ($params{subcorpus} =~ m/[^a-zA-Z0-9_]/) {
		# user entered name that doesn't conform to guidelines
		$error++;
		$errormessage="<B>Names for subcorpora can only contain letters, numbers and the underscore character (&quot;_&quot;)!</B><BR>";
		if ($params{subcorpus} =~ m/ /) {
			$errormessage.="<B>(The name you have chosen contains a space.)</B><BR>";
		}
	}
	if ($params{subcorpus} =~ m/\A(last_written|last_spoken)\Z/i) {
		# user entered name that doesn't conform to guidelines
		$error++;
		$errormessage="<B>The name <I>$params{subcorpus}</I> is a reserved name - please choose a different name.</B><BR>";
	}
	if (!$params{subcorpus}) {
		# user forgot to enter a name
		$error++;
		$errormessage="<B>You need to enter a name for your subcorpus!</B><BR>";		
	}
	
	if (($theQuery =~ m/&t=([^&]+)/) && ($theQuery =~ m/&all=([^&]+)/)) {
		# user checked both individual files and "all files"
		$error++;
		$errormessage="<B>You checked both &quot;include all files&quot; and individual files!</B><BR>";
	}

}
if (($error) || ($error1)) {
	# print error message
	&printTheHead();
	print <<END;
	<TABLE BORDER="0" WIDTH="100%" CELLPADDING=3 CELLSPACING=3>
	<TR>
		<TD HEIGHT="27" COLSPAN="2" BGCOLOR="#FF6666"><FONT SIZE="4"><B>Subcorpus Alert</B></FONT></TD>
	</TR>
	<TR>
		<TD BGCOLOR="#DDDDDD" COLSPAN="2" HEIGHT="37">
			<BR>$errormessage<BR>
			Please use the &quot;back&quot;-button of your browser and change your input 
			accordingly.<BR><BR>
		</TD>
	</TR>
	</TABLE>
END
	&printFooter();
	exit(0);
}

# compile options for pop-up menu
$optionSelector = "";
$thing = 'Location: /' . $bwCGIalias . '/BNCquery.pl?theQuery=search&urlTest=yes';
$optionSelector .= "<OPTION VALUE=\"$thing\">New Query";
$thing = 'Location: /' . $bwCGIalias . '/BNCquery.pl?theQuery=keyword&urlTest=yes';
$optionSelector .= "<OPTION VALUE=\"$thing\">Scan keywords/titles";
$thing = 'Location: /' . $bwCGIalias . '/BNCquery.pl?theQuery=genres&urlTest=yes';
$optionSelector .= "<OPTION VALUE=\"$thing\">Explore genre labels";
$thing = 'Location: /' . $bwCGIalias . '/BNCquery.pl?theQuery=writtentexts&showBox=no&urlTest=yes';
$optionSelector .= "<OPTION VALUE=\"$thing\">Written metatextual categories";
$thing = 'Location: /' . $bwCGIalias . '/BNCquery.pl?theQuery=spokentexts&showBox=no&urlTest=yes';
$optionSelector .= "<OPTION VALUE=\"$thing\">Spoken metatextual categories";
$thing = 'Location: /' . $bwCGIalias . '/BNCquery.pl?theQuery=subcorpus&info=' . $paramsEnc{info} . '&urlTest=yes';
$optionSelector .= "<OPTION VALUE=\"$thing\">Show subcorpora";

if ($params{action} eq "showcorpus") {
	if ($params{textOrSpeaker} eq "text") {
		$thing = 'Location: /' . $bwCGIalias . '/' . $thisProg . '?action=addFiles&spowri=written&subcorpus=' . $paramsEnc{subcorpus} . '&textOrSpeaker=' . $paramsEnc{textOrSpeaker} . '&username=' . $paramsEnc{username} . '&info=' . $paramsEnc{info} . '&urlTest=yes';
		$optionSelector .= "<OPTION VALUE=\"$thing\" SELECTED>Add files to subcorpus";
	} else {
		$thing = 'Location: /' . $bwCGIalias . '/' . $thisProg . '?action=addSpids&spowri=spoken&subcorpus=' . $paramsEnc{subcorpus} . '&textOrSpeaker=' . $paramsEnc{textOrSpeaker} . '&username=' . $paramsEnc{username} . '&info=' . $paramsEnc{info} . '&urlTest=yes';
		$optionSelector .= "<OPTION VALUE=\"$thing\" SELECTED>Add speaker IDs to subcorpus";
	}
}

if ($params{textOrSpeaker} eq "text") {
	$filesOrTexts = "texts";
	$filesOrTexts2 = "Texts";
} else {
	$filesOrTexts = "speakers";
	$filesOrTexts2 = "Speakers";
}


$title ='<TR><TD HEIGHT="27" COLSPAN="2" BGCOLOR="#CCCCFF"> <FONT SIZE="4"><B>Subcorpus Administration Page</B></FONT></TD></TR>';


# perform task according to desired action

if ($params{action} eq 'choose') {

	&choose();
	
} elsif (($params{action} eq "enter") || ($params{action} eq "overwrite")) {

	&enter();
	
} elsif ($params{action} eq 'delete') {

	&deleteIt();

} elsif ($params{action} eq 'showcorpus') {

	&showcorpus();

} elsif ($params{action} eq 'deleteFiles') {

	&deleteFiles();

} elsif ($params{action} eq 'define') {

	&define();

} elsif ($params{action} eq 'define2') {

	&define2();

} elsif ($params{action} eq 'addFiles') {

	&addFiles();

} elsif ($params{action} eq 'addSpids') {

	&addSpids();

}

exit(0);

sub choose {
	if ($params{subcorpus} eq "new") {
		# note: either make "new" a reserved word or use something less likely for the name
		&printTheHead();
		if ($params{duplicate}) {
			$copy = $params{duplicate} . "_copy";
		} else {
			$copy = "";
		}		
		
		print <<END;
	
		<FORM ACTION="/$bwCGIalias/${thisProg}" METHOD=GET>
		<INPUT TYPE="hidden" NAME="all" VALUE="$params{all}">
		<INPUT TYPE="hidden" NAME="action" VALUE="enter">
		
		<TABLE BORDER="0" WIDTH="100%" CELLPADDING=3 CELLSPACING=2>
		$title
		<TR>
			<TD HEIGHT="27" COLSPAN="2" BGCOLOR="#DDDDDD">
				Please enter a name for your new subcorpus:
			</TD>
		</TR>
		<TR>
			<TD HEIGHT="27" COLSPAN="1" BGCOLOR="#DDDDDD">
				<INPUT TYPE="text" NAME="subcorpus" VALUE="$copy" SIZE=34 MAXLENGTH=34>
			</TD>
			<TD HEIGHT="27" COLSPAN="1" BGCOLOR="#DDDDDD">
				<INPUT TYPE="hidden" NAME="username" VALUE="$params{username}">
				<INPUT TYPE="hidden" NAME="duplicate" VALUE="$params{duplicate}">
				<INPUT TYPE="HIDDEN" NAME="metatextual" VALUE="$params{metatextual}">
				<INPUT TYPE="HIDDEN" NAME="spowri" VALUE="$params{spowri}">
				<INPUT TYPE="HIDDEN" NAME="textOrSpeaker" VALUE="$params{textOrSpeaker}">
				<INPUT TYPE="HIDDEN" NAME="username" VALUE="$params{username}">
				<INPUT TYPE="hidden" NAME="type" VALUE="$params{type}">
				<INPUT TYPE="hidden" NAME="urlTest" VALUE="yes">
				<INPUT TYPE="submit" VALUE="Submit name">
				</FORM>
			</TD>
		</TR>
		</TABLE>
END
		&printFooter();
		exit(0);
	} else {
		&get_files_and_query();
		
		# list of files needs to be modified - only add those that aren't yet in the list, of course
		$sqlQuery = "SELECT fnums, numfiles, numwords, spowri FROM subcorpora where subcorpus='$params{subcorpus}' and username = '$params{username}'";
		$sth = $bncHandle->prepare($sqlQuery) or bark("Can't prepare $sqlQuery:" . $bncHandle::errstr);
		$res = $sth->execute or bark("Can't execute $sqlQuery: $sth::errstr");
		@rowArray=$sth->fetchrow_array;
		$fnums = $rowArray[0];
		$numfiles = $rowArray[1];
		$numwords = $rowArray[2];
		$spowri = $rowArray[3];
		
		if ($fnums=~m/\W+/) {
			@oldFiles = split (/\W+/, $fnums);
		} else {
			$oldFiles[0]=$fnums;
		}
		foreach $oldFile (@oldFiles) {
			$oldFiles{$oldFile} = 1;
		}
		
		$countNew = 0;
		$numwordsNew = 0;
		$sqlList="";
		foreach $newfile (@files) {
			unless ($oldFiles{$newfile}) {
				$countNew++;
				$fnums .= "·$newfile";
				if ($params{textOrSpeaker} eq "text") {
					$filename=&reverseFilemapping($newfile);
					$sqlList .= " OR fname = '$filename'";
				} else {
					$sqlList .= " OR snum = '$newfile'";
				}
			}
		}
		
		$sqlList=~s/\A OR //;
				
		if ($sqlList) {
			if ($params{textOrSpeaker} eq "text") {
				$sqlQuery = "SELECT sum(numwords) FROM headerInfo where $sqlList";
			} else {
				$sqlQuery = "SELECT sum(speakerWords) FROM speakers WHERE $sqlList";
			} 
			$sth1 = $bncHandle->prepare($sqlQuery) or bark("Can't prepare $sqlQuery:" . $bncHandle::errstr);
			$sth1->execute or bark("Can't execute $sqlQuery: $sth::errstr");
			@rowArray1=$sth1->fetchrow_array;
			$numwordsNew += $rowArray1[0];
			
			$numfiles += $countNew;
			$numwords += $numwordsNew;
			
			# change order of files so that output is in alphabetical order
			@files=split(/·/, $fnums);
			@sortedFiles = sort {$a <=> $b} @files;
			
			$fnums = '';
			foreach $file (@sortedFiles) {
				$fnums .= "·$file";
			}
			$fnums =~s /\A·//;
			
			$sqlQuery = "DELETE FROM subcorpora where subcorpus='$params{subcorpus}' and username = '$params{username}'";
			$bncHandle->do($sqlQuery) or bark("Can't delete $sqlQuery:" . $bncHandle::errstr);
			
			$metatextualQuote = $bncHandle->quote($params{metatextual});
			$sqlQuery = "INSERT INTO subcorpora (subcorpus, username, fnums, numfiles, numwords, spowri, textOrSpeaker, metatextual) values ('$params{subcorpus}', '$params{username}', '$fnums', $numfiles, $numwords, '$params{spowri}', '$params{textOrSpeaker}', $metatextualQuote)";
			$bncHandle->do($sqlQuery) or bark("Can't insert $sqlQuery:" . $bncHandle::errstr);
	
			$numwords=&makeDecimals($numwords);
			$numwordsNew=&makeDecimals($numwordsNew);
			
			&printTheHead();
			
			print <<END;
			<TABLE BORDER="0" WIDTH="100%" CELLPADDING=3 CELLSPACING=2>
			$title
			<TR>
				<TD HEIGHT="27" COLSPAN="2" BGCOLOR="#DDDDDD">
					<B>Your subcorpus <I>$params{subcorpus}</I> has been successfully modified.</B>
				</TD>
			</TR>
	
			<TR>
				<TD HEIGHT="27" COLSPAN="2" BGCOLOR="#EEEEEE">
					$filesOrTexts2 added: $countNew<BR>
					Number of words added: $numwordsNew<BR>
				</TD>
			</TR>
	
			<TR>
				<TD HEIGHT="27" COLSPAN="2" BGCOLOR="#EEEEEE">
					Your subcorpus now contains <B>$numfiles</B> $filesOrTexts with a total of <B>$numwords</B> words.
				</TD>
			</TR>
			<TR>
				<TD HEIGHT="27" BGCOLOR="#EEEEEE" VALIGN="LEFT">
					<FORM ACTION="/$bwCGIalias/dlogs2.pl" METHOD=GET>
					<SELECT NAME="selected">
						$optionSelector
					</SELECT>
				</TD>
				<TD HEIGHT="27" BGCOLOR="#EEEEEE" VALIGN="RIGHT">
					<INPUT TYPE="SUBMIT" VALUE="Go!">
					</FORM>
				</TD>
			</TR>
		</TABLE>
END

	} else {
		&printTheHead();
		print <<END;
		<TABLE BORDER="0" WIDTH="100%" CELLPADDING=3 CELLSPACING=2>
		$title
		<TR>
			<TD HEIGHT="27" COLSPAN="2" BGCOLOR="#FF9933">
				<B>Nothing was added to your subcorpus <I>$params{subcorpus}</I>.</B>
			</TD>
		</TR>

		<TR>
			<TD HEIGHT="27" COLSPAN="2" BGCOLOR="#EEEEEE">
				This may be because all speakers/files that you wanted to add were already part of your subcorpus.
			</TD>
		</TR>

		<TR>
			<TD HEIGHT="27" BGCOLOR="#EEEEEE" VALIGN="LEFT">
				<FORM ACTION="/$bwCGIalias/dlogs2.pl" METHOD=GET>
				<SELECT NAME="selected">
					$optionSelector
				</SELECT>
			</TD>
			<TD HEIGHT="27" BGCOLOR="#EEEEEE" VALIGN="RIGHT">
				<INPUT TYPE="SUBMIT" VALUE="Go!">
				</FORM>
			</TD>
		</TR>
	</TABLE>
END
		
	}
	&printFooter();
	exit(0);
	}
} 

sub enter {
	&get_files_and_query() unless ($params{duplicate});	
	
	$sqlQuery = "SELECT subcorpus FROM subcorpora where subcorpus='$params{subcorpus}' and username = '$params{username}'";
	
	$sth = $bncHandle->prepare($sqlQuery) or bark("Can't prepare $sqlQuery:" . $bncHandle::errstr);
	$sth->execute or bark("Can't execute $sqlQuery: $sth::errstr");
	$res = $sth->rows;
	if (($res) && ($params{action} ne "overwrite")) {
		# warn user that subcorpus already exists
		&printTheHead();
		print <<END;
		<TABLE BORDER="0" WIDTH="100%" CELLPADDING=3 CELLSPACING=3>
		<TR>
			<TD HEIGHT="27" COLSPAN="2" BGCOLOR="#FF6666"><FONT SIZE="4"><B>Subcorpus Name Alert</B></FONT></TD>
		</TR>
		<TR>
			<TD BGCOLOR="#DDDDDD" COLSPAN="2" HEIGHT="37">
				<B>A subcorpus with the name <I>$params{subcorpus}</I> already exists.</B><BR>
			</TD>
		</TR>
		
		<TR>
			<FORM ACTION="/$bwCGIalias/$thisProg" METHOD=GET>
				<TD BGCOLOR="#CCCCCC" WIDTH="50%">
					<INPUT TYPE="hidden" NAME="action" VALUE="overwrite">
					<INPUT TYPE="hidden" NAME="duplicate" VALUE="$params{duplicate}">
					<INPUT TYPE="hidden" NAME="subcorpus" VALUE="$params{subcorpus}">
					<INPUT TYPE="hidden" NAME="all" VALUE="$params{all}">
					<INPUT TYPE="HIDDEN" NAME="metatextual" VALUE="$params{metatextual}">
					<INPUT TYPE="hidden" NAME="spowri" VALUE="$params{spowri}">
					<INPUT TYPE="HIDDEN" NAME="textOrSpeaker" VALUE="$params{textOrSpeaker}">
					<INPUT TYPE="hidden" NAME="urlTest" VALUE="yes">
					<INPUT TYPE="submit" VALUE="Overwrite \'$params{subcorpus}\'">
				</TD>
			</FORM>
			<FORM ACTION="/$bwCGIalias/$thisProg" METHOD=GET>
				<TD BGCOLOR="#CCCCCC">
					<INPUT TYPE="hidden" NAME="action" VALUE="choose">
					<INPUT TYPE="hidden" NAME="duplicate" VALUE="$params{duplicate}">
					<INPUT TYPE="hidden" NAME="subcorpus" VALUE="new">
					<INPUT TYPE="hidden" NAME="all" VALUE="$params{all}">
					<INPUT TYPE="HIDDEN" NAME="metatextual" VALUE="$params{metatextual}">
					<INPUT TYPE="hidden" NAME="spowri" VALUE="$params{spowri}">
					<INPUT TYPE="HIDDEN" NAME="textOrSpeaker" VALUE="$params{textOrSpeaker}">
					<INPUT TYPE="hidden" NAME="urlTest" VALUE="yes">
					<INPUT TYPE="submit" VALUE="Change name">
				</TD>
			</FORM>
		</TR>
	</TABLE>
END
		&printFooter();
		exit(0);
	} else {
		if (($res) && ($params{action} eq "overwrite")) {
			# delete subcorpus
			$sqlQuery = "DELETE FROM subcorpora where subcorpus='$params{subcorpus}' and username = '$params{username}'";
			$bncHandle->do($sqlQuery) or bark("Can't delete $sqlQuery:" . $bncHandle::errstr);
		}
		
		if ($params{duplicate}) {
			$sqlQuery = "SELECT fnums, numfiles, numwords, spowri, textOrSpeaker, metatextual FROM subcorpora WHERE username = '$params{username}' and subcorpus='$params{duplicate}'";
			$sth = $bncHandle->prepare($sqlQuery) or bark("Can't prepare $sqlQuery: " . $bncHandle::errstr);
			$sth->execute or bark("Can't execute $sqlQuery: " . $sth::errstr);
			@rowArray=$sth->fetchrow_array;
			$fnums=$rowArray[0];
			$numfiles=$rowArray[1];
			$numwords=$rowArray[2];
			$spowri = $rowArray[3];
			$textOrSpeaker = $rowArray[4];
			$metatextual = $rowArray[4];
			$metatextualQuote = $bncHandle->quote($metatextual);
			$sqlQuery = "insert into subcorpora (subcorpus, username, fnums, numfiles, numwords, spowri, textOrSpeaker, metatextual) values ('$params{subcorpus}', '$params{username}', '$fnums', $numfiles, $numwords, '$spowri', '$textOrSpeaker', $metatextualQuote)";
			$bncHandle->do($sqlQuery) or bark("Can't insert $sqlQuery:" . $bncHandle::errstr);
			
			print "Location: /" . $bwCGIalias . "/BNCquery.pl?theQuery=subcorpus&urlTest=yes\n\n";
		} else {
			# save new (or overwritten old) subcorpus
			$metatextualQuote = $bncHandle->quote($params{metatextual});
			$sqlQuery = "insert into subcorpora (subcorpus, username, fnums, numfiles, numwords, spowri, textOrSpeaker, metatextual) values ('$params{subcorpus}', '$params{username}', '$params{all}', $numfiles, $numwords, '$params{spowri}', '$params{textOrSpeaker}', $metatextualQuote)";
			$bncHandle->do($sqlQuery) or bark("Can't insert $sqlQuery:" . $bncHandle::errstr);	
		}
		
		$numwords=&makeDecimals($numwords);
		
		&printTheHead();
		
		print <<END;
		<TABLE BORDER="0" WIDTH="100%" CELLPADDING=3 CELLSPACING=2>
		$title
		<TR>
			<TD HEIGHT="27" COLSPAN="2" BGCOLOR="#DDDDDD">
				<B>Your subcorpus <I>$params{subcorpus}</I> has been saved.</B>
			</TD>
		</TR>

		<TR>
			<TD HEIGHT="27" COLSPAN="2" BGCOLOR="#EEEEEE">
				It contains <B>$numfiles</B> $filesOrTexts with a total of <B>$numwords</B> words.
			</TD>
		</TR>
		<TR>
			<TD HEIGHT="27" BGCOLOR="#EEEEEE" VALIGN="LEFT">
				<FORM ACTION="/$bwCGIalias/dlogs2.pl" METHOD=GET>
				<SELECT NAME="selected">
					$optionSelector
				</SELECT>
			</TD>
			<TD HEIGHT="27" BGCOLOR="#EEEEEE" VALIGN="RIGHT">
				<INPUT TYPE="SUBMIT" VALUE="Go!">
			</TD>
			</FORM>
		</TR>
	</TABLE>
END
		&printFooter();
		exit(0);
	}
	
} 

sub define {
	# display form for creation of new corpus
	&printTheHead();
		
	print <<END;
	<FORM ACTION="/$bwCGIalias/${thisProg}" METHOD=GET>
	<INPUT TYPE="hidden" NAME="action" VALUE="enter">
	
	<TABLE BORDER="0" WIDTH="100%" CELLPADDING=3 CELLSPACING=2>
	$title
	<TR>
		<TD HEIGHT="27" COLSPAN="2" BGCOLOR="#DDDDDD">
			Please enter a name for your new subcorpus:
		</TD>
	</TR>
	<TR>
		<TD HEIGHT="27" COLSPAN="2" BGCOLOR="#DDDDDD">
			<INPUT TYPE="text" NAME="subcorpus" SIZE=34 MAXLENGTH=34>
		</TD>
	</TR>
	<TR>
		<TD HEIGHT="27" COLSPAN="2" BGCOLOR="#DDDDDD">
			Enter the text IDs you wish to combine to a subcorpus (use commas or spaces to separate the individual IDs):
		</TD>
	</TR>
	<TR>
		<TD BGCOLOR="#DDDDDD">
			<TEXTAREA NAME="theFiles" ROWS="5" COLS="58" WRAP="physical"></TEXTAREA>
		</TD>
		<TD BGCOLOR="#DDDDDD">
			<INPUT TYPE="hidden" NAME="username" VALUE="$params{username}">
			<INPUT TYPE="hidden" NAME="textOrSpeaker" VALUE="text">
			<INPUT TYPE="HIDDEN" NAME="username" VALUE="$params{username}">
			<INPUT TYPE="hidden" NAME="spowri" VALUE="written">
			<INPUT TYPE="hidden" NAME="urlTest" VALUE="yes">
			<INPUT TYPE="submit" VALUE="Create subcorpus">
			</FORM>
		</TD>
	</TR>
	</TABLE>
END
		&printFooter();
		exit(0);
	
}

sub define2 {
	# display form for creation of new corpus
	&printTheHead();
		
	print <<END;
	<FORM ACTION="/$bwCGIalias/${thisProg}" METHOD=GET>
	<INPUT TYPE="hidden" NAME="action" VALUE="enter">
	
	<TABLE BORDER="0" WIDTH="100%" CELLPADDING=3 CELLSPACING=2>
	$title
	<TR>
		<TD HEIGHT="27" COLSPAN="2" BGCOLOR="#DDDDDD">
			Please enter a name for your new subcorpus:
		</TD>
	</TR>
	<TR>
		<TD HEIGHT="27" COLSPAN="2" BGCOLOR="#DDDDDD">
			<INPUT TYPE="text" NAME="subcorpus" SIZE=34 MAXLENGTH=34>
		</TD>
	</TR>
	<TR>
		<TD HEIGHT="27" COLSPAN="2" BGCOLOR="#DDDDDD">
			Enter the speaker IDs you wish to combine to a subcorpus (use commas or spaces to separate the individual speaker IDs):
		</TD>
	</TR>
	<TR>
		<TD BGCOLOR="#DDDDDD">
			<TEXTAREA NAME="theSpids" ROWS="5" COLS="58" WRAP="physical"></TEXTAREA>
		</TD>
		<TD BGCOLOR="#DDDDDD">
			<INPUT TYPE="hidden" NAME="spowri" VALUE="spoken">
			<INPUT TYPE="hidden" NAME="textOrSpeaker" VALUE="speaker">
			<INPUT TYPE="HIDDEN" NAME="username" VALUE="$params{username}">
			<INPUT TYPE="hidden" NAME="urlTest" VALUE="yes">
			<INPUT TYPE="submit" VALUE="Create subcorpus">
			</FORM>
		</TD>
	</TR>
	</TABLE>
END
		&printFooter();
		exit(0);
	
}

sub addFiles  {
	# display form to add files to existing subcorpus
	&printTheHead();
		
	print <<END;
	<FORM ACTION="/$bwCGIalias/${thisProg}" METHOD=GET>
	<INPUT TYPE="hidden" NAME="action" VALUE="choose">
	<INPUT TYPE="hidden" NAME="subcorpus" VALUE="$params{subcorpus}">
	
	<TABLE BORDER="0" WIDTH="100%" CELLPADDING=3 CELLSPACING=2>
	$title
	<TR>
		<TD HEIGHT="27" COLSPAN="2" BGCOLOR="#DDDDDD">
			Enter the text IDs you wish to add to your subcorpus <I>$params{subcorpus}</I> (use commas or spaces to separate the individual IDs):
		</TD>
	</TR>
	<TR>
		<TD BGCOLOR="#DDDDDD">
			<TEXTAREA NAME="theFiles" ROWS="5" COLS="58" WRAP="physical"></TEXTAREA>
		</TD>
		<TD BGCOLOR="#DDDDDD">
			<INPUT TYPE="hidden" NAME="username" VALUE="$params{username}">
			<INPUT TYPE="hidden" NAME="spowri" VALUE="written">
			<INPUT TYPE="hidden" NAME="textOrSpeaker" VALUE="text">
			<INPUT TYPE="hidden" NAME="info" VALUE="$params{info}">
			<INPUT TYPE="hidden" NAME="urlTest" VALUE="yes">
			<INPUT TYPE="submit" VALUE="Add files">
			</FORM>
		</TD>
	</TR>
	</TABLE>
END
		&printFooter();
		exit(0);

}

sub addSpids  {
	# display form to add files to existing subcorpus
	&printTheHead();
		
	print <<END;
	<FORM ACTION="/$bwCGIalias/${thisProg}" METHOD=GET>
	<INPUT TYPE="hidden" NAME="action" VALUE="choose">
	<INPUT TYPE="hidden" NAME="spowri" VALUE="spoken">
	<INPUT TYPE="hidden" NAME="textOrSpeaker" VALUE="speaker">
	<INPUT TYPE="hidden" NAME="subcorpus" VALUE="$params{subcorpus}">
	<INPUT TYPE="hidden" NAME="info" VALUE="$params{info}">
	<INPUT TYPE="hidden" NAME="username" VALUE="$params{username}">
	
	<TABLE BORDER="0" WIDTH="100%" CELLPADDING=3 CELLSPACING=2>
	$title
	<TR>
		<TD HEIGHT="27" COLSPAN="2" BGCOLOR="#DDDDDD">
			Enter the speaker IDs you wish to add to your subcorpus <I>$params{subcorpus}</I> (use commas or spaces to separate the individual speaker IDs):
		</TD>
	</TR>
	<TR>
		<TD BGCOLOR="#DDDDDD">
			<TEXTAREA NAME="theSpids" ROWS="5" COLS="58" WRAP="physical"></TEXTAREA>
		</TD>
		<TD BGCOLOR="#DDDDDD">
			<INPUT TYPE="hidden" NAME="urlTest" VALUE="yes">
			<INPUT TYPE="submit" VALUE="Add files">
			</FORM>
		</TD>
	</TR>
	</TABLE>
END
		&printFooter();
		exit(0);

}


sub showcorpus {

	# display a list of all files in the subcorpus (filename, title, number of words) and a checkbox for deletion
	$sqlQuery = "select fnums, numfiles, numwords, spowri, textOrSpeaker from subcorpora WHERE username='$params{username}' and subcorpus = '$params{subcorpus}'";

	$sth = $bncHandle->prepare($sqlQuery) or bark("Can't prepare $sqlQuery:" . $bncHandle::errstr);
	$sth->execute or bark("Can't execute $sqlQuery: $sth::errstr");
	@rowArray=$sth->fetchrow_array;
	$fnums = $rowArray[0];
	$numfiles = $rowArray[1];
	$numwords = $rowArray[2];
	$spowri = $rowArray[3];
	$textOrSpeaker = $rowArray[4];
	
	if ($textOrSpeaker eq "text") {
		$filesOrTexts = "texts";
		$filesOrTexts2 = "Text";
		$filesOrTexts3 = "Title";
	} else {
		$filesOrTexts = "speakers";
		$filesOrTexts2 = "Speaker";
		$filesOrTexts3 = "Description";
	}
	
	$numwords=&makeDecimals($numwords);
	
	$navBar = &createNavigationLinks();
	
	&printTheHead();
	
	print <<END;
	<TABLE BORDER="0" WIDTH="100%" CELLPADDING=3 CELLSPACING=2>
	<TR>
		<TD HEIGHT="27" COLSPAN="6" BGCOLOR="#CCCCFF"> <FONT SIZE="4"><B>Subcorpus Administration Page</B></FONT></TD>
	</TR>
	<TR>
		<TD HEIGHT="27" COLSPAN="6" BGCOLOR="#EEEEEE">
			<B>Your subcorpus <I>$params{subcorpus}</I> consists of $numfiles $filesOrTexts with a total of $numwords words.</B>
		</TD>
	</TR>
	<FORM ACTION="/$bwCGIalias/dlogs2.pl" METHOD=GET>
	<TR BGCOLOR="#EEEEEE">
		$navBar
		<TD NOWRAP BGCOLOR="#DDDDDD">
			&#160;
			<SELECT NAME="selected">
				$optionSelector
			</SELECT>
			<INPUT TYPE="SUBMIT" VALUE="Go!">
		</TD>
		</FORM>
		<TD NOWRAP BGCOLOR="#DDDDDD" ALIGN="RIGHT">
			<FORM ACTION="/$bwCGIalias/subcorpAdmin.pl" METHOD="GET">
			<INPUT TYPE="HIDDEN" NAME="action" VALUE="deleteFiles">
			<INPUT TYPE="HIDDEN" NAME="subcorpus" VALUE="$params{subcorpus}">
			<INPUT TYPE="HIDDEN" NAME="textOrSpeaker" VALUE="$params{textOrSpeaker}">
			<INPUT TYPE="HIDDEN" NAME="spowri" VALUE="$params{spowri}">
			<INPUT TYPE="HIDDEN" NAME="username" VALUE="$params{username}">
			<INPUT TYPE="HIDDEN" NAME="info" VALUE="$params{info}">
			<INPUT TYPE="SUBMIT" VALUE="Delete marked files">
		</TD>
	</TR>
	</TABLE>
	
	<TABLE BORDER="0" WIDTH="100%" CELLPADDING=3 CELLSPACING=2>
	<TR>
		<TD BGCOLOR="#FFCC66">
			&#160;<B>No</B>
		</TD>
		<TD BGCOLOR="#FFCC66">
			&#160;<B>$filesOrTexts2</B>
		</TD>
		<TD BGCOLOR="#FFCC66">
			&#160;<B>$filesOrTexts3</B>
		</TD>
		<TD BGCOLOR="#FFCC66" ALIGN=CENTER>
			<B>No. of words</B>
		</TD>
		<TD BGCOLOR="#FFCC66">
			&#160;<B>Delete</B>
		</TD>
	</TR>
END

	if ($fnums=~m/·/) {
		@files=split(/·/, $fnums);
	} else {
		$files[0]=$fnums;
	}
	for ($i = $start; $i < $end; ++$i) {
		$fnum = $files[$i];
		if ($textOrSpeaker eq "text") {
			$filename=&reverseFilemapping($fnum);
			$sqlQuery = "SELECT numwords FROM headerInfo where fname='$filename'";
		} else {
			$sqlQuery = "SELECT speakerWords, filename FROM speakers where snum='$fnum'";
		}
		$sth = $bncHandle->prepare($sqlQuery) or bark("Can't prepare $sqlQuery:" . $bncHandle::errstr);
		$sth->execute or bark("Can't execute $sqlQuery: $sth::errstr");
		@rowArray=$sth->fetchrow_array;
		$number = $rowArray[0];
		$text = $rowArray[1];
		$number=&makeDecimals($number);
		
		if ($textOrSpeaker eq "text") {
			$sqlQuery = "SELECT title FROM headerInfo where fname='$filename'";
			$sth = $bncHandle->prepare($sqlQuery) or bark("Can't prepare $sqlQuery:" . $bncHandle::errstr);
			$sth->execute or bark("Can't execute $sqlQuery: $sth::errstr");
			@rowArray=$sth->fetchrow_array;
			$title = $rowArray[0];
		} else {


			$sqlQuery = "SELECT age, sex, class, nameFull, spid FROM speakers WHERE snum=$fnum";
			$sth5 = $bncHandle->prepare($sqlQuery) or bark("Can't prepare $sqlQuery: " . $bncHandle::errstr);
			$sth5->execute or bark("Can't execute $sqlQuery: " . $sth5::errstr);
			
			($age, $sex, $class, $nameFull, $spid) = $sth5->fetchrow_array;
			
			$value = "age=$age";
			$ageInfo = $catValues{$value};
			$value = "sex=$sex";
			$sexInfo = $catValues{$value};
			$value = "class=$class";
			$classInfo = $catValues{$value};
			
			unless ($nameFull eq "N/A") {
				$title = "<b>$nameFull</b> - "
			} else {
				$title = "";
			}
			$title .= "<i>$typeValues{sex}:</i> $sexInfo, <i>$typeValues{age}:</i> $ageInfo, <i>$typeValues{class}:</i> $classInfo ";

		}
		#$title =~ s/%([\dA-Fa-f][\dA-Fa-f])/pack ("C", hex ($1))/eg;
		$title=~s/\$1\$1\$2/ -- /g;
		$title=~s/ -- an electronic (transcription|version|sample|collection)\Z//g;
		$chunk=$title;
		$chunk = &output2($chunk);
		if ($textOrSpeaker eq "text") {
			$link = "<A HREF=\"/$bwCGIalias/${fileInfoCgi}?text=$filename&urlTest=yes\">";	
		} else {
			
			$link = "<A HREF=\"/$bwCGIalias/${speakerInfoCgi}?text=$text&spid=$spid&urlTest=yes\">";
		}
		
		$countNumber = $i + 1;
		
		if ($textOrSpeaker eq "text") {
			$forDisplay = $filename;
		} else {
			$forDisplay = $spid;
		}
		
		print <<END;
		
		<TR BGCOLOR="#DDDDDD">
			<TD VALIGN=TOP>
				&#160;<B>$countNumber</A></B>
			</TD>
			<TD VALIGN=TOP>
				&#160;<B>$link$forDisplay</A></B>
			</TD>
			<TD VALIGN=TOP>
				&#160;$chunk
			</TD>
			<TD VALIGN=TOP ALIGN="MIDDLE">
				$number
			</TD>
			<TD VALIGN=TOP>
				&#160;<INPUT TYPE="CHECKBOX" NAME="t" VALUE="$fnum">
			</TD>
		</TR>
		<INPUT TYPE="HIDDEN" NAME="info" VALUE="$params{info}">
		<INPUT TYPE="hidden" NAME="urlTest" VALUE="yes">
END

	}

	print <<END;

	
</TABLE>
</FORM>
END
	&printFooter();
	exit(0);

} 

sub deleteIt {
	# delete the whole subcorpus
	$sqlQuery = "DELETE FROM subcorpora where subcorpus='$params{subcorpus}' and username = '$params{username}'";
	$bncHandle->do($sqlQuery) or bark("Can't delete $sqlQuery:" . $bncHandle::errstr);
	print "Location: /$bwCGIalias/BNCquery.pl?theQuery=subcorpus&info=$paramsEnc{info}&urlTest=yes\n\n";
} 

sub deleteFiles {
	# user has selected some file(s) for deletion
	$sqlQuery = "select fnums from subcorpora WHERE username='$params{username}' and subcorpus = '$params{subcorpus}'";
	$sth = $bncHandle->prepare($sqlQuery) or bark("Can't prepare $sqlQuery:" . $bncHandle::errstr);
	$sth->execute or bark("Can't execute $sqlQuery: $sth::errstr");
	@rowArray=$sth->fetchrow_array;
	$fnums = $rowArray[0];
		
	if ($params{all}=~m/·/) {
		@files = split(/·/, $params{all});
	} else {
		$files[0]=$params{all};
	}
	$fnums = "·" . $fnums . "·";
	
	$numwordsDel = 0;
	$numfilesDel = 0;
	$sqlList="";
	foreach $file (@files) {
		$check = $fnums =~ s/·$file·/·/;
		if ($check) {
			$numfilesDel++;
			if ($params{textOrSpeaker} eq "text") {
				$filename=&reverseFilemapping($file);
				$sqlList .= " OR fname = '$filename'";
			} else {
				$sqlList .= " OR snum = '$file'";
			}
		}
	}
	$sqlList=~s/\A OR //;
	if ($params{textOrSpeaker} eq "text") {
		$sqlQuery = "SELECT sum(numwords) FROM headerInfo where $sqlList";
	} else {
		$sqlQuery = "SELECT sum(speakerWords) FROM speakers WHERE $sqlList";
	} 

	$sth1 = $bncHandle->prepare($sqlQuery) or bark("Can't prepare $sqlQuery: " . $bncHandle::errstr);
	$sth1->execute or bark("Can't execute $sqlQuery: $sth::errstr");
	@rowArray1=$sth1->fetchrow_array;
	$numwordsDel += $rowArray1[0];
		
	$fnums=~s/\A·//;
	$fnums=~s/·\Z//;
	
	$numfiles = $fnums=~s/·/·/g;
	$numfiles++;
	
	if ($fnums=~m/·/) {
		@files=split(/·/, $fnums);
	} else {
		$files[0]=$fnums;
	}
	$numwords=0;
	$sqlList="";
	foreach $file (@files) {
		if ($params{textOrSpeaker} eq "text") {
			$filename=&reverseFilemapping($file);
			$sqlList .= " OR fname = '$filename'";
		} else {
			$sqlList .= " OR snum = '$file'";
		}
	}
	
	$sqlList=~s/\A OR //;
	
	if ($params{textOrSpeaker} eq "text") {
		$sqlQuery = "SELECT sum(numwords) FROM headerInfo where $sqlList";
	} else  {
		$sqlQuery = "SELECT sum(speakerWords) FROM speakers WHERE $sqlList";
	} 

	$sth = $bncHandle->prepare($sqlQuery) or bark("Can't prepare $sqlQuery:" . $bncHandle::errstr);
	$sth->execute or bark("Can't execute $sqlQuery: $sth::errstr");
	@rowArray=$sth->fetchrow_array;
	$numwords += $rowArray[0];
	
	$sqlQuery = "UPDATE subcorpora SET fnums = '$fnums', numwords = $numwords, numfiles = $numfiles where subcorpus='$params{subcorpus}' and username = '$params{username}'";
	$bncHandle->do($sqlQuery) or bark("Can't delete $sqlQuery:" . $bncHandle::errstr);
	
	$numwords=&makeDecimals($numwords);
	$numwordsDel=&makeDecimals($numwordsDel);
	
	&printTheHead();

	
	print <<END;
		<TABLE BORDER="0" WIDTH="100%" CELLPADDING=3 CELLSPACING=2>
		$title
		<TR>
			<TD HEIGHT="27" COLSPAN="2" BGCOLOR="#DDDDDD">
				<B>Your subcorpus <I>$params{subcorpus}</I> has been successfully modified.</B>
			</TD>
		</TR>
	
		<TR>
			<TD HEIGHT="27" COLSPAN="2" BGCOLOR="#EEEEEE">
				$filesOrTexts2 deleted: $numfilesDel<BR>
				Number of words deleted: $numwordsDel<BR>
			</TD>
		</TR>
	
		<TR>
			<TD HEIGHT="27" COLSPAN="2" BGCOLOR="#EEEEEE">
				Your subcorpus now contains <B>$numfiles</B> $filesOrTexts with a total of <B>$numwords</B> words.
			</TD>
		</TR>
		<TR>
			<TD HEIGHT="27" BGCOLOR="#EEEEEE" VALIGN="LEFT">
				<FORM ACTION="/$bwCGIalias/dlogs2.pl" METHOD=GET>
				<SELECT NAME="selected">
					$optionSelector
				</SELECT>
			</TD>
			<TD HEIGHT="27" BGCOLOR="#EEEEEE" VALIGN="RIGHT">
				<INPUT TYPE="SUBMIT" VALUE="Go!">
			</TD>
			</FORM>
		</TR>
	</TABLE>
END
	&printFooter();
	exit(0);
	
} 


sub printTheHead {
	print "Content-type: text/html\n\n";
	print <<END;

	<!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 3.2 Final//EN">
	<HTML>
	<HEAD>
	
	<TITLE>Subcorpus Administration Page</TITLE>

	<META NAME="generator" CONTENT="BBEdit 4.5">
	<META HTTP-EQUIV="Content-Type" CONTENT="text/html; CHARSET=iso-8859-1">
	</HEAD>
	<BODY BGCOLOR="#FFFFFF">
END

}


sub createNavigationLinks {
	local($navBar);
	
	if (($numfiles / $params{inst}) > 1)  {
		# set start and end s number
		$start = ($params{chunk} * $params{inst}) - ($params{inst});
		$end = (($params{chunk} + 1) * $params{inst}) - ($params{inst});
		$end = $numfiles if ($end > $numfiles);
	} else {
		#print "nshow all  $params{inst}<BR>";
		$start = 0;
		$end = $numfiles;
	}

	# print links to other pages
	if (($params{inst} ne "count hits") || (($numfiles / $params{inst}) > 1) ) {
		$div = ($numfiles / $params{inst});
		$divInt = int($div);
		$divInt = $divInt + 1  if ($div > $divInt);
		setParam("max", "$divInt");		


		$theLink = '<A HREF="/' . $bwCGIalias . '/' . $thisProg . '?XYZ2">';
		$link = "action=$paramsEnc{action}&chunk=XXZ1&inst=$paramsEnc{inst}&max=$paramsEnc{max}&subcorpus=$paramsEnc{subcorpus}&metatextual=$paramsEnc{metatextual}&username=$paramsEnc{username}&textOrSpeaker=$paramsEnc{textOrSpeaker}&all=$paramsEnc{all}&urlTest=yes";
		$theLink =~ s/XYZ2/$link/o;
		$startFont="<FONT SIZE=3 FACE=\"Arial, Helvetica\"><B>";
		$endFont="</B></FONT>";
		if (($params{chunk} -1) >= 1) {
			$theLink1 = $theLink;
			$i = $params{chunk} - 1;
			$theLink1 =~ s/XXZ1/$i/;
			$navBar.= "<TD WIDTH=\"3%\" BGCOLOR=\"#DDDDDD\" NOWRAP><P ALIGN=\"CENTER\">${theLink1}$startFont&nbsp;&lt;&lt;&nbsp;$endFont</A></TD>\n";
		} else {
			$navBar.= "<TD WIDTH=\"3%\" BGCOLOR=\"#DDDDDD\" NOWRAP><P ALIGN=\"CENTER\">$startFont&nbsp;&lt;&lt;&nbsp;$endFont</TD>\n";
		}
		if (($params{chunk} +1) <= $divInt) {
			$theLink1 = $theLink;
			$i = $params{chunk} +1;
			$theLink1 =~ s/XXZ1/$i/;
			$navBar.= "<TD WIDTH=\"3%\" BGCOLOR=\"#DDDDDD\" NOWRAP><P ALIGN=\"CENTER\">${theLink1}$startFont&nbsp;&gt;&gt;&nbsp;$endFont</A></TD>\n";

		} else {
			$navBar.= "<TD WIDTH=\"3%\" BGCOLOR=\"#DDDDDD\" NOWRAP><P ALIGN=\"CENTER\">$startFont&nbsp;&gt;&gt;&nbsp;$endFont</TD>\n";
		}

		if ($params{chunk} != 1) {
			$theLink1 = $theLink;
			$theLink1 =~ s/XXZ1/1/;
			$navBar = "<TD WIDTH=\"3%\" BGCOLOR=\"#DDDDDD\" NOWRAP><P ALIGN=\"CENTER\">${theLink1}$startFont&nbsp;I&lt;&nbsp;$endFont</A></TD>$navBar\n";
		} else {
			$navBar = "<TD WIDTH=\"3%\" BGCOLOR=\"#DDDDDD\" NOWRAP><P ALIGN=\"CENTER\">$startFont&nbsp;I&lt;&nbsp;$endFont</TD>$navBar\n";
		}

		if ($params{chunk} < $divInt) {
			$theLink1 = $theLink;
			$i = $params{chunk} +1;
			$theLink1 =~ s/XXZ1/$divInt/;
			$navBar.= "<TD WIDTH=\"3%\" BGCOLOR=\"#DDDDDD\" NOWRAP><P ALIGN=\"CENTER\">${theLink1}$startFont&nbsp;&gt;I&nbsp;$endFont</A></TD>\n";
		} else {
			$navBar.= "<TD WIDTH=\"3%\" BGCOLOR=\"#DDDDDD\" NOWRAP><P ALIGN=\"CENTER\">$startFont&nbsp;&gt;I&nbsp;$endFont</TD>\n";
		}
		
		$pageInd = "   Page $params{chunk} \/ $divInt";
	}
	return($navBar);
}

sub get_files_and_query {
	$numwords=0;
	if ($params{all}=~m/\W/) {
		@files=split(/\W+/, $params{all});
	} else {
		$files[0] = $params{all};
	}
		
	$sqlList="";
	
	if ($params{textOrSpeaker} eq "text") {
		foreach $file (@files) {
			next unless ($file);
			$filename=&reverseFilemapping($file);
			$sqlList .= " OR fname = '$filename'";
		}
		$sqlList=~s/\A OR //;
		$sqlQuery = "SELECT sum(numwords) FROM headerInfo where $sqlList";
	} else {
		
		foreach $file (@files) {
			next unless ($file);
			$sqlList .= " OR snum = '$file'";
		}
		$sqlList=~s/\A OR //;
		$sqlQuery = "SELECT sum(speakerWords) FROM speakers where $sqlList";
	}
	$sth = $bncHandle->prepare($sqlQuery) or bark("Can't prepare $sqlQuery:" . $bncHandle::errstr);
	$sth->execute or bark("Can't execute $sqlQuery: $sth::errstr");
	@rowArray=$sth->fetchrow_array;
	$numwords += $rowArray[0];
	
	# get number of files
	$numfiles = $params{all}=~s/\W+/·/g;
	$numfiles++;

}