#!/usr/bin/perl
# road_names --- Otero Co. CO
# Author: Dan Jacobson https://www.jidanni.org/
# Copyright: https://www.gnu.org/licenses/gpl.html
# Created: 2023-09-24T10:06:26+0000
# Last-Updated: 2024-01-25T18:32:55+0000
#     Update #: 51

#Otero County Colorado USA road name letters and numbers, derived from their position in the address grid.
#Yes, e.g., Baca, ..., Kit Carson County, etc. use similar systems.

use strict;
use warnings q!all!;
use PointId2Address;
my @letter;
for my $r ( 1 .. 2 ) {    #Start at 1=A, not 0.
    for ( q(A) .. q(Z) ) {
        next if /[IOQ]/;
        push @letter, $_ x $r;
    }
}
unshift @letter, undef;    #Addresses start at 1000E. A=first, no zero.
my @b = [ (1000) x 2 ];
my %g = (
    num_per_mile => @b,
    origin       => {
        address => @b,
        id      => "CO060270S0590W0_100100",    # SW corner of the county
    }
);
while (<>) {
    chomp;
    my @F = split /,/;
    $g{target} =
      { id => $F[2] };    #we wipe out the previous {target}{miles}
    my @a = PointId2Address::id2addr( \%g );
    if ( $F[2] =~ /CO060..0S0530W0_100.00/ ) {    #East edge of county
        printf "%s,%s,%d %s\n", @F[ 0, 1 ], $a[2], $letter[ $a[2] / 1000 ];
    }
    elsif ( $F[2] =~ /CO060270S0..0W0_.00100/ ) {    #South edge of county
        printf "%s,%s,%d %s\n", @F[ 0, 1 ], $a[0], $a[0] / 1000;
    }
    else {    # e.g., a diagonal string of nodes representing where X=Y,
        die "Not ready for random points not on the diagonal"
          unless $a[0] == $a[2];
        printf "%s,%s,%d %d %s\n", @F[ 0, 1 ], $a[2], $a[0] / 1000,
          $letter[ $a[2] / 1000 ];
        ## But perhaps this is not the best county to do a diagonal,
        ## due to the letter / number mixture...
    }
}
exit;
## Older code:
#Input: lines that end in 12000E, 8000N etc.
#Output: tack road name letters/ numbers on back of input.
my $numbers_per_letter = my $lowest = 1000;
while (<>) {
    if ( $. == 1 && !/\d/ ) { print; next; }    #Header
    chomp;
    m!([-\d.]+)([NWSE]+)$! or die "No address on this line: $_";
    my $s = "$_(CR " . f( $1, $2 ) . ")\n";
    print $s;                                   #to die cleanly.
}

sub f {
    my ( $number, $direction ) = @_;
    die "Must be in NE quadrant" if $direction !~ /[NE]/;
    die "$number: Lowest address in this county is $lowest"
      if $number < $lowest;
    my $st = sprintf "%.2f", $number / $numbers_per_letter;
    if ( $direction =~ /N/ ) {
        my @v = split /\./, $st;
        die "I only have [0..$#letter] road names. You wanted the $v[0]th."
          if $v[0] > $#letter;
        return $letter[ $v[0] ] . "." . $v[1];
    }
    elsif ( $direction =~ /E/ ) { return $st; }
    die "Shouldn't have got here.";
}

# Speaking of this Otero County system, A..Z, AA..ZZ, one observes
# that it is an example of a system that is only good for about one
# county, else after a hundred miles we are already are at AAAA,
# BBBB,...