#!/usr/bin/perl

opendir(DIR, '.');
foreach $file (readdir(DIR)) {
    next if !($file =~ /\.old$/);
    $newfile = $file;
    $newfile =~ s/\.old//;

    open INFILE, $file or die "Error opening $file.";
    open OUTFILE, '>'.$newfile or die "Error opening $newfile.";

    while(<INFILE>) {
        chop;

	if(/^lines/) {
	    ($keyword, $lines) = split ', ', $_;
	} elsif(/^pixels/) {
	    ($keyword, $pixels) = split ', ', $_;
        } elsif(/^datatype/) {	    
	    $datatype = 2; # for single band images
            $datatype = 1 if $file =~ /^MOD09/; # 7 band images
	} elsif(/^interleaving/) {
	    ($keyword, $interleaving) = split ', ', $_;
        } elsif(/^bands/) {
	    ($keyword, $bands) = split ', ', $_; # this is likely wrong in the file
	    $bands = 1;
	    $bands = 7 if $file =~ /^MOD09/;
	} elsif(/^ulx/) {
	    ($keyword, $ulx) = split ', ', $_;           
        } elsif(/^uly/) {
	    ($keyword, $uly) = split ', ', $_;           
        } elsif(/^lrx/) {
	    ($keyword, $lrx) = split ', ', $_;           
        } elsif(/^lry/) {
	    ($keyword, $lry) = split ', ', $_;           
        } elsif(/^pwidth/) {
	    ($keyword, $pwidth) = split ', ', $_;           
        } elsif(/^pheight/) {
	    ($keyword, $pheight) = split ', ', $_;           
        } elsif(/^units/) {
	    ($keyword, $units) = split ', ', $_;           
        } elsif(/^proj/) {
	    ($keyword, $proj) = split ', ', $_;           
        } 
    }

    print "$file $bands $pixels $lines\n";

    print OUTFILE "ENVI\n";
    print OUTFILE "description = {$file}\n";
    print OUTFILE "samples = $pixels\n";
    print OUTFILE "lines = $lines\n";
    print OUTFILE "bands = $bands\n";
    print OUTFILE "data type = $datatype\n";
    print OUTFILE "header offset = 0\n";
    print OUTFILE "file type = ENVI Standard\n";
    print OUTFILE "interleave = bip\n";
    print OUTFILE "sensor type = MODIS\n";
    print OUTFILE "byte order = 0\n";
    print OUTFILE "x start = 0\n";
    print OUTFILE "y start = 0\n";
    print OUTFILE "map info = {UTM, 1.0, 1.0, $ulx, $uly, $pwidth, $pheight, 15, North, units=Meters}\n";

    close INFILE;
    close OUTFILE;
}
