#!/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.

# Shane Neph: July 7th, 2006
# Modified to provide case sensitive, lexicographical support
#  for chromosome ordering, followed by numerical coordinate
#  ordering.  Modified coordinate ordering to look at stop
#  coordinates when chromosome and first coordinate values match.

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);

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


