;+
; NAME:
;     WREGION
; PURPOSE:
;     WIDGET program to show solar active region information, including
;     pointing offsets.  Solar data are obtained from the EPHEM.REC file,
;     which is included in each data scan.
; CATEGORY:
;     OVRO APC SCHEDULE
; CALLING SEQUENCE:
;     wregion
; INPUTS:
; OPTIONAL (KEYWORD) INPUT PARAMETERS:
; ROUTINES CALLED:
; OUTPUTS:
; COMMENTS:
; SIDE EFFECTS:
; RESTRICTIONS:
; MODIFICATION HISTORY:
;     Written 17-Mar-1999 by Dale E. Gary
;     27-Jul-1999  DG
;       Significant changes to allow it to work more closely with the SCHEDULE.
;       The routine can be run within the widget heirarchy of SCHEDULE now,
;       and sends back information on the active region selected.
;     11-Jan-2000  DG
;       Eliminated hardwired directory locations.
;     22-Jul-2005  DG
;       Add code to handle case of NO numbered regions on disk
;-

pro set_labels,TableID

   curtime = strmid(systime(),10,6)
   WIDGET_CONTROL,TableID,GET_VALUE=table
   ncal = n_elements(table(0,*))
   row_labels = strarr(ncal)
   for i = 0, ncal-1 do begin
      rise = table(3,i)
      set =  table(4,i)
      row_labels(i) = '  '
      ; Determine if the source is up
      ; Add 24 h to set time for comparison with current time, if set < rise
      cursave = curtime
      if (set lt rise) then begin
         if (curtime lt set) then begin
            strput,curtime,string(strmid(curtime,1,2)+24,format='(i2)'),1
         endif
         strput,set,string(strmid(set,1,2)+24,format='(i2)'),1
      endif
      ; Add 24 h to curtime for comparison with rise time, if curtime
      if (rise lt curtime) and (set gt curtime) then begin
         hh = fix(strmid(set,1,2)) - fix(strmid(curtime,1,2))
         mm = fix(strmid(set,4,2)) - fix(strmid(curtime,4,2))
         if (mm lt 0) then begin
            hh = hh - 1
            mm = mm + 60
         endif
         row_labels(i) = 'UP for '+string(hh,mm,format='(I2.2,":",I2.2)')
      endif
      curtime = cursave
   endfor
   WIDGET_CONTROL,TableID,ROW_LABELS=row_labels
return
end

;--------------------------------------------------------------------------

PRO WRegion_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

  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]
            (*state.pAR).Name = ''
            if (state.select[0] eq 0 and state.select[2] eq 4) then begin
               ; This is a potentially good selection
               if (state.select[1] eq state.select[3]) then begin
                  row = state.select[1]
                  ; This is a valid selection
                  widget_control,state.TableId,get_value=ARlist
                  (*state.pAR).name = state.names[row]
                  (*state.pAR).HAO  = fix(ARlist[3,row]*1000.)
                  (*state.pAR).DECO = fix(ARlist[4,row]*1000.)
               endif
            endif
         endif
      END
   'EXIT_BUTTON': BEGIN
        (*state.pAR).Open = 0
        WIDGET_CONTROL, base, /DESTROY
        RETURN
      END
  ENDCASE
WRITE_STATE:
  WIDGET_CONTROL, stash, SET_UVALUE=state, /NO_COPY

END

;--------------------------------------------------------------------------

PRO WRegion, wBase, GROUP=Group, ar=pAR

  IF N_ELEMENTS(Group) EQ 0 THEN GROUP=0

  IF (n_elements(pAR) EQ 0) THEN BEGIN
     AR = {AR,Name:'',HAO:0,DECO:0,Open:0}
     pAR = ptr_new(AR)
  ENDIF

  IF (n_elements(wBase) eq 0) THEN BEGIN
      wBase = WIDGET_BASE(GROUP_LEADER=Group, $
                 COLUMN=1, $
                 MAP=1, XOFFSET=400,YOFFSET=278,$
                 TITLE='WRegion : Solar Active Region Info', $
                 UVALUE='RegionMain')
  ENDIF

  BASE2 = WIDGET_BASE(wBase, $
      COLUMN=1, $
      MAP=1, $
      TITLE='ExtraBase', $
      UVALUE='BASE2')

  curtime = strmid(systime(),10,6)

  ; Get Julian date for 20:00 UT today
  jd = long(systime(/jul)+0.5) - 0.5D + 20./24.
  ; Convert to modified Julian date
  mjd = jd - 2400000.D

  ; Get solar P-angle, B-angle and radius for today to 20 UT
  pandb,mjd,p,b,r
  ; Calculate the angle a region at the equator would rotate in 20 h
  rotangle = 13.83*(20./24.)  ; Equatorial rotation rate (degrees)
  HT = 10.   ; Height of the radio limb (10")

  ; Get EPHEM structure from EPHEM.REC file
  filename = !defaults.ephemdir+'ephem.rec'
  openr,lun,/get_lun,filename
  a = assoc(lun,intarr(1024))
  data = a(0)
  free_lun,lun
  ephem = decode(data,!SEGM.EPHEM)
  tls = tl_decode(data)

  ; Extract the REGION structure from the EPHEM structure
  regn = ephem.regn
  nregn = regn.nregn

  if (nregn eq 0) then begin
     ; Case of no numbered regions
     table = strarr(5,1)
     row_labels = ['SUNCTR']
     NS = 'N'
     EW = 'E'
     lat = 0
     lng = 0

     table[0,0] = string(NS,abs(lat),EW,abs(lng),format='(A1,I2.2,A1,I2.2)')
     table[1,0] = '   0'
     table[2,0] = 'No Region '
     table[3,0] = string(0.,format='(F6.3)')
     table[4,0] = string(0.,format='(F6.3)')

  endif else begin
     ; Put REGION structure information into a nice tabular form for the table.
     table = strarr(5,nregn)
     row_labels = strarr(nregn)
     for i = 0, nregn-1 do begin
        row_labels(i) = string(regn.info(i).noa,format='("AR",I4)')
        NS = 'N'
        EW = 'E'
        lat = regn.info(i).lat
        lng = regn.info(i).lng

        ; Get new longitude, correcting rotation rate for dependence
        ; on latitude (from Newton-Nunn formula) [NB: -rotangle because
        ; of definition of longitude as +E]
        lng = lng - rotangle*(1-0.2058*(sin(lat*!dtor)^2))
;     if (lng lt -90) then lng = -90 + lng

        if (lat lt 0) then NS = 'S'
        if (lng lt 0) then EW = 'W'
        table(0,i) = string(NS,abs(lat),EW,abs(lng),format='(A1,I2.2,A1,I2.2)')
        table(1,i) = string(regn.info(i).area,format='(I4)')
        table(2,i) = strmid(regn.info(i).magtype+'     ',0,10)

        ; Determine offsets [NB: Use -lng because of definition of longitude as +E]
        cnv_h2xy,p,b,r+HT,lat,-lng,x,y

        ; Convert offsets in arcsec to degrees HAO and DECO
        table(3,i) = string(x/3600.,format='(F6.3)')
        table(4,i) = string(y/3600.,format='(F6.3)')

     endfor
  endelse

  yr = strmid(systime(),20,4)
  doy = string(sysdoy(systime()),format='(I3.3)')
  timestr = ' Active Region Coordinates for '+tls.yrday+' at 20:00 UT '

  titleBase = WIDGET_BASE(wBase,/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(wBASE,VALUE=table,COLUMN_WIDTHS=[50,30,75,50,50],$;[70,40,100,70,70],$
       COLUMN_LABELS=['Coords','Area','Type','HAO','DECO'],ROW_LABELS=row_labels,$
       XSIZE=5,YSIZE=nregn,ALIGNMENT=1,UVALUE='TAB_SEL',$;FONT=font,
       /ALL_EVENTS)

  WIDGET_CONTROL, wBase, /REALIZE

  state = {TableID:TableID,CLOCK:clock,JD:JD,pAR:pAR,select:[0,0,0,0],Names:row_labels}

  ; Connect the STATE structure to the first child of the base widget

  WIDGET_CONTROL, WIDGET_INFO(wBase, /CHILD), SET_UVALUE=state, /NO_COPY

  XMANAGER, 'WRegion', wBase, /NO_BLOCK

END
