; Copyright (c) 2003, Max Planck Institute for Aeronomy
;   Unauthorized reproduction prohibited.
;+
; CLASS_NAME:
;   correlate_tab__define
;
; PURPOSE:
;   This defines the correlate_tab plugin module for the GUI tool.
;
; CATEGORY:
;   Main Module
;
; SUPERCLASSES:
;       Inherits from the plugin class
;
; SUBCLASSES:
;       List classes that inherit from this class, if any.
;
; CREATION:
;       Note how an object of this class is created.
;       Generally, this is just a reference to the class'
;       Init method.
;
; METHODS:
;       List the methods intrinsic to this class. There is no
;       need to list the inherited methods.
;
;   Update: A procedure for updating the tab in the Display Window belonging
;     to this plugin. This procedure is only called when this tab
;     is the currently selected one in the Display Window.
;
;   Init: For the creation of the tab.
;
;   GetProperty: retrieve information about the correlate_tab object.
;
; MODIFICATION HISTORY:
;   Written by:  Mark Cheung, April 2003.
;      Any additional mods get described here.  Remember to
;      change the stuff above if you add a new keyword or
;      something!

PRO correlate_tab::Refresh, resize=resize

IF N_ELEMENTS(resize) EQ 0 THEN resize=0

; Error handling for all trapped errors.
Catch, theError
IF theError NE 0 THEN BEGIN
   Catch, /Cancel
   ok = Error_Message(Traceback=1, /Error)
   RETURN
ENDIF

IF resize THEN BEGIN
   widget_control, self.drawID, XSize=self.tab_size[0], YSize=self.tab_size[1]
   free_horizontal_space = self.tab_size[0]
   free_vertical_space = self.tab_size[1]
   scr_aspect_ratio = float(free_vertical_space)/float(free_horizontal_space)

   self.DW->GetProperty, data_obj=data_obj, orientation=orientation
   data_obj->GetProperty, cube_ptr=cube_ptr

   height = 0.8*free_vertical_space
   width  = 0.7*free_horizontal_space

   height = round(height)
   width = round(width)
   horizontal_margin = round((free_horizontal_space-width)/2.)
   vertical_margin = round((free_vertical_space-height)/2.)
   self.active_draw_region = [horizontal_margin, vertical_margin,$
    horizontal_margin+width-0.1*free_horizontal_space, vertical_margin+height]
ENDIF


;self.DW->GetProperty, colorbar = colorbar

IF self.draw_colorbar THEN BEGIN
   self.DW->GetProperty, colorbar=colorbar
   widget_control, self.drawID, get_value = wid
   wset, wid
   colorbar->draw
ENDIF

self->Update

END

PRO correlate_tab::DrawPostscript

   self.DW->GetProperty, DW_ID=DW_ID, $
    DW_tabs = DW_tabs, $
    movie_player = movie_player, $
    orientation = orientation, $
    data_obj = data_obj, $
    colorbar = colorbar, $
    r=r, g=g, b=b

    i0 = self.active_draw_region[0]
    i1 = self.active_draw_region[2]
    j0 = self.active_draw_region[1]
    j1 = self.active_draw_region[3]
    width = i1-i0+1
    height = j1-j0+1

; Color protection on? Load color vectors if appropriate.
TVLCT, r, g, b

   data_obj->GetProperty, cube_ptr=cube_ptr, $
    minValue = minValue, maxValue = maxValue, $
    dx_vec = dx_vec, axes_units=axes_units

   ;Get the frame number from the slider in the movie player module.
   widget_control, movie_player, get_uvalue = movie_player_state
   widget_control, movie_player_state.frame_slider, get_value=frame_number

   levels = *(self.contour_levels_ptr)

    case orientation of
       1: begin
       image = reform((*cube_ptr)(*,frame_number,*))
       horiz_max = n_elements(image(*,0))
       vert_max = n_elements(image(0,*))
       xtitle = 'x ('+axes_units[0]+')'
       ytitle = 'z ('+axes_units[2]+')'
       x_axis = findgen(horiz_max)*dx_vec[0]
       y_axis = findgen(vert_max)*dx_vec[2]
       end
       2: begin
       image =  reform((*cube_ptr)(*,*,frame_number))
       horiz_max = n_elements(image(*,0))
       vert_max = n_elements(image(0,*))
       xtitle = 'x ('+axes_units[0]+')'
       ytitle = 'y ('+axes_units[1]+')'
       x_axis = findgen(horiz_max)*dx_vec[0]
       y_axis = findgen(vert_max)*dx_vec[1]
       end
       3: begin
       image = transpose(reform((*cube_ptr)(frame_number,*,*)))
       horiz_max = n_elements(image(*,0))
       vert_max = n_elements(image(0,*))
       xtitle = 'z ('+axes_units[2]+')'
       ytitle = 'y ('+axes_units[1]+')'
       x_axis = findgen(horiz_max)*dx_vec[2]
       y_axis = findgen(vert_max)*dx_vec[1]
       end
    endcase


free_horiz_space = !D.X_SIZE
free_vert_space = !D.Y_SIZE

IF self.draw_colorbar THEN free_horiz_space=0.75*free_horiz_space
ps_aspect_ratio = float(free_vert_space)/float(free_horiz_space)
slice_aspect_ratio = float(vert_max)/float(horiz_max)

IF (slice_aspect_ratio GT ps_aspect_ratio) THEN BEGIN
   ps_y_size = 0.8*free_vert_space
   ps_x_size = ps_y_size;/slice_aspect_ratio
ENDIF ELSE BEGIN
   ps_x_size = 0.8*free_horiz_space
   IF self.draw_colorbar THEN ps_x_size=0.75*ps_x_size
   ps_y_size = ps_x_size;*slice_aspect_ratio
ENDELSE

vert_margin = (free_vert_space - ps_y_size)/2.
horiz_margin = (free_horiz_space - ps_x_size)/2.

position = [horiz_margin+ps_x_size, vert_margin, horiz_margin+2.5*ps_x_size, $
   vert_margin+ps_y_size]


   data_obj->GetProperty, cube_ptr=cube_ptr, dx_vec=dx_vec, $
    minValue = minValue, maxValue = maxValue, axes_units=axes_units, $
    variable_name = variable_name, unit = unit

   self.data_obj2->GetProperty, cube_ptr=cube_ptr2, $
    minValue = minValue2, maxValue = maxValue2,$
    variable_name = variable_name2, unit = unit2

    case orientation of
       1: begin
       image = reform((*cube_ptr)(*,frame_number,*))
       image2= reform((*cube_ptr2)(*,frame_number,*))
       end
       2: begin
       image =  reform((*cube_ptr)(*,*,frame_number))
       image2 =  reform((*cube_ptr2)(*,*,frame_number))
       end
       3: begin
       image = reform((*cube_ptr)(frame_number,*,*))
       image2 = reform((*cube_ptr2)(frame_number,*,*))
       end
    endcase


    minValue = min(image)
    maxValue = max(image)
    minValue2= min(image2)
    maxValue2= max(image2)

    xtitle = variable_name + '(' + unit + ')'
    ytitle = variable_name2+ '(' + unit2 + ')'

;========Draw on Postscript=========
    nbinsx = self.nbinsx; 60;floor(width/30.)
    nbinsy = self.nbinsy; 60;floor(height/30.)
    bin1   = (maxValue-minValue)/float(nbinsx)
    bin2   = (maxValue2-minValue2)/float(nbinsy)
    histo  = hist_2D(image, image2, bin1=bin1, bin2=bin2, $
	    min1=minValue, max1=maxValue, $
            min2=minValue2, max2=maxValue2)
    histo  = alog10(1.0*histo) - alog10(N_ELEMENTS(image))



    slice_width = N_ELEMENTS(histo[*,0])
    slice_height= N_ELEMENTS(histo[0,*])

    print, nbinsx-N_ELEMENTS(histo[*,0]), nbinsy-N_ELEMENTS(histo[0,*])
    nbinsx = N_ELEMENTS(histo[*,0])
    nbinsy = N_ELEMENTS(histo[0,*])

    x_axis = (minValue+bin1/2.)+findgen(nbinsx)*(maxValue-minValue)/(nbinsx)
    y_axis = (minValue2+bin2/2.)+findgen(nbinsy)*(maxValue2-minValue2)/(nbinsy)

        ; Force color table to give black bg and white annotations
    TVLCT, r, g, b, /Get
        white_table = intarr(256)
    white_table[255] = 255
    white_table[0:254] = 0
    TVLCT, white_table, white_table, white_table

    ;============Restore original colortable===============
    TVLCT, r, g, b


    position = [horiz_margin, vert_margin, horiz_margin+ps_x_size, $
       vert_margin+ps_y_size]


    ;TVSCL, histo, i0, j0;, xsize=i1-i0-20, ysize=j1-j0-30
    contour, histo, x_axis, y_axis, xstyle=1, ystyle=1, $
        xtitle=xtitle, ytitle=ytitle, ticklen=-0.015, $
        /fill, nlevels=120, position=position, /device, zrange=[alog10(1.0/N_ELEMENTS(image)),0]

    IF self.draw_colorbar THEN BEGIN
        colorbar->GetProperty, Range=col_range, Title=col_title
        colorbar->SetProperty, Range=[alog10(1.0/N_ELEMENTS(image)),0], Title="Log(Frac.)"
        colorbar->draw
        colorbar->SetProperty, Range=col_range, Title=col_title
    ENDIF

END

;==================================================================
; METHODNAME:
;       correlate_tab::Update
;
; PURPOSE:
;   For updating the correlate tab in the Display Window if it is currently selected
;   and some event (user-driven or not) occurs.
;
; CALLING SEQUENCE:
;   correlate_tab->Update
;
; OPTIONAL INPUTS:
;
; RESTRICTIONS:
;   Describe any "restrictions" here.  Delete this section if there are
;   no important restrictions.
;
; PROCEDURE:
;   You can describe the foobar superfloatation method being used here.
;   You might not need this section for your routine.
;
; EXAMPLE:
;   The following example creates a Display_Window object named DW and retrives the
;   widget ID of the Display Window using the GetProperty function of this object.
;
;   correlate_tab = Obj_New("correlate_tab", DW=DW)
;   correlate_tab->Update
;
; MODIFICATION HISTORY:
;   Written by:  Mark Cheung, April 2003
;   April, 2003   Any additional mods get described here.  Remember to
;      change the stuff above if you add a new keyword or
;      something!

PRO correlate_tab::Update

   self.DW->GetProperty, DW_ID=DW_ID, $
    DW_tabs = DW_tabs, $
    movie_player = movie_player, $
    orientation = orientation, $
    data_obj = data_obj, $
    colorbar = colorbar, $
    r=r, g=g, b=b

    i0 = self.active_draw_region[0]
    i1 = self.active_draw_region[2]
    j0 = self.active_draw_region[1]
    j1 = self.active_draw_region[3]
    width = i1-i0+1
    height = j1-j0+1

widget_control, self.drawID, get_value=wid

IF (!D.Flags AND 256) NE 0 THEN WSet, wid

; Color protection on? Load color vectors if appropriate.
TVLCT, r, g, b

   data_obj->GetProperty, cube_ptr=cube_ptr, dx_vec=dx_vec, $
    minValue = minValue, maxValue = maxValue, axes_units=axes_units, $
    variable_name = variable_name, unit = unit

   self.data_obj2->GetProperty, cube_ptr=cube_ptr2, $
    minValue = minValue2, maxValue = maxValue2,$
    variable_name = variable_name2, unit = unit2

   widget_control, self.drawID, get_value = wid

   ;Get the frame number from the slider in the movie player module.
   widget_control, movie_player, get_uvalue = movie_player_state
   widget_control, movie_player_state.frame_slider, get_value=frame_number

   levels = *(self.contour_levels_ptr)

    case orientation of
       1: begin
       image = reform((*cube_ptr)(*,frame_number,*))
       image2= reform((*cube_ptr2)(*,frame_number,*))
       end
       2: begin
       image =  reform((*cube_ptr)(*,*,frame_number))
       image2 =  reform((*cube_ptr2)(*,*,frame_number))
       end
       3: begin
       image = reform((*cube_ptr)(frame_number,*,*))
       image2 = reform((*cube_ptr2)(frame_number,*,*))
       end
    endcase

    minValue = min(image)
    maxValue = max(image)
    minValue2= min(image2)
    maxValue2= max(image2)

    xtitle = variable_name + '(' + unit + ')'
    ytitle = variable_name2+ '(' + unit2 + ')'

    ;=========Draw on X device==========
    wset, wid
    ;plot, image, image2, xtitle=xtitle, ytitle=ytitle, psym=2
    nbinsx = self.nbinsx; 60;floor(width/30.)
    nbinsy = self.nbinsy; 60;floor(height/30.)
    bin1   = (maxValue-minValue)/float(nbinsx)
    bin2   = (maxValue2-minValue2)/float(nbinsy)
    ;histo  = hist_2D(image, image2, bin1=bin1, bin2=bin2, $
;	    min1=minValue, max1=maxValue, $
;            min2=minValue2, max2=maxValue2)
;    histo  = alog10(1.0*histo) - alog10(N_ELEMENTS(image))

    ;x_axis = minValue+findgen(nbinsx)*(maxValue-minValue)/float(nbinsx)
    ;y_axis = minValue2+findgen(nbinsy)*(maxValue2-minValue2)/float(nbinsy)


    ;slice_width = N_ELEMENTS(histo[*,0])
    ;slice_height= N_ELEMENTS(histo[0,*])

;    IF (slice_width ne width) OR (slice_height ne height) THEN BEGIN
;         width_interpol = findgen(width)*float(slice_width)/width
;         height_interpol = findgen(height)*float(slice_height)/height
;         histo = interpolate(histo, width_interpol, height_interpol, /grid)
;    ENDIF

    ;print, nbinsx-N_ELEMENTS(histo[*,0]), nbinsy-N_ELEMENTS(histo[0,*])
    ;nbinsx = N_ELEMENTS(histo[*,0])
    ;nbinsy = N_ELEMENTS(histo[0,*])
    ;help, histo
    

    x_axis = (minValue+bin1/2.)+findgen(nbinsx)*(maxValue-minValue)/(nbinsx)
    y_axis = (minValue2+bin2/2.)+findgen(nbinsy)*(maxValue2-minValue2)/(nbinsy)

        ; Force color table to give black bg and white annotations
    TVLCT, r, g, b, /Get
        white_table = intarr(256)
    white_table[255] = 255
    white_table[0:254] = 0
    TVLCT, white_table, white_table, white_table
    ;contour, histo, x_axis, y_axis, /device, position=[i0,j0,i1,j1], $
    ;   levels=-0.1, xstyle=1, ystyle=1, xtitle=xtitle, ytitle=ytitle, ticklen=-0.015

    ;============Restore original colortable===============
    TVLCT, r, g, b
    help, histo
    ;stop
    ;TVSCL, histo, i0, j0;, xsize=i1-i0-20, ysize=j1-j0-30
    ;contour, histo, x_axis, y_axis, xstyle=1, ystyle=1, $
    ;   xtitle=xtitle, ytitle=ytitle, ticklen=-0.015, $
    ;    /fill, nlevels=50, position=[i0,j0,i1,j1], /device, zrange=[alog10(1.0/N_ELEMENTS(image)),0]
    plot, image[*],image2[*], xstyle=1, ystyle=1, $
	xrange=[minValue,maxValue], yrange=[minValue2,maxValue2],$
        xtitle=xtitle, ytitle=ytitle, ticklen=-0.015, $
        position=[i0,j0,i1,j1], psym=3, /device

    IF self.draw_colorbar THEN BEGIN
        colorbar->GetProperty, Range=col_range, Title=col_title
        colorbar->SetProperty, Range=[alog10(1.0/N_ELEMENTS(image)),0], Title="Log(Frac.)"
        colorbar->draw
        colorbar->SetProperty, Range=col_range, Title=col_title
    ENDIF

END

; METHODNAME:
;       correlate_tab::SetProperty
;
; PURPOSE:
;   For modifying the attributes of a correlate_tab class object
;
; CALLING SEQUENCE:
;   correlate_tab = Obj_New("correlate_tab", DW=DW)
;   correlate_tab->SetProperty, plugin_name=plugin_name
;
; OPTIONAL INPUTS:
;
; RESTRICTIONS:
;   Describe any "restrictions" here.  Delete this section if there are
;   no important restrictions.
;
; PROCEDURE:
;   You can describe the foobar superfloatation method being used here.
;   You might not need this section for your routine.
;
; EXAMPLE:
;   The following example creates a Display_Window object named DW and retrives the
;   widget ID of the Display Window using the GetProperty function of this object.
;
;   correlate_tab = Obj_New("correlate_tab", DW=DW)
;   correlate_tab->SetProperty, plugin_name="New Pixel Tab"
;
; MODIFICATION HISTORY:
;   Written by:  Mark Cheung, April 2003
;   April, 2003   Any additional mods get described here.  Remember to
;      change the stuff above if you add a new keyword or
;      something!

PRO correlate_tab::SetProperty, $
    plugin_name = plugin_name, $
    active_draw_region = active_draw_region, $
    draw_canvas_size = draw_canvas_size, $
    draw_colorbar = draw_colorbar, $
    correlate_settings_window = correlate_settings_window, $
    contour_levels_ptr = contour_levels_ptr, $
    ax=ax, az = az, nbinsx = nbinsx, nbinsy=nbinsy, $
    data_obj2 = data_obj2

;Error Handling
Catch, theError
IF theError NE 0 THEN BEGIN
   Catch, Cancel=1
   ok = Dialog_Message('Error in SetProperty Method. Returning...')
   Print, ''
   Print, 'correlate_tab::SetProperty Method: ' + !Error_State.Msg
ENDIF

IF N_ELEMENTS(plugin_name) NE 0 THEN self.plugin_name=plugin_name
IF N_ELEMENTS(active_draw_region) NE 0 THEN self.active_draw_region=active_draw_region
IF N_ELEMENTS(draw_canvas_size) NE 0 THEN self.draw_canvas_size=draw_canvas_size
IF N_ELEMENTS(draw_colorbar) NE 0 THEN self.draw_colorbar = draw_colorbar
IF N_ELEMENTS(correlate_settings_window) NE 0 THEN self.correlate_settings_window=correlate_settings_window
IF N_ELEMENTS(contour_levels_ptr) NE 0 THEN self.contour_levels_ptr=contour_levels_ptr
IF N_ELEMENTS(ax) NE 0 THEN self.ax=ax
IF N_ELEMENTS(az) NE 0 THEN self.az=az
IF N_ELEMENTS(nbinsx) NE 0 THEN self.nbinsx=nbinsx
IF N_ELEMENTS(nbinsy) NE 0 THEN self.nbinsy=nbinsy
IF N_ELEMENTS(data_obj2) NE 0 THEN self.data_obj2=data_obj2

END

; METHODNAME:
;       correlate_tab::GetProperty
;
; PURPOSE:
;   For the retrieval of information about the correlate_tab object
;
; CALLING SEQUENCE:
;   correlate_tab = Obj_New("correlate_tab", DW=DW)
;   correlate_tab->GetProperty, plugin_name=plugin_name, ...
;
; OPTIONAL INPUTS:
;   plugin_name : Returns the name of this plugin
;   tab_ID: Returns the widget ID of the tab associated with this plugin
;   drawID: Returns the widget ID of the draw widget contained in the correlate tab.
;   DW : Returns an object pointer to the Display Window object to which
;     this plugin is attached.
;
; RESTRICTIONS:
;   Describe any "restrictions" here.  Delete this section if there are
;   no important restrictions.
;
; PROCEDURE:
;   You can describe the foobar superfloatation method being used here.
;   You might not need this section for your routine.
;
; EXAMPLE:
;   The following example creates a Display_Window object named DW and retrives the
;   widget ID of the Display Window using the GetProperty function of this object.
;
;   correlate_tab = Obj_New("correlate_tab", DW=DW)
;   correlate_tab->GetProperty, tab_ID=tab_ID, plugin_name=name
;
; MODIFICATION HISTORY:
;   Written by:  Mark Cheung, April 2003
;   April, 2003   Any additional mods get described here.  Remember to
;      change the stuff above if you add a new keyword or
;      something!

PRO correlate_tab::GetProperty, $
    plugin_name = plugin_name, $
    tab_ID = tab_ID, $
    DW = DW, $
    drawID = drawID, $
    draw_canvas_size = draw_canvas_size, $
    active_draw_region = active_draw_region, $
    draw_colorbar = draw_colorbar, $
    correlate_settings_window = correlate_settings_window, $
    context_menu = context_menu, $
    contour_levels_ptr = contour_levels_ptr, $
    ax = ax, az = az, nbinsx=nbinsx, nbinsy=nbinsy, $
    data_obj2 = data_obj2

;Error Handling
Catch, theError
IF theError NE 0 THEN BEGIN
   Catch, Cancel=1
   ok = Dialog_Message('Error in GetProperty Method. Returning...')
   Print, ''
   Print, 'correlate_tab::GetProperty Method: ' + !Error_State.Msg
ENDIF

plugin_name = self.plugin_name
tab_ID = self.tab_ID
DW = self.DW
drawID = self.drawID
draw_canvas_size = self.draw_canvas_size
active_draw_region = self.active_draw_region
draw_colorbar = self.draw_colorbar
correlate_settings_window = self.correlate_settings_window
context_menu = self.context_menu
contour_levels_ptr = self.contour_levels_ptr
ax = self.ax
az = self.az
nbinsx = self.nbinsx
nbinsy = self.nbinsy
data_obj2 = self.data_obj2

END

; METHODNAME:
;       correlate_tab::Init
;
; PURPOSE:
;   For the creation of a the correlate_tab plugin and it's tab in a Display Window
;
; CALLING SEQUENCE:
;   correlate_tab = Obj_New("correlate_tab", DW=DW)
;
; INPUTS:
;   DW: The Display Window Object to which this plugin is attached.
;
; OPTIONAL INPUTS:
;
; KEYWORD PARAMETERS:
;   KEY1: Document keyword parameters like this. Note that the keyword
;     is shown in ALL CAPS!
;
; OPTIONAL OUTPUTS:
;   Describe optional outputs here.  If the routine doesn't have any,
;   just delete this section.
;
; COMMON BLOCKS:
;   BLOCK1:   Describe any common blocks here. If there are no COMMON
;     blocks, just delete this entry. Object methods probably
;               won't be using COMMON blocks.
;
; SIDE EFFECTS:
;   Describe "side effects" here.  There aren't any?  Well, just delete
;   this entry.
;
; RESTRICTIONS:
;   Describe any "restrictions" here.  Delete this section if there are
;   no important restrictions.
;
; PROCEDURE:
;   You can describe the foobar superfloatation method being used here.
;   You might not need this section for your routine.
;
; EXAMPLE:
;   The following example creates a Display_Window object named DW and retrives the
;   widget ID of the Display Window using the GetProperty function of this object.
;
;   correlate_tab = Obj_New("correlate_tab", DW=DW)
;
; MODIFICATION HISTORY:
;   Written by:  Mark Cheung, April 2003
;   April, 2003   Any additional mods get described here.  Remember to
;      change the stuff above if you add a new keyword or
;      something!

FUNCTION correlate_tab::INIT, $
    DW=DW, $
    active_draw_region=active_draw_region, $
    draw_colorbar = draw_colorbar, ax=ax, ay=ay

;Error Handling
Catch, theError
IF theError NE 0 THEN BEGIN
   Catch, Cancel=1
   ok = Dialog_Message('Error in INIT Method. Returning...')
   Print, ''
   Print, 'data_set::INIT Method: ' + !Error_State.Msg
   RETURN, 0
ENDIF

IF N_ELEMENTS(tab_ID) EQ 0 THEN tab_ID=0L
IF N_ELEMENTS(active_draw_region) EQ 0 THEN active_draw_region=[20,20,307,307]
IF N_ELEMENTS(ax) EQ 0 THEN ax=30.
IF N_ELEMENTS(az) EQ 0 THEN az=30.
IF N_ELEMENTS(nbinsx) EQ 0 THEN nbinsx=60l
IF N_ELEMENTS(nbinsy) EQ 0 THEN nbinsy=60l
IF N_ELEMENTS(draw_colorbar) EQ 0 THEN draw_colorbar=1


;=====Pixel tab widget=================================
DW->GetProperty, xsize=xsize, $
    ysize=ysize, $
    DW_ID=DW_ID, $
    DW_tabs=DW_tabs

correlate_tab = widget_base(DW_tabs, Title="Correlate", xsize = xsize, ysize=ysize, $
   /context_events, event_pro="correlate_tab_events")
correlate_draw = widget_draw(correlate_tab, xsize=xsize, ysize=ysize-70, /button_events, $
   event_pro="correlate_tab_events")

;==============Context Menu for correlate Tab Plugin======================
context_menu = widget_base(correlate_tab, /context_menu)
scatter_vs_button = widget_button(context_menu, value="Scatter plot vs.:", $
   event_pro="correlate_context_menu_events", /Menu)

dummy_variable = obj_new("variable_type")
dummy_variable->VariablesMenuItems, menu_item_ids=scatter_vs_items, $
    menu_parent = scatter_vs_button, event_pro="correlate_tab_events"

settings = widget_button(context_menu, value="Settings", $
   event_pro="correlate_context_menu_events", xsize=80, /separator)
context_menu_state = {correlate_tab_obj:self, context_menu:context_menu, settings:settings}
widget_control, context_menu, set_uvalue=context_menu_state

widget_control, correlate_draw, get_value = correlate_wid
correlate_tab_state = {correlate_tab:correlate_tab, drawID:correlate_draw, context_menu:context_menu}

;============Initialize contour levels=======================
DW->GetProperty, data_obj = data_obj
data_obj->GetProperty, minValue=minValue, maxValue=maxValue
contour_levels = minValue + (maxValue-minValue)*[0.0, 0.2, 0.4, 0.6, 0.8, 1.0]

self.draw_canvas_size = [xsize,ysize-70]
self.tab_size = [xsize,ysize-70]
self.plugin_name='correlate Tab'
self.drawID = correlate_draw
self.tab_ID = correlate_tab
self.DW = DW
self.draw_colorbar = draw_colorbar
self.active_draw_region = active_draw_region
self.context_menu = context_menu
self.correlate_settings_window = 0L
self.contour_levels_ptr = Ptr_New(contour_levels)
self.ax = ax
self.az = az
self.nbinsx = nbinsx
self.nbinsy = nbinsy
self.data_obj2 = data_obj

widget_control, self.tab_ID, set_uvalue = self

RETURN, 1
END

PRO correlate_tab__define

struct = {correlate_tab, $
    drawID:0L, $      ; The widget ID of the draw canvas
    draw_canvas_size:intarr(2), $  ; The [width,height] of the draw widget with ID=drawID
    active_draw_region:intarr(4), $ ; The region [i0,j0,i1,j1] on the draw canvas used for displaying the 2D slice
    correlate_settings_window:0L, $   ; Widget ID for Settings Window
    draw_colorbar:0, $       ; whether to draw colorbar
    contour_levels_ptr:Ptr_New(), $    ; Pointer to array specifying contour levels
    ax: 0, $      ; Angle from x-axis}used as parameters in shade_surf
    az: 0, $      ; Angle from z-axis}
    nbinsx: 60l, $; Number of bins in x-axis for 2D histogram
    nbinsy: 60l, $; Number of bins in y-axis for 2D histogram
    data_obj2:Obj_New() , $ ;Second data set for scatter plotting
    INHERITS plugin $
    }
END

;=============Event Handler for this tab========================
PRO correlate_context_menu_events, event

   widget_control, widget_info(event.id, /parent), get_uvalue=context_menu_state
   correlate_tab_obj = context_menu_state.correlate_tab_obj
   correlate_tab_obj->GetProperty, correlate_settings_window=correlate_settings_window, DW=DW, $
    contour_levels_ptr=contour_levels_ptr, ax=ax, az=az, nbinsx=nbinsx, nbinsy=nbinsy
   DW->GetProperty, DW_ID=DW_ID, data_obj=data_obj
   data_obj->GetProperty, minValue=minValue, maxValue=maxValue
   widget_control, event.id, get_value=button_label

   CASE button_label OF
    "Settings": BEGIN
       IF NOT(widget_info(correlate_settings_window, /valid_id)) THEN BEGIN

       ;===============Build new Settings Window================
       ;stop
       correlate_settings_window = widget_base(xsize=350,ysize=180,row=3, $
          title="correlate Tab Settings", group_leader=DW_ID, $
          event_pro="correlate_context_menu_events")

       ax_label = widget_label(correlate_settings_window, value='Number of x-bins')
       ax_slider = widget_slider(correlate_settings_window, value=nbinsx, minimum=15,$
          maximum=100, /drag, event_pro='correlate_settings_window_events')
       az_label = widget_label(correlate_settings_window, value='Number of y-bins')
       az_slider = widget_slider(correlate_settings_window, value=nbinsy, minimum=15,$
          maximum=100, /drag, event_pro='correlate_settings_window_events')

       apply_button = widget_button(correlate_settings_window, value="Apply", event_pro=$
          "correlate_settings_window_events")
       done_button = widget_button(correlate_settings_window, value="Done", event_pro=$
          "correlate_settings_window_events")

       ;=============Save widget IDs======================
       correlate_tab_obj->SetProperty, correlate_settings_window=correlate_settings_window
       widget_control, correlate_settings_window, set_uvalue = {$
          correlate_tab_obj:correlate_tab_obj, $
          ax_slider:ax_slider, az_slider:az_slider,$
          correlate_settings_window:correlate_settings_window}

       ;==========Realize the Settings Window================
       widget_control, correlate_settings_window, /realize
            xmanager, 'correlate_context_menu_events', correlate_settings_window, $
          /just_reg, cleanup='correlate_settings_window_cleanup'

       ;==========Change context menu button label to "Hide Settings"===
       widget_control, event.id, set_value="Hide Settings"
       ENDIF
    ENDCASE

    "Hide Settings": BEGIN
       IF (widget_info(correlate_settings_window, /valid_id)) THEN BEGIN
       widget_control, correlate_settings_window, /destroy
        correlate_tab_obj->SetProperty, correlate_settings_window=0L
       ENDIF
    ENDCASE

    "Hide colorbar":BEGIN
       ;widget_control, event.id, set_value = "Show colorbar"
       ;correlate_tab_obj->SetProperty, draw_colorbar = 0
       ;correlate_tab_obj->Refresh, resize=1
    ENDCASE

    "Show colorbar":BEGIN
       widget_control, event.id, set_value = "Hide colorbar"
       correlate_tab_obj->SetProperty, draw_colorbar = 1
       correlate_tab_obj->Refresh, resize=1
    ENDCASE


    ELSE: BEGIN
    ENDCASE
   END
END

PRO correlate_settings_window_events, event

;=========Retrive Information about Settings Window==========
correlate_settings_window = event.top
widget_control, correlate_settings_window, get_uvalue = info

;===Retrieve label of the button that generated this event===

IF (TAG_NAMES(event, /STRUCTURE_NAME) EQ 'WIDGET_BUTTON') THEN BEGIN
   widget_control, event.id, get_value = button_label

   ;==================Handle different button events==================
   CASE button_label OF

    "Apply": BEGIN
       ;=======Apply settings changes to correlate Tab Plugin=====
       widget_control, info.ax_slider, get_value=nbinsx
       widget_control, info.az_slider, get_value=nbinsy
       info.correlate_tab_obj->SetProperty, nbinsx=nbinsx, nbinsy=nbinsy
       info.correlate_tab_obj->Update
    ENDCASE

    "Done": BEGIN
       widget_control, correlate_settings_window, /destroy
       info.correlate_tab_obj->SetProperty, correlate_settings_window=0L
    ENDCASE

    ELSE: BEGIN
       ; This shouldn't happen
    ENDCASE
   END
ENDIF

;============The following code handles slider events============
IF (TAG_NAMES(event, /STRUCTURE_NAME) EQ 'WIDGET_SLIDER') THEN BEGIN
   widget_control, info.ax_slider, get_value=nbinsx
   widget_control, info.az_slider, get_value=nbinsy
   info.correlate_tab_obj->SetProperty, nbinsx=nbinsx, nbinsy=nbinsy
   info.correlate_tab_obj->Update
ENDIF

END

PRO correlate_settings_window_cleanup, correlate_settings_window

   widget_control, correlate_settings_window, get_uvalue = info
   info.correlate_tab_obj->GetProperty, context_menu = context_menu
   widget_control, context_menu, get_uvalue = context_menu_state
   widget_control, context_menu_state.settings, set_value = "Settings"

   info.correlate_tab_obj->SetProperty, correlate_settings_window = 0L
   widget_control, correlate_settings_window, /destroy

END

PRO correlate_tab_events, event

  IF (TAG_NAMES(EVENT, /STRUCTURE_NAME) EQ "WIDGET_DRAW") THEN BEGIN
    ; For the settings menu
    IF (event.release EQ 4) THEN BEGIN
       print, "Calling from correlate_tab_events"
       widget_control, widget_info(event.id, /parent), get_uvalue = correlate_tab_obj
       correlate_tab_obj->GetProperty, context_menu = context_menu
       WIDGET_DISPLAYCONTEXTMENU, EVENT.ID, event.x, event.y, context_menu
    ENDIF
  ENDIF

  IF (TAG_NAMES(EVENT, /STRUCTURE_NAME) EQ "WIDGET_BUTTON") THEN BEGIN
    ; For changing the scatter plot variable
    DW_ID = event.top
    widget_control, DW_ID, get_uvalue = DW

    widget_control, widget_info(widget_info(widget_info(event.id, /parent), /parent),/parent), $
        get_uvalue = correlate_tab_obj
    correlate_tab_obj->GetProperty, data_obj2 = data_obj2
    data_obj2->GetProperty, variable_name = old_variable_name

    DW->GetProperty, data_obj=data_obj
    data_obj->GetProperty, variable_name=var1_name, nmod=nmod, dir=dir, $
        cube_ptr=cube_ptr, vertex1=vertex1, vertex2=vertex2, cube_size=cube_size

    widget_control, event.id, get_value = button_label

    dummy_variable = obj_new("variable_type")
    dummy_variable->GetProperty, variables_list = variables_list
    IF button_label EQ var1_name THEN BEGIN
         data_obj2 = data_obj
    ENDIF ELSE BEGIN
         cube_ptr = get_raw_cube_ptr(dir=dir, nmod=nmod, $
              variable_to_load=button_label, min=vertex1, max=vertex2, cube_size=cube_size)
         new_variable_obj = Obj_New(button_label)
         new_variable_obj->GetProperty, unit=unit2
         data_obj2 = Obj_New("data_set", data_type=0, dir=dir, nmod = nmod,$
            cube_ptr=cube_ptr, vertex1 = vertex1, vertex2 = vertex2, cube_size=cube_size,$
            variable_name = button_label, variable_object = new_variable_object)
         data_obj2->SetProperty, unit=unit2
    ENDELSE
    correlate_tab_obj->SetProperty, data_obj2 = data_obj2
    correlate_tab_obj->Update
  ENDIF
END
