#! /usr/bin/perl 

if ($#ARGV != 0) {
    print << "EOF";
Usage: $0 headerfile < string-file > msf-file

    Converts a string type alignment file to a msf-file using a msf-file as
	header file for the output file

(c) Goetz Schwandtner 2001
EOF

    exit -1;
}

# get header and sequence names from header file 

open( HEADER, "<$ARGV[0]");

$numofseq=0;

# eat up lines until double-dash line found. then alignment starts
while (($line=<HEADER>) && ($line !~ /\/\//) ) {
    # if line containing name (consisting of \w,_ and - chars) is found,
    # store name
    if ($line =~ /Name:\s*([\w_-]+)/) {
	$names[$numofseq] = $1;
	$numofseq++;
    }
    print $line;  
}

print "//\n";

# get sequences from inputfile
for ($i=0; $line=<STDIN>; $i++) {
    chop($line);
    $align[$i] = $line;
}

die "Wrong sequence count: Header: $numofseq, Alignment: $i"
    if ($i != $numofseq);


do {
    print "\n\n";
    for ($i=0; $i < $numofseq; $i++) {
	if ($align[$i] eq "") {
	    print $names[$i]."\n";
	} else {
	    $align[$i] =~ s/^(.{1,60})//;
	    print $names[$i]."           ".$1."\n";
	}
    } 
    # check whether there are still sequences left
    $emptyseq= 0;
    for ($i=0; $i < $numofseq; $i++) { 
        if ($align[$i] eq "" ) {
	    $emptyseq++;
	}
    }
} while ($emptyseq < $numofseq);
