#!/usr/bin/env perl

use warnings;
use strict;

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

my $min = -0.6;
my $max = 0.4;
my $width = 0.01;

my $low = 0;
my $high = 0;
my @bins;
my @nums;
for (my $mag = $min; $mag <= $max; $mag += $width) {
    push @bins, $mag;
    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 $mag = $line[7];
    my $qf1 = $line[24];
    my $qf2 = $line[57];
    my $diff = $line[67];
    next unless defined $qf1 and $qf1 ne '""' and $qf1 > 0.9;
    next unless defined $qf2 and $qf2 ne '""' and $qf2 > 0.9;
    next unless defined $mag and $mag ne '""' and $mag > -15 and $mag < -14;
    next unless defined $diff and $diff ne '""' ;
    if ($diff < $bins[0] - $width) {
        $low++;
        next;
    }
    if ($diff >= $bins[$#bins] + $width) {
        $high++;
        next;
    }
    for (my $i = 0; $i < scalar @bins; $i++) {
        if ($diff >= $bins[$i] - $width/2 and $diff < $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";
