#!/usr/bin/env perl

use warnings;
use strict;

my $in = shift @ARGV;
my $out = shift @ARGV;

my $col = shift @ARGV;
my $min = shift @ARGV;
my $max = shift @ARGV;
my $width = shift @ARGV;

my $low = 0;
my $high = 0;
my @bins;
my @nums;
for (my $val = $min; $val <= $max; $val += $width) {
    push @bins, $val;
    push @nums, 0;
}

open my $IN, "$in";
open my $OUT, "> $out";

my @in = <$IN>;
foreach my $line (@in) {
    $line =~ s/^\s+//;
    $line =~ s/\#.*//;
    next unless $line =~ /\S+/;
    my @line = split /\s+/, $line;
    my $val = $line[$col];
    if ($val < $bins[0] - $width) {
        $low++;
        next;
    }
    if ($val >= $bins[$#bins] + $width) {
        $high++;
        next;
    }
    for (my $i = 0; $i < scalar @bins; $i++) {
        if ($val >= $bins[$i] - $width/2 and $val < $bins[$i] + $width/2) {
            $nums[$i]++;
            last;
        }
    }
}

print $OUT "# LO $low\n";
for (my $i = 0; $i < scalar @bins; $i++) {
    print $OUT "$bins[$i] $nums[$i]\n";
}
print $OUT "# HI $high\n";
