# $Id: importNOS_Util.rb 7594 2022-01-05 18:50:26Z flaterco $
# Functions for importNOS.rb:
# Stupid string and math functions.

# Utility function for building up notes and comments.
def append(ins, addthis)
  if ins.nil?
    s = ""
  elsif ins[-1] != "\n"
    s = ins + "\n"
  else
    s = ins
  end
  s + addthis
end

# Test whether a name is all-caps.
def isAllCaps(name)
  name == name.upcase
end

# Also gets rid of extra spaces, but does not detect acronyms that should
# remain all-caps.
def deAllCapsify(name)
  name.split.map(&:capitalize).join(' ')
end

# Strip off suffixes of (2) (sub) or vice-versa.  Since the queries do select
# min(name), this will ALMOST always be overkill.
def chompname(name)
  name.sub(/ \((\d|sub)\)$/, "").sub(/ \((\d|sub)\)$/, "")
end

# Preserving the old, dumb function for removing repetition after the fact
# because it is useful for validating new code.  It catches things that fall
# through the cracks.
#
# Neither this nor the new code handle the case where a state name or
# abbreviation is suffixed to the tname or hname:
#   Somewhere, Va., subregion, region, Virginia
=begin
def removeRepetition(name)
  name_out = name.dup
  clauses = name.split(",").map(&:strip)
  clauses.each {|clause|
    # Want to replace
    #   Something, Something, Blah
    # and
    #   Blah, Something, Something
    # and
    #   Blah, Something, Something, Blah
    # but not
    #   Aransas, Aransas Pass, Texas
    unless clause == "New York"
      r1 = Regexp.new(", " + clause + ", " + clause + "$")  # end
      r2 = Regexp.new("^" + clause + ", " + clause + ",")   # beginning
      r3 = Regexp.new(", " + clause + ", " + clause + ",")  # middle
      name_out.gsub!(r1, ", " + clause)
      name_out.gsub!(r2, clause + ",")
      name_out.gsub!(r3, ", " + clause + ",")
    end
  }
  name_out
end
=end

# Remove HTML tags
#  and then do
# 1.15 "Word-Wrapping Lines of Text"
# Ruby Cookbook by Leonard Richardson, Lucas Carlson
# https://www.safaribooksonline.com/library/view/ruby-cookbook/0596523696/ch01s15.html
def wrapPlain(s, width=78)
  s.gsub(/<[^>]*>/, "").gsub(/(.{1,#{width}})(\s+|\Z)/, "\\1\n")
end

# Convert latitude and longitude to 3D coordinates.
def to_xyz(lat, lng)
  zenith  = (90.0 - lat) * Math::PI/180
  azimuth = lng * Math::PI/180
  [Math::cos(azimuth) * Math::sin(zenith),
    Math::sin(azimuth) * Math::sin(zenith),
    Math::cos(zenith)]
end

# The function to minimize.
# Could use Vector::norm.
def distfn(xyz1, xyz2)
  xyz1.zip(xyz2).map{|pair| (pair[0]-pair[1])**2}.reduce(:+)
end
