; Created Aug 14, 2004
; Executes the specified SQL query against the SEC
; Nathan Ching (nc@mssl.ucl.ac.uk)

; 	18-Nov-2004  rdb  set node to be the same as endpoint
;	                  enabled windows branch for testing

FUNCTION egso_query_sfc, query, endpoint=endpoint, save=save, verbose=verbose

services_home = GETENV("SERVICES_HOME")

IF (NOT KEYWORD_SET(services_home)) THEN BEGIN
   MESSAGE, "The SERVICES_HOME 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\sfc.bat"
           box_message,'WINDOWS version not yet tested'
;	   return, ''
      endif ELSE exec = services_home + "/bin/sfc.sh"

;   Set the command and endpoint
  IF KEYWORD_SET(endpoint) THEN BEGIN
          command = [ exec, "-e", endpoint, query ]
          node = endpoint
  ENDIF ELSE BEGIN
          command = [ exec, query ]
          node = 'linux2.inf.brad.ac.uk'
  ENDELSE

  print,''
  if keyword_set(verbose) then print, '* Trying Query: ',command
  if not have_network(node,/reset) then begin
    err_mess = 'Verify that you are connected to the network and retry'
    message,err_mess,/cont
    xtext,['Problem in trying to contact: '+node, err_mess],wait=10,/just_reg,title='EGSO_QUERY_SFC'
    return,''
  endif else message,'Network connection check OK: '+node,/cont
  
  ; Spawn the command
  exit_status = 0
  SPAWN, command, result, error, /NOSHELL, EXIT_STATUS=exit_status

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

if keyword_set(save) then begin
  caldat,systime(/julian),mon,dd,yy,hh,min,ss
  dstr = string(yy,mon,dd,hh,min,fix(ss),format='(i4.2,2i2.2,1h_,3i2.2)')
  filename = 'SFC_'+dstr+'.xml'
  print,'* Writing VOTable to: ',filename
  openw,lun,filename,/get_lun
  printf,lun,result             ; strjoin(result) ???
  free_lun,lun
endif

RETURN, result

END
