#!/usr/bin/perl

# splitld - Split census block to CA BOE district tables per county

use lib "$ENV{SMARTVOTER_PL}";
require("countyabb.pl");

open(BOE,"gunzip -c boe_equiv.tsv.gz|sort|");
open(DIST,">district-boe.tsv");

#Format sample
#BLOCK	DISTRICTID
#060650432722072	04
#060650432722026	04

while (<BOE>) {
    $line++;
    next if (/^BLOCK/);
    next if (/^\s*$/);
    ($id,$st,$cty,$ct,$blk,$boed)=
        /^((\d\d)(\d\d\d)(\d{6})(\d{4}))\t(\d+)\s*$/;
    !$st && die("Bad line $line:$_");
    if ($cty ne $lastcty) {
        close(OUT);
        open(OUT,"|gzip -c >./boe/boed-$cty.tsv.gz");
        $lastcty = $cty;
    }
    print OUT "$ct$blk\t$boed\n";
    $ctymap{"$boed\t$cty"}++;
}

foreach $k (sort(keys(%ctymap))) {
    ($boed,$cty)=split(/\t/,$k);
    $ctyname = countyFullNameTrim(countyabb(countyfips("$st$cty")));
    if ($boed ne $lastboed) {
        $lastboed = $boed;
        printf DIST "\nCalifornia State Board of Equalization\tDistrict %2d\t$ctyname",
            $boed;
    } else {
        print DIST "; $ctyname";
    }
    $ctyboed{$ctyname} .= "$boed ";
}
print DIST "\n";
close(DIST);

foreach $cty (sort(keys(%ctyboed))) {
    print "$cty\t$ctyboed{$cty}\n";
}



