#!/usr/bin/perl

use utf8;
use open ":utf8";

$fileLab = "/var/www/cgi-bin/resv/laboratories.txt";
$fileHTML = "/var/www/html/reserve/phonelist.html";
$fileBak = "/home/webmaster/laboratories.bak";

system("cp -f $fileLab $fileBak");

$html = "<html lang=\"ja\">\n";
$html .= "<head>\n";
$html .= "<meta http-equiv=\"Content-Type\" content=\"text/html; charset=UTF-8\">\n";
$html .= "<link rel=\"stylesheet\" href=\"style.css\" type=\"text/css\">\n";
$html .= "</head>\n";
$html .= "<body>\n<h1>内線番号一覧</h1>\n<table border>\n";
$html .= "<tr><th>研究室名</th><th>省略名称</th><th>内線番号</th></tr>\n";

$oldname = "";
@tels = ();
@names = ();
@snames = ();
$i = -1;
if(open(LAB, $fileLab)){
    while(<LAB>){
	chomp($_);
	($tel, $name, $sname) = split(/\t/, $_, 3);
	if($name eq $oldname){
	    $tels[$i] .= ", $tel";
	}
	else{
	    $i++;
	    $tels[$i] = $tel;
	    $names[$i] = $name;
	    $snames[$i] = $sname;
	    $oldname = $name;
	}
    }
    close(LAB);
}
else{
    print "Cannot open $fileLab\n";
    exit(1);
}

if(open(HTML, ">$fileHTML")){
    for($j = 0; $j <= $i; $j++){
	$html .= "<tr><td>$names[$j]</td><td>$snames[$j]</td><td>$tels[$j]</td></tr>\n";
    }
    $html .= "</table>\n</body>\n</html>";
    print HTML $html;
    close(HTML);
}
else{
    print "Cannot open $fileHTML\n";
    exit(1);
}


exit(0);
