#now we will make it read the time on its own rather than pressing enter
#time is then read rather than computed

require 5.003;
use Win32::SerialPort qw( :STAT 0.19 );
use IO::Socket;

$readport=new Win32::SerialPort("COM1")
or die "cant open read port";

$remote_host="192.168.0.104";
$remote_port=23;

$sendsocket=IO::Socket::INET->new(PeerAddr=>$remote_host,
			      PeerPort=>$remote_port,
			      Proto=>"tcp",
			      Type=>SOCK_STREAM)
    or die "cant connect to $remote_host:$remote_port : $@\n";


$sendsocket->autoflush(1);

$SCRIPT_FILENAME="output.txt";
$NEWSCRIPT_FILENAME="newscript.txt";
$URL="http://webtest.eventmatrix.com";
$EVENT_URL="http://esweb1.eventmatrix.com/index.html";  #url for 10 second ping

#$EVENT_URL="http://webtest.eventmatrix.com/jfaith/aoltv/index.html";
$FREQUENCY=10;

$START_OFFSET=0; #offset from script start time 

$PREFIX="tv"; #i.e. parent.bulkRequest(...


#------------------initialize the com port

$readport->handshake("xoff");
$flowcontrol=$readport->handshake;
@opts=$readport->handshake;

$readport->baudrate(9600);
$readport->parity("odd");
$readport->databits(8);
$readport->stopbits(1);
$readport->buffers(4096,4096);
$readport->read_interval(100);

#--------------------define message types for script.txt

%MessageTypes=();
$MessageTypes{'PollMessage'}="pollMessage";
$MessageTypes{'PollResultsMessage'}="pollResults";
$MessageTypes{'LeaderBoardMessage'}="leaderBoard";
$MessageTypes{'QuestionMessage'}="questionMessage";
$MessageTypes{'QuestionResultsMessage'}="questionResultMessage";
$MessageTypes{'AnswerMessage'}="answerMessage";
$MessageTypes{'TextMessage'}="textMessage";
$MessageTypes{'EventTriggerMessage'}="eventTriggerMessage";
$MessageTypes{'AdJuryResultsMessage'}="adJuryResultsMessage";
$MessageTypes{'DisplayAnswer'}="displayAnswer";

$MessageTypes{'IncrementPoints'}="incrementPoints";

$MessageTypes{'PollResults'}="pollResults";
$MessageTypes{'Leaderboard'}="leaderBoard";
$MessageTypes{'Answer'}="displayAnswer";
$MessageTypes{'Trivia'}="questionMessage";
$MessageTypes{'FunFact'}="textMessage";

$MessageTypes{'Sync'}="SYNC";


@ARGV[0]=$SCRIPT_FILENAME;
open(FH,">$NEWSCRIPT_FILENAME");

@IDVALS=();
@TYPEVALS=();
@TIMEVALS=();

#go through the original script
#convert to send object/script file 
#wait till start of event
#send the events as the timer goes



$linecnt=0;
while(<>) {
  $linecnt++;
  $_=substr($_,0,length($_)-1);
  local(@vals)=split(/,/,$_);
  local($time)=@vals[0];
  local($type)=@vals[1];
  local($id)=@vals[2];
  if($id eq ""||$type eq ""||$time eq "") {
     print "WARNING: Bad formed value in line $linecnt (check carriage return)\n";
  }
#create a queue of time values, type values, and id's
  push(@TIMEVALS,$time);
  push(@TYPEVALS,$type);
  push(@IDVALS,$id);


	
  print FH $entry;
  print $entry;
}
close(FH);

@TIMEVALS= reverse @TIMEVALS;
@TYPEVALS= reverse @TYPEVALS;
@IDVALS= reverse @IDVALS;




#make sure all triggers are in the queue

$done=0;

#replace this with autoread from port and dump



#print "Press Enter to begin event!\n";
#while(($done==0)&&($line=<STDIN>)) {
#  $done=1;
#}
print "Event Started...\n";
(local($hour),local($minute),local($second))=(localtime)[2,1,0];
$begin_time=$second+$minute*60+$hour*3600;

$done=0;
print "Press Ctrl-C anytime to abort\n";


#------------------ lets try reading readport and dumping its packet info 

$readport->read_interval(0);
$readport->read_const_time(10000);
$readport->is_read_interval(0xffffffff);


$InBytes=10;
$cnt=0;

my $in = $readport->read_bg(500);
my $done = 0;
my $blk;
my $err;
my $out;

$leftover="";
$oldtime=-1;
$done=0;
$tmp2=0;
$tickcount=0;
$lastvalidtime=0;

while($done==0) {
    $cnt++;
#print("1");
    #for($a=0;$a<155000;$a++) {}
    select(undef, undef, undef, .03); # sleep for 250 milliseconds
#print("2");
    $result=$readport->input;
#print("3");
    $len=length($result);
    $timechange=0;
    if($len == 10) {
          
#print("4");
#        $result=$leftover.$result; #we appended the leftovers to new data...

        $begin=index($result,chr(243));
#$begin=0;
        if($begin>=0) {$tmp=substr($result,$begin);} else {$tmp="";}
        
        while($begin>=0&&length($tmp)>=4) {
#print("5");
	   $result=substr($result,$begin);
              
   	   $n1=ord(substr($result,0,1));   
	   $n2=ord(substr($result,1,1));
	   $n3=ord(substr($result,2,1));
	   $n4=ord(substr($result,3,1));
	   $n5=ord(substr($result,4,1));
   	   $n6=ord(substr($result,5,1));   
	   $n7=ord(substr($result,6,1));
	   $n8=ord(substr($result,7,1));
	   $n9=ord(substr($result,8,1));
	   $n10=ord(substr($result,9,1));

           $seconds = ($n3 & 0x0f) + ((($n3 & 0xf0) >> 4) * 10);
           $minutes = ($n4 & 0x0f) + ((($n4 & 0xf0) >> 4) * 10);
           $hours   = ($n5 & 0x0f) + ((($n5 & 0xf0) >> 4) * 10);



           if ((($n1&0xf0) == 0xf0) && ($n1 != 0xff))
           {
	           $val=$seconds + $minutes*60 + $hours*3600;
#		   print "6";
                   $time=$val; 
                   if($oldtime!=$time) 
                   {
		      $tickcount=Win32::GetTickCount();
#since its 10 we use this value 
#if its not we use the gettickcount-lastreadoffset for a given system time 

                      $lastvalidtime=$time;
                      $timechange=1;
                      $oldtime=$time;
                      print("$hours:$minutes:$seconds\n");
                   }
           }
#print("7");
           $begin=index($result,chr(243));
           $tmp=substr($result,$begin);
           $begin=-1;
        }

        $leftover=$leftover.$result;
    } elsif ($tickcount>0&&$lastvalidtime>0) { 
       #now we do a checktickcount. subtract from the last real tickcount and offset the time
	$tickcount2=Win32::GetTickCount();
        $time=$lastvalidtime + int(($tickcount2 - $tickcount)/1000);
#        print "$lastvalidtime $tickcount2 $tickcount $time\n";
	$timechange=0;
        if($time!=$oldtime) {$timechange=1;print "NEw Artificial time $time $oldtime\n";$oldtime=$time;}
    }


#-------- now use the time
if($timechange) {
#print("8");
   if($time % $FREQUENCY ==0) {
#print("9");
        $tmp="";
	for($a=0;$a<$tmp2;$a++) {
	    $tmp=$tmp." ";
	    print "*";
        }
	$URL=$EVENT_URL."?$tmp2";
	$sendstring="<$URL>[n:Enhanced Dinner & a Movie$tmp][v:t]";
	$_=$sendstring;

	$nbytes=length($sendstring);
	$sum=0;
	for($count=0;$count<$nbytes;$count+=2) {
  	  $sum+=ord(substr($_,$count,1)) << 8;
  	  if($count!=$nbytes-1) 
	     {$sum+=ord(substr($_,$count+1,1));}
	  while($sum>=65536) {
             $sum-=65536;
             $sum+=1;
          }

        }
        $sum2=65535-$sum;
        $checksum=sprintf("\[%4X\]" ,$sum2);
	$checksum=~s/A-Z/a-z/g;
	$sendstring=$sendstring.$checksum;
#	print "A";
#	$port->write("$sendstring\r");
	print $sendsocket "$sendstring\r";
        print "Sent $sendstring\n";
        
   }
   local($ok)=0;
   while($ok==0) {
#print("B");
     $val=pop(@TIMEVALS);
     if($val<=$time) {
        $time=$val;
        $type=pop(@TYPEVALS);
        $id=pop(@IDVALS);
print("\n--> Inserting $type, id=$id, time=$hours:$minutes:$seconds\n");
	$sendstring="<$EVENT_URL>[v:1][s:bulkRequest('$MessageTypes{$type}',$id)]";
#print("C");
        if($MessageTypes{$type} eq "SYNC") {
#print("D");
 	     $sendstring="<>[gpi-changemode:$id]";
		$tmp2++; # increment the segment count used for announcement URLs
        }
	$_=$sendstring;

	$nbytes=length($sendstring);
	$sum=0;
	for($count=0;$count<$nbytes;$count+=2) {
  	  $sum+=ord(substr($_,$count,1)) << 8;
  	  if($count!=$nbytes-1) 
	     {$sum+=ord(substr($_,$count+1,1));}
	  while($sum>=65536) {
             $sum-=65536;
             $sum+=1;
          }

        }
        $sum2=65535-$sum;
        $checksum=sprintf("\[%4X\]" ,$sum2);
	$checksum=~s/A-Z/a-z/g;

#print("E");
	$sendstring=$sendstring.$checksum;
#	$port->write("$sendstring\r");
	print $sendsocket "$sendstring\r";
#print("F");
	print "\n".$sendstring."\n";

     } else {push(@TIMEVALS,$val);$ok=1;}
     if(@TIMEVALS[0] eq "") {
 	$done=1;$ok=1;
	print "ALL Done\n";
     }
   }
   
#   if($time % 1 ==0) {print " Time=".$time;}

}
#print("\n");
}


$readport->close || die "failed to close";
undef $readport;