#!/usr/bin/ruby
# Filename:	anyNames
# Author:	David Ljung Madison <DaveSource.com>
# See License:	http://MarginalHacks.com/License/
# Description:	Lookup names (using namespedia) to get frequency info

URL = 'http://www.namespedia.com/details/%s'

require 'open-uri'

##################################################
# Usage
##################################################
def fatal(*msg)
	msg.each { |m| $stderr.puts "[#{$0.sub(/.*\//,'')}] ERROR: #{m}" }
	exit(-1);
end

def usage(*msg)
	msg.each { |m| $stderr.puts "ERROR: #{m}" }
	$stderr.puts <<-USAGE

Usage:  #{$0.sub(/.*\//,'')} [-d] <name ...>
  Lookup name information (on namespedia)
  -d      Set debug mode

	USAGE
	exit -1;
end

def parseArgs
	opt = Hash.new
	opt[:names] = []
	loop {
		if (arg=ARGV.shift)==nil then break
		elsif arg == '-h' then usage
		elsif arg == '-?' then usage
		elsif arg == '-arg' then opt[:arg] = true
		elsif arg == '-d' then opt[:d] = true
		elsif arg =~ /^-/ then usage("Unknown arg [#{arg}]")
		else opt[:names].push(arg)
		end
	}

	usage("No names defined") if opt[:names].empty?
	
	opt
end

##################################################
# Main code
##################################################
def main
	opt = parseArgs
	
	opt[:names].each { |name|
		puts "Name: #{name}" if opt[:d]
		url = URL.gsub(/%s/,name)
		puts url if opt[:d]
		first,last = nil,nil
		begin
			open(url).each_line { |l|
				next unless l =~ /div id="content">(.+)/
				info = $1.gsub(/<\/?b>/,'')
				puts info if opt[:d]
				first = $1 if info =~ /first name was found (\d+)/i
				first = 0 if info =~ /no records about \S+ being used as firstname/i
				last = $1 if info =~ /surname \S+ is used at least (\d+)/i
				last = 0 if info =~ /no records about \S+ being used as surname/i	# Is this right?
				break if first!=nil || last!=nil
			}
		rescue OpenURI::HTTPError => e
			if e.message =~ /404/
				# Do nothing - first and last will just get 0
			else
				puts "Error fetching URL: #{e.message}"
				next
			end
		end
		#puts "No info found for #{name}" if first==nil && last==nil
		first ||= 0
		last ||= 0
		puts "#{name}  First: #{first}  Last: #{last}"
	}
end
main
