;+
; NAME:
;     WGETGPS
; PURPOSE:
;     WIDGET program to show global positioning satellite information, including
;     HA and DEC pointing coordinates.  What is shown in the table is the
;     rise/set times and positions over 24 h on today's date.  When a satellite
;     is selected, the HA and DEC is plotted for the selected satellite, for
;     the duration of its visible period.  The term visible means it is in a part
;     of the sky that the small antennas can point to.
; CATEGORY:
;     OVRO APC SCHEDULE
; CALLING SEQUENCE:
;     wgetgps,sat=sat,satinfo=satinfo
; INPUTS:
; OPTIONAL (KEYWORD) INPUT PARAMETERS:
;     sat   a pointer to a structure that contains information about the
;             selected satellite.
; ROUTINES CALLED:
; OUTPUTS:
; COMMENTS:
; SIDE EFFECTS:
; RESTRICTIONS:
; MODIFICATION HISTORY:
;     Written 13-Mar-2005 by Dale E. Gary
;     31-Jul-2007  DG
;       Completely rewritten to use the new, more accurate coordinates
;       from SP3 files.
;     11-Jan-2011  DG
;       Some kind of crazy bug where case of no good times for a satellite
;       was not handled properly.  Now fixed.
;-

PRO WGetGPS_Event, Event

  base = Event.handler
  stash = WIDGET_INFO(base, /CHILD)
  WIDGET_CONTROL, stash, GET_UVALUE=state, /NO_COPY

  WIDGET_CONTROL,Event.Id,GET_UVALUE=Ev
  if (size(Ev,/type) ne 7) then Ev = Event.value

  CASE Ev OF
   'TAB_SEL': BEGIN
         if (Event.Type eq 4) then begin
            state.select = [Event.sel_left,Event.sel_top,$
                            Event.sel_right,Event.sel_bottom]
            if (state.select[0] eq 0 and state.select[2] eq 7) then begin
               ; This is a potentially good selection
               if (state.select[1] eq state.select[3]) then begin
                  row = state.select[1]
                  i = row
                  out = state.sat
                  ; This is a valid selection
                  widget_control,state.TableId,get_value=satlist

                  ; Extract satellite name from satlist (column 7)
                  satname = strmid(satlist[6,i],0,1)+strmid(satlist[6,i],4,2)
                  ; Compare with satellite list to find index of satellite
                  k = where(out.name eq satname,n)

                  ; Extract start and end times (columns 1 and 2) and convert to
                  ; indexes j1 and j2
                  hh = (mm = 0)
                  reads,satlist[0,i],hh,mm,format='(I2,1x,I2)'
                  j1 = (hh*60+mm)/5 + 288
                  reads,satlist[1,i],hh,mm,format='(I2,1x,I2)'
                  j2 = (hh*60+mm)/5 + 288

                  if (state.ShowPlot eq 1) then begin
                     WIDGET_CONTROL,state.PlotiD,GET_VALUE=wid
                     wset,wid
                     ; Plot 24 hour path of satellite
                     plot,out.ha[j1:j2,k],out.dec[j1:j2,k],xran=[-60,60],yran=[-20,60],$
                        psym=1,title='Trajectory for '+strmid(satlist[6,i],0,6)+' for '$
                        +string(state.yr,state.doy,format='(I4,",",I3.3)'),background=255,color=0,$
                        xtit='Hour Angle (degrees)',ytit='Declination (degrees)'
                     npts = j2-j1+1
                     ishow = where(((indgen(npts)+j1-288) mod 6) eq 0,nshow)+j1
                     if (nshow ne 0) then ishow = [j1,ishow,j2] else ishow = [j1,j2]
					 nshow = nshow + 2
					 off = (out.ha[j1,k] gt 0) ? -6 : 6
					 ha = (out.ha[*,k])[ishow]+off
					 dec = (out.dec[*,k])[ishow]-1
                     for j = 0, nshow-1 do begin
                        hms = strmid(msec2str(((out.jd[ishow[j]]-0.5d) mod 1.0d)*86400000d),1,5)
                        xyouts,ha[j],dec[j],hms,charsize=0.7,color=0,align=0.5
                     endfor
                     oplot,(out.ha[*,k])[ishow],(out.dec[*,k])[ishow],psym=1,color=0,thick=2
                  endif
                  ; Return info for the selected satellite
				  *state.pinfo = [j1,j2,k]
               endif
            endif
         endif
      END
   'Show Plot': BEGIN
         state.showplot = 1-state.showplot
         if (state.showplot eq 1) then begin
            PlotID = WIDGET_DRAW(state.CrossBase,XSIZE=410,YSIZE=300)
            WIDGET_CONTROL, PlotID, GET_VALUE=wid
            wset,wid
            erase,255
            state.PlotID = PlotID
         endif else begin
            WIDGET_CONTROL, state.PlotID, /DESTROY
            state.PlotID = 0L
         endelse
      END
   'EXIT_BUTTON': BEGIN
        ;(*state.pSat).Open = 0
        WIDGET_CONTROL, base, /DESTROY
        RETURN
      END
    ELSE:
  ENDCASE
WRITE_STATE:
  WIDGET_CONTROL, stash, SET_UVALUE=state, /NO_COPY

END

;--------------------------------------------------------------------------

PRO WGetGPS, wBase, GROUP=Group, sat=pSAT,info=pinfo

  IF N_ELEMENTS(Group) EQ 0 THEN GROUP=0

;  SAT = {SAT,Name:'',HA:0.d,DEC:0.d,Open:1,Num:''}

  IF (n_elements(wBase) eq 0) THEN BEGIN
      wBase = WIDGET_BASE(GROUP_LEADER=Group, $
                 COLUMN=1, $
                 MAP=1, XOFFSET=400,YOFFSET=278,$
                 TITLE='WGetSats : Geostationary Satellite Info', $
                 UVALUE='GetSatMain')
  ENDIF

  BASE2 = WIDGET_BASE(wBase, $
      COLUMN=1, $
      MAP=1, $
      TITLE='ExtraBase', $
      UVALUE='BASE2')

  Crossbase = WIDGET_BASE(wBase, COLUMN=1, MAP=1,TITLE='Crossbase')

  curtime = strmid(systime(),10,6)

  ; Get Julian date for today
  jd = systime(/jul)

  ; Convert to modified Julian date
  mjd = jd - 2400000.5D

  ; Get satellite list for today
;  sat = getgpslist(jd)
;  nsat = n_elements(sat)
;  IF (n_elements(pSAT) NE 0) THEN *pSAT = sat[0] else pSat = ptr_new(sat[0])

  sat = *pSAT
  nsat = n_elements(sat.name)
  pgood = ptrarr(nsat*2)
  firstgood = intarr(nsat*2)
  isat = intarr(nsat*2)
  k = 0
  for i = 0, nsat-1 do begin
     good = where(sat.ha[*,i] gt -60 and sat.ha[*,i] le 60 and sat.dec[*,i] gt -20 and sat.dec[*,i] lt 45,ngood)
     ng2 = 0
     if (ngood ne 0) then begin
        g2 = where(good ge 288,ng2)
        if (ng2 ne 0) then good = good[g2] else good = -1
     endif
     if (ng2 ne 0) then begin
        ; split into contiguous sections
        isplt = where(good-shift(good,1) gt 1,nsplt)
        for j = k,k+nsplt do begin
           if (j eq k) then is = 0 else is = isplt[j-k-1]
           if (j eq k+nsplt) then ie = n_elements(good)-1 else ie = isplt[j-k]-1
           pgood[j] = ptr_new(good[is:ie])
           firstgood[j] = good[is]
           isat[j] = i
        endfor
        k = k + nsplt+1
     endif else begin
        ; No good values
        ;pgood[k] = ptr_new(good[0])
        ;firstgood[k] = good[0]
        ;isat[k] = i
        ;k = k + 1
     endelse
  endfor
  firstgood = firstgood[0:k-1]
  nsat = k
  ; Now have array of pointers to good indexes.  Sort them to get chronological order
  ksrt = sort(firstgood)

  ; Put SATELLITE information into a nice tabular form for the table.
  table = strarr(8,nsat)
  row_labels = strarr(nsat)
  for i = 0, nsat-1 do begin
     k = ksrt[i]
     ksat = isat[k]
     kmin = (*pgood[k])[0]
     kmax = (*pgood[k])[n_elements(*pgood[k])-1]
     table[0,i] = strmid(msec2str(((sat.jd[kmin]-0.5d) mod 1.0d)*86400000d),1,5)
     table[1,i] = strmid(msec2str(((sat.jd[kmax]-0.5d) mod 1.0d)*86400000d),1,5)
     table[2,i] = string(sat.ha[kmin,ksat],format='(F8.3)')
     table[3,i] = string(sat.ha[kmax,ksat],format='(F8.3)')
     table[4,i] = string(sat.dec[kmin,ksat],format='(F8.3)')
     table[5,i] = string(sat.dec[kmax,ksat],format='(F8.3)')
     table[6,i] = strmid(sat.name[ksat],0,1)+'PS '+strmid(sat.name[ksat],1,2)
     table[7,i] = string(0,format='(I2)')
     row_labels[i] = table[6,i]
  endfor

  yr = strmid(systime(),20,4)
  doy = string(sysdoy(systime()),format='(I3.3)')
  timestr = ' GPS Satellite Information for '+yr+','+doy

  colbase = WIDGET_BASE(Crossbase,/COLUMN)
  titleBase = WIDGET_BASE(colBase,/ROW)

  font = 'Arial*20*Bold'
  clock = WIDGET_LABEL(titleBase,/dynamic_resize,FONT=font,VALUE=timestr,FRAME=1)
  font = !defaults.font
  X = WIDGET_BUTTON(titleBase,VALUE='X',UVALUE='EXIT_BUTTON')
  TableId = WIDGET_TABLE(ColBASE,VALUE=table,COLUMN_WIDTHS=[40,40,50,50,50,50,50,30],$;[70,40,100,70,70],$
       COLUMN_LABELS=['Rise','Set','HA(rise)','HA(set)','Dec(rise)','Dec(set)','NAME','Age'],$
       ROW_LABELS=row_labels,$
       XSIZE=8,X_SCROLL_SIZE=8,YSIZE=nsat,Y_SCROLL_SIZE=8,ALIGNMENT=1,UVALUE='TAB_SEL',$;FONT=font,
       /ALL_EVENTS)

  ButtonBase = WIDGET_BASE(ColBase,ROW=1,MAP=1)
  ShowID = CW_BGROUP(ButtonBase,['Show Plot'],/NON,SET_VALUE=0, /COLUMN, /RETURN_NAME)

  WIDGET_CONTROL, wBase, /REALIZE

  pinfo = ptr_new([0,0,0])
  state = {TableID:TableID,CLOCK:clock,JD:JD,pinfo:pinfo,select:[0,0,0,0],yr:yr,doy:doy,$
             sat:sat,Nums:row_labels,crossbase:crossbase,showplot:0b,plotID:0L}

  ; Connect the STATE structure to the first child of the base widget

  WIDGET_CONTROL, WIDGET_INFO(wBase, /CHILD), SET_UVALUE=state, /NO_COPY

  XMANAGER, 'WGetGPS', wBase, /NO_BLOCK

END
