#No Warranty

#This program is distributed in the hope that it will be useful,
#but is provided AS IS with ABSOLUTELY NO WARRANTY;
#The entire risk as to the quality and performance
#of the program is with you. Should the program prove defective,
#you assume the cost of all necessary servicing, repair or correction.
#In no event will any of the developers, or any other party,
#be liable to anyone for damages arising out of the use or inability to use the program.

use strict;
use Device::SerialPort;
use Time::HiRes qw(usleep);
print "\n*** No Warranty\n*** \n";

print "*** This program is distributed in the hope that it will be useful,
*** but is provided AS IS with ABSOLUTELY NO WARRANTY;
*** The entire risk as to the quality and performance
*** of the program is with you. Should the program prove defective,
*** you assume the cost of all necessary servicing, repair or correction.
*** In no event will any of the developers, or any other party,
*** be liable to anyone for damages arising out of the use or inability to use the program.\n\n";

my $parameter="";
my $count=0;
my $dev="";
my $file="";

foreach  $parameter (@ARGV){
	if ($count==0){
		$dev=$parameter;
	}
	if($count==1){
		$file=$parameter;
	}
	$count++;
}

my $serial = Device::SerialPort->new("$dev");

if (!$serial){
	die ("Kann Schnittstelle nicht oeffnen: Schreibweise korrekt? (z.B. /dev/ttyUSB0)\n");
}

$serial->baudrate(115200);
$serial->databits(8);
$serial->purge_all();
$serial->rts_active(0);
$serial->dtr_active(0);
$serial->read_const_time(1000);

$count=0;#Anzahl der Zeilen bestimmen
my $datei;
open($datei, "<$file") || die "Datei wurde nicht gefunden.\n";#TomCat.flash
	while(<$datei>){
	$count++;
	}
close($datei);


open($datei, "<$file") || die "Datei wurde nicht gefunden.\n";
my $cur=0;
my $test="";
my $line="";

while(<$datei>){
	$cur=$cur+1;
	$line=$_;
	if ($line =~ /#.*/) {
		printf("Kommentar nicht uebertragen\n"); next; }
		while($line =~s/\n//){
	};

	while(1){
		$serial->write("$line");  
		print "$cur/$count: $line\n";

		if ($cur == $count){ 
			print "FERTIG!\n";
			close($datei);
			exit;
		}

		# Warten auf Rueckmeldung
		my $summe=0;
		my $buffer="";
		while (!($buffer =~ m/\+/)){
			my ($anzahl,$saw)=$serial->read(length($line)+1);
			$summe=$summe+$anzahl;	
			$buffer="$buffer$saw";
		}

		if (!($buffer=~/$line/)){
			print "  Die letzte Rueckgabe war: $buffer \n";
			sleep(1);
		} else {
			last; # Uebertragung erfolgreiceh
		}
	}
}
close($datei);

exit;
