#!/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");
$categorizeHandle = DBI->connect("DBI:mysql:$bwMYSQLcategorizetable:$bwMYSQLhost:$bwMysqlPort", "$bwMysqlUser", "$bwMysqlPwd");

$username = $ENV{'REMOTE_USER'};
$thisProg='categorizeAdmin.pl';
$referer=$ENV{'HTTP_REFERER'};
	
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};

# 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");
}

# perform task according to desired action

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

	&choose();
	
} elsif ($params{action} eq "create") {
	
	&create;
	
}  elsif ($params{action} eq 'update') {

	&update();

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

	&separate();

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

	&addValue();

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

	&addNewValue();

}

exit(0);

sub choose {
	
	$title ='</TR><TR><TD COLSPAN="2" HEIGHT="27" BGCOLOR="#CCCCFF"> <FONT SIZE="4"><B>Categorize Query Result</B></FONT></TD></TR>';

	&printHeader("Categorize Query Result");
	
	$theData2=&encodeForm($params{theData});
	
	print <<END;

	<FORM ACTION="/$bwCGIalias/${thisProg}" METHOD=GET>
	
	<TABLE BORDER="0" WIDTH="100%" CELLPADDING=3 CELLSPACING=2>
	$title
	<TR>
		<TD COLSPAN="2" HEIGHT="27" BGCOLOR="#DDDDDD">
			<B>Please enter a name for this set of categories:</B>
		</TD>
	</TR>
	<TR>
		<TD COLSPAN="2" HEIGHT="27" BGCOLOR="#DDDDDD">
			<INPUT TYPE="text" NAME="theName" VALUE="" SIZE=34 MAXLENGTH=50>
		</TD>
	</TR>
	<TR>
		<TD HEIGHT="2" BGCOLOR="#DDDDDD">
			Categories:
		</TD>
		<TD HEIGHT="2" BGCOLOR="#DDDDDD">
			Default category?
		</TD>
	</TR>
	<TR>
		<TD HEIGHT="2" BGCOLOR="#DDDDDD" WIDTH="10%">
			<INPUT TYPE="text" NAME="cat1" VALUE="" SIZE=34 MAXLENGTH=50>
		</TD>
		<TD HEIGHT="2" BGCOLOR="#DDDDDD" >
			&nbsp;&nbsp;&nbsp;<INPUT TYPE="CHECKBOX" NAME="t1" VALUE="1">
		</TD>
	</TR>
	<TR>
		<TD HEIGHT="2" BGCOLOR="#DDDDDD">
			<INPUT TYPE="text" NAME="cat2" VALUE="" SIZE=34 MAXLENGTH=50>
		</TD>
		<TD HEIGHT="2" BGCOLOR="#DDDDDD" >
			&nbsp;&nbsp;&nbsp;<INPUT TYPE="CHECKBOX" NAME="t2" VALUE="2">
		</TD>
	</TR>
	<TR>
		<TD HEIGHT="2" BGCOLOR="#DDDDDD">
			<INPUT TYPE="text" NAME="cat3" VALUE="" SIZE=34 MAXLENGTH=50>
		</TD>
		<TD HEIGHT="2" BGCOLOR="#DDDDDD" >
			&nbsp;&nbsp;&nbsp;<INPUT TYPE="CHECKBOX" NAME="t3" VALUE="3">
		</TD>
	</TR>
	<TR>
		<TD HEIGHT="2" BGCOLOR="#DDDDDD">
			<INPUT TYPE="text" NAME="cat4" VALUE="" SIZE=34 MAXLENGTH=50>
		</TD>
		<TD HEIGHT="2" BGCOLOR="#DDDDDD" >
			&nbsp;&nbsp;&nbsp;<INPUT TYPE="CHECKBOX" NAME="t4" VALUE="4">
		</TD>
	</TR>
	<TR>
		<TD HEIGHT="2" BGCOLOR="#DDDDDD">
			<INPUT TYPE="text" NAME="cat5" VALUE="" SIZE=34 MAXLENGTH=50>
		</TD>
		<TD HEIGHT="2" BGCOLOR="#DDDDDD" >
			&nbsp;&nbsp;&nbsp;<INPUT TYPE="CHECKBOX" NAME="t5" VALUE="5">
		</TD>
	</TR>
	<TR>
		<TD HEIGHT="2" BGCOLOR="#DDDDDD">
			<INPUT TYPE="text" NAME="cat6" VALUE="" SIZE=34 MAXLENGTH=50>
		</TD>
		<TD HEIGHT="2" BGCOLOR="#DDDDDD" >
			&nbsp;&nbsp;&nbsp;<INPUT TYPE="CHECKBOX" NAME="t6" VALUE="6">
		</TD>
	</TR>
	
	<TR>
		<TD COLSPAN="2" HEIGHT="2" BGCOLOR="#DDDDDD">
			<INPUT TYPE="hidden" NAME="action" VALUE="create">
			<INPUT TYPE="hidden" NAME="theData" VALUE="$theData2">
			<INPUT TYPE="hidden" NAME="inst" VALUE="$params{inst}">
			<INPUT TYPE="hidden" NAME="max" VALUE="$params{max}">
			<INPUT TYPE="hidden" NAME="qname" VALUE="$params{qname}">
			<INPUT TYPE="hidden" NAME="queryID" VALUE="$params{queryID}">
			<INPUT TYPE="hidden" NAME="thMode" VALUE="$params{thMode}">
			<INPUT TYPE="hidden" NAME="thin" VALUE="$params{thin}">
			<INPUT TYPE="hidden" NAME="qtype" VALUE="0">
			<INPUT TYPE="hidden" NAME="view" VALUE="$params{view}">
			<INPUT TYPE="hidden" NAME="program" VALUE="$params{program}">
			<INPUT TYPE="hidden" NAME="word" VALUE="$params{word}">
			<INPUT TYPE="hidden" NAME="dbname" VALUE="$params{dbname}">
			<INPUT TYPE="hidden" NAME="ot" VALUE="$params{ot}">
			<INPUT TYPE="hidden" NAME="sortpos" VALUE="$params{sortpos}">
			<INPUT TYPE="hidden" NAME="exclude" VALUE="$params{exclude}">
			<INPUT TYPE="hidden" NAME="letter" VALUE="$params{letter}">
			<INPUT TYPE="hidden" NAME="tag" VALUE="$params{tag}">
			<INPUT TYPE="hidden" NAME="numOfFiles" VALUE="$params{numOfFiles}">
			<INPUT TYPE="hidden" NAME="numOfSolutions" VALUE="$numOfSolutions">
			<INPUT TYPE="hidden" NAME="run" VALUE="$params{run}">
			<INPUT TYPE="hidden" NAME="theID" VALUE="$params{theID}">
			<INPUT TYPE="hidden" NAME="urlTest" VALUE="yes">
			<INPUT TYPE="submit" VALUE="Submit">
			</FORM>
		</TD>
	</TR>
	<TR>
		<TD COLSPAN="2" HEIGHT="2" BGCOLOR="#DDDDDD">
			<B>Instructions:</B><BR>
			<UL><LI>Names can only contain letters, numbers and the underscore character (&quot;_&quot;)</LI>
			<LI>The categories &quot;Unclear&quot; and &quot;Other&quot; will be automatically added to the list</LI>
			<LI>Selecting a default category will mean that all hits will be automatically set to this value. This can be useful if you expect most of the hits
			to belong to one particular category. However, it will mean that you have to go through the <b>complete</b> set of concordances (and not only the first 
			x number of hits of a randomly ordered query result).</LI>
			</UL>
		</TD>
	</TR>
	</TABLE>
END
	&printFooter();
	exit(0);

} 

sub addValue {

	$sqlQuery = "SELECT theValues, theName FROM categorize WHERE theName='$params{dbname}'";
	$sth= $bncHandle->prepare($sqlQuery) or bark("Can't prepare $sqlQuery: " . $bncHandle::errstr);
	$sth->execute or bark("Can't execute $sqlQuery: " . $sth::errstr);
	@array=$sth->fetchrow_array;
	$theValues=$array[0];
	$theName=$array[1];
	
	$theName =~s/${username}_cat_//;
	$theDispName = $';
	$theValues=~s/·/, /g;
	
	$title ='<TR><TD HEIGHT="27" COLSPAN="2" BGCOLOR="#CCCCFF"> <FONT SIZE="4"><B>Add value to existing set of categorization values for the query <i>' . $theName . '</i></B></FONT></TD></TR>';

	&printHeader("Query categorization");
	
	print <<END;

	<FORM ACTION="/$bwCGIalias/${thisProg}" METHOD=GET>
	
	<TABLE BORDER="0" WIDTH="100%" CELLPADDING=3 CELLSPACING=2>
	$title
	
	<TR><TD HEIGHT="27" BGCOLOR="#DDDDDD" WIDTH="20%">Current values:</td><td BGCOLOR="#DDDDDD"><i>$theValues</i></TD></TR>
	<TR>
		<TD HEIGHT="27" BGCOLOR="#DDDDDD">
			Additional value:
		<TD HEIGHT="27" BGCOLOR="#DDDDDD">
			<INPUT TYPE="text" NAME="theAdditionalValue" VALUE="" SIZE=34 MAXLENGTH=50>
		</TD>
	</TR>
	<TR>
		<TD COLSPAN="2" HEIGHT="27" BGCOLOR="#DDDDDD" ALIGN=CENTER>
			<INPUT TYPE="hidden" NAME="urlTest" VALUE="yes">
			<INPUT TYPE="hidden" NAME="dbname" VALUE="$params{dbname}">
			<INPUT TYPE="hidden" NAME="action" VALUE="addNewValue">
			<INPUT TYPE="submit" VALUE="Submit">
		</TD>
	</TR>
	</TABLE>
	
END
	&printFooter();
	exit(0);
}

sub addNewValue {
	
	unless (($params{theAdditionalValue}=~m/\A(other|unclear)\Z/i) || (!$params{theAdditionalValue})) {
		$sqlQuery = "SELECT theValues, theName FROM categorize WHERE theName='$params{dbname}'";
		$sth= $bncHandle->prepare($sqlQuery) or bark("Can't prepare $sqlQuery: " . $bncHandle::errstr);
		$sth->execute or bark("Can't execute $sqlQuery: " . $sth::errstr);
		@array=$sth->fetchrow_array;
		$theValues=$array[0];
		$theName=$array[1];
		
		$theName =~s/${username}_cat_//;
		$theDispName = $';
		
		@theValues =split(/·/, $theValues);
		$checkDuplicate = 0;
		$newValues = "";
		foreach $value (@theValues) {
			$checkDuplicate++ if ($value eq $params{theAdditionalValue});
			unless ($value eq "other") {
				$newValues .= "·" . $value;
			} else {
				$newValues .= "·" . $params{theAdditionalValue} . "·other";
			}
		}
		$newValues=~s/\A·//;
		
		$newValuesInsert = $bncHandle->quote($newValues);
		
		$sqlQuery = "update categorize set theValues = $newValuesInsert where theName='$params{dbname}'";
		
		$bncHandle->do($sqlQuery) or bark("Can't insert $sqlQuery: " . $bncHandle::errstr);
		
		}
	print "Location: /$bwCGIalias/BNCquery.pl?theQuery=categorizedQueries&chunk=1&user=$username&urlTest=yes\n\n";
	
}




sub create {

	unless ($params{theName}) {
		# print error message
		&printHeader("Error message");
		print <<END;
		<TABLE BORDER="0" WIDTH="100%" CELLPADDING=3 CELLSPACING=3>
		<TR>
			<TD HEIGHT="27" COLSPAN="2" BGCOLOR="#FF6666"><FONT SIZE="4"><B>Error message</B></FONT></TD>
		</TR>
		<TR>
			<TD BGCOLOR="#DDDDDD" COLSPAN="2" HEIGHT="37">
				<BR><B>You have not entered a name for your query result!</B><BR><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);
	}


	$error=0;
	$categories = "";
	for $i (1 .. 6) {
		if (($params{"cat$i"}) || ($params{"cat$i"} eq "0")) {
			$theValue = lc($params{"cat$i"});
			if ($params{"t$i"}) {
				$theDefault = $params{"cat$i"};
				$defaultCount++;
			}
			$error++ if ($theValue=~m/[^a-z0-9_]/);
			$categories .= "·" . $theValue unless $already{$theValue};
			setParam("cat$i", "");
			$already{$theValue}=1;
		} else {
			$countEmpty++;
		}
	}
	

	if ($error) {
		# print error message
		&printHeader("Error message");
		print <<END;
		<TABLE BORDER="0" WIDTH="100%" CELLPADDING=3 CELLSPACING=3>
		<TR>
			<TD HEIGHT="27" COLSPAN="2" BGCOLOR="#FF6666"><FONT SIZE="4"><B>Error message</B></FONT></TD>
		</TR>
		<TR>
			<TD BGCOLOR="#DDDDDD" COLSPAN="2" HEIGHT="37">
				<BR><B>Query names and values can only contain letters, numbers and the underscore character (&quot;_&quot;)!</B><BR><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);
	} elsif ($defaultCount > 1) {
		# print error message
		&printHeader("Error message");
		print <<END;
		<TABLE BORDER="0" WIDTH="100%" CELLPADDING=3 CELLSPACING=3>
		<TR>
			<TD HEIGHT="27" COLSPAN="2" BGCOLOR="#FF6666"><FONT SIZE="4"><B>Error message</B></FONT></TD>
		</TR>
		<TR>
			<TD BGCOLOR="#DDDDDD" COLSPAN="2" HEIGHT="37">
				<BR><B>Only one category can be selected as default value!</B><BR><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);
	} elsif  ($countEmpty == 6) {
		# print error message
		&printHeader("Error message");
		print <<END;
		<TABLE BORDER="0" WIDTH="100%" CELLPADDING=3 CELLSPACING=3>
		<TR>
			<TD HEIGHT="27" COLSPAN="2" BGCOLOR="#FF6666"><FONT SIZE="4"><B>Error message</B></FONT></TD>
		</TR>
		<TR>
			<TD BGCOLOR="#DDDDDD" COLSPAN="2" HEIGHT="37">
				<BR><B>You have not entered any categories!</B><BR><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);
	}
	
	setParam("theDefault", "$theDefault");

	$categories=~s/\A·//;
	$categories .= "·other" unless $already{other};
	$categories .= "·unclear" unless $already{unclear};


	$theName = $username . "_cat_" . $params{theName};
	$newQueryID = $theName;

	# Check whether categorized query of this name already exists
	$sqlQuery = "SELECT theName FROM categorize WHERE theName='$theName'";
	$sth= $bncHandle->prepare($sqlQuery) or bark("Can't prepare $sqlQuery: " . $bncHandle::errstr);
	$sth->execute or bark("Can't execute $sqlQuery: " . $sth::errstr);
	@array=$sth->fetchrow_array;
	$alreadyName=$array[0];
	if ($alreadyName) {
		# print error message
		&printHeader("Duplicate name alert");
		print <<END;
		<TABLE BORDER="0" WIDTH="100%" CELLPADDING=3 CELLSPACING=3>
		<TR>
			<TD HEIGHT="27" COLSPAN="2" BGCOLOR="#FF6666"><FONT SIZE="4"><B>Error message</B></FONT></TD>
		</TR>
		<TR>
			<TD BGCOLOR="#DDDDDD" COLSPAN="2" HEIGHT="37">
				<BR><B>A categorized query with the name &quot;$params{theName}&quot; already exists!</B><BR><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);
	
	}
	

	
	#######################################	
	CQPconnect(full);	
	
	
	$CQP->exec("set DataDirectory '/$bwTempPath/'");
	$CQP->exec("$bwCorpus");
	
	($numOfSolutions) = $CQP->exec("size $params{qname}");
	
	$CQP->exec("$theName = $params{qname}");
	$CQP->exec("set DataDirectory '/$bwTempPath/'");
	$CQP->exec("$bwCorpus");

	#$CQP->exec("sort $theName randomize 42");
	$CQP->exec("save $theName");


	
	$sqlQuery = "SELECT * FROM savedQueries WHERE queryID='$params{queryID}'";
	$sth= $bncHandle->prepare($sqlQuery) or bark("Can't prepare $sqlQuery: " . $bncHandle::errstr);
	$sth->execute or bark("Can't execute $sqlQuery: " . $sth::errstr);
	@array=$sth->fetchrow_array;
	$SQuser=$username;
	$SQquery=$array[2];
	$SQthMode=$array[3];
	$SQhits=$array[4];
	$SQtime_of_query=$array[5];
	#$SQrefnums=$array[8];
	$SQlink=$array[8];
	
	$SQquery=$bncHandle->quote($SQquery);
	$SQlink =$bncHandle->quote($SQlink);
	
		
	$thModeInsert = $params{thMode};
	$thModeInsert = $bncHandle->quote($thModeInsert);
	$categoriesInsert = $bncHandle->quote($categories);
	
	$sqlQuery = "insert into categorize (user, queryID, query, thMode, hits, time_of_query, link, theName, theValues) 
				values ('$SQuser', '$newQueryID', $SQquery, $thModeInsert, $numOfSolutions, $SQtime_of_query, $SQlink, '$theName', $categoriesInsert)";
	
	$bncHandle->do($sqlQuery) or bark("Can't insert $sqlQuery: " . $bncHandle::errstr);
	
	
	setParam("queryID", "$newQueryID");
	setParam("qname", "$theName");
	setParam("aim", "categorize");
	
	$theURL = getURLparams();
	
	CQPdisconnect();
	print "Location: /$bwCGIalias/distribution.pl?${theURL}&urlTest=yes\n\n";
	
	
}

sub update {
	
	if ($params{Leave} eq "New Query") {
		print "Location: /$bwCGIalias/BNCquery.pl?theQuery=search&urlTest=yes\n\n";
	}

	$qString = $ENV{'QUERY_STRING'};
	@items = split(/&/, $qString);
	foreach $item (@items) {
		$check = $item=~m/\Acat(\d+)=(\S+)\Z/;
		if ($check) {
			$refnumber = $1;
			$theValue = $2;
			$sqlQuery = "UPDATE $params{dbname} SET catName = '$theValue' WHERE refnumber = $refnumber";
			$categorizeHandle->do($sqlQuery) or bark("Can't update $sqlQuery: " . $userHandle::errstr);
			setParam("cat$refnumber", "");
		}
	}	
	$sqlQuery = "UPDATE `categorize` SET date_of_saving = CURRENT_TIMESTAMP WHERE theName = '$params{dbname}'";
	$bncHandle->do($sqlQuery) or bark("Can't update $sqlQuery: " . $bncHandle::errstr);	

	$chunk = $params{chunk};
	$chunk++ unless ($chunk == $params{max});
	setParam("chunk", "$chunk");
	if ($params{Leave} eq "Save categorization values for this page!") {
		$theURL = getURLparams();
		print "Location: /$bwCGIalias/main.pl?${theURL}&urlTest=yes\n\n";
	} else {
		setParam("categorize", "");
		$theURL = getURLparams();
		print "Location: /$bwCGIalias/BNCquery.pl?theQuery=categorizedQueries&user=$username&chunk=1&urlTest=yes\n\n";
	}
	
}

sub separate {

	CQPconnect(full);
	
	$CQP->exec("set DataDirectory '/$bwTempPath/'");
	$CQP->exec("$bwCorpus");
	
	($numOfSolutions) = $CQP->exec("size $params{dbname}");
	
	$params{dbname}=~m/\A$params{user}_cat_/;
	$theNamePart = $params{user} . "_" . $';

	$sqlQuery = "SELECT * FROM categorize WHERE theName='$params{dbname}'";
	$sth= $bncHandle->prepare($sqlQuery) or bark("Can't prepare $sqlQuery: " . $bncHandle::errstr);
	$sth->execute or bark("Can't execute $sqlQuery: " . $sth::errstr);
	@array=$sth->fetchrow_array;
	$thMode=$array[3];
	$user = $array[0];
	$query= $array[2];
	$SQlink = $array[7];
	$theValues = $array[9];
	$SQquery=$bncHandle->quote($query);
	$SQlink =$bncHandle->quote($SQlink);
	$time = time;

	
	$sqlQuery = "SELECT distinct(catName) FROM $params{dbname}";

	$sth= $categorizeHandle->prepare($sqlQuery) or bark("Can't prepare $sqlQuery: " . $bncHandle::errstr);
	$sth->execute or bark("Can't execute $sqlQuery: $sth2::errstr");
	$res = $sth->rows;
	$table = $sth->fetchall_arrayref or bark("Can't fetchrow_arrayref $sqlQuery: $sth2::errstr");
	
	@theValues = split(/·/, $theValues);
	
	foreach $catName (@theValues) {
	
		$qNameNew = $theNamePart . "_" . $catName;
		$qNameNew2 = $username . "_" . time;

		unlink("/$bwTempPath/$bwCorpus:$qNameNew") if -f "/$bwTempPath/$bwCorpus:$qNameNew";
		
		$sqlQuery = "SELECT $params{dbname}.beginPosition, $params{dbname}.endPosition INTO OUTFILE '/$bwMySQLTempPath/$qNameNew' FROM $params{dbname} WHERE $params{dbname}.catName = '$catName'";
		$sth1 = $categorizeHandle->prepare($sqlQuery) or bark("Can't prepare $sqlQuery: " . $bncHandle::errstr);
		$sth1->execute or bark("Can't execute $sqlQuery: ". $sth::errstr);
		$numOfSolutions=$sth1->rows;
		
		if ($numOfSolutions) {
			qx{echo $numOfSolutions | cat - '/$bwTempPath/$qNameNew' > '/$bwTempPath/$qNameNew2'};
			$CQP->exec("set DataDirectory '/$bwTempPath/'");
			$CQP->exec("$bwCorpus");
			
			$CQP->exec("undump $qNameNew < '/$bwTempPath/$qNameNew2'");
			unlink("/$bwTempPath/$qNameNew") if -f "/$bwTempPath/$qNameNew";
			unlink("/$bwTempPath/$qNameNew2") if -f "/$bwTempPath/$qNameNew2";
			
			#$CQP->exec("set DataDirectory '/$bwTempPath/'");
			#$CQP->exec("$bwCorpus");
			
			$CQP->exec("save $qNameNew");
			@stat = stat("/$bwTempPath/$bwCorpus:$qNameNew");
			$fileSize = $stat[7];
			
			$thModeNew = $thMode;
			$thModeNew .= "##Q" . $catName . "#" . $numOfSolutions;
			
			$thModeInsert = $bncHandle->quote($thModeNew);
			
			
			$sqlQuery = "SELECT * FROM savedQueries WHERE theName='$qNameNew' and user='$user'";
			$sth2= $bncHandle->prepare($sqlQuery) or bark("Can't prepare $sqlQuery: " . $bncHandle::errstr);
			$sth2->execute or bark("Can't execute $sqlQuery: " . $sth2::errstr);
			$res = $sth2->rows;

			if ($res) {
				$sqlQuery = "DELETE FROM savedQueries WHERE theName='$qNameNew' and user='$user'";
				$bncHandle->do($sqlQuery) or bark("Can't insert $sqlQuery: " . $bncHandle::errstr);
			}
			
			$sqlQuery = "insert into savedQueries (user, queryID, query, thMode, hits, time_of_query, saved, link, theName, fileSize) 
						values ('$user', '$qNameNew', $SQquery, $thModeInsert, $numOfSolutions, $time, 1, $SQlink, '$qNameNew', $fileSize)";
			$bncHandle->do($sqlQuery) or bark("Can't insert $sqlQuery: " . $bncHandle::errstr);
		} else {
			$sqlQuery = "DELETE FROM savedQueries WHERE theName='$qNameNew' and user='$user'";
			$bncHandle->do($sqlQuery) or bark("Can't insert $sqlQuery: " . $bncHandle::errstr);
			unlink("/$bwTempPath/$qNameNew") if -f "/$bwTempPath/$qNameNew";
			unlink("/$bwTempPath/$bwCorpus:$qNameNew") if -f "/$bwTempPath/$bwCorpus:$qNameNew";
		}
	}
	
	CQPdisconnect();
	print "Location: /$bwCGIalias/BNCquery.pl?theQuery=savedQueries&user=$username&chunk=1&urlTest=yes\n\n";

	
}

