#!/usr/bin/perl -w
#Author: Feng Cheng
use warnings;
use strict;

my ($posA,$posB,$dirw) = ($ARGV[0],$ARGV[1],$ARGV[2]);

open(FR,$posA);
my $out1 = "$dirw/temp/a_coordfile.pre";
open(FW1,">$out1");
my $out2 = "$dirw/temp/a_coordfile";
open(FW2,">$out2");
my ($chr,$pos,$ttm);
while(defined($_=<FR>)) {
  /^([^\t]+)\t([^\t]+)\t([^\t]+\t[^\t]+)\t([^\t]+)/;
  $chr = $2;
  $pos = $3;
  $ttm = $1;
  print FW1 "$chr\t$ttm\t$pos\n"; 
}
close(FR);
close(FW1);

open(FR1,$out1);
my @input1 = map{[$_,(split(/\t/))[0],(split(/\t/))[2],(split(/\t/))[3]]} <FR1>;
my @input2 = sort{$a->[1] cmp $b->[1] || $a->[2] <=> $b->[2] || $a->[3] <=> $b->[3]} @input1;
my @sorted = map{$_->[0]} @input2;
for(@sorted) {
  print FW2 "$_";
}
close(FR1);
close(FW2);
unlink $out1;

open(FR,$posB);
$out1="$dirw/temp/b_coordfile.pre";
open(FW1,">$out1");
$out2="$dirw/temp/b_coordfile";
open(FW2,">$out2");
while(defined($_=<FR>)) {
  /^([^\t]+)\t([^\t]+)\t([^\t]+\t[^\t]+)\t([^\t]+)/;
  $chr = $2;
  $pos = $3;
  $ttm = $1;
  print FW1 "$chr\t$ttm\t$pos\n"; 
}
close(FR);
close(FW1);

open(FR1,$out1);
@input1 = map{[$_,(split(/\t/))[0],(split(/\t/))[2],(split(/\t/))[3]]} <FR1>;
@input2 = sort{$a->[1] cmp $b->[1] || $a->[2] <=> $b->[2] || $a->[3] <=> $b->[3]} @input1;
@sorted = map{$_->[0]} @input2;
for(@sorted) {
  print FW2 "$_";
}
close(FR1);
close(FW2);
unlink $out1;

#---rearrange gene file
my $in = "$dirw/temp/a_coordfile";
open(FR,$in);
my $outa = "$dirw/temp/a_gene_sorted";
open(FW,">$outa");
my @input = map{[(split(/\t/))[1],(split(/\t/))[0],(split(/\t/))[2],(split(/\t/))[3]]} <FR>;
for(@input) {
  print FW "$$_[0]\t$$_[1]\t$$_[2]\t$$_[3]";
}
close(FR);
close(FW);

$in = "$dirw/temp/b_coordfile";
open(FR,$in);
my $outb = "$dirw/temp/b_gene_sorted";
open(FW,">$outb");
@input = map{[(split(/\t/))[1],(split(/\t/))[0],(split(/\t/))[2],(split(/\t/))[3]]} <FR>;
for(@input) {
  print FW "$$_[0]\t$$_[1]\t$$_[2]\t$$_[3]";
}
close(FR);
close(FW);


