QScript Functions for Geography

From Q
Jump to navigation Jump to search
This page is currently under construction, or it refers to features which are under development and not yet available for use.
This page is under construction. Its contents are only visible to developers!
// for inDisplayr, getVariables, preventDuplicateQuestionName, correctTerminology
includeWeb("QScript Utility Functions");
includeWeb("QScript R Output Functions");  // for stringToRName 

const AVAILABLE_TYPES = {
    'USA': ['ZIP code', 'Place (city, town, etc.)', 'County', 'State', 'Region'],
    'USA and Canada': ['Place (city, town, etc.)', 'ZIP code/Postal code',
			      'State/Province', 'Region', 'Country'],
    'Canada': ['Postal code', 'Place (city, town, etc.)', 'Province', 'Region'],
    'Europe (including UK)': ['Place (city, town, etc.)', 'Postcode', 
			      'Community/District', 'Province/County', 'State/Region', 'Country code'],
    'Europe': ['Postcode', 'Place (city, town, etc.)', 'Community',
	       'Province', 'State', 'Country code'],
    'UK': ['Postcode', 'Place (city, town, etc.)', 'County',
	   'District', 'Region', 'Country'],
    'Australia and New Zealand': ['Place (city, town, etc.)', 'Postcode',
                 'Local government area (LGA)', 'State/Region'],
    'Australia': ['Postcode', 'Place (city, town, etc.)',
		  'Local government area (LGA)', 'State'],
    'New Zealand': ['Postcode', 'Place (city, town, etc.)',
		    'Local government area (LGA)', 'Region']
};

function controlInputsForGeography(variable, region, output_type) {
    let data_file = variable.question.dataFile;    
    let first_region = region.replace(/( and | \(includ).*$/,'');
    let input_type;
    let ctrl_inputs = {formVariables: variable.guid,
                       formRegion: region};
    let text = variable.uniqueValues;
    let vtype = variable.variableType;
    if (vtype !== 'Text')
    {
        let vattr = variable.valueAttributes;
        text = text.map(val => vattr.getLabel(val));
    }

    if (output_type.startsWith("Country") && IPAddressDetected(variable)) {
        createCategoricalVariableFromIPs(variable, output_type);
        return "IP";
    }

    let duplicates = [];
    if (vtype !== 'Numeric')
        duplicates = ambiguousPlaceText(text, first_region);
    if (duplicates.length > 0) {
        let prompt = 'We have detected that your data contains place names, such as ' +
            'cities and towns, is this correct?';
        let change_input_type = !askYesNo(prompt);
        if (change_input_type) {
            let input_types = AVAILABLE_TYPES[[region]];
            input_types.pop();  // can't convert largest available type to anything
            input_types = input_types.filter(input => !/^Place/.test(input));
            prompt = 'Please select the type of geographic data in your variable:';
            let selected_idx = selectOne(prompt, input_types);
            input_type = input_types[selected_idx];
        } else {
            input_type = 'Place (city, town, etc.)';
            let place = duplicates.length === 1 ? "place" : "places";
            let pronoun = duplicates.length === 1 ? "it" : "they each";
            let region_msg = (region.startsWith("U") ? "the " : "") + region;
            let  prompt = `More information is required to combine the following ${place} because ${pronoun} could refer to multiple locations in ${region_msg}: ${duplicates.slice(0,3).join(', ')}. `;
            prompt += "Select an additional variable containing " +
                'state/province/administrative region information to determine the ' +
                'proper conversion.';
            let candidate_vars = getVariables(data_file.questions);
            let extra_var = selectOneVariableByNameAndLabel(prompt,
                                                            candidate_vars, 
                                                            false);
            ctrl_inputs[['formTextExtra']] = extra_var.guid;
        }
    }else
        input_type = determineGeographicInputTypeViaR(variable, region, output_type);
    ctrl_inputs[['formInputType' + region.replace(/[ ()]/g, '')]] = input_type;
    let output_ctrl_name = 'formOutputType' + region.concat(input_type).replace(/[/(,.) ]/g,'');
    ctrl_inputs[[output_ctrl_name]] = output_type;
    return ctrl_inputs;
}

function determineGeographicInputTypeViaR(input_var, region, output_type) {
    let first_region = region.replace(/( and | \(includ).*$/,'');    
    let all_types = AVAILABLE_TYPES[[first_region]];
    let out_type_idx = all_types.findIndex(type => output_type.startsWith(type));
    let input_type = all_types[out_type_idx - 1]; // default to next smallest region
    function typeDetectionRCode(v, region, disambiguate) {
        let input_name = disambiguate ? disambiguateInputName(v) : stringToRName(v.name);
        let r_code = "x <- " + input_name +";";
        r_code += "x <- x[seq_len(min(length(x),5000))];";
        r_code += "type <- flipGeoData:::detectInputType(x,'" + first_region + "');";
        r_code += "type <- if (type == \"post.code\"){\"Postcode\"}else{";
        r_code += "sub(\"\\\\.\",\" \", sub(\"^([A-z](?:ip|ga)?)\", \"\\\\U\\\\1\", type, perl = TRUE))}";
        return r_code;
    }

    let group = inDisplayr() && project.currentPage ? project.currentPage() : project.report;
    let r_output = group.appendR(typeDetectionRCode(input_var, region, false));
    if (r_output.error !== null) {
        if (/R code is ambiguous|not found/.test(r_output.error)) {
            r_output.code = typeDetectionRCode(input_var, region, true);
            r_output.update();
            if (r_output.error === null)
                input_type = r_output.data.get([])[0];
        }
    }else
        input_type = r_output.data.get([])[0];
    r_output.deleteItem();
    if (region !== first_region)
	input_type = AVAILABLE_TYPES[[region]].find(type => type.startsWith(input_type));
    return input_type;
}

function disambiguateInputName(input) {
    return (input.type === "Question" ?
            ("`" + stringToRName(input.dataFile.name) + "`$Questions$`" +
             stringToRName(input.name) + "`") :
            ("`" + stringToRName(input.question.dataFile.name) + "`$Variables$`" +
             stringToRName(input.name) + "`"));

}

function ambiguousPlaceText(text, region) {
    let DUPLICATE_PLACE_NAMES = {'USA':["eagle river","bethel","healy","anderson","fairbanks","two rivers","haines","juneau","douglas",
"homer","hope","seward","sterling","marshall","saint marys","perryville","pilot point","palmer",
"big lake","sutton","willow","houston","saint michael","nome","wales","wainwright","buckland",
"deering","ambler","craig","sitka","pelican","eagle","cordova","valdez","whittier","petersburg",
"grayling","holy cross","mc grath","beaver","central","circle","galena","hughes","minto","ruby",
"marbury","jones","elberta","fairhope","foley","lillian","little river","montrose","robertsdale",
"seminole","stapleton","stockton","summerdale","clayton","clio","eufaula","louisville","centreville",
"green pond","woodstock","randolph","cleveland","hayden","oneonta","midway","union springs",
"chapman","greenville","mc kenzie","anniston","oxford","alexandria","bynum","jacksonville",
"piedmont","wellington","cusseta","valley","five points","lafayette","cedar bluff","leesburg",
"stanton","butler","melvin","needham","pennington","ward","dickinson","fulton","coffeeville",
"jackson","campbell","thomasville","ashland","delta","lineville","edwardsville","heflin","elba",
"enterprise","kinston","cherokee","leighton","sheffield","tuscumbia","evergreen","brooklyn","lenox",
"rockford","equality","andalusia","lockhart","river falls","wing","glenwood","luverne","rutledge",
"bremen","garden city","joppa","logan","daleville","newton","ozark","selma","plantersville",
"orrville","safford","sardis","tyler","collinsville","crossville","dawson","geraldine","mentone",
"rainsville","sylvania","valley head","elmore","kent","millbrook","tallassee","gadsden","altoona",
"walnut grove","berry","fayette","glen allen","hodges","spruce pine","vina","russellville",
"bellwood","black","chancellor","geneva","hartford","malvern","clinton","knoxville","akron",
"moundville","greensboro","newbern","sawyerville","abbeville","newville","dothan","ashford",
"columbia","cottonwood","gordon","webb","bridgeport","dutton","hollywood","langston","paint rock",
"pisgah","princeton","stevenson","trenton","woodville","bryant","flat rock","adamsville","alton",
"bessemer","brookside","clay","fairfield","gardendale","graysville","kimberly","leeds","morris",
"mount olive","new castle","pinson","pleasant grove","sayre","shannon","trafford","watson",
"birmingham","beaverton","detroit","kennedy","millport","vernon","cloverdale","florence","lexington",
"rogersville","waterloo","courtland","hillsboro","moulton","mount hope","auburn","salem","waverly",
"athens","lester","mooresville","ardmore","fort davis","brownsboro","gurley","hazel green","madison",
"new hope","new market","normal","huntsville","jefferson","linden","magnolia","thomaston",
"bear creek","brilliant","hamilton","winfield","union grove","grant","albertville","boaz","horton",
"creola","irvington","mount vernon","saint elmo","satsuma","wilmer","beatrice","franklin","megargel",
"mexia","monroeville","cecil","grady","mathews","pine level","ramer","montgomery","decatur",
"danville","eva","somerville","trinity","marion","uniontown","carrollton","banks","goshen","troy",
"graham","roanoke","wadley","woodland","fort mitchell","moody","ragland","riverside","springville",
"wattsville","ashville","steele","calera","chelsea","columbiana","helena","pelham","saginaw",
"shelby","vincent","westover","wilsonville","wilton","gainesville","livingston","panola","cuba",
"york","alpine","lincoln","sycamore","munford","camp hill","dadeville","buhl","cottondale",
"duncanville","northport","peterson","ralph","vance","dora","empire","quinton","jasper",
"carbon hill","eldridge","kansas","nauvoo","oakman","parrish","calvert","deer park","leroy",
"mc intosh","malcolm","saint stephens","sunflower","coy","alberta","arlington","camden","furman",
"oak hill","pine hill","addison","delmar","lynn","natural bridge","de witt","ethel","gillett",
"humphrey","saint charles","hamburg","portland","wilmot","gamaliel","henderson","lakeview",
"mountain home","avoca","bentonville","bella vista","garfield","gateway","gentry","lowell",
"maysville","rogers","sulphur springs","little rock","harrison","alpena","everton","lead hill",
"omaha","valley springs","hermitage","jersey","warren","hampton","thornton","berryville","oak grove",
"eudora","lake village","curtis","amity","okolona","corning","greenway","rector","saint francis",
"success","edgemont","quitman","concord","ida","kingsland","emerson","mc neil","waldo","taylor",
"jerusalem","menifee","springfield","jonesboro","egypt","lake city","alma","cedarville","chester",
"dyer","mulberry","van buren","crawfordsville","proctor","cherry valley","carthage","fordyce",
"arkansas city","dumas","pickens","monticello","winchester","conway","damascus","enola","greenbrier",
"guy","wooster","altus","branch","charleston","elizabeth","glencoe","viola","royal","lonsdale",
"grapevine","leola","prattsville","sheridan","beech grove","walcott","columbus","washington",
"bismarck","donaldson","friendship","benton","mineral springs","nashville","saratoga","batesville",
"charlotte","locust grove","newark","pleasant plains","salado","horseshoe bend","melbourne",
"mount pleasant","pineville","newport","tupelo","white hall","moscow","redfield","sherrill","tucker",
"wright","clarksville","hartman","lamar","bradley","buckner","lewisville","hoxie","minturn",
"powhatan","sedgwick","smithville","strawberry","aubrey","la grange","marianna","moro","gould",
"star city","yorktown","ogden","winthrop","blue mountain","delaware","paris","scranton","booneville",
"ratcliff","austin","cabot","carlisle","combs","kingston","saint paul","wesley","oakland","summit",
"genoa","texarkana","bassett","osceola","wilson","dell","etowah","manila","clarendon","monroe",
"norman","oden","sims","story","bluff city","emmet","prescott","rosston","willisville","compton",
"hasty","marble falls","ponca","stephens","bigelow","perry","barton","oneida","poplar grove",
"turner","wabash","kirby","langley","murfreesboro","fisher","harrisburg","cove","hatfield","atkins",
"dover","hector","london","pottsville","biscoe","des arc","hazen","ulm","alexander",
"college station","hensley","sherwood","roland","scott","sweet home","woodson","wrightsville",
"maynard","pocahontas","warm springs","caldwell","goodwin","palestine","harvey","boles","mansfield",
"parks","waldron","gilbert","leslie","saint joe","fort smith","greenwood","huntington","midland",
"ben lomond","horatio","cave city","hardy","poughkeepsie","sidney","fox","mountain view","el dorado",
"junction city","lawson","mount holly","strong","choctaw","scotland","shirley","fayetteville",
"elkins","evansville","farmington","greenland","johnson","morrow","springdale","winslow","bradford",
"el paso","garner","kensett","russell","west point","augusta","gregory","hunter","patterson",
"belleville","bluffton","briggsville","centerville","havana","ola","plainview","concho","greer",
"saint johns","chambers","fort defiance","ganado","lupton","saint michaels","sanders","rock point",
"round rock","benson","bisbee","bowie","hereford","saint david","cameron","fredonia","page",
"williams","claypool","miami","payson","pine","roosevelt","san carlos","eden","fort thomas",
"solomon","thatcher","clifton","duncan","morenci","parker","phoenix","new river","mesa","chandler",
"paradise valley","glendale","avondale","buckeye","cashion","morristown","palo verde","peoria",
"sun city","tonopah","surprise","colorado city","kingman","hackberry","golden valley","littlefield",
"valentine","heber","lakeside","pinedale","woodruff","holbrook","sun valley","indian wells","pinon",
"green valley","vail","coolidge","kearny","maricopa","picacho","red rock","stanfield","superior",
"mammoth","elgin","bagdad","clarkdale","dewey","humboldt","jerome","kirkland","mayer","seligman",
"san luis","yuma","fremont","hayward","livermore","pleasanton","dublin","union city","berkeley",
"albany","kirkwood","ione","kit carson","martell","pine grove","pioneer","plymouth","volcano",
"bangor","chico","durham","gridley","nelson","oroville","paradise","palermo","arnold","avery",
"wallace","colusa","grimes","maxwell","alamo","antioch","brentwood","byron","canyon","pleasant hill",
"crockett","oakley","pittsburg","rodeo","walnut creek","richmond","crescent city","coloma",
"garden valley","georgetown","placerville","rescue","somerset","twin bridges","huron","big creek",
"clovis","dunlap","fowler","hume","lakeshore","mendota","fresno","riverdale","sanger","elk creek",
"glenn","orland","eureka","bayside","bridgeville","ferndale","fortuna","orleans","petrolia","scotia",
"trinidad","willow creek","bard","imperial","fontana","shoshone","bishop","darwin","independence",
"little lake","delano","edison","glennville","lamont","mc farland","taft","wasco","weldon",
"bakersfield","caliente","edwards","johannesburg","keene","ridgecrest","rosamond","stratford",
"clearlake","cobb","finley","lucerne","middletown","doyle","janesville","litchfield","milford",
"standish","wendel","westwood","bell","beverly hills","downey","hawthorne","lawndale","maywood",
"venice","torrance","montebello","norwalk","artesia","avalon","bellflower","lakewood","wilmington",
"carson","long beach","arcadia","monrovia","pasadena","winnetka","chatsworth","encino","newhall",
"valencia","burbank","universal city","claremont","glendora","pomona","walnut","alhambra","acton",
"lancaster","littlerock","llano","palmdale","madera","north fork","oakhurst","raymond","san rafael",
"fairfax","inverness","larkspur","ross","coulterville","albion","boonville","elk","fort bragg",
"manchester","philo","talmage","ukiah","westport","yorkville","leggett","atwater","delhi","gustine",
"le grand","winton","canby","lookout","alturas","eagleville","carmel","gonzales","greenfield",
"king city","lockwood","monterey","seaside","castroville","oakville","rutherford","saint helena",
"soda springs","grass valley","cypress","sunset beach","irvine","lake forest","westminster","tustin",
"atwood","fullerton","garden grove","orange","villa park","loomis","newcastle","roseville","penryn",
"alta","applegate","colfax","weimar","homewood","belden","quincy","taylorsville","vinton","beaumont",
"blythe","mecca","whitewater","homeland","norco","corona","sacramento","fair oaks","folsom","galt",
"hood","mather","antelope","hollister","ontario","montclair","upland","amboy","baker","barstow",
"bloomington","bryn mawr","colton","crestline","daggett","essex","ludlow","hesperia","highland",
"patton","sugarloaf","bonita","campo","la mesa","national city","pine valley","spring valley",
"carlsbad","julian","oceanside","ramona","san marcos","santee","valley center","san diego",
"san ysidro","clements","french camp","holt","lodi","victor","woodbridge","tracy","lathrop","ripon",
"cambria","creston","harmony","san miguel","shandon","templeton","belmont","burlingame","san mateo",
"los alamos","santa maria","sunnyvale","stanford","coyote","santa clara","san jose","davenport",
"felton","freedom","mount hermon","santa cruz","redding","big bend","millville","round mountain",
"callahan","etna","greenview","grenada","montague","weed","rio vista","dixon","elmira","santa rosa",
"annapolis","forestville","sebastopol","windsor","ceres","hickman","keyes","modesto","newman",
"oakdale","salida","waterford","robbins","live oak","meridian","sutter","manton","mill creek",
"mineral","lewiston","weaverville","exeter","farmersville","ivanhoe","lindsay","porterville",
"three rivers","tipton","tulare","woodlake","badger","cutler","groveland","jamestown","moccasin",
"sonora","standard","oak park","ventura","fillmore","brooks","clarksburg","davis","rumsey","winters",
"wheatland","marysville","browns valley","brownsville","aurora","dupont","bennett","strasburg",
"watkins","denver","brighton","eastlake","hooper","byers","englewood","littleton","vilas","walsh",
"boulder","nederland","lyons","buena vista","monarch","granite","arapahoe","dumont","capulin",
"la jara","romeo","sanford","chama","crowley","sugar city","wetmore","cory","crawford","castle rock",
"franktown","lone tree","sedalia","burns","mc coy","avon","basalt","gypsum","wolcott","agate",
"elbert","kiowa","monument","cascade","fountain","ramah","rush","yoder","coaldale","hillside",
"howard","penrose","rockvale","carbondale","black hawk","central city","fraser","granby","parshall",
"winter park","almont","gunnison","ohio city","parlin","pitkin","gardner","coalmont","walden",
"arvada","golden","morrison","eads","bethune","burlington","stratton","climax","twin lakes",
"bayfield","durango","drake","glen haven","laporte","loveland","masonville","branson","weston",
"hugo","fleming","grand junction","loma","palisade","slater","cortez","lewis","pleasant view",
"cimarron","olathe","paradox","orchard","wiggins","snyder","cheraw","rocky ford","swink","ridgway",
"bailey","como","fairplay","shawnee","lake george","amherst","holyoke","paoli","meredith","granada",
"holly","wiley","beulah","boone","rye","meeker","south fork","clark","oak creek","phippsburg",
"center","villa grove","silverton","norwood","ophir","ovid","breckenridge","dillon","frisco",
"cripple creek","divide","florissant","lindon","otis","anton","cope","erie","frederick","johnstown",
"mead","severance","eaton","evans","galeton","gill","greeley","hudson","kersey","la salle","pierce",
"platteville","grover","stoneham","wray","newtown","sandy hook","shelton","trumbull","easton",
"sherman","brookfield","danbury","darien","greenwich","ridgefield","southport","stamford",
"bloomfield","bristol","canton","east berlin","berlin","north canton","plainville","rocky hill",
"enfield","unionville","west hartford","newington","marlborough","southington","canaan","colebrook",
"lakeville","new hartford","norfolk","riverton","salisbury","sharon","winsted","bethlehem",
"bridgewater","cornwall","new milford","northfield","roxbury","torrington","watertown","woodbury",
"cobalt","cromwell","deep river","east hampton","haddam","middlefield","westbrook","ansonia",
"branford","cheshire","derby","guilford","meriden","north haven","seymour","wallingford","new haven",
"hamden","bethany","waterbury","prospect","middlebury","naugatuck","lebanon","new london","baltic",
"gilman","ledyard","groton","hanover","montville","mystic","niantic","norwich","preston",
"stonington","versailles","colchester","ellington","bolton","somers","stafford","andover","coventry",
"hebron","abington","chaplin","dayville","pomfret","putnam","south windham","south woodstock",
"thompson","windham","canterbury","oneco","plainfield","harrington","kenton","marydel","smyrna",
"woodside","odessa","rockland","townsend","ellendale","frankford","laurel","millsboro","milton",
"nassau","ocean view","seaford","selbyville","archer","la crosse","newberry","olustee","sanderson",
"youngstown","titusville","orlando","rockledge","sebastian","murdock","hernando","middleburg",
"lake geneva","naples","copeland","goodland","old town","atlantic beach","gretna","jennings",
"bowling green","ona","brooksville","spring hill","lake placid","sebring","venus","brandon","durant",
"riverview","ruskin","tampa","ponce de leon","westville","roseland","wabasso","bascom","campbellton",
"graceville","grand ridge","malone","lloyd","mayo","eustis","grand island","paisley","sorrento",
"umatilla","clermont","minneola","alva","pineland","bronson","williston","sumatra","lee","palmetto",
"ellenton","candler","anthony","reddick","belleview","silver springs","summerfield","stuart",
"homestead","marathon","hilliard","milligan","laurel hill","valparaiso","maitland","ocoee",
"kenansville","saint cloud","greenacres","crystal springs","san antonio","land o lakes",
"saint petersburg","clearwater","ozona","lakeland","auburndale","babson park","bartow","dundee",
"eagle lake","fort meade","kathleen","nichols","polk city","bostwick","grandin","lake como",
"melrose","elkton","saint augustine","hastings","jay","navarre","nokomis","longwood","bushnell",
"coleman","webster","wildwood","o brien","wellborn","shady grove","edgewater","pierson","seville",
"cassadaga","orange city","crawfordville","argyle","freeport","paxton","caryville","wausau",
"saint george","pearson","hardwick","milledgeville","baldwin","cartersville","cassville","white",
"macon","hoboken","waynesville","barney","dixie","morven","pembroke","richmond hill","portal",
"girard","keysville","waynesboro","morgan","white oak","woodbine","pulaski","bowdon","mount zion",
"temple","whitesburg","ringgold","bloomingdale","savannah","menlo","summerville","holly springs",
"winterville","lovejoy","rex","forest park","fargo","homerville","marietta","acworth",
"powder springs","ambrose","harlem","adel","sparks","grantville","moreland","sargent","sharpsburg",
"turin","arabi","bainbridge","clarkston","scottdale","atlanta","chauncey","eastman","lilly",
"montezuma","pinehurst","unadilla","vienna","putney","winston","cedar springs","rincon","bowman",
"norristown","adrian","bellville","daisy","blue ridge","epworth","morganton","tyrone","lindale",
"rome","silver creek","cumming","franklin springs","roswell","fairburn","red oak","gibson",
"mitchell","brunswick","fairmount","calhoun","ranger","cairo","siloam","white plains","norcross",
"grayson","lawrenceville","loganville","duluth","buford","alto","mount airy","lula","murrayville",
"oakwood","sparta","buchanan","tallapoosa","waco","ellerslie","shiloh","bowersville","stockbridge",
"elko","commerce","nicholson","denton","hazlehurst","matthews","perkins","kite","gray","barnesville",
"dexter","dudley","allenhurst","lincolnton","lake park","naylor","dearing","thomson","crescent",
"ideal","marshallville","carlton","colbert","danielsville","hull","gay","cotton","culloden",
"forsyth","tarrytown","high shoals","cisco","crandall","covington","dallas","hiram","fort valley",
"marble hill","williamson","zebulon","aragon","dillard","lakemont","mountain city","oliver",
"iron city","griffin","martin","richland","americus","andersonville","de soto","plains","collins",
"manassas","reidsville","reynolds","rupert","milan","boston","chula","omega","vidalia","lagrange",
"ashburn","jeffersonville","blairsville","flintstone","la fayette","rossville","lookout mountain",
"good hope","manor","millwood","warrenton","jewell","oconee","sandersville","jesup","parrott",
"helen","dalton","rochelle","allentown","mc intyre","oakfield","sumner","sylvester","warwick",
"pearl city","princeville","adair","orient","carbon","dorchester","harpers ferry","lansing",
"waterville","cincinnati","moravia","plano","audubon","hamlin","belle plaine","blairstown",
"garrison","keystone","luzerne","mount auburn","norway","urbana","cedar falls","dewar",
"gilbertville","luther","madrid","tripoli","fairbank","hazleton","stanley","rowley","newell",
"truesdale","linn grove","allison","austinville","bristow","greene","parkersburg","manson","pomeroy",
"carroll","dedham","glidden","lanesboro","manning","ralston","anita","atlantic","cumberland",
"massena","marne","clarence","mechanicsville","stanwood","west branch","mason city","clear lake",
"dougherty","rock falls","rockwell","marcus","alta vista","fredericksburg","ionia","nashua",
"new hampton","north washington","murray","woodburn","spencer","dickens","fostoria","edgewood",
"farmersburg","garber","volga","mc gregor","marquette","low moor","denison","manilla","granger",
"woodward","grand river","leon","van wert","earlville","hopkinton","ryan","sperry","west burlington",
"yarmouth","spirit lake","bernard","farley","luxemburg","new vienna","worthington","armstrong",
"oran","wadena","west union","floyd","charles city","chapin","tabor","thurman","cooper","dana",
"conrad","dike","holland","stout","wellsburg","bagley","bayard","casey","jamaica","yale","ellsworth",
"randall","stanhope","britt","crystal lake","woden","alden","hubbard","new providence","union",
"gifford","mount union","wayland","riceville","elma","cresco","dakota city","rutland","battle creek",
"galva","holstein","arthur","marengo","millersburg","parnell","williamsburg","bellevue","miles",
"springbrook","monmouth","baxter","ira","kellogg","lynnville","mingo","prairie city","batavia",
"libertyville","packwood","hills","north liberty","solon","tiffin","morley","olin","wyoming",
"keswick","thornburg","harper","keota","hayesville","martinsburg","lakota","bancroft","burt",
"fenton","lone rock","whittemore","denmark","donnellson","houghton","pilot grove","center point",
"ely","hiawatha","lisbon","palo","toddville","walker","cedar rapids","grandview","lucas","alvord",
"george","inwood","macksburg","peru","truro","new sharon","beacon","cedar","oskaloosa","rose hill",
"university park","pleasantville","clemons","ferguson","haverhill","rhodes","saint anthony",
"mineola","silver city","carpenter","osage","stacyville","mapleton","rodney","whiting","moorhead",
"soldier","elliott","conesville","fruitland","montpelier","west liberty","calumet","sutherland",
"sheldon","sanborn","hartley","ashton","sibley","harris","shenandoah","blanchard","curlew",
"west bend","hinton","kingsley","merrill","remsen","westfield","fonda","havelock","laurens","plover",
"berwick","bondurant","elkhart","johnston","mitchellville","des moines","windsor heights","hancock",
"honey creek","macedonia","minden","neola","underwood","harlan","grinnell","guernsey","hartwick",
"mount ayr","early","nemaha","lake view","blue grass","buffalo","new liberty","pleasant valley",
"irwin","defiance","elk horn","panama","portsmouth","westphalia","granville","maurice","matlock",
"ames","cambridge","nevada","buckingham","dysart","elberon","toledo","vining","bedford","clearfield",
"thayer","afton","mount sterling","stockport","agency","chillicothe","eddyville","eldon","kirkville",
"indianola","lacona","liberty center","milo","ainsworth","wellman","west chester","allerton",
"corydon","millerton","fort dodge","barnum","burnside","clare","dayton","lehigh","forest city",
"lake mills","leland","castalia","fort atkinson","highlandville","ossian","ridgeway","cushing",
"lawton","salix","sloan","smithland","fertile","grafton","northwood","clarion","goldfield","star",
"council","indian valley","bern","fernwood","plummer","aberdeen","firth","pingree","carey","ketchum",
"lowman","oldtown","laclede","iona","eastport","arco","howe","moore","hill city","greenleaf",
"middleton","parma","wilder","grace","almo","burley","malta","dubois","lenore","elk river","ellis",
"island park","emmett","bliss","hagerman","wendell","elk city","ferdinand","pollock","hamer",
"roberts","hazelton","athol","genesee","harvard","may","carmen","richfield","peck","grand view",
"murphy","new plymouth","felt","donnelly","lake fork","midvale","liberty","lima","loraine","mendon",
"mc clure","miller city","olive branch","unity","smithboro","belvidere","caledonia","capron","buda",
"dalzell","malden","manlius","new bedford","brussels","hardin","chadwick","lanark","savanna",
"virginia","bondville","longview","penfield","rantoul","saint joseph","savoy","edinburg","kincaid",
"morrisonville","dennison","martinsville","clay city","flora","xenia","germantown","hoffman",
"new baden","mattoon","arlington heights","glenview","kenilworth","park ridge","wheeling","bartlett",
"franklin park","hines","broadview","evanston","berwyn","crestwood","midlothian","hometown",
"justice","posen","willow springs","worth","elmwood park","niles","cicero","robinson","greenup",
"jewett","cortland","esmond","hinckley","sandwich","dewitt","kenney","lane","arcola","camargo",
"tuscola","elmhurst","itasca","roselle","wayne","wheaton","lemont","woodridge","eola","hinsdale",
"lisle","warrenville","brocton","vermilion","west salem","effingham","altamont","mason","bingham",
"ramsey","brownstown","vandalia","saint peter","kempton","ewing","thompsonville","valier","royalton",
"ellisville","fairview","smithfield","astoria","lewistown","liverpool","norris","junction","eldred",
"hillview","kane","rockbridge","coal city","kinsman","verona","dahlgren","dale","la harpe","ferris",
"niota","warsaw","elizabethtown","gladstone","media","raritan","atkinson","geneseo","alpha",
"kewanee","woodhull","buckley","danforth","iroquois","ava","dowell","gorham","vergennes","hidalgo",
"wheeler","willow hill","dix","texico","woodlawn","medora","nora","grantsburg","simpson","hampshire",
"big rock","sugar grove","union hill","millington","oswego","galesburg","abingdon","altona","rio",
"victoria","williamsfield","barrington","deerfield","fox lake","highland park","highwood",
"ingleside","round lake","wadsworth","wauconda","ransom","cedar point","oglesby","ottawa","seneca",
"utica","saint francisville","lee center","paw paw","sublette","dwight","odell","blackstone",
"cornell","fairbury","pontiac","strawn","latham","emden","hartsburg","new holland","industry",
"macomb","sciota","cary","mchenry","ringwood","spring grove","huntley","cooksville","danvers",
"downs","le roy","mc lean","merna","towanda","blue mound","warrensburg","bunker hill","staunton",
"chesterfield","palmyra","scottville","shipman","hamel","maryville","roxana","wood river","worden",
"centralia","iuka","odin","patoka","henry","washburn","topeka","bath","kilbourne","oakford","aledo",
"new boston","alexis","new windsor","irving","lovington","sullivan","baileyville","forreston",
"holcomb","mount morris","oregon","polo","laura","brimfield","elmwood","cerro gordo","hammond",
"la place","barry","chambersburg","kinderhook","nebo","new canton","new salem","pearl","pittsfield",
"rockport","golconda","mound city","mounds","villa ridge","hennepin","menard","modoc","rockwood",
"tilden","dundas","olney","noble","rock island","hillsdale","moline","port byron","freeburg",
"new athens","o fallon","saint libory","smithton","eldorado","raleigh","mechanicsburg","pawnee",
"rochester","chatham","new berlin","williamsville","browning","rushville","herrick","sigel",
"findlay","shelbyville","castleton","dakota","lena","orangeville","morton","pekin","tremont",
"deer creek","delavan","hopedale","anna","wolf lake","east lynn","rankin","alvin","tilton","henning",
"muncie","potomac","allendale","mount carmel","little york","ashley","du bois","johnsonville","emma",
"lyndon","crete","elwood","frankfort","markham","joliet","lockport","manhattan","carterville",
"energy","hurst","durand","rockton","roscoe","winnebago","metamora","berne","preble","zanesville",
"clifford","hartsville","jonesville","boswell","zionsville","advance","morgantown","rockfield",
"galveston","logansport","new waverly","walton","young america","charlestown","henryville","memphis",
"new washington","poland","forest","leavenworth","milltown","sulphur","dillsboro","lawrenceburg",
"west harrison","greensburg","new point","corunna","garrett","spencerville","gaston","ireland",
"new paris","wakarusa","new albany","attica","brookville","cedar grove","owensville","fowlerton",
"linton","fishers","charlottesville","wilkinson","laconia","lanesville","new middletown",
"brownsburg","coatesville","north salem","pittsboro","kennard","mooreland","new lisbon","springport",
"kokomo","greentown","hemlock","andrews","remington","rensselaer","dunkirk","scipio","nineveh",
"bicknell","bruceville","decker","monroe city","syracuse","silver lake","cedar lake","crown point",
"hobart","saint john","gary","hanna","kingsbury","la porte","michigan city","union mills",
"tunnelton","ingalls","pendleton","summitville","west newton","bourbon","culver","tippecanoe",
"tyner","crane","shoals","converse","macy","mexico","clear creek","harrodsburg","darlington",
"new richmond","waveland","wingate","eminence","avilla","ligonier","rising sun","bellmore",
"bridgeton","rockville","rosedale","branchville","cannelton","leopold","portage","cynthiana",
"new harmony","greencastle","ridgeville","cross plains","holton","napoleon","osgood","pierceville",
"falmouth","milroy","new carlisle","walkerton","wyatt","south bend","scottsburg","fairland","fulda",
"lincoln city","hamlet","knox","angola","pleasant lake","bennington","patriot","west lafayette",
"battle ground","clarks hill","montmorenci","romney","westpoint","goldsmith","hobbs","sharpsville",
"cayuga","perrysville","riley","state line","west lebanon","williamsport","newburgh","tennyson",
"campbellsburg","hardinsburg","fountain city","hagerstown","petroleum","uniondale","brookston",
"idaville","churubusco","columbia city","iola","moran","colony","garnett","cummings","isabel",
"albert","great bend","garland","morrill","douglass","rosalia","chautauqua","sedan","weir",
"clay center","green","morganville","wakefield","concordia","clyde","glasco","coldwater","wilmore",
"maple city","rock","udall","frontenac","dresden","oberlin","abilene","white cloud","lawrence",
"belpre","hays","lorraine","bucklin","ford","wellsville","ulysses","virgil","fall river","kendall",
"hesston","circleville","hoyt","nortonville","valley falls","burr oak","mankato","edgerton",
"stilwell","mission","cunningham","zenda","haviland","dennis","edna","parsons","dighton","linwood",
"barnard","beverly","winona","emporia","allen","reading","windom","inman","lincolnville",
"lost springs","peabody","axtell","home","vermillion","bucyrus","louisburg","beloit","caney","tyro",
"white city","rolla","almena","norton","overbrook","vassar","delphos","minneapolis","burdett","agra",
"long island","phillipsburg","prairie view","westmoreland","coats","pratt","sawyer","herndon",
"mc donald","hutchinson","nickerson","partridge","plevna","republic","scandia","chase","bison",
"nekoma","luray","salina","new cambria","scott city","bentley","cheney","liberal","tecumseh",
"selden","kensington","gaylord","mayfield","south haven","colby","brewster","levant","rexford",
"maple hill","sharon springs","linn","benedict","piqua","toronto","kansas city","gradyville",
"scottsville","barlow","la center","wickliffe","etoile","glasgow","park city","olympia","calvin",
"ingram","parksville","foster","lost creek","custer","union star","mount washington","dunbar",
"hazel","new concord","california","bardwell","milburn","ghent","worthville","carter","willard",
"crofton","whitesville","ravenna","elizaville","banner","blue river","lackey","mc dowell",
"wheelwright","corinth","crittenden","williamstown","hickory","water valley","clarkson",
"summersville","flatwoods","south shore","cecilia","upton","white mills","bledsoe","lynch",
"hardyville","port royal","earlington","hanson","madisonville","manitou","annville","fairdale",
"staffordsville","stambaugh","raven","bush","blaine","martha","adams","louisa","saint helens",
"asher","chappell","stinnett","wendover","eolia","jenkins","letcher","millstone","crab orchard",
"kings mountain","waynesburg","ledbetter","lewisburg","paducah","berea","falcon","gunlock","loretto",
"saint mary","gilbertsville","inez","tomahawk","warfield","minerva","knob lick","mize","beech creek",
"belton","powderly","nazareth","moorefield","beaver dam","centertown","mc henry","hazard","buckhorn",
"happy","pikeville","belcher","belfry","forest hills","myra","phelps","regina","varney","brodhead",
"simpsonville","mannsville","allensville","guthrie","cadiz","sturgis","providence","corbin",
"campton","pine ridge","egan","morse","effie","dry creek","longville","saline","elm grove","gilliam",
"oil city","vivian","bell city","hayes","westlake","clarks","kelly","harrisonburg","haynesville",
"acme","gloster","stonewall","winnsboro","wisner","lydia","grand isle","elton","lake arthur",
"youngsville","holden","bastrop","collinston","oak ridge","mora","natchez","west monroe","livonia",
"morganza","oscar","echo","boyce","elmer","forest hill","tioga","woodworth","rayville","luling",
"saint james","paulina","reserve","eunice","sunset","melville","amelia","morgan city","pearl river",
"saint benedict","slidell","downsville","leesville","franklinton","cullen","tunica","dodson","joyce",
"pocasset","sagamore","hyannis","forestdale","north chatham","south dennis","wellfleet","berkshire",
"north adams","southfield","drury","rehoboth","swansea","berkley","taunton","merrimac","gloucester",
"ipswich","newbury","topsfield","west newbury","ashfield","heath","lake pleasant","rowe",
"sunderland","hampden","monson","thorndike","west springfield","hadley","haydenville","northampton",
"southampton","west chesterfield","ashby","stow","westford","everett","medford","waltham","new town",
"newtonville","bellingham","cohasset","foxboro","medway","stoughton","walpole","brookline","accord",
"greenbush","hingham","marshfield","minot","north scituate","brockton","carver","halifax","whitman",
"hyde park","revere","barre","south barre","hubbardston","lunenburg","leicester","millbury",
"north brookfield","shrewsbury","worcester","rawlings","galesville","harwood","millersville",
"severn","baltimore","boring","fork","freeland","glyndon","kingsville","monkton","parkton",
"white marsh","middle river","nottingham","port republic","goldsboro","ridgely","hampstead",
"sykesville","north east","waldorf","hughesville","indian head","la plata","newburg","welcome",
"adamstown","point of rocks","rocky ridge","tuscarora","walkersville","woodsboro","friendsville",
"grantsville","swanton","churchville","fallston","dhs","savage","jessup","chestertown","bethesda",
"beallsville","boyds","silver spring","brandywine","cheltenham","bladensburg","fort washington",
"church hill","price","stevensville","callaway","ridge","newcomb","royal oak","nanticoke",
"pittsville","quantico","bishopville","ocean city","snow hill","houlton","frenchville","limestone",
"mars hill","oxbow","perham","presque isle","sinclair","stockholm","casco","pownal","dryden",
"phillips","west farmington","gouldsboro","blue hill","surry","farmingdale","gardiner","readfield",
"belgrade","owls head","whitefield","chamberlain","brownfield","lovell","porter","east andover",
"newry","rumford","stillwater","winn","brownville","topsham","anson","hartland","saint albans",
"shawmut","belfast","burnham","sandy point","vanceboro","calais","columbia falls","machias",
"steuben","alfred","cornish","limerick","newfield","ocean park","saco","wells","buxton",
"black river","harrisville","grand marais","hopkins","pullman","alba","bellaire","lanse",
"middleville","bay city","watervliet","eau claire","new buffalo","sodus","ceresco","marcellus",
"bay shore","tower","hulbert","rudyard","trout lake","farwell","lake","elsie","frederic","channing",
"vulcan","olivet","vermontville","flushing","gaines","goodrich","otisville","flint","burton",
"ramsay","ithaca","north star","saint louis","frontier","osseo","pittsford","dodgeville","hubbell",
"kearsarge","south range","ruth","dansville","williamston","muir","saranac","hale","long lake",
"iron river","shepherd","comstock","scotts","vicksburg","rapid city","ada","sand lake",
"grand rapids","mohawk","idlewild","columbiaville","north branch","blissfield","britton",
"sand creek","howell","new baltimore","ray","bear lake","wellston","champion","walhalla",
"chippewa lake","carney","powers","spalding","stephenson","merritt","carleton","lambertville",
"carson city","crystal","edmore","fenwick","vestaburg","coral","gowen","hillman","whitehall",
"sylvan beach","clawson","madison heights","west bloomfield","leonard","white lake","ortonville",
"hart","mears","alger","trout creek","white pine","vanderbilt","conklin","spring lake","zeeland",
"brant","allenton","fair haven","saint clair","colon","sandusky","mayville","richville","willis",
"ypsilanti","dearborn","inkster","lincoln park","northville","romulus","westland","wyandotte",
"redford","mcgregor","ogema","richwood","white earth","rice","pemberton","vernon center","new ulm",
"cologne","hackensack","pine river","bena","stacy","hawley","crosby","ironton","merrifield",
"burnsville","frost","chatfield","ostrander","rushford","glenville","hollandale","welch","kenyon",
"pine island","herman","crystal bay","mound","grandy","marble","bigfork","deer river","max",
"big falls","mizpah","boyd","isabella","silver bay","oak island","hendricks","garvin","plato",
"stewart","alvarado","fairmont","grove city","little falls","lyle","racine","currie",
"new york mills","pine city","rock creek","sandstone","bruno","kerrick","mcintosh","trail",
"crookston","euclid","mentor","lowry","starbuck","vesta","olivia","angora","cook","embarrass",
"forbes","jordan","becker","gibbon","new auburn","kimball","cold spring","collegeville",
"paynesville","saint stephen","appleton","holloway","hewitt","staples","aldrich","bayport",
"cottage grove","butterfield","annandale","granite falls","wood lake","brashear","cosby","rosendale",
"westboro","benton city","eagle rock","amsterdam","drexel","gipsy","hallsville","sturgeon","de kalb",
"new bloomfield","montreal","gordonville","harrisonville","creighton","freeman","billings","spokane",
"kearney","missouri city","mosby","trimble","eugene","saint thomas","jefferson city","blackwater",
"cherryville","davisville","leasburg","gallatin","jamesport","clarksdale","stewartsville","cardwell",
"clarkton","rives","beaufort","catawissa","pacific","robertsville","rosebud","bland","strafford",
"laredo","deepwater","pottersville","bixby","blue springs","joplin","asbury","purcell","barnhart",
"cedar hill","crystal city","fletcher","knox city","novelty","baring","lynchburg","halltown",
"marionville","miller","la belle","truxton","whiteside","meadville","dawn","goodman","powell",
"callao","fredericktown","belle","hannibal","philadelphia","mercer","olean","iberia","bertrand",
"high point","holliday","santa fe","stoutsville","new florence","rocky mount","marston",
"portageville","diamond","neosho","stella","wentworth","clearmont","elmo","skidmore","myrtle",
"hayti","duke","curryville","bolivar","fair play","flemington","morrisville","polk","renick",
"henrietta","lesterville","doniphan","saint peters","blackwell","hazelwood","valley park","downing",
"queen city","chaffee","kelso","blodgett","brownwood","hurley","kirbyville","point lookout",
"rockaway beach","raymondville","roby","yukon","metz","richards","wright city","irondale",
"mineral point","potosi","mill spring","elkland","hartville","glen","benoit","bruce","pattison",
"port gibson","coahoma","farrell","jonestown","terry","west","louise","paulding","moss","lumberton",
"saltillo","brookhaven","ridgeland","algoma","pontotoc","thaxton","belen","crowder","lambert",
"mendenhall","enid","swan lake","ripley","tishomingo","redwood","stoneville","wayside",
"bellefontaine","maben","scobey","vaughan","pryor","chinook","edgar","great falls","simms","vaughn",
"big sandy","forest grove","roy","coram","sand springs","drummond","hall","philipsburg","box elder",
"kremlin","basin","hobson","wolf creek","stryker","trego","brockway","vida","ennis","virginia city",
"ringling","white sulphur springs","condon","frenchtown","brady","deer lodge","elliston","fallon",
"mildred","corvallis","darby","culbertson","poplar","ingomar","hot springs","outlook","westby",
"butte","mc leod","ethridge","stony point","fleetwood","todd","west jefferson","linville","colerain",
"arden","catawba","conover","terrell","topton","boiling springs","whiteville","maple","albertson",
"davidson","gates","gatesville","sunbury","whitsett","kipling","dunn","erwin","hendersonville",
"middlesex","comfort","broadway","vale","old fort","highlands","otto","jamesville","oak city",
"cornelius","bakersville","candor","mount gilead","henrico","richlands","hillsborough","chapel hill",
"alliance","lowland","rocky point","farmville","saluda","tryon","franklinville","sophia",
"proctorville","rowland","ruffin","faith","gold hill","ellenboro","turkey","king","sandy ridge",
"ararat","almond","wise","creswell","boomer","thurmond","black creek","valley city","tokio",
"willow city","lansford","powers lake","driscoll","amenia","ayr","tower city","dodge","braddock",
"hague","glenfield","manvel","niagara","cooperstown","tuttle","cartwright","turtle lake","drayton",
"mountain","rugby","wolford","penn","christine","medina","epping","brainard","cedar creek","cody",
"kilgore","lodgepole","potter","howells","schuyler","broken bow","oconto","westerville","whitney",
"overton","big springs","north bend","elkhorn","strang","oshkosh","endicott","wilcox","brule",
"lemoyne","mills","sprague","hershey","lorton","venango","mclean","bartley","falls city","prague",
"lyman","bee","deshler","halsey","thurston","elyria","blair","bradshaw","gresham","gilmanton",
"marlow","stoddard","groveton","chichester","franconia","piermont","pike","hollis","warner","bow",
"loudon","derry","londonderry","north hampton","seabrook","grantham","guild","buena","dorothy",
"landisville","fort lee","lyndhurst","ridgewood","glen rock","bogota","haworth","montvale",
"wrightstown","somerdale","rio grande","tuckahoe","whitesboro","delmont","maplewood","mantua",
"pitman","malaga","rosemont","high bridge","quakertown","whitehouse","hopewell","freehold","keyport",
"long branch","marlboro","allenwood","long valley","wharton","gillette","beach haven","bayville",
"beachwood","haskell","newfoundland","west milford","paterson","bedminster","manville","ogdensburg",
"sussex","layton","garwood","johnsonburg","quemado","springer","hatch","mesquite","loving","newkirk",
"tatum","hondo","white rock","deming","zuni","kenna","pep","blanco","pecos","las vegas","la joya",
"grenville","spring creek","montello","beatty","nixon","reno","glenmont","richburg","scio",
"johnson city","perrysburg","yorkshire","allegany","east randolph","cherry creek","clymer","erin",
"champlain","new lebanon","harford","bloomville","glenham","holmes","tivoli","bowmansville","depew",
"farnham","sardinia","burke","round top","tannersville","old forge","antwerp","theresa",
"beaver falls","nunda","hunt","cazenovia","brockport","east rochester","mumford","port washington",
"hempstead","roslyn","bethpage","jericho","levittown","hicksville","barker","middleport","newfane",
"barneveld","clayville","oriskany","blooming grove","harriman","washingtonville","westtown",
"lyndonville","mallory","orwell","east springfield","sunnyside","orangeburg","palisades",
"north lawrence","brier hill","newton falls","potsdam","star lake","saratoga springs","fultonham",
"gilboa","perkinsville","centerport","port jefferson","shoreham","calverton","manorville",
"bloomingburg","hortonville","rock hill","richford","glenford","spring glen","modena","stony creek",
"red creek","rose","walworth","south salem","blue creek","beaverdam","dorset","pierpont",
"nelsonville","the plains","neffs","cable","christiansburg","south charleston","gettysburg",
"galloway","parkman","coalton","chesapeake","summit station","gratiot","reedsville","celina",
"west milton","clarington","oak harbor","port clinton","stockdale","pandora","jackson center",
"new philadelphia","sandyville","springboro","doylestown","blakeslee","bryan","rudolph","atoka",
"hitchcock","caddo","kemp","carnegie","chattanooga","geronimo","randlett","oilton","shamrock",
"weatherford","custer city","thomas","colcord","oaks","arnett","wynnewood","nash","loyal",
"wilburton","muse","boynton","edmond","harrah","canadian","alderson","maud","cheyenne","sweetwater",
"gore","gans","comanche","texhoma","brightwood","sandy","rainier","post","brookings","bend",
"redmond","sutherlin","wilbur","long creek","bonanza","gilchrist","deadwood","fall creek","crabtree",
"troutdale","la grande","joseph","mcminnville","turtle creek","wood","douglassville","springtown",
"point pleasant","silverdale","croydon","cresson","driftwood","thorndale","spring city","troutville",
"olanta","townville","new cumberland","north springfield","masontown","everson","endeavor",
"huntingdon","josephine","big run","corsica","reynoldsville","honey grove","jermyn","christiana",
"ephrata","martindale","mountville","hillsville","lawn","cyclone","telford","minersville",
"valley view","mcadoo","dimock","white deer","clintonville","prosperity","woonsocket","carolina",
"aiken","graniteville","blacksburg","cottageville","liberty hill","west columbia","north",
"white stone","clover","dante","irene","watauga","buffalo gap","ridgeview","castlewood","estelline",
"emery","reva","harrold","draper","nemo","whitewood","reliance","union center","trent","wall",
"meadow","rosholt","kyle","manderson","java","jacksboro","speedwell","tazewell","del rio","bells",
"fruitvale","birchwood","reagan","mascot","southside","gordonsville","gleason","arrington","chilton",
"marlin","hico","kingwood","munday","kerens","burkeville","deweyville","mineral wells","onalaska",
"emory","milam","keller","diana","midkiff","van","glen flora","kermit","hawkins","corinne",
"green river","ephraim","hurricane","craigsville","ladysmith","woodford","red house","haywood",
"seaview","barboursville","green bay","bluefield","pound","thorp","chattaroy","saxon","rock springs",
"smoot","cora"],
'Canada':["bon accord","st brides","chipman","mclaughlin","jasper","trout lake","fairview","st isidore",
"garden river","tilley","rowley","stirling","glenwood","bellevue","coleman","linden","lethbridge",
"eagle lake","cochrane","springbrook","halfmoon bay","beaumont","island lake","lloydminster","field",
"creston","windermere","erickson","galloway","kitchener","charlie lake","altona","blind bay",
"clearwater","burton","fauquier","greenwood","midway","hazelton","ware","greenville","clinton",
"cumberland","hope","princeton","rosedale","kimberley","vernon","coldstream","maple ridge","delta",
"white rock","richmond","thornhill","sidney","victoria","ladysmith","ridgeville","churchill",
"woodlands","inwood","balmoral","warren","oak point","garson","notre dame de lourdes","austin",
"amaranth","oakville","woodside","sandy lake","arden","russell","bethany","eden","franklin",
"belmont","cartwright","minto","souris","killarney","douglas","elgin","roblin","st andrews",
"selkirk","springfield","cartier","grande pointe","mitchell","dundas","saint-philippe",
"stoney creek","whitney","williamstown","saint-irenee","sainte-rose","clifton","black rock",
"big river","sheffield","mount hope","campbellton","glencoe","scotchtown","flowers cove","wickham",
"long creek","londonderry","springdale","waterford","hillsdale","newtown","alma","weldon",
"baltimore","hebron","west river","waterside","middleton","dorchester","rockport","upper sackville",
"middle sackville","cookville","baie verte","bayfield","port elgin","melrose","portage",
"saint-maurice","saint-norbert","harcourt","bass river","saint-paul","saint-damien","saint-louis",
"havelock","forest glen","bayside","utopia","bethel","breadalbane","hampstead","lakeside","hampton",
"kingston","long point","salt springs","berwick","salmon river","summerville","kars","shannon",
"richardson","cardigan","williamsburg","maple grove","red rock","millville","southampton",
"lake george","keswick","scotch lake","bear island","clair","saint-jacques","saint-basile",
"saint-leonard","everett","enterprise","oxbow","beaconsfield","kincardine","bath","avondale",
"centreville","charleston","lansdowne","greenfield","mount pleasant","oakland","windsor",
"belleville","woodstock","wakefield","lindsay","grafton","benton","kirkland","maxwell","pembroke",
"elmwood","wilmot","rockland","st thomas","cloverdale","carlisle","dalhousie","black point",
"saint-laurent","sainte-louise","saint-sauveur","saint-isidore","inkerman","escuminac",
"grand lake road","priceville","chelmsford","holyrood","south river","north river","st marys",
"bloomfield","charlottetown","swift current","hillview","lumsden","brookfield","hermitage",
"brighton","sandy cove","burlington","westport","heatherton","st davids","lourdes","paradise",
"deer lake","new haven","cleveland","inverness","frankville","lunenburg","sherbrooke","trenton",
"eureka","wentworth","maitland","newport","walton","milford","alton","waterville","auburn",
"cambridge","woodville","shelburne","caledonia","milton","tiverton","clyde river","carleton",
"kemptville","westmount","florence","point edward","new glasgow","elmsdale","wellington","goodwood",
"tantallon","bedford","amherst","chelsea","waterloo","labelle","sandford","norwood","millbrook",
"melville","troy","queensville","chesterville","odessa","cornwall","akwesasne","kendal","borden",
"mansfield","alberton","rama","georgetown","prince albert","springwater","york","melbourne",
"belle river","maidstone","elmira","stratford","lasalle","hudson","ebenezer","harrington",
"albertville","scott","stornoway","davidson","denholm","radisson","candiac","mayo",
"beaver creek"],
'Europe':[""],
'UK':["newton ward","belle vale ward","st. pauls ward","abbey ward","southwick","stockton","boyton",
"corton","bourton","chapmanslade","westbury","heywood","holt","staverton","wingfield","marshfield",
"st. catherine","north stoke","camerton","yeovil","halstock","claverton","limpley stoke","wellow",
"corston","westfield","blackburn","livesey","bradford","cross hills","ridge","steeple","east stoke",
"shapwick","horton","whitmore","grange ward","burton","ringwood","bury","preston","east ward",
"bristol","whitchurch","winterbourne","kenn","yatton","hutton","churchill","wick","thornbury",
"clutton","burrington","redhill","felton","brockley","gilsland","featherstone","chester",
"mollington","croughton","picton","stoke","elton","farndon/holt","huntington","coddington","farndon",
"stretton","caldecott","barrow","hatton","harthill","rossett","eaton","poulton","ledsham",
"woodlands ward","longford ward","winsford","weston","willington","rushton","tiverton","beeston",
"moulton","cuddington","whitley","marston","derwent ward","belmont","brandon","stanley","ovington",
"barningham","hope","marwood","mickleton","winston","westwick","bowes","cockfield","woodland",
"hilton","crook","chilton","langton","denton","stainton","rawcliffe","bottesford ward","crowle",
"luddington","barton ward","broughton","park ward","hatfield","cantley","wolds ward","south ward",
"wootton","central ward","norton","fenwick","stainforth","west end","belton","gibbs marsh","farnham",
"dorchester","batcombe","hermitage","moreton","frampton","fleet","preston ward","allington",
"castleton","haydon","north wootton","leigh","doddington","sedgley ward","greenlands ward","linton",
"high wycombe","bradenham","haddenham","stone","dinton","kingswood","ludgershall","oakley",
"hardwick","dunton","buckland","halton","speen","bovingdon","coleshill","winchmore hill","sutton",
"marden","wellington","withington","bacton","longtown","newton","grafton","harewood","thruxton",
"kingstone","hay-on-wye","clifford","pembridge","bishopstone","kimbolton","wacton","donnington",
"lea","gorsley and kilcot","aldbrough","easington","brough","newport","beverley","st. mary's ward",
"leven","etton","st. andrew's ward","warley ward","town ward","manor ward","hale","kirkby",
"northwood ward","whiston","knighton","combe","presteigne","stapleton","burley","langham","ashwell",
"exton","gunthorpe","hambleton","whitwell","brooke","wing","normanton","seaton","pilton","ashley",
"middleton","carlton","hawksworth","otley","collingham","wetherby","walton","morley","ilkley",
"streatley","parkside ward","toddington","eaton bray","leighton buzzard","slapton","village ward",
"priory ward","broadheath ward","st. peter's ward","chatham","cliffe","gillingham","watling ward",
"milton keynes","whaddon","thornton","twyford","finmere","leckhampstead","wicken","calverton",
"bedford","castle ward","queens park ward","oakley ward","clapham","bromham","warrington",
"ravenstone","st. mary's","dinnington","horsley","whittington","wall","blyth","valley ward",
"riverside ward","bellingham","cresswell","ashington","warkworth","netherton","embleton",
"whittingham","ellingham","lowick","kirknewton","ford","dales ward","rushden","welton","hinton",
"newnham","boddington","alderton","silverstone motor racing circuit","whitfield","aynho","orton",
"harrington","rothwell","woodford","clopton","islip","ringstead","rural west ward","gretton",
"boughton","great houghton","upton","upton ward","st. james ward","welford","elkington","stanford",
"winwick","watford","hannington","draughton","quinton","ashton","gayton","upper heyford","wilby",
"hargrave","shaw ward","farnborough","fawley","banbury","peterborough","west ward","thorney",
"market deeping","lutton","thurning","warmington","stamford","barnack","pickworth","uffington",
"victoria","rock","nelson ward","northwood","reading","wargrave","hurley","compton","boxford",
"minster ward","tadley","swallowfield/riseley","stratfield mortimer","theale","bradfield",
"pangbourne","basildon","goring","henley-on-thames","sheffield","woodhouse ward","dronfield",
"wentworth","wingfield ward","north east ward","dalton","bramley","barnsley","old town ward",
"langford","everton","prestbury ward","sutton ward","new mills","slough","dorney","maidenhead",
"dorney reach","hurley/danesfield","marlow","denham","west lavington","swindon","chippenham",
"nettleton","charlton","st. andrews ward","marlborough","fyfield","mildenhall","froxfield",
"buttermere","oare","alton","woodborough","easton","wilsford","stapleford","ansty","west dean",
"west wellow","morgan's vale","downton","shaftesbury","st. anne's ward","coryton","stonebridge",
"stoke-on-trent","pant","bickley","bradley","threapwood","overton","edge","barton","hampton",
"bicton","dorrington","tatworth","kilham","haggerston","tibberton","troon","st. martin's","st. ives",
"skelton","bishopton","claxton","greatham","london","croft","appleton","kingsley","aston",
"heath ward","pontefract","normanton ward","fulford","kexby","driffield","wigginton",
"stamford bridge","hayton","melbourne","cambridge","foxton","barrington","kingston","willingham",
"milton","rampton","burwell","girton","downham","christchurch","wistow","holme","brampton",
"houghton","colne","chesterton","clifton","stainburn","crosby","thornhill","harbour ward","dalston",
"woodside","osmotherley","colton","staveley","burton upon trent","tutbury/hatton","morton","kilburn",
"sawley","eckington","barlow","bradwell ward","bradwell","moor ward","creswell","st. john's ward",
"buxton","west hill","monkton","bampton","merton","ashford","arlington","farringdon","kenton",
"yelverton","ashburton","chillington","friston","laughton","crawley","hurst green","mayfield",
"heathfield","beckley","langley","great easton","st. johns ward","stanway","halstead","stroud",
"stonehouse","westgate ward","blakeney","newland","coleford","taynton","staunton","teddington",
"sandhurst","cranham","southam","woodmancote","oddington","shipton","broadwell","northwick park",
"bisley","cherington","chepstow","stanton","bentley","clanfield","newtown","steventon","hook",
"long sutton","sparsholt","bullington","kimpton","martin","long marston","benington","arbury ward",
"harefield","holywell ward","ash","river","newington","bridge","barham","crundale","tunstall",
"sherwood ward","cranbrook","higham","barnoldswick","rufford","forton","hornby","silverdale",
"warton","longridge","weeton","atherstone","woodhouse","wymondham","somerby","welby","drayton",
"stoughton","greenhill ward","thurlaston","west stockwith","scotton","stow","thorganby","horsington",
"roughton","alford","ingham","well","willoughby","fiskerton","reepham","branston ward","walcott",
"walesby","linwood","thimbleby","long bennington","caythorpe","honington","kirton","ashill",
"cawston","hanworth","plumstead","hickling","howe","besthorpe","kimberley","broome","barford",
"walpole","grimston","barwick","watlington","thorpe","brompton","bilton ward","ripley","oxton",
"barnby","tollerton","newburgh","misterton","lound","carlton ward","south stoke","grove","abingdon",
"horley","somerton","st. margaret's ward","forest hill","holton","sydenham","blackford","cudworth",
"broadway","oulton","cavendish","parham","whitton","cookley","barnham","hunston","st. nicolas ward",
"warwick","westbourne","fairfield","southgate","hillside","dundonald","ferndale","valley",
"springfield","seven sisters","larkhall","crossgates","bridgend"],
'Australia':["parliament house","parkes","black mountain","acton","o'connor","forrest","red hill","griffith",
"kingston","hughes","lyons","chifley","mawson","weston","stirling","holder","coree","fisher","reid",
"cook","macquarie","hawker","macgregor","latham","spence","flynn","lawson","bruce","paddys river",
"oxley","monash","gowrie","macarthur","chisholm","theodore","gilmore","gordon","mitchell","casey",
"franklin","palmerston","amaroo","waterloo","rosebery","camperdown","kensington","miranda",
"sutherland","northbridge","crows nest","st leonards","manly","epping","seven hills","castle hill",
"st marys","ashfield","burwood","granville","auburn","guildford","fairfield","darlington",
"beaconsfield","paddington","centennial park","queens park","waverley","rose bay","kingsford",
"coogee","glebe","annandale","leichhardt","newtown","st peters","sydenham","abbotsford","stanmore",
"lewisham","riverview","northwood","willoughby","killara","st ives","brooklyn","forestville",
"cremorne","seaforth","clontarf","freshwater","queenscliff","collaroy","cromer","bayview","newport",
"the basin","palm beach","meadowbank","melrose park","dundas","oatlands","cheltenham","eastwood",
"newington","croydon","croydon park","strathfield","enfield","burwood heights","mortlake","cabarita",
"homebush","rookwood","rosehill","clyde","regents park","girraween","toongabbie","prospect",
"kings park","forest glen","arcadia","carramar","lansdowne","smithfield west","smithfield",
"glenfield","green valley","hinchinbrook","sandy point","wattle grove","canterbury","punchbowl",
"carlton","sandringham","penshurst","kangaroo point","como","heathcote","bangor","springfield",
"mount elliot","yattalunga","blackwall","palmdale","palm grove","rocky point","magenta",
"shelly beach","san remo","mirrabooka","sunshine","killingworth","belmont","valentine","swansea",
"lakelands","fassifern","balmoral","cardiff","glendale","fletcher","highfields","mount hutton",
"charlestown","wickham","carrington","stockton","waratah","georgetown","hamilton","mayfield",
"sandgate","shoal bay","nelson bay","boat harbour","taylors beach","one mile","oyster cove",
"rosebrook","melville","maitland","bolwarra","allandale","woodville","windermere","black hill",
"hexham","thornton","buchanan","four mile creek","osterley","swan bay","cedar creek","merriwa",
"cassilis","broke","singleton","camberwell","bulga","greenlands","reedy creek","ravensworth",
"st clair","howick","dunolly","clydesdale","westbrook","greta","elderslie","stanhope","aberdeen",
"glenrock","parkville","dry creek","sandy creek","timor","scotts creek","cattle creek","somerton",
"westdale","kingswood","yarraman","winton","halls creek","ironbark","argyle","abington","lyndhurst",
"retreat","watsons creek","uralla","bakers creek","sapphire","oakwood","newstead","paradise",
"spring mountain","woodstock","limestone","bonshaw","ashford","glencoe","tenterden","georges creek",
"ben lomond","bassendean","stonehenge","morven","torrington","deepwater","rocky creek","bungulla",
"woodside","timbarra","orange grove","curlewis","chichester","salisbury","brookfield","sugarloaf",
"trevallyn","tocal","paterson","barrington","invergordon","kia ora","stratford","mount george",
"washpool","booral","forster","tipperary","killawarra","kew","lorne","deep creek","gladstone",
"millbank","sherwood","greenhill","north haven","moorland","lakewood","north shore","riverside",
"long flat","birdwood","redbank","kings creek","rosewood","south arm","bucca","cascade","marengo",
"safety beach","lawrence","mountain view","stockyard creek","wombat creek","southampton","lilydale",
"calliope","swan creek","coldstream","ashby","sandon","woodford","yamba","iluka","theresa creek",
"camira","myrtle creek","sandilands","chatsworth","ellangowan","codrington","broadwater","the gap",
"esk","ettrick","the glen","lynwood","coolgardie","pimlico","binna burra","eureka","corndale",
"richmond hill","bentley","federal","clunes","lismore","eltham","palmwoods","north arm","fernvale",
"bray park","eungella","crystal creek","casuarina","spring hill","lilyvale","scarborough","clifton",
"mount pleasant","flinders","dunmore","blackbutt","avondale","cleveland","curramore","willow vale",
"coolangatta","broughton","woodhill","rosedale","woodlands","surf beach","milton","myola",
"falls creek","longreach","bangalee","cadgee","kianga","beauty point","bald hills","lochiel",
"wyndham","nelson","wandella","greendale","black range","stony creek","rossmore","woodbine",
"campbelltown","appin","bradbury","wedderburn","blair athol","st andrews","oakdale","spring farm",
"cawdor","camden park","glenmore","picton","wilton","buxton","maldon","avon","balaclava",
"wattle ridge","robertson","beaumont","avoca","yarrunga","bundanoon","big hill","exeter","richlands",
"baw baw","bannister","carrick","breadalbane","manton","cavan","kialla","wallaroo","burra","sutton",
"st george","araluen","majors creek","sassafras","colinton","rocky plain","cooma","myalla","maffra",
"mount cooper","craigie","cathcart","glenroy","coppabella","mountain creek","nyora","ringwood",
"wentworth","ellerslie","pomona","kooringal","springvale","forest hill","taradale","osborne",
"lockhart","brookdale","ryan","henty","tara","sebastopol","mimosa","springdale","reefton","yenda",
"myall park","argoon","barratta","hay","clare","maude","aratula","pine lodge","little river",
"westwood","sandy gully","speewa","emu heights","silverdale","hobartville","londonderry","richmond",
"tennyson","clarendon","windsor","mulgrave","wilberforce","ebenezer","oakhurst","plumpton",
"box hill","woodcroft","glenwood","bidwill","blaxland","st albans","wrights creek","sun valley",
"springwood","linden","blackheath","bell","edith","black springs","hampton","kanimbla","hartley",
"dunkeld","llanarth","glanmire","eglinton","o'connell","locksley","kelso","newbridge","forest grove",
"raglan","charlton","wattle flat","white rock","vittoria","bowen","windera","springside","lucknow",
"shadforth","spring creek","glenelg","pinnacle","walmer","apsley","maryvale","wellington","gin gin",
"ravenswood","babinda","miandetta","collie","pine grove","irymple","bulla","kulwin","hungerford",
"barringun","portland","olinda","camboon","windeyer","budgee budgee","collingwood","havilah",
"cross roads","green gully","worlds end","yarrawonga","hill end","peak hill","forbes","warroo",
"corinella","tottenham","five ways","mount hope","trida","ivanhoe","sunset strip","silverton",
"mingoola","camp creek","coonawarra","eaton","the gardens","the narrows","hidden valley","southport",
"margaret river","wishart","acacia hills","pinelands","durack","gray","virginia","pine creek",
"cossack","flying fox","gregory","arnold","delamere","nicholson","tablelands","elliott","calvert",
"ross","stuart","hart","tanami","davenport","simpson","larapinta","ascot","albion","northgate",
"brighton","margate","redcliffe","grange","chapel hill","sumner","jindalee","middle park","west end",
"rocklea","salisbury east","heathwood","woodridge","hillcrest","browns plains","underwood",
"mansfield","daisy hill","waterford","carina","chandler","victoria point","bannockburn","steiglitz",
"alberton","gilberton","parkwood","lamington","running creek","mount lindesay","collingwood park",
"churchill","woodend","pine mountain","boonah","eskdale","fulham","mount walker","rosevale",
"lockyer","northlands","murphys creek","ramsay","preston","woodleigh","douglas","emu creek",
"st helens","stoneleigh","the pines","western creek","greenmount","elphinstone","hendon",
"cunningham","willowvale","gladfield","montrose","warwick","killarney","glenlyon","riverton",
"inglewood","balgowan","devon park","greenwood","grassdale","hopeland","pelham","sunnyside",
"wellesley","cockatoo","simmie","bungil","cornwall","lumeah","moorina","donnybrook","glenfern",
"armstrong creek","landsborough","golden beach","burnside","parklands","ridgewood","ross creek",
"victory heights","greens creek","redgate","melrose","runnymede","ventnor","langley","maryborough",
"netherby","glenorchy","torquay","happy valley","childers","goodwood","st agnes","st kilda",
"taunton","round hill","clinton","the range","stewarton","anakie","nine mile","shoalwater",
"pheasant creek","midgee","woodbury","glenlee","castle creek","dromedary","emerald","elgin",
"winchester","buckland","beaufort","pine hill","dunrobin","garfield","jericho","middleton",
"alexandra","epsom","hampden","burton","dysart","palmyra","mia mia","brandy creek","crystal brook",
"collinsville","newlands","inkerman","wangaratta","parkside","eight mile creek","mount stuart",
"hyde park","cranbrook","prairie","greenvale","cosgrove","black river","basalt","southern cross",
"mosman park","bellfield","cambridge","warburton","georgina","soldiers hill","pioneer","buckingham",
"barkly","menzies","mornington","sturt","forrest beach","rockingham","goldsborough","mount sheridan",
"manoora","whitfield","germantown","strathmore","laura","moresby","shannonvale","wonga","kimberley",
"bonnie doon","mowbray","clifton beach","millstream","bellevue","highbury","dixie","palmer",
"hindmarsh","dudley park","beverley","queenstown","albert park","seaton","west beach","hilton",
"mitchell park","somerton park","blackwood","malvern","mitcham","hawthorn","highgate","myrtle bank",
"wattle park","norwood","evandale","maylands","skye","tranmere","walkerville","fitzroy",
"hope valley","kangaroo flat","gawler","piccadilly","macclesfield","longwood","bridgewater",
"ashbourne","bull creek","seaford","normanville","seddon","millbrook","woodhouse","mount barker",
"toora","woods point","rocky gully","mount observation","strathalbyn","clayton","narrung","bunbury",
"wild dog valley","pelican point","sherlock","mindarie","williamstown","altona","swan reach",
"bright","alma","woolshed flat","stanley","dawson","erskine","peterborough","black rock",
"hill river","spring gully","emu flat","spalding","bungaree","rochester","melton","port arthur",
"new town","north beach","yelta","marion bay","brentwood","butler","venus bay","jamieson","panitya",
"wandana","leigh creek","coopers creek","copley","garden island","claremont","rokeby","sandford",
"mangalore","shannon","hastings","york plains","victoria valley","fitzgerald","molesworth",
"ellendale","tyenna","bushy park","plenty","apollo bay","woodbridge","acton park","wattle hill",
"fortescue","orford","fingal","beaumaris","seymour","invermay","strzelecki","white hills","derby",
"glengarry","perth","longford","cressy","westbury","middlesex","beulah","lillico","flowerdale",
"seabrook","irishtown","christmas hills","arthur river","broadmeadows","robinson","laverton",
"hillside","brunswick","reservoir","macleod","deepdene","armadale","glen iris","bayswater",
"huntingdale","herne hill","ferguson","dartmoor","teesdale","brown hill","learmonth","talbot",
"kenmare","hopetoun","baynton","serpentine","kimbolton","woodvale","murchison","moora","shelley",
"st james","ferndale","trafalgar","paynesville","somerville","sorrento","welshpool"],
'New Zealand':["sunnyvale","woodhill","hillsborough","avondale","ngapuna","kensington","tokomaru","parkvale",
"waipawa","waverley","palmerston","roxburgh","mataura","richmond","meremere","murchison"]
    };
    let duplicate_places_in_region = DUPLICATE_PLACE_NAMES[[region]];
    let duplicates = text.filter(str =>
                                 duplicate_places_in_region.indexOf(str.toLowerCase()) > -1);
    return duplicates;
}

function reverse_geo_r_code_str(var_name)
{
    return `library(flipGeoData)
env <- new.env(parent = getNamespace("flipGeoData"))
source("https://raw.githubusercontent.com/Displayr/flipGeoData/master/R/reversegeocode.R", local = env)
formOutputType <- ifelse(startsWith(formOutputType, "Admin"), "Admin1", "Country")
${var_name} <- env$ReverseGeocode(latitude = formLatitude,
    longitude = formLongitude,
    output.type = formOutputType,
    tol = formTolerance)`;
}

function reverse_go_js_code_str()
{
return `form.dropBox({name: 'formLatitude', types: ['Variable:!filter'],
    prompt: 'Select input variable containing latitude coordinates (numeric values between -90 and 90)',
    label: 'Latitude variable', required: true, multi: false});
form.dropBox({name: 'formLongitude', types: ['Variable:!filter'],
    prompt: 'Select input variable containing longitude coordinates (numeric values between -180 and 180)',
    label: 'Longitude variable', required: true, multi: false});
form.comboBox({name: 'formOutputType',
        label: 'Output geographic type',
        alternatives: ['Administrative region (state, province, etc.)', 'Country'],
        prompt: 'Select geographic unit to convert coodinates into'});

form.numericUpDown({name: 'formTolerance', label: 'Match tolerance (km)',
    prompt: 'Maximum distance in kilometres that a point can be from its nearest region and still declared a match.',
    default_value: 100, minimum: 0, maximum: 10000});

form.setHeading('Merge Categories - Latitude/Longitude');
`;
}

function reverseGeocode(output_type) {
    const is_displayr = inDisplayr();
    let user_selections = getAllUserSelections();
    let selected_vars =[];

    function _invalidSelectionsError(){
        const is_displayr = inDisplayr();
        let msg = (is_displayr ? "Please select both the latitude and longitude variables " +
            "or a single variable containing IP addresses from Data Sets " +
		   "on the left and rerun." : "No suitable text or numeric variables " +
		   " containing latitude and longitude data were found in your project.");
        log(msg);
        return false;
    }

    function _promptForSelections(){
        includeWeb("QScript Selection Functions");
        let data_file = requestOneDataFileFromProject();
        let candidate_vars = getVariables(data_file.questions);
        let allowed_types = ['Numeric', 'Text'];
        candidate_vars = candidate_vars.filter(v => allowed_types.includes(v.variableType));
        if (candidate_vars.length === 0)
            return [];
        let prompt = "Select the variable containing the latitude coordinates";
        let selected_vars = [selectOneVariableByNameAndLabel(prompt,
                                                             candidate_vars, false)];
        prompt = "Select the variable containing the longitude coordinates";
        selected_vars.push(selectOneVariableByNameAndLabel(prompt,
                                                           candidate_vars, false));
        return selected_vars;
    }
    
    if (exactlyNSelected(user_selections, "Variable", 1, false)) {
        if (IPAddressDetected(user_selections.selected_variables[0]))
            return createCategoricalVariableFromIPs(user_selections.selected_variables[0],
                                                   output_type);
        else if (!is_displayr)
            selected_vars = _promptForSelections();
    }else if (!exactlyNSelected(user_selections, "Variable", 2, false)) {
        if (!is_displayr)
            selected_vars = _promptForSelections();
    }else
        selected_vars = user_selections.selected_variables;

    if (selected_vars.length !== 2)
        return _invalidSelectionsError();
    
    // Try to detect and correct if user has selected longitude variable before latitude variable
    if (selected_vars[0].rawValues.some(value => value < -90 || value > 90))
	selected_vars = [selected_vars[1], selected_vars[0]];
    
    if (selected_vars.some(v => !v.question.isValid)) {
        let structure = correctTerminology("variable set");
        log("The selected " + structure + " is not valid." +
            "Please select only valid " + structure + "s and rerun.");
    }
    
    createRVariable(selected_vars, output_type);
    return;
}

function createRVariable(lat_long_variables, output_type) {
    let new_r_question;
    let data_file = lat_long_variables[0].question.dataFile;
    if (data_file.name != lat_long_variables[1].question.dataFile.name) {
        log("Input latitude and longitude variables must be from the same data set.");
        return false;
    }
	
    let new_question_name = preventDuplicateQuestionName(data_file,
                                                         "Combined categories from " +
                                                         lat_long_variables[0].label + ", " +
							                             lat_long_variables[1].label);
    let new_var_name = preventDuplicateVariableName(data_file,
                                                    "combined_" +
                                                    lat_long_variables[0].name + "_" +
						                            lat_long_variables[1].name);

    let inputs = {formLatitude: lat_long_variables[0].guid, formLongitude: lat_long_variables[1].guid,
		  formOutputType: output_type};
    try {
        new_r_question = data_file.newRQuestion(reverse_geo_r_code_str(new_var_name),
                                                new_question_name, new_var_name,
                                                lat_long_variables[1], reverse_go_js_code_str(), inputs);
        new_r_question.questionType = "Pick One";
        insertAtHoverButtonIfShown(new_r_question);
    }catch (e) {
        let structure_name = correctTerminology("variable set");
        log("Sorry, an error occurred merging the geographic data in this " +
            structure_name + " : " + e);
        return false;
    }
    return;
}

function IPAddressDetected(variable) {
    const regexIPv4 = /^(25[0-5]|2[0-4][0-9]|[01]?[0-9][0-9]?)\.(25[0-5]|2[0-4][0-9]|[01]?[0-9][0-9]?)\.(25[0-5]|2[0-4][0-9]|[01]?[0-9][0-9]?)\.(25[0-5]|2[0-4][0-9]|[01]?[0-9][0-9]?)$/;
    const regexIPv6 = /(([0-9a-fA-F]{1,4}:){7,7}[0-9a-fA-F]{1,4}|([0-9a-fA-F]{1,4}:){1,7}:|([0-9a-fA-F]{1,4}:){1,6}:[0-9a-fA-F]{1,4}|([0-9a-fA-F]{1,4}:){1,5}(:[0-9a-fA-F]{1,4}){1,2}|([0-9a-fA-F]{1,4}:){1,4}(:[0-9a-fA-F]{1,4}){1,3}|([0-9a-fA-F]{1,4}:){1,3}(:[0-9a-fA-F]{1,4}){1,4}|([0-9a-fA-F]{1,4}:){1,2}(:[0-9a-fA-F]{1,4}){1,5}|[0-9a-fA-F]{1,4}:((:[0-9a-fA-F]{1,4}){1,6})|:((:[0-9a-fA-F]{1,4}){1,7}|:)|fe80:(:[0-9a-fA-F]{0,4}){0,4}%[0-9a-zA-Z]{1,}|::(ffff(:0{1,4}){0,1}:){0,1}((25[0-5]|(2[0-4]|1{0,1}[0-9]){0,1}[0-9])\.){3,3}(25[0-5]|(2[0-4]|1{0,1}[0-9]){0,1}[0-9])|([0-9a-fA-F]{1,4}:){1,4}:((25[0-5]|(2[0-4]|1{0,1}[0-9]){0,1}[0-9])\.){3,3}(25[0-5]|(2[0-4]|1{0,1}[0-9]){0,1}[0-9]))/gi;

    let ip_vals = variable.rawValues;
    return ip_vals.some(val => regexIPv4.test(val) || regexIPv6.test(val));
}

function createCategoricalVariableFromIPs(ip_variable, output_type) {
    if (!output_type.startsWith("Country"))
    {
        log("We've detected that you have IP addresses, but we are only able to " +
            "combine them to the country of origin at this time, sorry.");
        return;
    }
    function _geocodeIPRCode(v, disambiguate) {
        let input_name = disambiguate ? disambiguateInputName(v) : stringToRName(v.name);
        return 'result <- as.factor(flipAPI::GeocodeIPs(ips = ' + input_name + ')[, 3])';
    }        
    let data_file = ip_variable.question.dataFile;
    let r_code = _geocodeIPRCode(ip_variable, false);
    let country_label = preventDuplicateQuestionName(data_file,
                                                    "Combined categories from " + ip_variable.label);
    let country_name = preventDuplicateVariableName(data_file,
                                                    "combined_" + ip_variable.name);
    let new_var;
    try {
        new_var = data_file.newRVariable(r_code, country_name, country_label,
                                             ip_variable);
    } catch (e) {
        if (/R code is ambiguous|not found/.test(e.message)) {
            r_code = _geocodeIPRCode(ip_variable, true);
            try {
                new_var = data_file.newRVariable(r_code, country_name, country_label,
                                             ip_variable);
            }catch(e) {
                log("No cases of the IP variable can be geocoded: " + e.message + ".");
                return;
            }
        }else{
            log("No cases of the IP variable can be geocoded: " + e.message + ".");
            return;
        }
    }
    insertAtHoverButtonIfShown(new_var.question);
    project.report.setSelectedRaw([new_var]);
    return;
}