#!/bin/sh

# /bin/sh interprets this part, but wish ignores it...
#\
exec wish "$0" "$@"

#GEODAS Coastline Extractor
#Written by:
##     Dan Metzger 2001


#set directory variables
if {[file exists ./geodas.cfg]} {
  set _pathconfig "./"
} elseif {[file exists ~/geodas/geodas.cfg]} {
  set _pathconfig [glob ~]/geodas
} elseif {[file exists ~/gdas/geodas.cfg]} {
  set _pathconfig [glob ~]/gdas
} else {
   set temp $env(PATH)
   regsub  -all ":" $temp " " temp
   set found 0
   foreach i $temp {
      if {[file exists $i/geodas.cfg]} {
         break
      }
   }
   set _pathconfig $i
}

if {[file exists $_pathconfig/geodas.cfg]} {
  source $_pathconfig/geodas.cfg
} else {
   puts "Could not find a geodas.cfg in home path, current path, or in PATH"
   exit
}

load $_paths(lib)/libgeodastcl.so Geodastcl   ;#load the geodas commands

catch {
  tk_setPalette $_settings(colorscheme)
}

#expand ~/ if found in work path
if [string match ~ [string range $_paths(work) 0 0]] {
  set _paths(work) "[glob ~][string range $_paths(work) 1 end]"
}


set screenw [winfo screenwidth .]

if {$screenw >= 1280} {
  set _mapwidth 1024
  set _mapheight 768
} elseif {$screenw >= 1024} {
  set _mapwidth 800
  set _mapheight 600
} elseif {$screenw >= 800} {
  set _mapwidth 640
  set _mapheight 480
} else {
  set _mapwidth 600
  set _mapheight 400
}

 #puts "_mapwidth:$_mapwidth"
 #puts "_mapheight:$_mapheight"



##########################
#   GEODAS Help System based on html_library (see file html_library for licence terms)
##########################
source $_paths(lib)/html_library
#global help_initialized
#global _contents
#global _index
#global outPath
set help_initialized 0
set _contents cont_ce.htm
set _index index_ce.htm


#check here for prog path, check where needed for other paths...
if {![info exists _paths(prog)] || $_paths(prog)==""} {
   puts "geodas.cfg error -- no PROG= path specified!"
   exit
}
set auto_path "$_paths(prog) $auto_path"

if { $_paths(work)==""} {
   puts "geodas.cfg error -- work path not available/specified!"
   exit
}
 #puts "this is path to work: $_paths(work)"
if {![file isdirectory $_paths(work)]} {
   file mkdir $_paths(work)
}

     set ups_status disabled

   if {[find_coast]==0} {
      exit
   }
   #set _entry(0) $_area
   #entry(0) seems to be used for storage of all polygon areas (one in this program)
   #entry(1) is used for temporary storage of elements like zoom box, polygon areas, etc.

   set action nothing
#   set bind_switch on
   set Debug n
   #set Debug "y" ;#for now, testing
   set user_view A ;#map always starts
   set _key "DEBUG"  ;#for now, testing


#initialize the main window
   wm title . "GEODAS Coastline Extractor"
   set x [expr $_mapwidth / 10]
   set y [expr $_mapheight / 10]
   wm geometry . +$x+$y
   wm geometry . "$_mapwidth\x$_mapheight"
   wm iconbitmap . "@$_paths(images)/geodas.ico"
   wm protocol . WM_DELETE_WINDOW {exit}

   set _uspoly {{-66.62 47.07} {-66.62 44.46} {-69.96 42.97} {-69.53 41.61} {-73.74 39.93} {-75.54 36.95} {-75.29 35.03} {-81.11 30.68} {-80.0 26.7} {-80.2 24.6} {-82.4 24.4} {-83.78 29.2} {-89.72 28.7} {-94.0 29.2} {-96.97 24.97} {-115.05 32.42} {-118.52 32.42} {-121.0 33.91} {-125.27 40.24} {-124.96 48.68} {-121.31 49.12} {-85.45 49.43}}

   set _limits(top) 90.0
   set _limits(bot) -90.0
   set _limits(left) -180.0
   set _limits(right) 180.0
   set _limits(z360) 0
   set user_view A
   set coastname ""
   set resfactor ""
   set strres ""
   set strcoast ""
   set _entry(0) ""
   set coastfileformat "dfNONE"
   set outPath "$_paths(work)"
   set outFile ""
   set outExt ""
   set outPathFile ""

   set t .t      ;#these 3 should be of no use anymore
   set m .mid
   set b .bot

   frame .top -borderwidth 3 -relief groove
   frame .mid
   frame .bot -borderwidth 3 -relief groove
   # jbh changes, 6/98 -create bordering frames for lat/lon values...
   frame .mid.top -height 33
   frame .mid.bot -height 33
   frame .mid.left -width 40
   frame .mid.right -width 40

   pack .top -fill x -side top
   pack .mid -side top -fill both -expand 1
   pack .bot -side bottom -fill x

   #set up the t frame: menubar...
   # *******************************************************************
   #this is the file button. OK (accept) Cancel, Clear All
   menubutton .top.file -text "File" -underline 0 -menu .top.file.m -pady 2
   menu .top.file.m -tearoff 0

   .top.file.m add command -label "Plot Coastlines..." -underline 0 -command {
     get_default_coast .mid.map $_limits(top) $_limits(bot) $_limits(left) $_limits(right) \
                                 coastname resfactor
     dialog_select_coast coastname resfactor
     if {$confirmStatus} {
       get_coast_res_names $coastname $resfactor strcoast strres
       set _areahint "$strcoast at $strres"
       remap .mid.map $coastname $resfactor
     }
   }
   .top.file.m add command -label "Save As..." -underline 0 -state disabled -command {
      get_coastfile_format coastfileformat
      switch $coastfileformat {
        dfA00 {
          set outExt .a00
          set filetypes_out {
            { "GEODAS VCT00 ASCII Format" { .a00 }}
          }
        }
        dfGEN {
          set outExt .gen
          set filetypes_out {
            { "Arc/Info Ungenerate File" { .gen }}
          }
        }
        default {
          return 0
        }
      } ;#switch
     set outPathFile [tk_getSaveFile -initialdir $outPath -defaultextension $outExt \
         -filetypes $filetypes_out -title "Save Coastline File As" -parent .]
     set outPath [file dirname $outPathFile]
     set outFile [file tail $outPathFile]
     set outExt [file extension $outFile]
 #puts "outPath outFile outExt outPathFile:$outPath,$outFile,$outExt,$outPathFile|"
     if {$outPathFile == ""} {
       return 0
     }
     #note that _entry(0) has been set up for multiple polygons
     set polyargs ""
     foreach i $_entry(0) {
       foreach j $i {
         lappend polyargs [format "%.3f" [lindex $j 0]]
         lappend polyargs [format "%.3f" [lindex $j 1]]
       }
     }
 #puts "polyargs:$polyargs"
 #puts "llength polyargs:[llength $polyargs]"
     set numpts [expr [llength $polyargs] / 2]
 #puts "numpts:$numpts"
     set launchstring "|$_paths(prog)/gx_coast $_paths(coast)/ $coastname.b00 $resfactor \
                       $outPath/ $outFile $coastfileformat $numpts $polyargs"
     if [string match DEBUG [string range $outFile 0 4]] {
     puts $launchstring
     }
# if ![string match x $launchstring] {
#   puts "artificial exit"
#   return 0
# }
     set _active [open $launchstring r+]
     fileevent $_active readable {
     if [eof $_active] {
       set mess "An error occurred. Coastline Extractor program ended prematurely!^GEODAS ERROR^ERROR"
     } else {
       gets $_active mess
    }
     if [string match DEBUG [string range $outFile 0 4]] {
       puts $mess
     }
     set ndx1 [string first ^ $mess]
     set ndx2 [string last ^ $mess]
     set msg [string range $mess 0 [expr $ndx1 - 1]]
     set caption [string range $mess [expr $ndx1 + 1] [expr $ndx2 -1]]
     set mtype [string range $mess [expr $ndx2 + 1] end]
     #replace | with \n
     set ndx1 [string first | $msg]
     while {$ndx1 != -1} {
       set msg "[string range $msg 0 [expr $ndx1 - 1]]\n[string range $msg [expr $ndx1 + 1] end]"
       set ndx1 [string first | $msg]
     }
     switch $mtype {
       ERROR {
         catch {close $_active}
#        .fr.cancel configure -state disabled
         tk_messageBox -icon error -title $caption -message "$msg"
         catch {close $_active}
#      .menubar.mFile entryconfigure "Open Grid File" -state normal
#      .menubar.mFile entryconfigure "Design-a-Grid" -state normal
      #wm deiconify .
       }
       OK {
         tk_messageBox -type ok -icon info -title $caption -message "$msg"
         puts $_active "OK"
         flush $_active
       }
       OKCANCEL {
         set result [tk_messageBox -type okcancel -icon info -title $caption -message "$msg"]
         if [string match ok $result] {
           puts $_active OK
           flush $_active
         } else {
           puts $_active CANCEL
           flush $_active
           catch {close $_active}
#           .fr.cancel configure -state disabled
#           .menubar.mFile entryconfigure "Open Grid File" -state normal
#           .menubar.mFile entryconfigure "Design-a-Grid" -state normal
           #wm deiconify .
         }
       }
       OKCANCELIGNORE {
         set result [tk_dialog .dialog $caption $msg info 0 Ok Cancel Ignore]
         if {$result == 0} {
           puts $_active OK
           flush $_active
         } elseif {$result == 1} {
           puts $_active CANCEL
           flush $_active
           catch {close $_active}
#           .fr.cancel configure -state disabled
#           .menubar.mFile entryconfigure "Open Grid File" -state normal
#           .menubar.mFile entryconfigure "Design-a-Grid" -state normal
           #wm deiconify .
         } elseif {$result == 2} {
           puts $_active IGNORE
           flush $_active
         }
       }
       PROGRESS {
#         gauge_value .fr.gauge $msg
         update
       }
       INPUT {
         set ndx1 [string first \[ $msg]
         set ndx2 [string first \] $msg]
         set response [string range $msg [expr $ndx1 + 1] [expr $ndx2 - 1]] ;#default response
         set msg [string range $msg 0 [expr $ndx1 - 1]]
         set result [my_inputdialog $caption $msg response]
         if {$result} {  ;#if OK pressed
           puts $_active $response
           flush $_active
         } else {        ;#if Cancel pressed
           puts $_active "CANCEL"
           flush $_active
           catch {close $_active}
#           .fr.cancel configure -state disabled
#           .menubar.mFile entryconfigure "Open Grid File" -state normal
#           .menubar.mFile entryconfigure "Design-a-Grid" -state normal
        #wm deiconify .
         }
       }
       END {
         catch {close $_active} IEE_error
#         .fr.cancel configure -state disabled
         tk_messageBox -type ok -icon info -title $caption -message "$msg"
#         .menubar.mFile entryconfigure "Open Grid File" -state normal
#         .menubar.mFile entryconfigure "Design-a-Grid" -state normal
      #wm deiconify .
       }
       default {
 #puts $mess
       }
     } ;#switch

     } ;#fileevent

   }
   .top.file.m add command -label "Exit" -underline 1 -command {
      exit
   }

   # **************************************************************************
   #this is the view button. Really only pertinent to the canvas with zooming...
   menubutton .top.view -text "View" -underline 0 -menu .top.view.m -pady 2
   menu .top.view.m -tearoff 0
   .top.view.m add cascade -label "Zoom In" -underline 5 -menu .top.view.m.zoom
      menu .top.view.m.zoom -tearoff 0
      .top.view.m.zoom add command -label "Drag Box w/ Mouse" \
         -command {
            set _areahint "Drag mouse over area to zoom to"
            set action zoom
            if {$Debug == "y"} {puts "the zoom action has been set"}
         }
      .top.view.m.zoom add command -label "Dialog Lat/Lon Entry" -underline 0 \
         -command {
            set _areahint "Enter Latitude/Longitude with precision up to 1/1000 of a degree"
            #same dialog box as define lat/lon dialog area...
            area_dialog_box $_limits(top) $_limits(bot) $_limits(left) $_limits(right) $_limits(z360)
            if {$_entry(1)!=""} {
               set _limits(top) [lindex [lindex $_entry(1) 0] 0]
               set _limits(bot) [lindex [lindex $_entry(1) 2] 0]
               set _limits(left) [lindex [lindex $_entry(1) 0] 1]
               set _limits(right) [lindex [lindex $_entry(1) 2] 1]
               if {$_limits(right) > $_limits(left)} {
                 set _limits(z360) 0
               } else {
                 set _limits(right) [expr $_limits(right) + 360.0]
                 set _limits(z360) 1
               }
               get_default_coast .mid.map $_limits(top) $_limits(bot) $_limits(left) $_limits(right) \
                                 coastname resfactor
               dialog_select_coast coastname resfactor
               get_coast_res_names $coastname $resfactor strcoast strres
               set _areahint "$strcoast at $strres"
               remap .mid.map $coastname $resfactor
               # this is just in case the user clicks on an action (such as
               # zoom or select) but then decides to go do something else -
               # we don't want the bindings hanging around... nullify 'em dude
            }
         }
   .top.view.m add command -label "Zoom Out" -underline 5 -command {
      set dif [expr ($_limits(top)-$_limits(bot))/4]
      set _limits(top) [expr $_limits(top)+$dif]
      if {$_limits(top)>90.0} {set _limits(top) 90.0}
      set _limits(bot) [expr $_limits(bot)-$dif]
      if {$_limits(bot)<-90.0} {set _limits(bot) -90.0}
      set dif [expr ($_limits(right)-$_limits(left))/4]
      set _limits(left) [expr $_limits(left)-$dif]
      set _limits(right) [expr $_limits(right)+$dif]
      if {$_limits(z360)} {
        if {$_limits(left) < 0.0} {
          set _limits(left) 0.0
        }
        if {$_limits(right) > 360.0} {
          set _limits(right) 360.0
        }
      } else { ;#not z360
        if {$_limits(left) >= 0.0} {  ;#all positive
           if {$_limits(right) > 180.0} {
             set _limits(z360) 1
           }
        } elseif {$_limits(right) <= 0} { ;#all negative
          if {$_limits(left) < -180.0} {
            set _limits(left) [expr $_limits(left) + 360.0]
            set _limits(right) [expr $_limits(right) + 360.0]
            set _limits(z360) 1
          }
        } else {
          if {$_limits(left) < -180.0} {
            set _limits(left) -180.0
          }
          if {$_limits(right) > 180.0} {
            set _limits(right) 180.0
          }
        }
      }
#parray _limits
      get_default_coast .mid.map $_limits(top) $_limits(bot) $_limits(left) $_limits(right) \
                                 coastname resfactor
      dialog_select_coast coastname resfactor
      get_coast_res_names $coastname $resfactor strcoast strres
      set _areahint "$strcoast at $strres"
      remap .mid.map $coastname $resfactor
   }
   .top.view.m add separator
   .top.view.m add command -label "World 180-180" -underline 6 -command {
      set _limits(top) 90.0
      set _limits(bot) -90.0
      set _limits(left) -180.0
      set _limits(right) 180.0
      set _limits(z360) 0
      set user_view A
      get_default_coast .mid.map $_limits(top) $_limits(bot) $_limits(left) $_limits(right) \
                                 coastname resfactor
      dialog_select_coast coastname resfactor
      get_coast_res_names $coastname $resfactor strcoast strres
      set _areahint "$strcoast at $strres"
      remap .mid.map $coastname $resfactor
   }
   .top.view.m add command -label "World 0-360" -underline 6 -command {
      set _limits(top) 90.0
      set _limits(bot) -90.0
      set _limits(left) 0.0
      set _limits(right) 360.0
      set _limits(z360) 1
      set user_view B
      get_default_coast .mid.map $_limits(top) $_limits(bot) $_limits(left) $_limits(right) \
                                 coastname resfactor
      dialog_select_coast coastname resfactor
      get_coast_res_names $coastname $resfactor strcoast strres
      set _areahint "$strcoast at $strres"
      remap .mid.map $coastname $resfactor
   }
#done creating the view menu
 
# *****************************************************************************
#this is the select area button. Pretty important for selecting boxes/polgyons...
   menubutton .top.select -text "Select Area" -underline 0 -menu .top.select.m -pady 2
   menu .top.select.m -tearoff 0
      .top.select.m add command -label "Clear Selection" -underline 0 \
         -state $ups_status -command {
         set _entry(0) [lreplace $_entry(0) end end] ;#replace last element with nothing
         if {$_entry(0) == {}} {
           .top.select.m entryconfigure "Clear Selection" -state disabled
           .top.select.m entryconfigure "Lat/Lon Box" -state normal
           .top.select.m entryconfigure "Polygon" -state normal
           .top.file.m entryconfigure "Save As..." -state disabled
         }
         remap .mid.map $coastname $resfactor
      }
      .top.select.m add separator

      .top.select.m add cascade -label "Lat/Lon Box" -underline 0 -menu .top.select.m.box
         menu .top.select.m.box -tearoff 0
         .top.select.m.box add command -label "Drag Box(s) w/ Mouse" -underline 15 \
            -command {
               set _areahint "Drag mouse over area to Select"
               set action select
            }
         .top.select.m.box add command -label "Dialog Lat/Lon Entry" -underline 0 \
            -command {

               set _areahint "Enter Latitude/Longitude with precision up to 1/1000 \
                   of a degree"
               area_dialog_box $_limits(top) $_limits(bot) $_limits(left) $_limits(right) $_limits(z360)
               #I must assign _entry(0) from _entry(1) here b/c I also
               #use function for mouse box zoom
               if {$_entry(1)!={}} {
                  set llon [lindex [lindex $_entry(1) 0] 1]
                  set rlon [lindex [lindex $_entry(1) 1] 1]
                  if {$rlon < $llon} {
                    set x180 1
                  } else {
                    set x180 0
                  }
                  toofaraway $x180
                  lappend _entry(0) $_entry(1)
                  draw_poly .mid.map $_entry(1)
                  .top.select.m entryconfigure "Clear Selection" -state normal
                  .top.select.m entryconfigure "Lat/Lon Box" -state disabled
                  .top.select.m entryconfigure "Polygon" -state disabled
                  .top.file.m entryconfigure "Save As..." -state normal
               }
               set _areahint "Use menu to select Map View, Select Area, etc."
            }
      .top.select.m add cascade -label "Polygon" -underline 0 -menu .top.select.m.poly
         menu .top.select.m.poly -tearoff 0
         .top.select.m.poly add command -label "Define Using Mouse" -underline 13 -command {
            set _areahint "Click Mouse Button to define each point. Double click last point (don't repeat first pt)"
            set action select
         }
         .top.select.m.poly add command -label "Dialog Lat/Lon Entry" -underline 0 \
            -command {

               set _areahint "Enter latitude/longitude pairs to define polygon area"
               area_dialog_poly
               
               if {$_entry(1)!={}} {
                  .top.select.m entryconfigure 0 -state normal
                  toofaraway $_limits(z360) ;#base decision of which-way-around-world on current map
                  lappend _entry(0) $_entry(1)
                  draw_poly .mid.map $_entry(1)
                  .top.select.m entryconfigure "Clear Selection" -state normal
                  .top.select.m entryconfigure "Lat/Lon Box" -state disabled
                  .top.select.m entryconfigure "Polygon" -state disabled
                  .top.file.m entryconfigure "Save As..." -state normal
               }
               set _areahint "Use menu to select Map View, Select Area, etc."
            }
#end definitions on select area menubutton

  button .top.help -text Help -underline 0 -command {
    help h_howce.htm
  }


   pack .top.file .top.view .top.select .top.help -side left
#this tk function sets up default bindings for traversal across menus...
   tk_menuBar .top .top.file .top.view .top.select .top.help

   #set up the neato little hints bar at the bottom of the screen!
   label .bot.hint -textvariable _areahint -anchor w
   pack .bot.hint -side left


   #At this point I would do something with .mid because that's where I'll stick the canvas...
   canvas .mid.map -bg white -relief flat -borderwidth 0 -highlightthickness 0

   #Tkwait is necessary to assign the proper aspect ratios, otherwise it can't
   #calculate the size of the parent window...
   tkwait visibility .mid
   #below won't work; iguess .mid.map not ready for prime time
   #get_default_coast .mid.map $_limits(top) $_limits(bot) $_limits(left) $_limits(right) \
                      coastname resfactor
   set coastname hersey
   set resfactor 1
   get_coast_res_names $coastname $resfactor strcoast strres
   set _areahint "$strcoast at $strres"
   remap .mid.map $coastname $resfactor
   set _a_lastx -1
   set _a_lasty -1
   set _a_poly 0
   set _a_width [winfo width .]
   set _a_height [winfo height .]

   #This checks to see if the window size changed. If so, it redraws the map.
   bind . <Configure> {
      if {([winfo width .]!=$_a_width) || ([winfo height .]!=$_a_height)} {
         set _a_width [winfo width .]
         set _a_height [winfo height .]
         update
         remap .mid.map $coastname $resfactor
      }
   }
   # editions, 6/98

 #puts "action:$action"
   if {$Debug =="y"} {puts "we're at the while loop..."}
   while {![string match exit $action]} {
      #This is the select case - a few pages below is the zoom case 6/98
      if {$action == "select"} {
         #button one is either a polygon -- _a_poly>=2 or else a box _a_poly=0
         #if button one is released and _a_poly is 0, it draws a box, otherwise,
         #it's a polygon point & it'll connect to the last point set...
         bind .mid.map <1> {
            if {$_a_poly!=0} { ;#polygon
               incr _a_poly
               set w [winfo width .mid.map]
               set h [winfo height .mid.map]

               #if this is the second point, register it as such
               if {$_a_poly==2} {
                  set lon [expr ($_a_lastx*($_limits(right)-$_limits(left)))/$w+$_limits(left)]
                  set lat [expr ($h-$_a_lasty)*($_limits(top)-$_limits(bot))/$h+$_limits(bot)]
                  if {$_limits(right)>180 && $lon>180} {set lon [expr $lon-360.0]}
                  lappend _entry(1) [list $lat $lon]
                  set _a_firstx $_a_lastx
                  set _a_firsty $_a_lasty
               }

               #draw a line
               set x [.mid.map canvasx %x]
               set y [.mid.map canvasy %y]
               set lon [expr ($x*($_limits(right)-$_limits(left)))/$w+$_limits(left)]
               set lat [expr ($h-$y)*($_limits(top)-$_limits(bot))/$h+$_limits(bot)]
               if {$_limits(right)>180 && $lon>180} {set lon [expr $lon-360.0]}
               lappend _entry(1) [list $lat $lon]

               .mid.map create line $_a_lastx $_a_lasty $x $y -fill blue
         
               set _a_lastx $x
               set _a_lasty $y
            } else {    ;#box
               set _a_lastx [.mid.map canvasx %x]
               set _a_lasty [.mid.map canvasy %y]
               set _a_poly 1
               set _entry(1) {} 
               set sizebox {}
            }
         }

         bind .mid.map <Double-Button-1> {
            if {$_a_poly>=2} {   ;#polygon
               set w [winfo width .mid.map]
               set h [winfo height .mid.map]

               #puts the last series of points into _entry(1)
               set lon [expr ($_a_lastx*($_limits(right)-$_limits(left)))/$w+$_limits(left)]
               set lat [expr ($h-$_a_lasty)*($_limits(top)-$_limits(bot))/$h+$_limits(bot)]
               if {$_limits(right)>180 && $lon>180} {set lon [expr $lon-360.0]}
               lappend $_entry(1) [list $lat $lon]

               #draws a line from the last point to current point
               #then draws a line from the current point to starting point...
               set x [.mid.map canvasx %x]
               set y [.mid.map canvasy %y]
               .mid.map create line $_a_lastx $_a_lasty $x $y -fill blue
               .mid.map create line $_a_firstx $_a_firsty $x $y -fill blue
          
               #stores the polygon away in _entry(0)

               if {$_entry(1)==""} continue
               toofaraway $_limits(z360) ;#check any pts > 180 deg apart add a pt...

               lappend _entry(0) $_entry(1)   ;#adds this list to areas list, methinks

               #tell everybody that I'm not drawing a polygon anymore...
               set _a_poly 0
               .top.select.m entryconfigure "Clear Selection" -state normal
               .top.select.m entryconfigure "Lat/Lon Box" -state disabled
               .top.select.m entryconfigure "Polygon" -state disabled
               .top.file.m entryconfigure "Save As..." -state normal
               set action nothing
            }
         }

         bind .mid.map <B1-Motion> {
            if {($_a_lastx!=-1) && ($_a_poly<=1)} {
               .mid.map delete $sizebox
               set x [.mid.map canvasx %x]
               set y [.mid.map canvasy %y]
               set sizebox \
               [.mid.map create rect $_a_lastx $_a_lasty $x $y -outline blue]
               set _a_poly 0
            }
         }
         bind .mid.map <ButtonRelease-1> {
            #this binding takes a square drawn by a button 1 (search square) and
            #then translates the corners to points on a list... 
            if {$_a_poly==0} { 
               set x [.mid.map canvasx %x]
               set y [.mid.map canvasy %y]
               set w [winfo width .mid.map]
               set h [winfo height .mid.map]
   
               #checks to see if it's just a dot...
               if {($_a_lastx!=%x) && ($_a_lasty!=%y)} {
                  set x1 [expr ($x*($_limits(right)-$_limits(left)))/$w+$_limits(left)]
                  if {$x1 < $_limits(left)} {
                    set x1 $_limits(left)
                  } elseif {$x1 > $_limits(right)} {
                    set x1 $_limits(right)
                  }
                  set x2 [expr ($_a_lastx*($_limits(right)-$_limits(left)))/$w+$_limits(left)]
                  set y1 [expr ($h-$y)*($_limits(top)-$_limits(bot))/$h+$_limits(bot)]
                  if {$y1 > $_limits(top)} {
                   set y1 $_limits(top)
                 } elseif {$y1 < $_limits(bot)} {
                   set y1 $_limits(bot)
                 }
                  set y2 [expr ($h-$_a_lasty)*($_limits(top)-$_limits(bot))/$h+$_limits(bot)]
                  if {$x1 > $x2} {
                     set l $x2
                     set r $x1
                  } else {
                     set l $x1
                     set r $x2
                  }
                  if {$y1 > $y2} {
                     set t $y1
                     set b $y2
                  } else {
                     set t $y2
                     set b $y1
                  }
                  if {$_limits(z360)} {
                     if {$r > 180} {set r [expr $r-360.0]}
                     if {$l > 180} {set l [expr $l-360.0]}
                  }
     
                  set _entry(1) {}
                  lappend _entry(1) [list $t $l] [list $t $r] [list $b $r] \
                                       [list $b $l]

                  if {$_entry(1)==""} continue
                  toofaraway $_limits(z360)

                  lappend _entry(0) $_entry(1)
                  set _entry(1) {}
                  #I don't need to draw a poly here because it's already        mapped...
                  set _a_lastx -1
                  set _a_lasty -1
                  .top.select.m entryconfigure "Clear Selection" -state normal
                  .top.select.m entryconfigure "Lat/Lon Box" -state disabled
                  .top.select.m entryconfigure "Polygon" -state disabled
                  .top.file.m entryconfigure "Save As..." -state normal
                  set action nothing
               } else {
                   .mid.map delete $sizebox
               }
               set _a_poly 0
            }
         } ;#bind  
      } ;#if {$action == "select"} 
# ***********************************************************************************
      #If zoom has been selected, the proper bindings are set...
      if {$action == "zoom"} {
         bind .mid.map <Double-Button-1> {} ;#kill this binding
         bind .mid.map <1> {
            set _a_lastx [.mid.map canvasx %x]
            set _a_lasty [.mid.map canvasy %y]
            set sizebox {}
         }
   
         bind .mid.map <B1-Motion> {
            if {$_a_lastx!=-1} {
               .mid.map delete $sizebox
               set x [.mid.map canvasx %x]
               set y [.mid.map canvasy %y]
               set sizebox \
               [.mid.map create rect $_a_lastx $_a_lasty $x $y -outline red]
            }
         }

         bind .mid.map <ButtonRelease-1> {
         #this binding checks to see if a square for a zoom has been drawn
         #if it has, it translates the screen coords to lat lons and then 
         #attempts to redraw the map appropriately.
            set x [.mid.map canvasx %x]
            set y [.mid.map canvasy %y]
            set w [winfo width .mid.map]
            set h [winfo height .mid.map]
 #puts "bounds: $_limits(top) $_limits(bot) $_limits(left) $_limits(right)"
            if {($_a_lastx!=%x) && ($_a_lasty!=%y)} {
               set x1 [expr ($x*($_limits(right)-$_limits(left)))/$w+$_limits(left)]
               if {$x1 < $_limits(left)} {
                 set x1 $_limits(left)
               } elseif {$x1 > $_limits(right)} {
                 set x1 $_limits(right)
               }
               set x2 [expr ($_a_lastx*($_limits(right)-$_limits(left)))/$w+$_limits(left)]
               set y1 [expr ($h-$y)*($_limits(top)-$_limits(bot))/$h+$_limits(bot)]
                if {$y1 > $_limits(top)} {
                 set y1 $_limits(top)
               } elseif {$y1 < $_limits(bot)} {
                 set y1 $_limits(bot)
               }
               set y2 [expr ($h-$_a_lasty)*($_limits(top)-$_limits(bot))/$h+$_limits(bot)]
               if {$x1 > $x2} {
                  set _limits(left) $x2
                  set _limits(right) $x1
               } else {
                  set _limits(left) $x1
                  set _limits(right) $x2
               }
               if {$y1 > $y2} {
                  set _limits(top) $y1
                  set _limits(bot) $y2
               } else {
                  set _limits(top) $y2
                  set _limits(bot) $y1
               }
               if {$_limits(z360)} {
                 if {$_limits(right) <= 180.0} {
                   set _limits(z360) 0
                 } elseif {$_limits(left) >= 180.0} {
                   set _limits(left) [expr $_limits(left) - 360.0]
                   set _limits(right) [expr $_limits(right) - 360.0]
                   set _limits(z360) 0
                 }
               }
               get_default_coast .mid.map $_limits(top) $_limits(bot) $_limits(left) $_limits(right) \
                                 coastname resfactor
               dialog_select_coast coastname resfactor
               get_coast_res_names $coastname $resfactor strcoast strres
               set _areahint "$strcoast at $strres"
               remap .mid.map $coastname $resfactor
               set _a_lastx -1
               set _a_lasty -1
               set action nothing
            } else {
               .mid.map delete $sizebox
            }
         }
      } ;#if {$action == "zoom"}

      if {$action != "zoom" && $action != "select"} {
        bind $m.map <1> {}
        bind $m.map <B1-Motion> {}
        bind $m.map <Double-Button-1> {}
        bind $m.map <ButtonRelease-1> {}
      }


      update
      if {$Debug =="y"} {
      puts "we're just past the bindings and the value of action is:$action"
      }
      # the program should wait here if the condition in my comment 
      # above isn't met.
      if ![string match exit $action ] {
         tkwait variable action
      }
      if {$Debug == "y"} {puts "this is the end of the bindings...."}
      # end of bindings
   } ;# end of while loop

   if {$Debug == "y"} {puts "the while loop has been exited"}

   destroy .  ;#or exit???
#end  of coastline extractor

