use strict;

#define input file name for detault
my $infile = 'beta-BaZn2As2 (Zn-As fixed L=3.5) Band Structure.csv';

#read input file name from keyboard
print "Input file name>>";
my $line = <>;  # read from keyboard
chomp($line);   # remove linefeed characters from the input
if($line ne '') { # if some string is input, use it for the input file name
	$infile = $line;
}

# Read input file
print "Read from [$infile]\n";

open(IN, $infile) or die "Can not read [$infile].\n";

my $line;
my @data;
my $nColumns;
for(my $i = 0 ; ; $i++) {
	$line = <IN>;
	last if(eof(IN));

#print "$line\n";
	chomp($line);
	my @columns = split(',', $line);
	last if(@columns == 0);

#print "nCoulumns for #$i: ", scalar @columns, "\n";
	$nColumns = @columns;
	$data[$i] = \@columns;
}
close(IN);

my $ndata = @data;
print "nData: $ndata\n";

# Write DOS files
for(my $c = 3 ; $c < $nColumns ; $c += 2) {
	my $outfile = sprintf("dos%03d.csv", $c);
	print "Save to [$outfile]\n";
	open(OUT, ">$outfile") or die "Can not write to [$outfile].\n";
	print OUT "E,DOS $c\n";

	for(my $i = 0 ; $i < $ndata ; $i++) {
		my $p = $data[$i];
		print OUT  $p->[$c+1]   . ',' . $p->[$c] . "\n";
	}

	close(OUT);
}

# Write Band file
my $outfile = "band.csv";
print "Save to [$outfile]\n";
open(OUT, ">$outfile") or die "Can not write to [$outfile].\n";
print OUT "E,Band\n";
for(my $i = 0 ; $i < $ndata ; $i++) {
	my $p = $data[$i];

	 if($p->[1]  > 1.0e300) {
	 	print OUT "\n";
	 }
	 else {
		print OUT  $p->[0]  .  ',' . $p->[1] . "\n";
	}
}
close(OUT);

exit;

