#!/usr/bin/perl -w
# FILE: sort-bed
# AUTHOR: William Stafford Noble
# CREATE DATE: 11 Jan 2005
# PROJECT: HS
# DESCRIPTION: Sort BED lines by genomic coordinates.
use strict;

# Read all lines in.
my @lines = <>;

# Print them in sorted order.
print(join('', sort by_genomic_position @lines));

# Comparison function for BED lines.
sub by_genomic_position {
  my ($a_chr, $a_start, $a_stop) = split(' ', $a);
  my ($b_chr, $b_start, $b_stop) = split(' ', $b);

  # Remove the "chr"
  $a_chr = substr($a_chr, 3);
  $b_chr = substr($b_chr, 3);

  # Deal with randoms.
  ($a_chr, my $a_random) = split("_", $a_chr);
  ($b_chr, my $b_random) = split("_", $b_chr);

  # Convert autosomes to integers.
  if ($a_chr eq "X" or $a_chr eq "x") {
    $a_chr = 23;
  } elsif ($a_chr eq "Y" or $a_chr eq "y") {
    $a_chr = 24;
  } elsif ($a_chr eq "M" or $a_chr eq "m") {
    $a_chr = 25;
  }

  if ($b_chr eq "X" or $b_chr eq "x") {
    $b_chr = 23;
  } elsif ($b_chr eq "Y" or $b_chr eq "y") {
    $b_chr = 24;
  } elsif ($b_chr eq "M" or $b_chr eq "m") {
    $b_chr = 25;
  }

  # Deal with randoms.
  if (defined($a_random)) {
    $a_chr += 26;
  }
  if (defined($b_random)) {
    $b_chr += 26;
  }


  # Sort first by chromosome and then by postion.
  if ($a_chr != $b_chr) {
    return($a_chr <=> $b_chr);
  } else {
    if ( $a_start eq $b_start ) {
        return($a_stop <=> $b_stop);
    }
    return($a_start <=> $b_start);
  }
}


