#!/usr/bin/env perl   

#  -*- perl -*-

use strict;
use warnings FATAL => qw ( all );
use Data::Dumper;

# >>>>>>>>>>>>>>>>>> XX <<<<<<<<<<<<<<<<<<<<

my ( @entries, $file, @print, $line );

( $file ) = @ARGV;

@entries = &read_col ( $file );

&write_txt ( @entries );

# >>>>>>>>>>>>>>>>>> SUBROUTINES <<<<<<<<<<<<<<<<<<<<<<<

sub write_txt
{
    # WRITE_TXT v1.2: outputs txt file.
    # Ebbe Sloth Andersen, October 2005.

    my ( @entries ) = @_;

    # Returns nothing.

    my ( $entry,       # running through entries array
	 $TYPE,        # for translation
	 $ENTRY,
	 $residue,     # for split and join
	 @residue,
         $length,      # longest name
         @length,
         $former,
	 );

    # find length of longest name
    $former = 0;
    $length = 10;
    foreach $entry ( @entries ) {
        $length = length $entry->{'ENTRY'};
        if ( $length > $former ) {
            $former = $length;
        }
    }
    $length = $former + 2;

    # print it
    foreach $entry ( @entries ) {
	@residue = ( );
	$ENTRY = $entry->{'ENTRY'};
	if ( defined $entry->{residue} ) {
	    @residue = split ( /,/, $entry->{residue} );
	    $residue = join ( "", @residue );
	    printf "%-" . "$length" . "s ", $ENTRY;
	    print "$residue\n";
	}
    }
}

sub read_col
{
    # Ebbe Sloth Andersen, December 2004.

    # READ_COL: Reads column format into data structure with an array of hashes.
    # Reads any number of columns with any kind of data.
   
    my ( $fname ) = @_;

    # Returns an array of hashes. The key corresponds to the header.
    # The value contains body data points seperated by comma.

    my ( $line,        # input lines
	 @entries,     # the output array of hashes
	 @cols, 
	 $TYPE,        
	 @COL,         # any number of columns
	 $ENTRY, 
	 @data, 
	 $i,           # counting numbers
	 $length,
	 $counter );
    
    $counter = 0;	    
    @data = ( );
    @entries = ( );
    @COL = ( );

    if ( not open FILE, "< $fname" ) {
	die "file not found!";
    }

    while ( $line = <FILE> )
    {
	if ( $line =~ /^; \*+/ )            # finds footer
	{
	    push @entries, 
	    {
		"TYPE" => $TYPE,
		"ENTRY" => $ENTRY,
	    };

	    for ( $i=0; $i<$length; $i++ ) {
		map { $entries[$counter]->{$COL[$i]} = $data[$i] } @entries;
	    }
	    $counter = $counter + 1;
	    @data = ( );
	    @COL = ( );
	}
	elsif ( $line =~ /^;/ )            # reads header
	{
	    if ( $line =~ /^; TYPE\s+(\S+)/ ) {
		$TYPE = $1;
	    } elsif ( $line =~ /^; COL\s+\S+\s+(\S+)/ ) {
		push ( @COL, $1 );
	    } elsif ( $line =~ /^; ENTRY\s+(\S+)/ ) { 
		$ENTRY = $1;
	    }
	}
	else                               # reads body
	{
	    @cols = split(/\s+/, $line);
	    $length = scalar @cols;

	    # add sequences on an array

	    for ( $i=0; $i<$length; $i++ ) {
		$data[$i] .= "$cols[$i],";
	    }
	}   
    } 
    close FILE;
    return wantarray ? @entries : \@entries;
}
