Title:   "Fast Google Search"
    Date:    11-May-2001
    Version: 0.1.0
    File:    %google-search.r
    Author:  "Christopher Ross-Gill"
    Owner:   "Arran Multimedia Studio"
    Rights:  "Copyright ©2001 Arran Multimedia Studio"
    Purpose: "To Utilise the Google Search Engine"
    Usage:   {
        target-url: google-search "Apples Oranges"

;o) Encodes message to CGI notation

encode-cgi: func [
    {Converts string to a CGI argument string.}
    args [any-string!] "Starts at first argument word"
    space-to-plus: func [arg /local seek chr] [
        if any [none? arg empty? arg] [return ""]
        seek: arg
        while [seek: find seek #" "] [
            change seek #"+"
            seek: next seek
        head arg
    to-url space-to-plus copy args

;o) Get a Google response...

google-search: func [
    {Returns top-ranking site from a Google Search}
    search-string [any-string!] {Google search string}
    trys: 0
    while [
        and trys < 3 error: error? try [
            google-response: copy {}
            google-port: open tcp://
            insert google-port rejoin [
                {GET /search?q=} encode-cgi lowercase copy search-string
                {&btnI=I'm+Feeling+Lucky HTTP/1.1} newline
                {host:} newline
                {connection: close} newline newline
            while [
                google-wire: copy google-port
                append google-response google-wire
            close google-port
            parse/all google-response [
                thru {Location: }
                copy google-result to newline
                to end
            google-result: to-url google-result
        trys: trys + 1
        wait 1
    if error [google-result: 'error]
    return google-result

;o) View the google

x-google: [
    style field field edge [size: 2x2 color: black effect: none]
    space 10
    backdrop effect [fit]
    banner "Google Search"
    text bold "Returns top Google match from search string"
    i-search: field 230 "rebol"
    btn 60 "Lookup" [o-url/text: google-search i-search/text show o-url]
    o-url: field 230 ""
    btn 60 "Browse" [browse to-url o-url/text]
    btn 60 "Copy" [write clipboard:// o-url/text]

if not system/script/args [
    view/title center-face layout x-google "Google Search"