#!/opt/perl/bin/perl
use strict;
use GOA::Stacov;
use Carp;
use Getopt::Long;
use File::Basename;

my $progname=basename $0;

my $usage=<<"EOT";
 $progname delete sites or parameters from a stacov file.
 The output is to STDOUT or a file and is reorganized 
 by sorting the sites alphabetically, 
 The option -full will allow to write the full 
 corr. coeff. matrix adding zeros where necessary.

 Usage:
   with output to STDOUT
   $progname -i stacov_in  -site  [[sta1,sta2,...,stan]|file] [-pname VEL,...] [-full]
   
 Example :
   delete VEL parameter with output to stacov_out, and write full corr. coeff matrix.
   $progname -i stacov_in  -pname VEL -o stacov_out -full

  Multiple sites are given by using commas in between
  or supplying a filename with a list of site names.

  Parameter names can also be given separated by commas.
  Valid parameters are:
  STA : station
  VEL : velocity

EOT

my $author="Marcelo Santillan 2006-MAR-07\n";

my $file_in = '';
my $file_out = '';
my $help = '';
my $site = '';
my $pname= '';
my $full = 0;
my $xv=0;
my $args = @ARGV;

GetOptions (
         'i:s'  => \$file_in,
         'o:s'  => \$file_out,
         'xv'    => \$xv,
         'site:s'  => \$site,
         'pname:s' => \$pname,
         'full'    => \$full,
         'help'    => \$help,
) || die "ERROR in Options\n";

if ( ! $args ) { die "$usage\n$author\n" };
if (  $help ) {  print "$usage\n$author\n";exit; }



my (@sites,@pn);

if ( -e $site ) {
  @sites = read_sites( $site );
  die "No sites after reading $site\n$usage\n" if ! @sites;
}
elsif ( $site )  {
  @sites= grep { /^.{4}$/ } split(',',uc $site);
  die "No sites found in $site\n$usage\n" if ! @sites; 
}

if ( $xv ) {
 @pn=qw(AAS AAC ASS ASC JMP);
}
if ( $pname  ) {
   @pn=grep { /^(STA|VEL|AAS|AAC|ASS|ASC|JMP)$/ } split(',',uc $pname);
   die "No valid parameter name in $pname\n$usage\n" if ! @pn;
}


my $stacov=GOA::Stacov->new( file => $file_in );
# Get a list of all of the sites in the stacov file
my(@unwanted_sites) = $stacov->sites();
# Iterate over the list of sites we want and remove their names
# creating a list of sites we don't want
foreach my $wanted_site (@sites) {
    @unwanted_sites = grep {$_ ne $wanted_site} @unwanted_sites;
}
# Remove the sites we don't want
$stacov->remove( site => \@unwanted_sites, pname => \@pn , full => $full ); 

if ( $file_out ) {
  $stacov->print( file => $file_out );
}
else {
  $stacov->print;
}


#====================================================================
sub read_sites {
   my $f = shift;
   my @sites=();
   open (my $fh,"<",$f ) or croak "Couldn't open $f $!\n";
   while ( <$fh> ) {
      chomp;
      s/#.*$//;
      s/^\s+//;
      s/\s+$//;
      next unless length;
      push @sites,uc $_ if /\w{4}/;
   }
    return @sites
}

