#!C:/APerl/bin/perl.exe --
use CGI qw(:standard);
use CGI::Carp qw(warningsToBrowser fatalsToBrowser);
use strict;
use Socket;


my $arParDb = "cgi-bin/arPar.db";
my $arDataDb = "cgi-bin/arData.db";
my $arLog = "cgi-bin/arLog.txt";
my $arHtm="cgi-bin/arHtm.eng";
my $arEmail="cgi-bin/arEmail.eng";

my $slHome="http://localhost/web";
my $slCgiHome="http://localhost/cgi-bin";
my $slDBBackupCount = 1;      # number of db backup files *.ba0,*.ba1
my $slMailTool="|/usr/lib/sendmail -oi -t -odq";

my $emailSales="sales\@solutionlanguage.com";
my $slFormError="";
my $s_e=";//;";
my $s_m="~&&~";
my ($passwd, $date, $lock_ex,$lock_un,$to_begin,$to_end);
my ($userError, $pcodeError, $emailAddrError, $hwError,$err, $err1, $errMsg);
my $htmlSubs="";
my $noMail=1;

$lock_ex=2; $lock_un=8; $to_begin=1; $to_end=2;
$userError=""; $pcodeError=""; $emailAddrError=""; $hwError=""; $err=0; $err1=0; $errMsg="";
#
# *******************************
# Only Post protocol is accepted.
# *******************************
#
if(param("cmd") ne "oladmin") 
{&logVisitor;}
#if ($ENV{REQUEST_METHOD} ne "POST") {print header;&subError ("Unknown request");exit;}
if(param("cmd") eq "put")
{
 my $dbrec;
 print header;
 (my $date,my $datetime,my $sec)=getDate();
 $dbrec=$datetime."|".encode2(param("id"))."|";
 $dbrec=$dbrec.encode2(param("0"))."|";
 $dbrec=$dbrec.encode2(param("1"))."|";$dbrec=$dbrec.encode2(param("2"))."|";$dbrec=$dbrec.encode2(param("3"))."|";
 $dbrec=$dbrec.encode2(param("4"))."|";$dbrec=$dbrec.encode2(param("5"))."|";$dbrec=$dbrec.encode2(param("6"))."|";
 $dbrec=$dbrec.encode2(param("7"))."|";$dbrec=$dbrec.encode2(param("8"))."|";$dbrec=$dbrec.encode2(param("9"))."|";$dbrec=$dbrec.encode2(param("10"))."|";
 $dbrec=$dbrec.encode2(param("11"))."|";$dbrec=$dbrec.encode2(param("12"))."|";$dbrec=$dbrec.encode2(param("13"))."|";
 $dbrec=$dbrec.encode2(param("14"))."|";$dbrec=$dbrec.encode2(param("15"))."|";
 &openFile("$arDataDb","+>>",1,1) or &subError ("PutReq100: Datalogger database opening error (write).");
 &setFile($to_end,1);
 print FILE1 "\n".$dbrec;
 &closeFile(1,1);
 my %rec=getDBRec($arParDb,"loggerId",encode2(param("id")));
 print $rec{cflag};
# print $rec{"cflag"}." OK";
 purge(encode2(param("id")));
 exit;
}

elsif(param("cmd") eq "getp")
# ar.cgi?cmd=getp&id=126&p=a
# ar.cgi?cmd=getp&id=126&p=0
{
 print header;
 my %rec=getDBRec($arParDb,"loggerId",encode2(param("id")));
 if(param("p") eq "a")
 {
  print $rec{sms_phone}." ".$rec{email}." ".$rec{passw}." ".$rec{delta_t};
 }
 else
 {
  print $rec{param("p")};
 }
 exit;
}

elsif(param("cmd") eq "putp")
{
 print header;
 my %rec=getDBRec($arParDb,"loggerId",encode2(param("id")));
 $rec{param("p")}=param("v");
 &putDBRec($arParDb,"loggerId",encode2(param("id")),\%rec);
 purge(encode2(param("id")));
 exit;
}


elsif(param("cmd") eq "signIn")
{
 print header;
 my %rec=getDBRec($arParDb,"loggerId",encode2(param("loggerId")));
 if ((encode2(param("email")) eq "admin") && (encode2(param("passw")) eq "admin")) {printLaunch("launchAdm");}
 elsif (($rec{loggerId} eq encode2(param("loggerId"))) && ($rec{loggerId} ne "")) {printLaunch("launchUser",encode2(param("loggerId")));}
 else {printLaunch("home2");}
 exit;
}

elsif(param("cmd") eq "anim")
{
 print header;
 my %rec=getDBRec($arParDb,"loggerId",encode2(param("loggerId")));
 if (($rec{loggerId} eq encode2(param("loggerId"))) && ($rec{loggerId} ne "")) {printImages("launchUser",encode2(param("loggerId")));}
 else {printLaunch("home2");}
 exit;
}

elsif(param("cmd") eq "play")
{
 print header;
 my %rec=getDBRec($arParDb,"loggerId",encode2(param("loggerId")));
 if (($rec{loggerId} eq encode2(param("loggerId"))) && ($rec{loggerId} ne "")) {&animateImages("launchUser",encode2(param("loggerId")));}
 else {printLaunch("home2");}
 exit;
}

elsif(param("cmd") eq "exit_control")
{
 print header;
 my %rec=getDBRec($arParDb,"loggerId",encode2(param("loggerId")));
 if (($rec{loggerId} eq encode2(param("loggerId"))) && ($rec{loggerId} ne "")) {printExits("exit",encode2(param("loggerId")));}
 else {printLaunch("home2");}
 exit;
}

elsif(param("cmd") eq "alarm_control")
{
 print header;
 my %rec=getDBRec($arParDb,"loggerId",encode2(param("loggerId")));
 if (($rec{loggerId} eq encode2(param("loggerId"))) && ($rec{loggerId} ne "")) {printAlarms("exit",encode2(param("loggerId")));}
 else {printLaunch("home2");}
 exit;
}


elsif(param("cmd") eq "sGraph")
# ar.cgi?cmd=sGraph&id=126&0=1&1=1
{
 my ($dbName,$dbTitle,$dbKey, $dbRec, $ind, $delta);
 my (@dbFieldNames,@dbFieldValues);
 my ($count,$recNo,$startTime,$stopTime,$startTimeStr,$stopTimeStr,$eTimeMins,$eTimeHours,$eTimeDays,$labels,$loggerId,$from,$navTab);
 my ($d0,$d1,$d2,$d3,$d4,$d5,$d6,$d7,$d8,$d9,$d10,$d11,$d12,$d13,$d14,$d15);
 my ($d0cnt,$d1cnt,$d2cnt,$d3cnt,$d4cnt,$d5cnt,$d6cnt,$d7cnt,$d8cnt,$d9cnt,$d10cnt,$d11cnt,$d12cnt,$d13cnt,$d14cnt,$d15cnt);
 my $sampleCnt;
 $d0cnt=0;$d1cnt=0;$d2cnt=0;$d3cnt=0;$d4cnt=0;$d5cnt=0;$d6cnt=0;$d7cnt=0;$d8cnt=0;$d9cnt=0;$d10cnt=0;$d11cnt=0;$d12cnt=0;$d13cnt=0;$d14cnt=0;$d15cnt=0;
 $d0="";$d1="";$d2="";$d3="";$d4="";$d5="";$d6="";$d7="";$d8="";$d9="";$d10="";$d11="";$d12="";$d13="";$d14="";$d15=""; $navTab="";
 $from=param("from"); if($from eq "") {$from=0;}
 $sampleCnt=param("cnt"); if($sampleCnt eq "") {$sampleCnt=100;}
 print header;
 $loggerId=encode2(param("id"));
# my %rec=getDBRec($arParDb,"loggerId",encode2(param("id")));
 openFile($arDataDb,"",0,0);
 my $dbTitle1=<FILE0>;
  @dbFieldNames=(split(/\|/, $dbTitle1));
  $ind=0;
  while($ind<@dbFieldNames)
   {
#    print "<th class='h2'>$dbFieldNames[$ind]</th>";
    $ind++;
   }
  $recNo=0;
  my $processedRecCnt=0;
  while($dbRec=<FILE0>)
  {
     if ($recNo % $sampleCnt eq 0) {$navTab = updateNav($navTab,$recNo,$sampleCnt,$from);}
     if (($recNo >= $from)&& ($recNo < $from+$sampleCnt))
     {
       $ind=0;
       while($ind<@dbFieldNames-1)
       {
        @dbFieldValues=(split(/\|/, $dbRec));
        if ($dbFieldValues[1] eq $loggerId)
         {
#         print "<p>$dbFieldValues[$ind]</p>";
           if(($processedRecCnt==0) && ($ind==0)) {$startTime=getMinutes($dbFieldValues[$ind]);$startTimeStr=$dbFieldValues[$ind];}
           $processedRecCnt++;
           if ($ind==0) {$stopTime=getMinutes($dbFieldValues[$ind]);$stopTimeStr=$dbFieldValues[$ind];}
           if(($ind==2) && (param("0") eq "1"))
            {
             if($d0cnt>0) {$d0=$d0.",";} $d0=$d0.$dbFieldValues[$ind]; $d0cnt++;
            }
           elsif(($ind==3) && (param("1") eq "1"))
            {
             if($d1cnt>0) {$d1=$d1.",";} $d1=$d1.$dbFieldValues[$ind]; $d1cnt++;
            }
           $ind++;
          }
        else {$ind=@dbFieldNames-1;}
       }
      }
      if ($dbFieldValues[1] eq $loggerId) {$recNo++;}
  }

 $eTimeMins=0;$eTimeHours=0;$eTimeDays=0;
 $eTimeMins=$stopTime-$startTime; $eTimeHours=int($eTimeMins/60); $eTimeDays=int($eTimeHours/24);
 $ind=0; $delta=1; $labels="";
 if($eTimeDays > 2) 
  {
    if($eTimeDays > 20) {$delta=4;}  elsif($eTimeDays > 10) {$delta=2;}
    while($ind < $eTimeDays)
     {
      if($ind>0) {$labels=$labels.",";}
      $labels=$labels.$ind;
      $ind=$ind+$delta;
     }
  }
 elsif ($eTimeHours > 2)
  {
    if($eTimeHours > 20) {$delta=4;}  elsif($eTimeHours > 10) {$delta=2;}
    while($ind < $eTimeHours)
     {
      if($ind>0) {$labels=$labels.",";}
      $labels=$labels.$ind;
      $ind=$ind+$delta;
     }
  }
 else
  {
    if($eTimeMins > 20) {$delta=4;}  elsif($eTimeMins > 10) {$delta=2;}
    while($ind < $eTimeMins)
     {
      if($ind>0) {$labels=$labels.",";}
      $labels=$labels.$ind;
      $ind=$ind+$delta;
     }
  }
 printLc("lc1");
 print $d0; printLc("lc2"); print $d1; printLc("lc3"); print $labels; printLc("lc4");
 if ($recNo % $sampleCnt ne 0) {$navTab = updateNav($navTab,$recNo,$sampleCnt,$from);}
 $navTab = updateNav($navTab,$recNo,$recNo,0); $navTab = addHomeBtn($navTab);
 print("<br><tr><td>$navTab </td><td>&nbsp;&nbsp;</td><td><input TYPE=\"text\" class=\"bodyText\" value=\"$startTimeStr\"></td><td>&nbsp;-&nbsp;</td><td><input TYPE=\"text\" class=\"bodyText\" value=\"$stopTimeStr\"></td></tr>");
 printLc("lc5");
 exit;
}

elsif(param("cmd") eq "oladmin")
{
 my ($dbName,$dbTitle,$dbKey, $dbRec, $ind);
 my (@dbFieldNames,@dbFieldValues);
 my ($count,$from,$recNo,$navTab);
 $count=50;
 $from=param("from"); if($from eq "") {$from=0;}
 $recNo=0; $navTab="";
 print header;
# purge(126);
 if((param("dbName") eq "Logger parameters database") || (param("dbName") eq ""))  {$dbName=$arParDb; $dbKey="loggerId";}
 if(param("dbName") eq "Logger data database") {$dbName=$arDataDb; $dbKey="time";}
 if(param("dbName") eq "Visitor log") {$dbName=$arLog; $dbKey="";}
 if(param("p1") eq "upd")
 {
  my %rec=getDBRec($dbName,$dbKey,param("p2"));
  $rec{param("p3")}=param("p4");
  if(param("dbName") eq "Logger parameters database")
   {
    if((param("p3") eq "loggerId") || (param("p3") eq "sms_phone") || (param("p3") eq "email") || (param("p3") eq "delta_t")) {$rec{"cflag"}=$rec{"cflag"} | 0x10000;}
    if(param("p3") eq "0") {$rec{"cflag"}=$rec{"cflag"} | 0x00001;} if(param("p3") eq "1") {$rec{"cflag"}=$rec{"cflag"} | 0x00002;}
    if(param("p3") eq "2") {$rec{"cflag"}=$rec{"cflag"} | 0x00004;} if(param("p3") eq "3") {$rec{"cflag"}=$rec{"cflag"} | 0x00008;}
    if(param("p3") eq "4") {$rec{"cflag"}=$rec{"cflag"} | 0x00010;} if(param("p3") eq "5") {$rec{"cflag"}=$rec{"cflag"} | 0x00020;}
    if(param("p3") eq "6") {$rec{"cflag"}=$rec{"cflag"} | 0x00040;} if(param("p3") eq "7") {$rec{"cflag"}=$rec{"cflag"} | 0x00080;}
    if(param("p3") eq "8") {$rec{"cflag"}=$rec{"cflag"} | 0x00100;} if(param("p3") eq "9") {$rec{"cflag"}=$rec{"cflag"}  | 0x00200;}
    if(param("p3") eq "10") {$rec{"cflag"}=$rec{"cflag"} | 0x00400;} if(param("p3") eq "11") {$rec{"cflag"}=$rec{"cflag"} | 0x00800;}
    if(param("p3") eq "12") {$rec{"cflag"}=$rec{"cflag"} | 0x01000;} if(param("p3") eq "13") {$rec{"cflag"}=$rec{"cflag"} | 0x02000;}
    if(param("p3") eq "14") {$rec{"cflag"}=$rec{"cflag"} | 0x04000;} if(param("p3") eq "15") {$rec{"cflag"}=$rec{"cflag"} | 0x08000;}
   }
  &putDBRec($dbName,$dbKey,param("p2"),\%rec);
 }
 elsif((param("p1") eq "add") && ($dbName eq $arParDb))
 {
  &openFile("$arParDb","+>>",1,1) or &subError ("AdminDb100: Arduino parameters database opening error (write).");
  print FILE1 "\n"."newRecord"."|"."0x000000000"."\|||||||||||||||||||||";
  &closeFile(1,1);
 }
 elsif(param("p1") eq "del")
 {
  if ($dbName eq $arLog)
  {
   &openFile("$dbName",">",1,1) or &subError ("AdminDb99: Arduino log opening error (write).");
   (my $date,my $datetime,my $sec)=getDate();
   print FILE1 "Title\nVisitor log created: $datetime\n" ;
   &closeFile(1,1);
  }
  else
  {
    &delDBRec($dbName,$dbKey,param("p2"));
  }
 }
 if(openFile($dbName,"",0,0)==0) {subError("AdminDb101: Database $dbName opening error (read).");} my $dbTitle1=<FILE0>; 
 &printAdminTop;
 if ($dbName eq $arLog)
 {
  while($dbRec=<FILE0>)
  {
   if ($recNo % $count eq 0) {$navTab = updateNav($navTab,$recNo,$count,$from);}
   if (($recNo >= $from)&& ($recNo < $from+$count)) {print "<tr>";print "<td>$dbRec</td>"; print "</tr>";}
   $recNo=$recNo+1;
  }
   if ($recNo % $count ne 0) {$navTab = updateNav($navTab,$recNo,$count,$from);}
   $navTab = addHomeBtn($navTab);
   print("<tr><td>$navTab <input class=\"bodyText\" type=\"button\" value=\"Delete Log File\" onclick=\"delFile()\"></td></tr>");

 }
 else
 {
  @dbFieldNames=(split(/\|/, $dbTitle1));
  $ind=0;
  while($ind<@dbFieldNames)
   {
    print "<th class='h2'>$dbFieldNames[$ind]</th>";
    $ind++;
   }
  while($dbRec=<FILE0>)
  {
   if ($recNo % $count eq 0) {$navTab = updateNav($navTab,$recNo,$count,$from);}
   if (($recNo >= $from)&& ($recNo < $from+$count))
    {
     $ind=0;
     print "<tr>";
     while($ind<@dbFieldNames-1)
     {
      @dbFieldValues=(split(/\|/, $dbRec));
      my $len=length($dbFieldValues[$ind]);
      if ($len==0) {$len=2;}
      if ($len<30) {print "<td><input TYPE=\"text\" class=\"bodyText\" SIZE=\"$len\" MAXLENGTH=\"256\" onchange=\"updateDb(\'$dbFieldValues[0]\',\'$dbFieldNames[$ind]\',this)\" value=\"$dbFieldValues[$ind]\"></td>";}
      else {print "<td><textarea class=\"bodyText\" cols=\"40\" rows=\"3\" onchange=\"updateDb(\'$dbFieldValues[0]\',\'$dbFieldNames[$ind]\',this)\">$dbFieldValues[$ind]</textarea></td>";}
      $ind++;
     }
     print("<td><input class=\"bodyText\" type=\"button\" value=\"Del\" onclick=\"delRecord(\'$dbFieldValues[0]\')\"></td>");
     print "</tr>\n";
    }
    $recNo = $recNo+1;
   }
   if ($recNo-1 % $count ne 0) {$navTab = updateNav($navTab,$recNo,$count,$from);}
   $navTab = addHomeBtn($navTab);
   print("<tr><td colspan='10'>$navTab</td></tr>");
  if ($dbName eq $arParDb)
   {
    print("<tr><td><input class=\"bodyText\" type=\"button\" value=\"Insert record\" onclick=\"insertRecord()\"></td></tr>");
   }
 }
 &closeFile(0,0);
 &printAdminBottom;
}

elsif(param("cmd") eq "oladmin_user")
{
 my ($dbName,$dbTitle,$dbKey, $dbRec, $ind);
 my (@dbFieldNames,@dbFieldValues);
 print header;
 if(param("pass") != 1)
 {
  my %rec=getDBRec($arParDb,"loggerId",encode2(param("p2")));
  if ((encode2(param("email")) eq "admin") && (encode2(param("passw")) eq "admin")) {printLaunch("launchAdm");exit;}
  elsif (($rec{loggerId} eq encode2(param("p2"))) && ($rec{loggerId} ne "") && ($rec{email} eq encode2(param("email"))) && ($rec{passw} eq encode2(param("passw")))) {;}
  else {printLaunch("home2"); exit();}
 }


 $dbName=$arParDb; $dbKey="loggerId";
 if(openFile($dbName,"",0,0)==0) {subError("AdminDb101: Database $dbName opening error (read).");} 
 $dbTitle=<FILE0>;
 @dbFieldNames=(split(/\|/, $dbTitle));
 &closeFile(0,0);
 if(param("p1") eq "upd")
 {
  my %rec=getDBRec($dbName,$dbKey,param("p2"));
  $rec{param("p3")}=param("p4");
  $rec{cflag}="1";
  &putDBRec($dbName,$dbKey,param("p2"),\%rec);
 }
 elsif((param("p1") eq "add") && ($dbName eq $arParDb))
 {
  $ind=9; my $colno=0;
  my %nrec=getDBRec($dbName,$dbKey,param("p2"));
  while (length($nrec{$dbFieldNames[$ind]}) > 0) {$ind=$ind+2;$colno++;}
  $nrec{$dbFieldNames[$ind]}="P=07/2/5/0/0/1/0x0/0/0";
  $nrec{$dbFieldNames[$ind+1]}="M=D6T/resx=4/resy=4/imPos=x,y,x,y,x,y,x,y";
  &putDBRec($dbName,$dbKey,param("p2"),\%nrec);
 }
 elsif(param("p1") eq "del")
 {
  my %nrec=getDBRec($dbName,$dbKey,param("p2"));
  $ind=param("p3");
  $nrec{$dbFieldNames[$ind]}="";  $nrec{$dbFieldNames[$ind+1]}="";
  while(length($nrec{$dbFieldNames[$ind+2]}) > 0)
   {$nrec{$dbFieldNames[$ind]}=$nrec{$dbFieldNames[$ind+2]};
    $nrec{$dbFieldNames[$ind+1]}=$nrec{$dbFieldNames[$ind+3]};
    $ind++;$ind++;
   }
  $nrec{$dbFieldNames[$ind]}="";  $nrec{$dbFieldNames[$ind+1]}="";
  &putDBRec($dbName,$dbKey,param("p2"),\%nrec);
 }
 my %nrec=getDBRec($dbName,$dbKey,param("p2"));
 my $lid=$nrec{'loggerId'}; #param("p4");
 my $h_email=$nrec{email};
 my $h_passw=$nrec{passw};
 my $h_sms_phone=$nrec{sms_phone};
 my $h_delta_t=$nrec{delta_t};
 my $h_guard=$nrec{function};
 if ($h_guard eq "1") {$h_guard="checked";}
 elsif (($h_guard eq "0") || ($h_guard eq "")) {$h_guard="";}
 my $bg="bg0";
 &printMana($lid,$h_email,$h_passw,$h_sms_phone,$h_delta_t,$bg,$h_guard);

 $ind=9;
  my @fields;my @fields1;my @tmp;my @tmp1;
 while (length($nrec{$dbFieldNames[$ind]}) > 0) 
 {
#P=01/2/5/0/0/1/0xFF00/10/120

  @fields=(split(/\//, $nrec{$dbFieldNames[$ind]}));
  @fields1=(split(/\//, $nrec{$dbFieldNames[$ind+1]}));
  @tmp=(split(/=/, $fields[0]));
  @tmp1=(split(/=/, $fields1[0]));
  my $h_camId=$dbFieldNames[$ind];
  my $h_camState=$fields[5];
  my $h_camType=$tmp1[1];
  my $h_channel=$tmp[1];
  @tmp= (split(/=/, $fields1[1]));
  @tmp1=(split(/=/, $fields1[2]));
  my $h_resolution=$tmp[1]."*".$tmp1[1];
  my $h_laserPorts=$fields[1]."/".$fields[2];
  my $h_laserStates=$fields[3]."/".$fields[4];
  @tmp=(split(/=/, $fields1[3]));
  @tmp1=(split(/,/, $tmp[1]));
  my $h_P0=$tmp1[0].",".$tmp1[1];
  my $h_P3=$tmp1[2].",".$tmp1[3];
  my $h_P12=$tmp1[4].",".$tmp1[5];
  my $h_P15=$tmp1[6].",".$tmp1[7];
  my $h_exitArea=$fields[6];
  my $h_doorDelay=$fields[7];
  my $h_exitDelay=$fields[8];
# M=D6T/resx=4/resy=4/imPos=345,340,170,340,345,195,170,195/door=Palasi laboratorioon,Poistui laboratoriosta,Kurkistus laboratorion ovesta
  @tmp=(split(/=/, $fields1[4]));
  @tmp1=(split(/,/, $tmp[1]));
  my $h_msgExit=$tmp1[1];
  my $h_msgEntry=$tmp1[0];
  my $h_msgExitEntry=$tmp1[2];
  my $bg;
  if(($ind/2 % 2) == 0) {$bg="bg1";} else {$bg="bg2";}
  printCam($h_camId,$h_camState,$h_camType,$h_channel,$h_resolution,$h_laserPorts,$h_laserStates,$h_P0,$h_P3,$h_P12,$h_P15,$h_exitArea,
  $h_doorDelay,$h_exitDelay,$lid,$bg,$h_msgExit,$h_msgEntry,$h_msgExitEntry);
  print "<a href=\"#\" class=\"irStyle success button\" onClick=\"delCam('$lid','$ind')\">Poista: $h_camId</a>
 </div>
</div>";

  $ind++; $ind++;
#  print "\n  </tr>";
 }
#  print "</table><br>";
  print "<a href=\"#\" class=\"irStyle success button\" onClick=\"insertCam('$lid','$ind')\">Lisää kamera</a>";
#  print"     <input class=\"bodyText\" type=\"button\" value=\"Lisää mittausyksikkö\" onclick=\"insertCam('$lid','$ind')\">";
 &printUserAdmin("userAdmin3",param("p2"));

  if ($dbName eq $arParDb)
   {
#    print("<tr><td><input class=\"bodyText\" type=\"button\" value=\"Insert record\" onclick=\"insertRecord()\"></td></tr>");
   }
# &closeFile(0,0);
# &printAdminBottom;
}

else
{
#unknown request
  print header;
&subError ("Invalid HTTP request.");
exit;
}

sub purge
{
 my $loggerId=shift;
 my (@dbFieldNames,@dbFieldValues);
 my $dbRec;
 my $recNo=0; my $recMax=0; my $eraseCnt=0;
 my $timeStamp=0;
 my %rec=getDBRec($arParDb,"loggerId",$loggerId);
 {
  $recMax=$rec{15};
 }
 if ($recMax eq "") {return;}
 my $dbTitle1=<FILE0>;
 openFile($arDataDb,"",0,0);
 while($dbRec=<FILE0>)
  {
   @dbFieldValues=(split(/\|/, $dbRec));
   if ($dbFieldValues[1] eq $loggerId) {$recNo++;}
  }
 $eraseCnt=$recNo-$recMax; if ($eraseCnt < 0) {$eraseCnt=0;}
# print("$loggerId tietueita $recNo kappaletta. Poistetaan: $eraseCnt\n");
 &closeFile(0,0);
 my $ind=0;
 while ($ind < $eraseCnt)
 {
  openFile($arDataDb,"",0,0); 
  while($dbRec=<FILE0>)
  {
   @dbFieldValues=(split(/\|/, $dbRec));
   if ($dbFieldValues[1] eq $loggerId) 
    {$timeStamp=$dbFieldValues[0]; goto out;}
  }
  out:
  &closeFile(0,0);
  if($timeStamp ne 0) {&delDBRec($arDataDb,"time",$timeStamp); $timeStamp=0;}
  $ind++;
 }
}


sub logVisitor
{
 my ($visitorIp,$visitorName,$gm,$agent,$data,$date,$datetime,$sec);
 ($date,$datetime,$sec)=getDate();
 $visitorIp=$ENV{REMOTE_ADDR};
# $visitorName=gethostbyaddr(inet_aton($visitorIp),AF_INET);
 $agent=$ENV{HTTP_USER_AGENT};
 $data="";
 foreach my $p (param())
  {
   $data=$data." ".$p."=".encode2(param($p));
  }
 &openFile("$arLog","+>>",1,1) or &subError ("Log visitor101: Log file opening error.");
 print FILE1 "\n".$datetime." ".$visitorIp." ".$visitorName.$data." ".$agent;
 &closeFile(1,1);
}

sub makeUid
{
    my $time=time();
    return $ENV{REMOTE_ADDR}.":".int(1000+rand($time));
}

sub encode
{
 my $buf=shift;
 $buf =~ s/\|/%7c/g;
 return $buf;
}

sub encode1
{
 my $buf=shift;
 $buf =~ s/\|/%7c/g;
 $buf =~ s/\n/%0a/g;
 $buf =~ s/\r/%0d/g;
 return $buf;
}

sub encode2
{
 my $buf=shift;
 $buf =~ s/\|/%7c/g;
 $buf =~ s/\n/ /g;
 $buf =~ s/\r/ /g;
 return $buf;
}

sub encode22
{
 my $buf=shift;
 $buf =~ s/\|/%7c/g;
 $buf =~ s/\n//g;
 $buf =~ s/\r//g;
 return $buf;
}
sub decode
{
 my $buf=shift;
 $buf =~ s/%7c/\|/g;
 return $buf;
}

sub isKeyRequest
{
#
# Note: Before publishing this must be updated with 
# the actual store number of the Solution Language.
#
if((param("o_no") ne "") && (param("pub") ne "") && (param("email") ne "") && (param("ip") ne ""))
  {return 1;}
 else
  {return 0;}
}

sub sendKey
{
 my $productCode = shift; my $to = shift; my $key = shift;
 $htmlSubs='\$emailSales'.$s_m."$emailSales".$s_e.
    '\$productCode'.$s_m."$productCode".$s_e.
    '\$to'.$s_m."$to".$s_e.
    '\$key'.$s_m."$key".$s_e;
 &emailOut($arEmail,"sendActivationKey",$htmlSubs);
}


sub getDBRec
{
 my $fn = shift; my $keyName = shift; my $keyValue = shift; my %result;
 my ($title,$tmp);
 if(openFile($fn,"",0,0)==0) {subError("getDBrec1: Database $fn opening error (read).");}
 $title=<FILE0>;
 $title =~ s/\s+$//;   # added 16.5.2006
 my @fields=(split(/\|/, $title));
 my $i=0;
 while(($i<@fields) && ($fields[$i] ne $keyName)) {$i++;}
 if ($fields[$i] ne $keyName) { closeFile(0,0);return "";}
 while(<FILE0>)
 {
    $tmp=(split(/\|/, $_))[$i];
    if($tmp eq $keyValue) {last;}
 }
 if($tmp ne $keyValue) { closeFile(0,0);return "";}
 my @rec=(split(/\|/, $_));
 $i=0;
 while($i<@fields)
 {
  $result{$fields[$i]}=&decode($rec[$i]);
#print("getDBRec: @fields[$i] @rec[$i]<br>");
  $i++;
 }
 closeFile(0,0);
 return %result;
}

sub putDBRec()
{
 my ($fn, $keyName, $keyValue, $hash)=@_;
 my ($i,$k,$title,$tmp,$rec);
 my $newLineCntrl=0;
 $k=$slDBBackupCount;
 if (-e $fn.".ba".$k) {unlink($fn.".ba".$k);}
 while ($k>=0)
  {
   if (-e $fn.".ba".$k) {rename($fn.".ba".$k,$fn.".ba".($k+1));}
   $k--;
  }
 rename($fn,$fn.".ba0");
 if(openFile($fn.".ba0","",0,0)==0) {subError("putDBrec0: Database $fn backup opening error.");}
 $title=<FILE0>;
 my @fields=(split(/\|/, $title));
 $k=0;
 while(($k<@fields) && ($fields[$k] ne $keyName)) {$k++;}
 if ($fields[$k] ne $keyName) { closeFile(0,0);return "";}
 if(openFile($fn,">",1,1)==0) {closeFile(0,0);subError("putDBrec1: Database $fn opening error.");}
 print FILE1 $title;
 while(<FILE0>)
 {
    $tmp=(split(/\|/,$_))[$k];
    chomp $tmp;
    if($tmp eq $keyValue) 
    {
     $i=0;$k=0; $newLineCntrl=1;
     while($k<@fields)
      {
       while((my $keyn, my $value)=each %$hash)
        {if(($keyn eq $fields[$k]) && ($keyn ne "\n"))
          {
#          print("putDBRec: $keyn $value<br>");
#           $value=&encode($value);
           $value=&encode22($value);
           print FILE1 "$value|";
           $i++;
          }
         }
        $k++;
       }
     }
     else
     {
      if($newLineCntrl==1) {print FILE1 "\n"; $newLineCntrl=0;}
      print FILE1 $_;
     }
 }
 closeFile(0,0);
 closeFile(1,1);
}

sub delDBRec()
{
 my ($fn, $keyName, $keyValue)=@_;
 my ($i,$k,$title,$tmp,$rec);
 my $newLineCntrl=0;
 $k=$slDBBackupCount;
 if (-e $fn.".ba".$k) {unlink($fn.".ba".$k);}
 while ($k>=0)
  {
   if (-e $fn.".ba".$k) {rename($fn.".ba".$k,$fn.".ba".($k+1));}
   $k--;
  }
 rename($fn,$fn.".ba0");
 if(openFile($fn.".ba0","",0,0)==0) {subError("delDBrec0: Database $fn backup opening error.");}
 $title=<FILE0>;
 my @fields=(split(/\|/, $title));
 $k=0;
 while(($k<@fields) && ($fields[$k] ne $keyName)) {$k++;}
 if ($fields[$k] ne $keyName) { closeFile(0,0);return "";}
 if(openFile($fn,">",1,1)==0) {closeFile(0,0);subError("delDBrec1: Database $fn opening error.");}
 $title =~ s/\n//g;
 print FILE1 $title;
 $newLineCntrl=1;
 while($rec=<FILE0>)
 {
    $tmp=(split(/\|/,$rec))[$k];
    $rec =~ s/\n//g;
    if($tmp ne $keyValue) {if($newLineCntrl==1) {print FILE1 "\n";} print FILE1 $rec;}
 }
 closeFile(0,0);
 closeFile(1,1);
}

sub delDBRec1()
# for slCart.db
{
 my ($fn, $keyName, $keyValue)=@_;
 my ($i,$k,$title,$tmp,$rec);
 my $newLineCntrl=0;
 $k=$slDBBackupCount;
 if (-e $fn.".ba".$k) {unlink($fn.".ba".$k);}
 while ($k>=0)
  {
   if (-e $fn.".ba".$k) {rename($fn.".ba".$k,$fn.".ba".($k+1));}
   $k--;
  }
 rename($fn,$fn.".ba0");
 if(openFile($fn.".ba0","",0,0)==0) {subError("delDBrec0: Database $fn backup opening error.");}
 $title=<FILE0>;
 my @fields=(split(/\|/, $title));
 $k=0;
 while(($k<@fields) && ($fields[$k] ne $keyName)) {$k++;}
 if ($fields[$k] ne $keyName) { closeFile(0,0);return "";}
 if(openFile($fn,">",1,1)==0) {closeFile(0,0);subError("delDBrec1: Database $fn opening error.");}
 $title =~ s/\n//g;
 print FILE1 $title; print FILE1 "\n";
 $newLineCntrl=1;
 while($rec=<FILE0>)
 {
    $tmp=(split(/\|/,$rec))[$k];
    $rec =~ s/\n//g;
    if($tmp ne $keyValue) {print FILE1 $rec; if($newLineCntrl==1) {print FILE1 "\n";}}
 }
 closeFile(0,0);
 closeFile(1,1);
}

sub dBQuery
{
 my $fn = shift; my $keyName = shift; my $keyValue = shift; my %result;
 my ($title,$tmp);
 if(openFile($fn,"",0,0)==0) {subError("dBQuery1: Database $fn opening error.");}
 $title=<FILE0>;
 my @fields=(split(/\|/, $title));
 my $i=0;
 my $k=0;
 while(($i<@fields) && ($fields[$i] ne $keyName)) {$i++;}
 if ($fields[$i] ne $keyName) { closeFile(0,0);return "";}
 while(<FILE0>)
 {
    $tmp=(split(/\|/, $_))[$i];
    if($keyValue eq "*") {$result{$k}=$_;$k++;}
    elsif($tmp eq $keyValue) {$result{$k}=$_;$k++;}
 }
 closeFile(0,0);
 return %result;
}



sub setError
{
 my $msg=shift;
 return '<font color="#FF0000">* '.$msg.'</font>';
}

sub openFile
{
 my $fn = shift; my $mode=shift; my $lock=shift; my $fcnt=shift;
 if($fcnt==0) {open(FILE0,$mode." ".$fn) or return 0;}
 elsif($fcnt==1) {open(FILE1,$mode." ".$fn) or return 0;}
 elsif($fcnt==2) {open(FILE2,$mode." ".$fn) or return 0;}
 elsif($fcnt==3) {open(FILE3,$mode." ".$fn) or return 0;}
 elsif($fcnt==4) {open(FILE4,$mode." ".$fn) or return 0;}
 if ($lock == 1) 
  {if($fcnt==0) {flock(FILE0,$lock_ex);}
   elsif ($fcnt==1) {flock(FILE1,$lock_ex);}
   elsif ($fcnt==2) {flock(FILE2,$lock_ex);}
   elsif ($fcnt==3) {flock(FILE3,$lock_ex);}
   elsif ($fcnt==4) {flock(FILE4,$lock_ex);}
  }
 return 1;
}

sub closeFile
{
 my $lock=shift; my $fcnt=shift;
 if ($lock == 1)
  {if($fcnt==0) {flock(FILE0,$lock_un);}
   elsif ($fcnt==1) {flock(FILE1,$lock_un);}
   elsif ($fcnt==2) {flock(FILE2,$lock_un);}
   elsif ($fcnt==3) {flock(FILE3,$lock_un);}
   elsif ($fcnt==4) {flock(FILE4,$lock_un);}
  }
 if($fcnt==0) {close FILE0;}
   elsif ($fcnt==1) {close FILE1;}
   elsif ($fcnt==2) {close FILE2;}
   elsif ($fcnt==3) {close FILE3;}
   elsif ($fcnt==4) {close FILE4;}
}

sub setFile
{
 my $pos=shift; my $fcnt=shift;
 if ($pos == $to_begin) 
   {
   if($fcnt==0) {seek(FILE0,0,0);}
   elsif ($fcnt==1) {seek(FILE1,0,0);}
   elsif ($fcnt==2) {seek(FILE2,0,0);}
   elsif ($fcnt==3) {seek(FILE3,0,0);}
   elsif ($fcnt==4) {seek(FILE4,0,0);}
   }
 else 
   {
   if($fcnt==0) {seek(FILE0,0,2);}
   elsif ($fcnt==1) {seek(FILE1,0,2);}
   elsif ($fcnt==2) {seek(FILE2,0,2);}
   elsif ($fcnt==3) {seek(FILE3,0,2);}
   elsif ($fcnt==4) {seek(FILE4,0,2);}
   }
}


sub subError
{
print header;
    my $msg = shift;
    print "<p class=\"bodyText\">Web server is busy or otherwise unable to serve your request.<br>Incident code: <b>$msg</b><br><br>
    Link to home page: <a href=\"http://www.solutionlanguage.com\">http://www.solutionlanguage.com</a><br><br>
    Link to contact us page: <a href=\"http://www.solutionlanguage.com/slContact.htm\">http://www.solutionlanguage.com/slContact.htm</a><br><br>
    Web server has recorded required details of your request so that we can<br>solve the problem as soon as possible.<br>
    </p>";
    exit 1;
}


sub getDate
{
    my $time=time();
    my @gmt = localtime($time);
#    my @gmt = gmtime($time);
    my $date=$gmt[3].".".($gmt[4]+1).".".($gmt[5]+1900)." ".($gmt[2]).":".$gmt[1].":".$gmt[0];
    my $simpleDate=$gmt[3].".".($gmt[4]+1).".".($gmt[5]+1900);
    return $simpleDate,$date,int(100+rand(10*$gmt[0]*$gmt[1]));
}


sub getMinutes
{
 my $date = shift;
 my $dateInDays=1*(split(/\./,$date))[0]+30*(split(/\./,$date))[1]+365*(split(/\./,$date))[2]-2000*365;
 my $dateHours=(split(/\ /,$date))[1];
 $dateHours=(split(/\:/,$dateHours))[0];
 my $dateMinutes=(split(/\:/,$dateHours))[1];
 return 60*24*$dateInDays+60*1*$dateHours+1*$dateMinutes;
}

sub printCam
{
 my $h_camId=shift; my $h_camState=shift; my $h_camType=shift; my $h_channel=shift;  my $h_resolution=shift; 
 my $h_laserPorts=shift; my $h_laserStates=shift; my $h_P0=shift; my $h_P3=shift; my $h_P12=shift; my $h_P15=shift; 
 my $h_exitArea=shift; my $h_doorDelay=shift; my $h_exitDelay=shift; my $lid=shift; my $bg=shift;
 my $h_msgExit=shift; my $h_msgEntry=shift; my $h_msgExitEntry=shift;
 $htmlSubs='\$h_camId'.$s_m."$h_camId".$s_e.
     '\$h_camState'.$s_m."$h_camState".$s_e.
     '\$h_camType'.$s_m."$h_camType".$s_e.
     '\$h_channel'.$s_m."$h_channel".$s_e.
     '\$h_resolution'.$s_m."$h_resolution".$s_e.
     '\$h_laserPorts'.$s_m."$h_laserPorts".$s_e.
     '\$h_laserStates'.$s_m."$h_laserStates".$s_e.
     '\$h_P0'.$s_m."$h_P0".$s_e.
     '\$h_P3'.$s_m."$h_P3".$s_e.
     '\$h_P12'.$s_m."$h_P12".$s_e.
     '\$h_P15'.$s_m."$h_P15".$s_e.
     '\$h_exitArea'.$s_m."$h_exitArea".$s_e.
     '\$h_doorDelay'.$s_m."$h_doorDelay".$s_e.
     '\$h_exitDelay'.$s_m."$h_exitDelay".$s_e.
     '\$bg'.$s_m."$bg".$s_e.
     '\$h_msgExit'.$s_m."$h_msgExit".$s_e.
     '\$h_msgEntry'.$s_m."$h_msgEntry".$s_e.
     '\$h_msgxExitEntry'.$s_m."$h_msgExitEntry".$s_e.
     '\$lid'.$s_m."$lid".$s_e;
     &htmlBlockOut($arHtm,"userAdmin2",$htmlSubs);
}

sub printMana
{
 my $lid=shift; my $h_email=shift; my $h_passw=shift; my $h_sms_phone=shift; my $h_delta_t=shift; my $bg=shift; my $guard=shift;
 $htmlSubs='\$lid'.$s_m."$lid".$s_e.
     '\$h_email'.$s_m."$h_email".$s_e.
     '\$h_passw'.$s_m."$h_passw".$s_e.
     '\$h_sms_phone'.$s_m."$h_sms_phone".$s_e.
     '\$h_delta_t'.$s_m."$h_delta_t".$s_e.
     '\$slCgiHome'.$s_m."$slCgiHome".$s_e.
     '\$bg'.$s_m."$bg".$s_e.
     '\$guard'.$s_m."$guard".$s_e.
     '\$id'.$s_m."$lid".$s_e;
     &htmlBlockOut($arHtm,"userAdmin1",$htmlSubs);
}


sub printAdminTop
{
 my $arPar_selected="";
 my $arData_selected="";
 my $visitors_selected="";
 my $skey="";
 if(param("skey") eq "") {($skey,,)=getDate();} else {$skey=param("skey");}
 if(param("dbName") eq "Logger parameters database") {$arPar_selected="selected";}
 elsif(param("dbName") eq "Logger data database") {$arData_selected="selected";}
 elsif(param("dbName") eq "Visitor log") {$visitors_selected="selected";}
 else {$arPar_selected="selected";}
 $htmlSubs='\$slHome'.$s_m."$slHome".$s_e.
     '\$slCgiHome'.$s_m."$slCgiHome".$s_e.
     '\$arPar_selected'.$s_m."$arPar_selected".$s_e.
     '\$arData_selected'.$s_m."$arData_selected".$s_e.
     '\$visitors_selected'.$s_m."$visitors_selected".$s_e.
     '\$skey'.$s_m."$skey".$s_e;
 &htmlBlockOut($arHtm,"admin1",$htmlSubs);
}

sub printUserAdmin
{
 my $par=shift;
 my $id=shift;
 $htmlSubs='\$slHome'.$s_m."$slHome".$s_e.
     '\$id'.$s_m."$id".$s_e.
     '\$slCgiHome'.$s_m."$slCgiHome".$s_e;
 &htmlBlockOut($arHtm,$par,$htmlSubs);
}

sub printAdminBottom
{
 $htmlSubs="";
 &htmlBlockOut($arHtm,"admin2",$htmlSubs);
}

sub printLc
{
  my $par=shift;
 $htmlSubs="";
 $htmlSubs='\$slHome'.$s_m."$slHome".$s_e.
     '\$slCgiHome'.$s_m."$slCgiHome".$s_e;
 &htmlBlockOut($arHtm,$par,$htmlSubs);
}

sub printLaunch
{
 my $par=shift;
 my $id=shift;
 $htmlSubs="";
 $htmlSubs='\$slHome'.$s_m."$slHome".$s_e.
     '\$id'.$s_m."$id".$s_e.
     '\$slCgiHome'.$s_m."$slCgiHome".$s_e;
 &htmlBlockOut($arHtm,$par,$htmlSubs);
}

sub printImages
{
 my $par=shift;
 my $id=shift;
 my $xres; my $yres; my $imPos=""; my $lineTrAB=""; my $cameraType; my $rec;
 my %dbRec=getDBRec($arParDb,"loggerId",$id);
 my $ind; my $rec; my $tmp; my $dataRec; my $imageInd=0;
 my (@dbFieldValues,@images,@imageIds,@newestImages);
 my $timeLastItem="";
 $ind=0;
 $rec=$dbRec{"$ind"."_0"};
 while (index($rec,"M=")==0)
 {
 if($ind == 0) {$cameraType=(split /\//,$rec) [0]; $cameraType=(split /=/,$cameraType) [1];}
 if($ind == 0) {$xres=(split /\//,$rec) [1]; $xres=(split /=/,$xres) [1];}
 if($ind == 0) {$yres=(split /\//,$rec) [2]; $yres=(split /=/,$yres) [1];}
 $tmp=$imPos;
 $imPos=(split /\//,$rec) [3]; $imPos=(split /=/,$imPos) [1]; 
 if($ind>0) {$imPos=$tmp.",".$imPos;}
 $ind++;  $rec=$dbRec{"$ind"."_0"};
 }

openFile($arDataDb,"",0,0);
while($dataRec=<FILE0>)
  {
   @dbFieldValues=split(/\|/, $dataRec);
   if ($dbFieldValues[1] eq $id) 
    {
     $images[$imageInd]=$dbFieldValues[2];
     if((split /=/,$images[$imageInd])[0] ne "Id") {goto exit_if;}
     my $imValue=(split /im=/,$images[$imageInd])[1];
     my $idValue=(split /,/,$images[$imageInd])[0];
     $idValue=(split /=/,$idValue)[1];
     $images[$imageInd]=$imValue;
     $imageIds[$imageInd]=$idValue;
     $newestImages[$idValue]=$images[$imageInd];
     $timeLastItem=$dbFieldValues[0];
#print "\r\n $dbFieldValues[0] $idValue  $imValue";
     $imageInd++;
    exit_if:
    }
  }
  my $size=@newestImages;
  my $animatableImages="";
  my $k=0;
  while ($k<$size)
  {
   if(length($newestImages[$k])>0) {$animatableImages=$animatableImages."$k,200,".$newestImages[$k].",";}
   $k++;
  }
my $ssecs=toSec(param("time"));
if(param("data") eq "newest") 
{
 
 if (toSec($timeLastItem) >= $ssecs) {chop($animatableImages);print "$timeLastItem=$animatableImages";exit();}
 else {print "-1";exit();}
}

$htmlSubs='\$slHome'.$s_m."$slHome".$s_e.
     '\$slCgiHome'.$s_m."$slCgiHome".$s_e.
     '\$id'.$s_m."$id".$s_e.
     '\$xres'.$s_m."$xres".$s_e.
     '\$yres'.$s_m."$yres".$s_e.
     '\$imPos'.$s_m."$imPos".$s_e.
     '\$timeLastItem'.$s_m."$timeLastItem".$s_e.
     '\$animatableImages'.$s_m."$animatableImages".$s_e;


&htmlBlockOut($arHtm,"animateTemperatures",$htmlSubs);
&closeFile(0,0);
}

sub animateImages
{
my $par=shift;
 my $id=shift;
 my $xres; my $yres; my $imPos=""; my $lineTrAB=""; my $cameraType; my $rec;
 my %dbRec=getDBRec($arParDb,"loggerId",$id);
 my $ind; my $rec; my $tmp; my $dataRec; my $imageInd=0;
 my (@dbFieldValues,@bursts,@imageIds,@tempVal,@b0,@b1,@b2,@b3,@b4,@b5,@b6,@b7);
 my @imInd=(0,0,0,0,0,0,0,0); my $timeStr="";
 my $delta_t;
 $delta_t=$dbRec{"delta_t"};
 $b0[0]=0;$b1[0]=0;$b2[0]=0;$b3[0]=0;$b4[0]=0;$b5[0]=0;$b6[0]=0;$b7[0]=0;
 $ind=0;
 $rec=$dbRec{"$ind"."_0"};
 while (index($rec,"M=")==0)
 {
 if($ind == 0) {$cameraType=(split /\//,$rec) [0]; $cameraType=(split /=/,$cameraType) [1];}
 if($ind == 0) {$xres=(split /\//,$rec) [1]; $xres=(split /=/,$xres) [1];}
 if($ind == 0) {$yres=(split /\//,$rec) [2]; $yres=(split /=/,$yres) [1];}
 $tmp=$imPos;
 $imPos=(split /\//,$rec) [3]; $imPos=(split /=/,$imPos) [1];
 if($ind>0) {$imPos=$tmp.",".$imPos;}
 $ind++;  $rec=$dbRec{"$ind"."_0"};
 }
my $systemTime = param("animationEnd");
my $lineCount=0;
openFile($arDataDb,"",0,0);

my $previousBurst=0;
while($dataRec=<FILE0>)
  {
   @dbFieldValues=split(/\|/, $dataRec);
   if ($dbFieldValues[1] eq $id)
    {
#     $timeStr=$dbFieldValues[0];
     $bursts[$imageInd]=$dbFieldValues[2];
     my $idValue=(split /,/,$bursts[$imageInd])[0];
     $idValue=(split /=/,$idValue)[1];
     if((split /=/,$bursts[$imageInd])[0] ne "image") {goto exit_if;}
     if((param("data") eq "newest") && (toSec($dbFieldValues[0]) <= toSec(param("time")))) {goto exit_if;}
     $timeStr=$dbFieldValues[0];
     my $burstTime=(split /time=/,$bursts[$imageInd])[1];
     $burstTime=(split /,/,$burstTime)[0]; 
     my $imValue=(split /burst=/,$bursts[$imageInd])[1];
     @tempVal=split(/,/,$imValue);
     if(($lineCount == 0) && ($systemTime == 0)) {$systemTime=$burstTime; $previousBurst=$burstTime; $lineCount=1;}
     my $i=0; 
     if($burstTime + @tempVal <= $systemTime) {goto exit_if;}
#     if($burstTime <= $systemTime) {goto exit_if;}
     while($i<@tempVal)
      {
       if ($idValue == 0)
        {
         $b0[$imInd[$idValue]++]=$burstTime++;
         $b0[$imInd[$idValue]++]=hex($tempVal[$i]);
        }
       elsif ($idValue == 1)
        {
         $b1[$imInd[$idValue]++]=$burstTime++;
         $b1[$imInd[$idValue]++]=hex($tempVal[$i]);
        }
       elsif ($idValue == 2)
        {
         $b2[$imInd[$idValue]++]=$burstTime++;
         $b2[$imInd[$idValue]++]=hex($tempVal[$i]);
        }
       elsif ($idValue == 3)
        {
         $b3[$imInd[$idValue]++]=$burstTime++;
         $b3[$imInd[$idValue]++]=hex($tempVal[$i]);
        }
       elsif ($idValue == 4)
        {
         $b4[$imInd[$idValue]++]=$burstTime++;
         $b4[$imInd[$idValue]++]=hex($tempVal[$i]);
        }
       $i++;
      } #while ($i<@tempVal)
    } #if ($dbFieldValues[1] eq $id)
  exit_if:
  } #while($dataRec=<FILE0>)
  out:
  my $bs0="";my $bs1="";my $bs2="";my $bs3="";
  my $bs4="";my $bs5="";my $bs6="";my $bs7="";
  my $i=0;
  $i=0; while($i<$imInd[0]) {$bs0=$bs0.$b0[$i].",".$b0[$i+1].",";$i=$i+2;}
  $i=0; while($i<$imInd[1]) {$bs1=$bs1.$b1[$i].",".$b1[$i+1].",";$i=$i+2;}
  $i=0; while($i<$imInd[2]) {$bs2=$bs2.$b2[$i].",".$b2[$i+1].",";$i=$i+2;}
  $i=0; while($i<$imInd[3]) {$bs3=$bs3.$b3[$i].",".$b3[$i+1].",";$i=$i+2;}
  $i=0; while($i<$imInd[4]) {$bs4=$bs4.$b4[$i].",".$b4[$i+1].",";$i=$i+2;}
  $i=0; while($i<$imInd[5]) {$bs5=$bs5.$b5[$i].",".$b5[$i+1].",";$i=$i+2;}
  $i=0; while($i<$imInd[6]) {$bs6=$bs6.$b6[$i].",".$b6[$i+1].",";$i=$i+2;}
  $i=0; while($i<$imInd[7]) {$bs7=$bs0.$b7[$i].",".$b7[$i+1].",";$i=$i+2;}
#      $i=0; while($i<$imInd[1]) {print "<p>$b1[$i],$b1[$i+1]</p>";$i=$i+2;}

$htmlSubs='\$slHome'.$s_m."$slHome".$s_e.
     '\$slCgiHome'.$s_m."$slCgiHome".$s_e.
     '\$id'.$s_m."$id".$s_e.
     '\$xres'.$s_m."$xres".$s_e.
     '\$yres'.$s_m."$yres".$s_e.
     '\$imPos'.$s_m."$imPos".$s_e.
     '\$systemTime'.$s_m."$systemTime".$s_e.
     '\$delta_t'.$s_m."$delta_t".$s_e.
     '\$timeStr'.$s_m."$timeStr".$s_e.     
     '\$bs0'.$s_m."$bs0".$s_e.
     '\$bs1'.$s_m."$bs1".$s_e.
     '\$bs2'.$s_m."$bs2".$s_e.
     '\$bs3'.$s_m."$bs3".$s_e.
     '\$bs4'.$s_m."$bs4".$s_e.
     '\$bs5'.$s_m."$bs5".$s_e.
     '\$bs6'.$s_m."$bs6".$s_e.
     '\$bs7'.$s_m."$bs7".$s_e;
#     '\$animatableImages'.$s_m."$animatableImages".$s_e;
 if(param("data") ne "newest")
  {&htmlBlockOut($arHtm,"playTemperatures",$htmlSubs);}
 elsif ($timeStr ne "")
  {chop($bs0);chop($bs1);chop($bs2);chop($bs3);chop($bs4);chop($bs5);chop($bs6);
   print "$timeStr;0=$bs0 1=$bs1 2=$bs2 3=$bs3 4=$bs4 5=$bs5 6=$bs6 7=$bs7";}
 else {print "-1";}
&closeFile(0,0);
}

sub printExits
{
 my $par=shift;
 my $id=shift;
 my %dbRec=getDBRec($arParDb,"loggerId",$id);
 my $ind; my $rec; my $tmp; my $dataRec; my $action;
 my (@dbFieldValues,@doors);
 $ind=0;
 $rec=$dbRec{"$ind"."_0"};
 while (index($rec,"M=")==0)
 {
  if(index($rec,"door=") > 0)
  {
   $doors[$ind]=(split /door=/,$rec)[1];
  }
  else
  {
   $doors[$ind]="";
  }
  $ind++;  $rec=$dbRec{"$ind"."_0"};
 }
$htmlSubs='\$slHome'.$s_m."$slHome".$s_e.
     '\$slCgiHome'.$s_m."$slCgiHome".$s_e.
     '\$id'.$s_m."$id".$s_e;
&htmlBlockOut($arHtm,"exit",$htmlSubs);

openFile($arDataDb,"",0,0);
while($dataRec=<FILE0>)
  {
   @dbFieldValues=split(/\|/, $dataRec);
   if ($dbFieldValues[1] eq $id) 
    {
     if(index($dbFieldValues[2],"door=") >= 0)
     {
      $tmp=(split /=/,$dbFieldValues[2])[1];
      $ind=(split /:/,$tmp)[0];
      $action=(split /:/,$tmp)[1];
      if ($action eq "Entry") {$action=(split /\,/,$doors[$ind])[0];}
      elsif ($action eq "Exit") {$action=(split /\,/,$doors[$ind])[1];}
      elsif ($action eq "Quick_Exit_Entry") {$action=(split /\,/,$doors[$ind])[2];}
      else {$action = "N/A";}
      print("<tr><td>$dbFieldValues[0]</td><td align='center'>$ind</td><td>$action</td></tr>");
     }
    }
  }
$htmlSubs='\$slHome'.$s_m."$slHome".$s_e.
     '\$slCgiHome'.$s_m."$slCgiHome".$s_e.
     '\$id'.$s_m."$id".$s_e;
&htmlBlockOut($arHtm,"exit1",$htmlSubs);
&closeFile(0,0);
}

sub printAlarms
{
 my $par=shift;
 my $id=shift;
 my %dbRec=getDBRec($arParDb,"loggerId",$id);
 my $ind; my $rec; my $tmp; my $dataRec; my $action;
 my (@dbFieldValues,@doors);
 $ind=0;
 $rec=$dbRec{"$ind"."_0"};
$htmlSubs='\$slHome'.$s_m."$slHome".$s_e.
     '\$slCgiHome'.$s_m."$slCgiHome".$s_e.
     '\$id'.$s_m."$id".$s_e;
&htmlBlockOut($arHtm,"alarm",$htmlSubs);

openFile($arDataDb,"",0,0);
while($dataRec=<FILE0>)
  {
   @dbFieldValues=split(/\|/, $dataRec);
   if ($dbFieldValues[1] eq $id) 
    {
     if(index($dbFieldValues[2],"alarm=") >= 0)
     {
      $tmp=(split /=/,$dbFieldValues[2])[1];
      $ind=(split /:/,$tmp)[0];
      $action=(split /:/,$tmp)[1];
      print("<tr><td>$dbFieldValues[0]</td><td align='center'>$ind</td><td>$action</td></tr>");
     }
    }
  }
$htmlSubs='\$slHome'.$s_m."$slHome".$s_e.
     '\$slCgiHome'.$s_m."$slCgiHome".$s_e.
     '\$id'.$s_m."$id".$s_e;
&htmlBlockOut($arHtm,"alarm1",$htmlSubs);
&closeFile(0,0);
}



sub htmlBlockOut
{
 my ($fn,$bn,$sdata)=@_; 
 my $rec=""; my $strippedRec=""; my $ind; my $b_begin="<!--BB ".$bn."-->"; my $b_end="<!--EB ".$bn."-->";
 my $subItem;
 if(openFile($fn,"",0,4)==0) {return;};
 while($ind=index($rec,$b_begin) == -1) {if(!($rec=<FILE4>)) {closeFile(0,4);return;}}
 $strippedRec=$rec;
 $/ = "\r\n"; chomp $strippedRec; # for UNIX
 $/ = "\n"; chomp $strippedRec;       # for PC, could be commented out in final release
 if(length($strippedRec)>length($b_begin)) {$rec=substr($rec,$ind+length($b_begin),length($rec));} 
 else {$rec="";}
 while (index($rec,$b_end) == -1)
 {
  foreach $subItem (split($s_e, $sdata))
  {
   my $var=(split($s_m, $subItem))[0];
   my $val=(split($s_m, $subItem))[1];
  $rec =~ s/$var/$val/g;
  }
  print "$rec";
  if(!($rec=<FILE4>)) {closeFile(0,4);return;};
 }
 $strippedRec=$rec;
 $/ = "\r\n"; chomp $strippedRec; # for UNIX
 $/ = "\n"; chomp $strippedRec;       # for PC, could be commented out in final release
 if(length($strippedRec)>length($b_end)) {$rec=substr($rec,0,length($rec)-length($b_end)-1);print "$rec";}
 closeFile(0,4);
 return;
}

sub emailOut
{
 my ($fn,$bn,$sdata)=@_; 
 my $rec=""; my $strippedRec=""; my $ind; my $b_begin="<!--BB ".$bn."-->"; my $b_end="<!--EB ".$bn."-->";
 my $subItem;
 if($noMail==1) 
   {
    htmlBlockOut($fn,$bn,$sdata);
    return;
   }
 $ENV{PATH} = '/usr/sbin';
 open(SENDMAIL,"|/usr/sbin/sendmail -t") or &subError ("Send email error 100.");
 if(openFile($fn,"",0,4)==0) {return;};
 while($ind=index($rec,$b_begin) == -1) {if(!($rec=<FILE4>)) {closeFile(0,4);return;}}
 $strippedRec=$rec;
 $/ = "\r\n"; chomp $strippedRec; # for UNIX
 $/ = "\n"; chomp $strippedRec;       # for PC, could be commented out in final release
 if(length($strippedRec)>length($b_begin)) {$rec=substr($rec,$ind+length($b_begin),length($rec));} 
 else {$rec="";}
 while (index($rec,$b_end) == -1)
 {
  foreach $subItem (split($s_e, $sdata))
  {
   my $var=(split($s_m, $subItem))[0];
   my $val=(split($s_m, $subItem))[1];
   $rec =~ s/$var/$val/g;
  }
  print SENDMAIL "$rec";
  if(!($rec=<FILE4>)) {closeFile(0,4);return;};
 }
 $strippedRec=$rec;
 $/ = "\r\n"; chomp $strippedRec; # for UNIX
 $/ = "\n"; chomp $strippedRec;       # for PC, could be commented out in final release
 if(length($strippedRec)>length($b_end)) {$rec=substr($rec,0,length($rec)-length($b_end)-1);print SENDMAIL "$rec";}
 close(SENDMAIL) or &subError ("Send email error 101.");
 closeFile(0,4);
 return;
}

    sub checkEmailAddress ($) { 
        my ($addr) = @_;
        my $atext = qr/[A-Za-z0-9\!\#\$\%\&\'\*\+\-\/\=\?\^\_\`\{\|\+\~]/;
        my $dot_atom_text = qr/$atext+(\.$atext+)*/;

        my $no_ws_ctl_char = qr/[\x01-\x08\x0b\x0c\x0e-\x1f\x7f]/;
        my $qtext_char = qr/([\x21\x23-\x5b\x5d-\x7e]|$no_ws_ctl_char)/;
        my $text = qr/[\x01-\x09\x0b\x0c\x0e-\x7f]/;
        my $qtext = qr/($qtext_char|\\$text)*/;
        my $quoted_string = qr/"$qtext"/;

        my $quotedpair = qr/\\$text/;
        my $dtext = qr/[\x21-\x5a\x5e-\x7e\x01-\x08\x0b\x0c\x0e-\x1f\x7f]/;
        my $dcontent = qr/($dtext|$quotedpair)/;        
        my $domain_literal = qr/\[(${dcontent})*\]/;

        if ( $addr =~ /^($dot_atom_text|$quoted_string)\@($dot_atom_text|$domain_literal)$/ ) { 
                return 1;
        } else {
                return 0;
        }
    }

sub splitItems
{
  my $dbRec=shift;
  my $cdate=(split(" ",$dbRec))[0];
  my $ctime=(split(" ",$dbRec))[1];
  my $cip=(split(" ",$dbRec))[2];
  my $chost=(split(" ",$dbRec))[3];
  my $cpage="";
  if (index($chost,"page=") == -1) {$cpage=(split(" ",$dbRec))[4];}
  else {$cpage=$chost; $chost="";}
  my $minutes=toMinutes($cdate,$ctime);
  return ($cdate,$ctime,$cip,$chost,$cpage,$minutes);
}

sub updateSession
{
  my $cdate=shift; my $ctime=shift; my $cip=shift; my $chost=shift;my $cpage=shift; my $addPage=shift;
  my $dbRec="";
  $addPage=(split("=",$addPage))[1];
  if($addPage eq "") {$dbRec=$cdate." ".$ctime." ".$cip." ".$chost." ".$cpage;}
  else {$dbRec=$cdate." ".$ctime." ".$cip." ".$chost." ".$cpage.",".$addPage;}
#print "<p>dbRec=$dbRec</p>";
  return $dbRec;
}

sub toMinutes
{
 my $d = shift; my $t = shift;
 my $day=(split(/\./,$d))[0];
 my $mon=(split(/\./,$d))[1];
 my $yr=(split(/\./,$d))[2];
 my $hour=(split(":",$t))[0];
 my $min=(split(":",$t))[1];
 return 518400*$yr+43200*$mon+1440*$day+60*$hour+$min;
}

sub toSec
{
#18.2.2017 20:3:51
 my $x = shift;
 my $d = (split(" ",$x))[0]; 
 my $t = (split(" ",$x))[1];
 my $day=(split(/\./,$d))[0];
 my $mon=(split(/\./,$d))[1];
 my $yr=(split(/\./,$d))[2];
 my $hour=(split(":",$t))[0];
 my $min=(split(":",$t))[1];
 my $sec=(split(":",$t))[2];
 return 60*(518400*$yr+43200*$mon+1440*$day+60*$hour+$min) + $sec;
}

sub toSeconds
{
 my $t = shift;
 my $hour=(split(":",$t))[0];
 my $min=(split(":",$t))[1];
 my $sec=(split(":",$t))[2];
 return 60*60*$hour+60*$min+$sec;
}

sub updateNav
{
 my $navTab=shift;
 my $recNo=shift;
 my $count=shift;
 my $from=shift;
 if ($recNo != 0) 
  {my $lower = $recNo-$count;
   my $upper = $recNo-1;
   if($recNo % $count ne 0)
    {
     $lower=$recNo - $recNo % $count;
     $upper=$recNo-1;
    }
   if(($lower >= $from) && ($upper < $from+$count))
    {$navTab=$navTab."<input class=\"errorText\" type=\"button\" value=\""."$lower"."-"."$upper"."\""." onclick=\"setStart($lower,$count)\"> ";}
   else
    {$navTab=$navTab."<input class=\"bodyText\" type=\"button\" value=\""."$lower"."-"."$upper"."\""." onclick=\"setStart($lower,$count)\"> ";}
   
  }
 return $navTab;
}

sub addHomeBtn
{
 my $navTab=shift;
 $navTab=$navTab."<input class=\"bodyText\" type=\"button\" value=\"Home\""." onclick=\"goHome()\"> ";
 return $navTab;
}

