;+
; NAME:
;       egso_query_dso
; PURPOSE:
;       Executes the specified SQL query against the DSO
; CALLING SEQUENCE:
;       result = egso_query_dso(query)
;
; INPUTS:
;       query        sql query to be submitted  (format specified elsewhere)
; OUTPUTS:
;       result       string containing returned VOTable
; KEYWORDS: 
;       backup       use 2ndry Special Provider server  (def is primary)
;       endpoint     specify endpoint URL to be used (instead of primary URL)
;       save         save returned string as file
;
; RESTRICTIONS:
;       Must be connected to Internet to work correctly
;       JAVA version 1.4 or later required
; HISTORY:
;       02-Nov-2004  Written by Bob Bentley (MSSL/UCL)
;                    Based on routine be Nathan Ching (nc@mssl.ucl.ac.uk)
;       21-Apr-2005  rdb  generalize, updated node used for DSO
;                         added backup keyword to call 2nd server
;       05-May-2005  rdb  added address of 2nd server
;       12-May-2005  rdb  small amount of tidying
;       30-May-2005  rdb  Moved selection of node into egso_specprov_node; tidying
;       08-Jan-2007  rdb  Made use of backup switch more consistent
;
;-

FUNCTION egso_query_dso, query, endpoint=endpoint, backup=backup, $
	save=save, verbose=verbose

services_home = GETENV("EGSO_RELATED")

IF services_home eq '' THEN BEGIN
   MESSAGE, "The EGSO_RELATED environment variable is not assigned"
   return, ''

endif else begin

;   Set the wrapper script to use according to OS family
  IF (!VERSION.OS_FAMILY EQ "windows") THEN begin
;          exec = services_home + "\bin\dso.bat" $
           box_message,'Windows not yet supported'
	   return, ''
      endif ELSE exec = services_home + "/bin/dso.sh"

;   Set the command and endpoint
  IF KEYWORD_SET(endpoint) THEN BEGIN
    node = endpoint
    if not have_network(node,/reset) then message, 'Problem with node: '+node
  ENDIF ELSE BEGIN
    node = egso_specprov_node(/dso, backup=backup)
    if datatype(node) ne 'STR' then message,'NO working node found - DSO'
  ENDELSE

  command = [ exec, "-e", node, query ]  
  print,''
  if keyword_set(verbose) then print, '* Trying Query: ',command
  
  ; Spawn the command
  tm0 = systime(1)
  exit_status = 0
  SPAWN, command, result, error, /NOSHELL, EXIT_STATUS=exit_status
  print,'CMD spawn took:',systime(1)-tm0

  ; Return result or report error
  if (exit_status > 0) then begin
    message, "*** Query Failed ***",/cont
    if max(strpos(error,'NoSuchMethodError')) gt 0 then $
	message,'JAVA V1.4 or later required - please ensure you are running this',/cont
    print,''
    print,error
    print,''
    print,'Command was: ',command
    return,''
  endif
  
endelse

if keyword_set(save) then begin
  filename = name_egso_votable(/dso)
  print,'* Writing VOTable to: ',filename
  openw,lun,filename,/get_lun
  printf,lun,result             ; strjoin(result) ???
  free_lun,lun
endif

RETURN, result

END
