#!/usr/bin/perl
# PLSS point ids to addresses, for Lake County, IL.

# Author: Dan Jacobson https://www.jidanni.org/
# Copyright: https://www.gnu.org/licenses/gpl.htm
# Created: 2023-11-20T22:22:01+0000
# Last-Updated: 2023-12-14T12:56:52+0000
#     Update #: 238
#
use strict;
use warnings q(all);
use PointId2Address;
my %grid = (
    origin => {    #SW corner of Lake Co.
        id      => "IL030430N0090E0_300100",
        address => [ -29000, 20000 ],
    },
    num_per_mile => [ (1000) x 2 ]
);
if (0) {
## Well what might the address of
    my $state_and_madison = "IL030390N0140E0_400500";
## be in this system?
    $grid{target} = { id => $state_and_madison };
    my @a = PointId2Address::id2addr( \%grid );
    print "@a\n";
    exit; #2000!! E 0 N. Did they correct for the correction lines or something?
    ## OK, they must have corrected for the E-W shift at Central St. (Evanston),
    ## But well they ignored the N-S chop there though.
}
my $warned;
while (<>) {
    chomp;
    my @F = split /,/;
    my @fn;
    if ( $F[2] =~ /0430N0..0E0_...100/ ) {    #south edge of county
        @fn = ( 0, 1 );
    } #Yes, the point at the origin qualifies for both labels, but we only give it one.
    elsif ( $F[2] =~ /...0N0090E0_300.../ ) {    #west edge of county
        @fn = ( 2, 3 );
    }
    else { next; }                                #skip
    $grid{target} = { id => $F[2] };   #we wipe out any previous {target}{miles}
    my @adr = ( PointId2Address::id2addr( \%grid ) )[@fn];
    next if $adr[1] eq "W" && $adr[0] > 29000;    #No McHenry Co.
    if ( $adr[1] eq "N" && $adr[0] > 43000 ) {
        unless ($warned) {
            warn
              "Can't deal with final stunted section at state line! Skipping.";
            $warned++;
        }
        next;
    }
    my $t = sprintf "%.3f", $adr[0];    #Hack to fix up floating point mess
    $t += 0;
    printf "%s,%s,%s%s", @F[ 0, 1 ], $t, $adr[1];
    if ( $ENV{debug} ) { print ",$F[2]"; }
    print "\n";
}
