# $Id: importNOS_Util.rb 6708 2018-01-06 23:59:51Z 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

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

# Escape for SQL
def mangle(s)
  s.gsub("'","''")
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
