#!/usr/local/bin/perl -w
#use File::Copy;
#use File::Basename; 

$filcrd=$ARGV[0];
$filvel=$ARGV[1];
$filnou=$ARGV[2];

open(INP,$filcrd);
<INP>;<INP>;<INP>;<INP>;<INP>;<INP>;
while (<INP>) {
    chomp;
    last unless $_;
    $sta=substr($_,5,16);
    $x  =substr($_,21,15)+0.;
    $y  =substr($_,36,15)+0.;
    $z  =substr($_,51,15)+0.;

    $r   =sqrt($x*$x+$y*$y+$z*$z);
    $q   =sqrt($x*$x+$y*$y);
    
    if ($q > 0) {
        $cosl=$x/$q;
        $sinl=$y/$q;
        $cost=$z/$r;
        $sint=$q/$r;

        $cl{$sta}=$cosl;
        $sl{$sta}=$sinl;
        $ct{$sta}=$cost;
        $st{$sta}=$sint;

        $l{$sta}=atan2($sinl,$cosl)*180./3.164;
        $b{$sta}=atan2($cost,$sint)*180./3.164;
        
#        print "$sta $r $l{$sta} $b{$sta}\n";

    }
}
close(INP);

open(INP,$filvel);
<INP>;<INP>;<INP>;<INP>;<INP>;<INP>;
while (<INP>) {
    chomp;
    last unless $_;
    $sta=substr($_,5,16);
    $x  =substr($_,21,15)+0.;
    $y  =substr($_,36,15)+0.;
    $z  =substr($_,51,15)+0.;
    
    if (defined($cl{$sta})) {
        
        $cl=$cl{$sta};
        $sl=$sl{$sta};
        $ct=$ct{$sta};
        $st=$st{$sta};
        
        $n=-$ct*$cl*$x-$ct*$sl*$y+$st*$z;
        $e=    -$sl*$x    +$cl*$y       ;
        $u= $st*$cl*$x+$st*$sl*$y+$ct*$z;

        $nitrf{$sta}=$n;
        $eitrf{$sta}=$e;

#      print "$sta $n $e $u\n";
    }
}
close(INP);


open(INP,$filnou);
<INP>;<INP>;<INP>;<INP>;<INP>;<INP>;
while (<INP>) {
    chomp;
    last unless $_;
    $sta=substr($_,5,16);
    $x  =substr($_,21,15)+0.;
    $y  =substr($_,36,15)+0.;
    $z  =substr($_,51,15)+0.;
    
    if (defined($cl{$sta})) {
        $cl=$cl{$sta};
        $sl=$sl{$sta};
        $ct=$ct{$sta};
        $st=$st{$sta};
        
        $n=-$ct*$cl*$x-$ct*$sl*$y+$st*$z;
        $e=    -$sl*$x    +$cl*$y       ;
        $u= $st*$cl*$x+$st*$sl*$y+$ct*$z;
        
        $nnuvel{$sta}=$n;
        $enuvel{$sta}=$e;
        
#        print "$sta $n $e $u\n";
    }
}
close(INP);

foreach $sta (keys %nitrf) {
    $name=$sta;
    $name=~s/ /_/g;
    print "$name  $l{$sta} $b{$sta}  $nitrf{$sta} $eitrf{$sta}  $nnuvel{$sta} $enuvel{$sta}\n";
}


__END__
