$nfile=0;

for($i=0;$i<=20;$i++){
    for($j=0;$j<=5;$j++){
	$Q[$i][$j]=0;
    }
}

opendir(DIR,"./") or die "could not open $dir: $!";
while ($fname=readdir(DIR)){
    if ($fname =~ /.csv$/){
	print "\t$n\t$fname\n";
	open(csv_file,"<$fname") or die "open:$file  $!";
	$nfile++;
    }else{
	next;
    }

    $stu=-1;
    while(<csv_file>){
	$stu++;
	if($stu==0){
	    next;
	}
	@oneline=split(/,/,$_);
	for($j=1;$j<=20;$j++){
	    if($oneline[$j+4] eq " "){
		$oneline[$j+4]=0;
		print "$stu\t$j\n";
	    }
	    $Q[$j][$oneline[$j+4]]++;
	}
    }
    print "stduents : $stu\n";

    for($j=1;$j<=20;$j++){
	print "$j:\t$Q[$j][0]\t$Q[$j][1]\t$Q[$j][2]\t$Q[$j][3]\t$Q[$j][4]\t$Q[$j][5]\n";
    }

    close csv_file;

}

print "number of files : $nfile\n";

#========== write result =================
open(result,">result.txt") or die "open: $!";

print result "rank,";
for($i=1;$i<=19;$i++){
    print result "Q$i,";
}
print result "Q$i\n";

for($i=0;$i<=5;$i++){
    print result "$i,";
    for($j=1;$j<20;$j++){
	print result "$Q[$j][$i],";
    }
    	print result "$Q[20][$i]\n";
}


close(result);
$nfile=0;

for($i=0;$i<=20;$i++){
    for($j=0;$j<=5;$j++){
	$Q[$i][$j]=0;
    }
}

opendir(DIR,"./") or die "could not open $dir: $!";
while ($fname=readdir(DIR)){
    if ($fname =~ /.csv$/){
	print "\t$n\t$fname\n";
	open(csv_file,"<$fname") or die "open:$file  $!";
	$nfile++;
    }else{
	next;
    }

    $stu=-1;
    while(<csv_file>){
	$stu++;
	if($stu==0){
	    next;
	}
	@oneline=split(/,/,$_);
	for($j=1;$j<=20;$j++){
	    if($oneline[$j+4] eq " "){
		$oneline[$j+4]=0;
		print "$stu\t$j\n";
	    }
	    $Q[$j][$oneline[$j+4]]++;
	}
    }
    print "stduents : $stu\n";

    for($j=1;$j<=20;$j++){
	print "$j:\t$Q[$j][0]\t$Q[$j][1]\t$Q[$j][2]\t$Q[$j][3]\t$Q[$j][4]\t$Q[$j][5]\n";
    }

    close csv_file;

}

print "number of files : $nfile\n";

#========== write result =================
open(result,">result.txt") or die "open: $!";

print result "rank,";
for($i=1;$i<=19;$i++){
    print result "Q$i,";
}
print result "Q$i\n";

for($i=0;$i<=5;$i++){
    print result "$i,";
    for($j=1;$j<20;$j++){
	print result "$Q[$j][$i],";
    }
    	print result "$Q[20][$i]\n";
}


close(result);
