;+
;show magnifier image
;+
PRO sesCalibrat::ShowImage , eventX , eventY
	COMPILE_OPT IDL2
	oSystem = self.oSystem

	oView = self.preView
	oView->GetProperty, Location = viewLoc , dimensions = dim
	self.magModel->GetProperty, UValue = image

	x0 = (30>(eventX-viewLoc[0]))<(dim[0]-31)
	y0 = (30>(eventY-viewLoc[1]))<(dim[1]-31)
	drawSize = [120,120]
	rate = 2
	img_lox = x0 - drawSize[0]/2
	img_loy = y0 - drawSize[1]/2
	win_size = drawSize/rate/2.

	x_low = (x0 - win_size[0])+viewLoc[0]
	x_high = (x0 + win_size[0]+viewLoc[0])
	y_low = (y0 - win_size[1])+viewLoc[1]
	y_high = (y0 + win_size[1]+viewLoc[1])
	zoom_img = Congrid(image $
					   [*,x_low:x_high, y_low:y_high], $
		               3, drawSize[0], drawSize[1])
	self.magImage->SetProperty, data=zoom_img
	self.showWindow->Draw,self.showView
END
;+
;create backboard,backModel is the changingModel,preModel is the backboard
;+
PRO sesCalibrat::CreateInstance,Type=type,OWindow=oWindow,$
	BackModel=backModel,UnchangeModel=unchangeModel,OView=oView

	COMPILE_OPT IDL2

	IF ~Keyword_Set(type) THEN type = 0B
	IF ~type THEN BEGIN
		backModel->SetProperty, /Hide
		oWindow->Draw, oView, /Create_Instance
		unchangeModel->SetProperty, /Hide
		backModel->SetProperty, Hide=0
		oView->SetProperty, /Transparent
	ENDIF ELSE BEGIN
		unchangeModel->SetProperty, Hide=0
		oView->SetProperty, Transparent=0
	ENDELSE
END
;+
;show velovect
;+
PRO sesCalibrat::Velovect1,U,V,X,Y,Missing=missing,Length=length,Dots=dots,_Extra=extra

	;Return to caller if an error occurs
	On_Error,2
	s = Size(u)
	t = Size(v)
	IF s[0] NE 2 THEN BEGIN
	baduv:   Message, 'U and V parameters must be 2D and same size.'
	ENDIF
	IF Total(Abs(s[0:2]-t[0:2])) NE 0 THEN goto,baduv

	IF N_Params(0) LT 3 THEN x = FIndGen(s[1]) ELSE $
	    IF N_Elements(x) NE s[1] THEN BEGIN
		badxy:   Message, 'X and Y arrays have incorrect size.'
	    ENDIF
	IF N_Params(1) LT 4 THEN y = FIndGen(s[2]) ELSE $
	    IF N_Elements(y) NE s[2] THEN goto,badxy

	IF N_Elements(missing) LE 0 THEN missing = 1.0e30
	IF N_Elements(length) LE 0 THEN length = 1.0

	;Magnitude.
	mag = Sqrt(u^2.+v^2.)

	;Subscripts of good elements
	;# of missing points
	nbad = 0
	IF N_Elements(missing) gt 0 THEN BEGIN
	good = Where(mag gt missing)
	IF Keyword_Set(dots) THEN bad = Where(mag ge missing, nbad)
	ENDIF ELSE BEGIN
	    good = LIndGen(N_Elements(mag))
	ENDELSE

	ugood = u[good]
	vgood = v[good]
	;Get scaling
	x0 = Min(x)
	x1 = Max(x)
	y0 = Min(y)
	y1 = Max(y)
	; Convert to float. Integer math
	; Could result in divide by 0
	x_step=(x1-x0)/(s[1]-1.0)
	y_step=(y1-y0)/(s[2]-1.0)

	maxmag=Max([Max(Abs(ugood/x_step)),Max(Abs(vgood/y_step))])
	sina = length * (ugood/maxmag)
	cosa = length * (vgood/maxmag)
	temp = sqrt(sina*sina+cosa*cosa)
    temp = temp[sort(temp)]

	x_b0=x0-x_step
	x_b1=x1+x_step
	y_b0=y0-y_step
	y_b1=y1+y_step

	r = .3                          		;len of arrow head
	angle = 22.5 * !dtor            		;Angle of arrowhead
	st = r * Sin(angle)             		;sin 22.5 degs * length of head
	ct = r * Cos(angle)

	h_color = Bytscl(temp)
	loadct, 34, /silent
	tvlct, r, g, b, /get

	;添加磁场显示的箭头
	FOR i=0,N_Elements(good)-1 DO BEGIN
		uu = sqrt(sina[i]*sina[i]+cosa[i]*cosa[i])

		oo = Where(uu EQ temp)
		rr = r[h_color[oo[0]]]
		gg = g[h_color[oo[0]]]
		bb = b[h_color[oo[0]]]

		x0 = x[good[i] MOD s[1]]
		dx = sina[i]
		x1 = x0 + dx
		y0 = y[good[i] / s[1]]
		dy = cosa[i]
		y1 = y0 + dy
		xd=x_step
		yd=y_step

		a=[[x0,y0],[x1,y1],[x1-(ct*dx/xd-st*dy/yd)*xd,y1-(ct*dy/yd+st*dx/xd)*yd],[x1,y1],$
			[x1-(ct*dx/xd+st*dy/yd)*xd,y1-(ct*dy/yd-st*dx/xd)*yd]]

		d=[5,0,1,2,3,4]

		xConv=[0.,self.drawX/s[1]]
		yConv=[0.,self.drawY/s[2]]
		sPolyline = Obj_New('IDLgrPolyline'			,$
							data=a					,$
							polylines=d				,$
							Color=[rr,gg,bb]		,$
							XCoord_Conv=xConv		,$
							YCoord_Conv=yConv		)

		self.calContainer->Add,sPolyline
		self.preModel->Add,sPolyline
	ENDFOR
	h_color=0
	r=0
	g=0
	b=0

END
;+
;calibrat
;+
PRO sesCalibrat::Coalign

	Widget_Control , self.PreDraw , Get_UValue = stat

	l = stat.l
	q = stat.q
	u = stat.u
	sdat = stat.sdat
	tdat = stat.tdat
	rdat = stat.rdat

	self.click=0
	x1=Min([self.x1,self.x2],Max=x2)
	y1=Min([self.y1,self.y2],Max=y2)
	ssdat=sdat(x1:x2,y1:y2)
	ttdat=tdat(x1:x2,y1:y2)
	rrdat=rdat(x1:x2,y1:y2)
	Acpole,ssdat,ttdat,shtx,shty
	Acpole,ssdat,rrdat,shrx,shry
	q=Shift(q,shtx,shty)
	u=Shift(u,shrx,shry)

	stat.l = l
	stat.q = q
	stat.u = u

	Widget_Control , self.PreDraw , Set_UValue = stat

	shtx=String(shtx)
	shty=String(shty)
	shrx=String(shrx)
	shry=String(shry)
	Widget_Control,self.preText,Set_Value=['Correlation Position:  ','',shtx+shty,'',$
											'Correlation Position:  ','',shrx+shry]
END
;+
;select point
;+
PRO sesCalibrat::Click,event

	COMPILE_OPT IDL2

	;press
	IF (event.press EQ 1) AND (self.click EQ 0) THEN BEGIN
	;选第一个点
		self.x1=(event.x>0)<639
		self.y1=(event.y>0)<479
		x1 = String(self.x1)
		y1 = String(self.y1)
		IF Obj_Valid(self.oPolyGon) THEN BEGIN
			self.oPolyGon->SetProperty,hide = 0
		ENDIF
		IF Obj_Valid(self.oPolyGon1) THEN BEGIN
			self.oPolyGon1->SetProperty,hide = 0
		ENDIF
		IF ~Obj_Valid(self.oPolyGon) THEN BEGIN
			self.oPolyGon = Obj_New('IDLgrPolyGon' 				, $
									Alpha_Channel = 0.3   		, $
									Thick = 1					, $
									Style = 2					, $
		                          	Color = [133,162,205]		, $
									Name = 'oPolyGon'			  )

			self.oPolyGon1 = Obj_New('IDLgrPolyGon' 			, $
									Alpha_Channel = 1   		, $
									Thick = 1					, $
									Style = 1					, $
									Linestyle = 0				, $
		                          	Color = [243,194,70]		, $
									Name = 'oPolyGon1'			  )
			self.backModel->Add,self.oPolyGon
			self.backModel->Add,self.oPolyGon1
		ENDIF
		self->CreateInstance,oWindow=self.preWindow,oView=self.preView,$
			  backModel=self.backModel,unchangeModel=self.preModel
		Widget_Control,self.preText,$
		Set_Value=['	--------------------------- ','	First point:',$
					'','		X1 = '+x1,'',$
					'		Y1 = '+y1,'	--------------------------- ']
		self.click = self.click+1
	ENDIF

	;motion
	IF (event.type EQ 2) AND (self.click EQ 1) THEN BEGIN
		x0 = self.x1
		y0 = self.y1
		x1 = (event.x>0)<639
		y1 = (event.y>0)<479
		newBox = [[x0, y0], $
				  [x1, y0], $
				  [x1, y1], $
				  [x0, y1]]

		info = {box:newBox}
		self.oPolyGon->SetProperty, Data = newBox, UValue = info
		ox = [min(newBox[0,*]),max(newBox[0,*])]
		oy = [min(newBox[1,*]),max(newBox[1,*])]
		oData = [[ox[0]-1,oy[0]-0.9],[ox[1]+1,oy[0]-0.9] , $
		         [ox[1]+1,oy[1]+0.9],[ox[0]-1,oy[1]+0.9]]
		self.oPolyGon1->SetProperty, Data = oData, UValue = info
		self.preWindow->Draw,self.preView,/Draw_Instance

		x2 = String(event.x)
		y2 = String(event.y)
		Widget_Control,self.preText,$
				Set_Value=['	-------------------------------','	Second point:',$
							'','		X2 = '+x2,'',$
							'		Y2 = '+y2,'	-------------------------------']
	ENDIF

	;release
	IF (event.type EQ 1) AND (self.click EQ 1)  THEN BEGIN
		;选第二个点
		self.x2=(event.x>0)<639
		self.y2=(event.y>0)<479
		x2 = String(self.x2)
		y2 = String(self.y2)
		self->CreateInstance,/Type,oWindow=self.preWindow,oView=self.preView,$
			  backModel=self.backModel,unchangeModel=self.preModel
		Widget_Control,self.preText,$
		Set_Value=['	-------------------------------','	Second point:',$
					'','		X2 = '+x2,'',$
					'		Y2 = '+y2,'	-------------------------------']
		self->Coalign
	ENDIF
END
;+
;select point
;+
PRO sesCalibrat::Show,event

	COMPILE_OPT IDL2

	Widget_Control , self.calibrateButton , Get_UValue = cStat

	l = cStat.l
	bt = cStat.tt
	bx = cStat.bx
	by = cStat.by

	bx = Congrid(bx,640,480,/INTERP)
	by = Congrid(by,640,480,/INTERP)
	bt = Sqrt(bx^2+by^2)

	x = (event.x>0)<639
	y = (event.y>0)<479
	bz = l[x,y]
	bt = bt[x,y]
	bx = bx[x,y]
	by = by[x,y]
	b = Sqrt(Double(bz)^2+bx^2+by^2);B总
	tempA = Atan(bt,by)
	tempB = Atan(by,bx)
	x = String(x)
	x = Strtrim(x,2)
	y = String(y)
	y = Strtrim(y,2)
	bz = String(bz)
	bz = Strtrim(bz,2)
	bx = String(bx)
	bx = Strtrim(bx,2)
	by = String(by)
	by = Strtrim(by,2)
	b = String(b)
	b = Strtrim(b,2)
	tempA = String(tempA)
	tempA = Strtrim(tempA,2)
	tempB = String(tempB)
	tempB = Strtrim(tempB,2)

	;press
	IF event.press EQ 1 THEN BEGIN
		Widget_Control,self.preShowBase,Map = 1
		Widget_Control,self.preShowBase1,Map = 0
		self.click = 1
		Widget_Control,self.preText,$
		Set_Value=[' ----------- Result Information --------------'	,$
				   ' 	 B	  :		'+b								,$
				   '	 Φ	  :		'+tempA							,$
				   ' 	 λ	  :		'+tempB							,$
				   ' 	 X	  :		'+x								,$
				   ' 	 Y	  :		'+y								,$
				   ' 	 Bz	  :		'+bz							,$
				   ' 	 Bx	  :		'+bx							,$
				   ' 	 By	  :		'+by							,$
				   ' ---------------------------------------------']
	ENDIF
	IF event.press EQ 4 THEN BEGIN
		Widget_Control,self.preShowBase,Map = 0
		Widget_Control,self.preShowBase1,Map = 1
		self.click = 4
		image_Obj = self.preWindow -> Read()
		image_Obj -> GetProperty, Data = imageData
		Obj_Destroy,image_Obj
		self.magModel = Obj_New('IDLgrModel', name='MagModel')
		self.showView->Add, self.magModel
		IF ~Obj_Valid(self.magImage) THEN BEGIN
			self.magImage = Obj_New('IDLgrImage',imageData, name='magImage')
			self.calContainer ->Add, self.magImage
		ENDIF ELSE BEGIN
			self.magImage->SetProperty,Data = imageData
		ENDELSE
		self.magModel->setproperty, uvalue=Temporary(imageData)
		self.magModel->Add,	self.magImage
		self.calContainer->Add,self.magModel
		self->ShowImage,event.x,event.y
	ENDIF

	;motion
	IF event.type EQ 2 THEN BEGIN
		IF self.click EQ 1 THEN BEGIN
			Widget_Control,self.preText,$
			Set_Value=[' ----------- Result Information --------------'	,$
					   ' 	 B	  :		'+b								,$
					   '	 Φ	  :		'+tempA							,$
					   ' 	 λ	  :		'+tempB							,$
					   ' 	 X	  :		'+x								,$
					   ' 	 Y	  :		'+y								,$
					   ' 	 Bz	  :		'+bz							,$
					   ' 	 Bx	  :		'+bx							,$
					   ' 	 By	  :		'+by							,$
					   ' ---------------------------------------------'  ]
		ENDIF
		IF self.click EQ 4 THEN BEGIN
			self->ShowImage,event.x,event.y
		ENDIF
	ENDIF


	;release
	IF (event.type EQ 1) AND ((self.click EQ 1) OR (self.click EQ 4)) THEN BEGIN
		IF Obj_Valid(self.magModel) THEN BEGIN
			Obj_Destroy,self.magModel
			Obj_Destroy,self.magImage
			self.showWindow->Draw,self.showView
		ENDIF
		self.click = 0
	ENDIF
END
;+
;cerate flow
;+
PRO sesCalibrat::CreateFlow
	Widget_Control , self.PreDraw , Get_UValue = stat
	l = stat.l
	q = stat.q
	u = stat.u
	lh = stat.lh
	qh = stat.qh
	uh = stat.uh
	xd = stat.xd
	yd = stat.yd
	sdat = stat.sdat
	tdat = stat.tdat
	rdat = stat.rdat
	ss_name = stat.ss_name
	tt_name = stat.tt_name
	rr_name = stat.rr_name
	oready = stat.oready


	;将校准后的数据进行计算，获得磁场纵向分量和磁场横向分量，生成需要的图形以及数据
	IF oready EQ 1 THEN BEGIN
		l=l*(self.tenthousand)/self.calibrat;Sxpar(lh,'CALIBRAT')
		templ = l
		q=q*(self.tenthousand)/self.calibrat;Sxpar(qh,'CALIBRAT')
		u=u*(self.tenthousand)/self.calibrat;Sxpar(uh,'CALIBRAT')
	ENDIF ELSE BEGIN
		l=l*(self.tenthousand)/Sxpar(lh,'CALIBRAT')
		templ = l
		q=q*(self.tenthousand)/Sxpar(qh,'CALIBRAT')
		u=u*(self.tenthousand)/Sxpar(uh,'CALIBRAT')
	ENDELSE
	smoothvalue = 4
	binxy = 8
	low = 550
	length = 1200.
	l=Smooth(l,smoothvalue);磁场纵向分量
	q=Smooth(q,smoothvalue)
	u=Smooth(u,smoothvalue)
	q=Smooth(q,smoothvalue)
	u=Smooth(u,smoothvalue)
	l=Congrid(l,xd/4,yd/4,/interp)
	xxdim=xd/binxy
	yydim=yd/binxy
	ll=Congrid(l,xxdim,yydim,/interp)
	qq=Congrid(q,xxdim,yydim,/interp)
	uu=Congrid(u,xxdim,yydim,/interp)

	tt=Float(qq)*qq+Float(uu)*uu
	tt=Sqrt(tt)
	tt=(self.Ct)*Sqrt(tt);磁场横向分量
	re=Where(tt le low)
	IF re(0) NE -1 THEN BEGIN
		tt[re]=0.
		uu[re]=0.
		qq[re]=1.
	ENDIF
	angle=0.5*(-Atan(uu,qq)+3.14159);横向分量方位角
	xsi=Size(ll)
	ysi=xsi(2)
	xsi=xsi(1)
	xstep=1./(xsi+1.)
	ystep=1./(ysi+1.)
	tt[0,*]=0
	tt[*,0]=0
	tt[xsi-1,*]=0
	tt[*,ysi-1]=0
	tlength=Max(tt)/length
	bx=tt*Cos(angle)
	by=tt*Sin(angle)

	;180度不确定消除
	Free_field,ll,0,0,pbx,pby,pbz
	test=(((pbx*bx+pby*by) GT 0.0)-0.5)*2
	bx=bx*test
	by=by*test

	xConv=[0.,self.drawX/(Size(l))[1]]
	yConv=[0.,self.drawY/(Size(l))[2]]
	zMax=Max(l,Min=zMin)
    ratio=2./(zMax-zMin)
  	zConv=[-1.-zMin*ratio,ratio]
	self.sContour = Obj_New('IDLgrContour',l				 	, $
							C_Value = self.rv				 	, $
							C_LineStyle = self.rl	 			, $
							C_Color = self.rc					, $
							GeomZ = l						 	, $
							XCoord_Conv = xConv				 	, $
							YCoord_Conv = yConv				 	, $
							ZCoord_Conv = zConv				 	, $
							UValue = ''                 	 	, $
							C_Thick = 1					  	   )

	self.calContainer->Add,self.sContour
	self->Velovect1,bx,by,length=tlength,missing=low
	self.preModel->Add,self.sContour
	self.preWindow->Draw,self.preView

	;存储数据以供在处理完后显示8个参数时调用
	l = templ;stat.l
	cStat = { l 	: l 		, $
			  tt	: tt		, $
			  bx	: bx		, $
			  by	: by		  $
	       	 }
	Widget_Control , self.calibrateButton , Set_UValue = cStat
END
;+
;save bmp file
;+
PRO sesCalibrat::SaveBMP , event
	COMPILE_OPT IDL2

	IF Obj_Valid(self.oPolyGon) THEN BEGIN
		self.oPolyGon->SetProperty,hide = 1
	ENDIF
	IF Obj_Valid(self.oPolyGon1) THEN BEGIN
		self.oPolyGon1->SetProperty,hide = 1
	ENDIF
	self.preWindow -> Draw, self.preView
	image_Obj = self.preWindow -> Read()
	image_Obj -> GetProperty, Data = save_img
	Obj_Destroy,image_Obj

	filename = 'test.ps'
	PS_Plotter,save_img,event,filename
	self.havesaved = 1


END
;+
;load file
;+
PRO sesCalibrat::FileLoad
	COMPILE_OPT IDL2
	sep = (self.oSystem).sep
	path = self.RootDir+sep+'data'+sep+'dat'
	ll_name=Dialog_Pickfile(Filter='L*.fit',Path = path)
	IF ll_name EQ '' THEN BEGIN
	Widget_Control,self.saveButton,Sensitive=0
	Widget_Control,self.coalignButton,Sensitive=0
	Widget_Control,self.calibrateButton,Sensitive=0
	Return
	ENDIF
	qq_name=Dialog_Pickfile(Filter='Q*.fit',Path = path)
	IF qq_name EQ '' THEN BEGIN
	Widget_Control,self.saveButton,Sensitive=0
	Widget_Control,self.coalignButton,Sensitive=0
	Widget_Control,self.calibrateButton,Sensitive=0
	Return
	ENDIF
	uu_name=Dialog_Pickfile(Filter='U*.fit',Path = path)
	IF uu_name EQ '' THEN BEGIN
	Widget_Control,self.saveButton,Sensitive=0
	Widget_Control,self.coalignButton,Sensitive=0
	Widget_Control,self.calibrateButton,Sensitive=0
	Return
	ENDIF

	Widget_Control,self.saveButton,Sensitive=1
	Widget_Control,self.coalignButton,Sensitive=1
	Widget_Control,self.calibrateButton,Sensitive=1

	l=Prereadfits(ll_name,lh)
	q=Prereadfits(qq_name,qh)
	u=Prereadfits(uu_name,uh)
	header=lh

	IF N_Elements(swap) EQ 0 THEN BEGIN
		l=Swap_endian(l)
		q=Swap_endian(q)
		u=Swap_endian(u)
	ENDIF

	xd=Sxpar(header,'NAXIS1')
	yd=Sxpar(header,'NAXIS2')

	l_name=Strsplit(ll_name,sep,/extract)
	l_name=l_name[N_Elements(l_name)-1]
	q_name=Strsplit(qq_name,sep,/extract)
	q_name=q_name[N_Elements(q_name)-1]
	u_name=Strsplit(uu_name,sep,/extract)
	u_name=u_name[N_Elements(u_name)-1]
	IF N_Elements(o_name) EQ 0 THEN BEGIN
		o_name=strsplit(l_name,'.',/extract)
		o_name=o_name[0]+'.vps'
	ENDIF
	llen1=StrLen(ll_name)
	llen2=StrLen(l_name)
	qlen1=StrLen(qq_name)
	qlen2=StrLen(q_name)
	ulen1=StrLen(uu_name)
	ulen2=StrLen(u_name)
	ss_name=ll_name
	tt_name=qq_name
	rr_name=uu_name
	Strput,ss_name,'S',llen1-llen2
	Strput,tt_name,'T',llen1-llen2
	Strput,rr_name,'R',llen1-llen2

	stmp=FindFile(ss_name)
	ttmp=FindFile(tt_name)
	rtmp=FindFile(rr_name)
	IF (stmp[0] NE '') AND (stmp[0] NE '') AND (rtmp[0] NE '') THEN BEGIN
		sdat=Prereadfits(ss_name)
		tdat=Prereadfits(tt_name)
		rdat=Prereadfits(rr_name)
	ENDIF ELSE BEGIN
		wrong = Dialog_Message('Need matching file,Please reselect the right file!', Title = 'Wrong File')
		Return
	ENDELSE

	xConv=[0.,self.drawX/(Size(sdat))[1]]
	yConv=[0.,self.drawY/(Size(sdat))[2]]
	zMax=Max(l,Min=zMin)
    ratio=2./(zMax-zMin)
  	zConv=[-1.-zMin*ratio,ratio]
	self.sImage=Obj_New('IDLgrImage'		, $
						sdat				, $
						InterLeave=0		, $
						Location=[0,0,0]	, $
						XCoord_Conv=xConv	, $
						YCoord_Conv=yConv	  $
						)
	sImage = self.sImage
	self.preModel->Add,self.sImage
	self.preWindow->Draw,self.preView
	self.calContainer->Add,self.sImage

	;显示一些有用的系统信息
	hsos_no=Sxpar(header,'HSOS_NO')
	obs_date=Sxpar(header,'T_START')
	obs_time=StrLen(obs_date)
	obs_time=StrMid(obs_date,10,obs_time-10+1)
	obs_time=StrCompress(obs_time,/remove_all)
	IF StrLen(obs_time) EQ 7 THEN obs_time='0'+obs_time
	obs_date=StrMid(obs_date,0,10)
	wavelength=Sxpar(header,'WAVELENG')
	iframe=Sxpar(header,'FRAME')
	iframe=StrCompress(String(iframe),/remove_all)
	xpos=Sxpar(header,'LONGITUD')
	IF xpos LE 0 THEN BEGIN
		Strput,xpos,'E',0
	ENDIF ELSE BEGIN
		xpos='W'+xpos
	ENDELSE
	ypos=sxpar(header,'LATITUDE')
	IF ypos LE 0 THEN BEGIN
		Strput,ypos,'S',0
	ENDIF ELSE BEGIN
		ypos='N'+ypos
	ENDELSE


	Widget_Control,self.preText,$
	Set_Value=[' ----------- Useful information --------------',$
			   ' HSOS No.:		'+hsos_no								,$
			   ' Obs. Date:		'+obs_date								,$
			   ' Time:			'+obs_time								,$
			   ' Seeing:		'+sxpar(header,'SEEING')				,$
			   ' Wavelength:		'+wavelength						,$
			   ' Integrated frames:	'+iframe							,$
			   ' Disk coordinate:	'+xpos+', '+ypos					,$
			   ' ---------------------------------------------']

	;定义oready参数表示是否已经载入等值线
	oready = 0
	;自定义结构变量，存储需要调用的数据
	stat = { l 		: l 		, $
			 q 		: q 		, $
			 u 		: u 		, $
			 lh		: lh		, $
			 qh		: qh		, $
			 uh		: uh		, $
			 xd		: xd		, $
			 yd		: yd		, $
			 sdat	: sdat		, $
			 tdat	: tdat		, $
			 rdat	: rdat		, $
			 xConv	: xConv		, $
			 yConv	: yConv		, $
			 oready	: oready	, $
			 ss_name: ss_name	, $
			 tt_name: tt_name	, $
			 rr_name: rr_name	  $
	       }
	Widget_Control,self.preDraw,Set_UValue = stat
END
;+
;handle event
;+
PRO sesCalibrat::HandleEvent, event

	COMPILE_OPT IDL2

	oSystem = self.oSystem
	IF Tag_Names(event, /Structure_Name) EQ 'WIDGET_KILL_REQUEST' THEN BEGIN
		IF (self.sImage EQ Obj_New()) OR (self.havesaved EQ 1) THEN BEGIN
			Widget_Control, event.top, /Destroy
		ENDIF ELSE BEGIN
			status = Dialog_Message('Save the Image?', Title = 'Save', /Question)
			IF status EQ 'Yes'THEN BEGIN
				self->SaveBMP , event
				Widget_Control, event.top, /Destroy
			ENDIF
			IF status EQ 'No'THEN BEGIN
				Widget_Control, event.top, /Destroy
			ENDIF
		ENDELSE
	    Return
	ENDIF

	IF (Tag_Names(event,/Structure_Name) EQ 'WIDGET_TRACKING') THEN BEGIN
		Return
	ENDIF

	uName = Widget_Info(event.id, /UName)

	CASE uName OF
		'Pretreat':BEGIN
		END
		'PreDraw':BEGIN
			;鼠标取点事件入口
			IF self.mouseStat EQ 'Click' THEN self->Click,event
			IF self.mouseStat EQ 'Show' THEN self->Show,event
			IF event.type EQ 4 THEN BEGIN
				self.preWindow->Draw,self.preView
			ENDIF
		END
		'Read':BEGIN
			IF Obj_Valid(self.sImage) THEN BEGIN
				Obj_Destroy,self.preModel
				IF Obj_Valid(self.oPolyGon) THEN BEGIN
					Obj_Destroy,self.oPolyGon
					Obj_Destroy,self.oPolyGon1
				ENDIF
				self.mouseStat = ''
				Widget_Control,self.preDraw,Set_UValue=''
				Widget_Control,self.calibrateButton,Set_UValue=''
				Widget_Control,self.preText,Set_Value=''
				Widget_Control,self.preShowBase,Map = 1
				Widget_Control,self.preShowBase1,Map = 0
				self.preModel = Obj_New('IDLgrModel',Name='preModel')
				self.calContainer->Add,self.preModel
				self.preView->Add,self.preModel
				self.preWindow->Draw,self.preView
			ENDIF ELSE BEGIN
			END
			Widget_Control,self.saveButton,Sensitive=0
			Widget_Control,self.coalignButton,Sensitive=0
			Widget_Control,self.calibrateButton,Sensitive=0

			self->FileLoad

		END
		'Save':BEGIN
			self->SaveBMP , event
		END
		'Coalign':BEGIN
			Widget_Control,self.preShowBase,Map = 1
			Widget_Control,self.preShowBase1,Map = 0
			Widget_Control,self.preText,Set_Value=['','		Pick the first point']
			Obj_Destroy,self.oPolyGon
			Obj_Destroy,self.oPolyGon1
			self.mousestat = 'Click'
		END
		'Calibrate':BEGIN

			Obj_Destroy,self.oPolyGon
			Obj_Destroy,self.oPolyGon1
			IF Obj_Valid(self.sContour) THEN BEGIN
				Obj_Destroy,self.preModel
				self.preModel = Obj_New('IDLgrModel',Name = 'preModel')
				self.calContainer->Add,self.preModel
				self.preView->Add,self.preModel
				Widget_Control,self.preDraw,Get_UValue = stat
				sdat = stat.sdat
				xConv = stat.xConv
				yConv = stat.yConv
				oready = 1
				stat.oready = oready
				self.sImage=Obj_New('IDLgrImage'		, $
									sdat				, $
									InterLeave=0		, $
									Location=[0,0,0]	, $
									XCoord_Conv=xConv	, $
									YCoord_Conv=yConv	  $
									)
				self.preModel->Add,self.sImage
				self.calContainer->Add,self.sImage
				self.preWindow->Draw,self.preView
				Widget_Control,self.preDraw,Set_UValue = stat
			ENDIF ELSE BEGIN
			END

			self->CreateFlow

			Widget_Control,self.preText,Set_Value=['',$
			'	The fit format data has been calibrated.']
			self.mouseStat = 'Show'
		END
		'LevelSheet':BEGIN
			IF Obj_Valid(self.sContour) AND (event.type EQ 0) THEN BEGIN
				contourValue = Widget_Info(self.prop, Component = event.component  , $
										       Property_Value = event.identifier     )
			    event.component -> GetProperty, UValue = levelname
				FOR i = 0 , 1  DO BEGIN
					name = 'level'+Strtrim(String(i+1),2)
					IF levelname EQ name THEN BEGIN
						CASE event.identifier OF
						 	'MY_COLOR' : BEGIN
			                     self.conColor[i,*] = contourValue
			                     rv = (self.rv LT 0)
			                     self.rc = BytArr(3,28)
								 FOR j = 0,27 DO BEGIN
								 	IF rv[j] EQ 1 THEN BEGIN
			                     		self.rc[*,j] = self.rc[*,j] + (Transpose(self.conColor))[*,0]
			                     	ENDIF
			                     	IF rv[j] EQ 0 THEN BEGIN
			                     		self.rc[*,j] = self.rc[*,j] + (Transpose(self.conColor))[*,1]
			                     	ENDIF
			                     ENDFOR
			                     self.sContour -> setproperty, C_Color= self.rc
							END
							'MY_LINESTYLE' : BEGIN
							 	 self.conLineSet[i] = contourValue
							 	 rv = (self.rv LE 0)
			                     self.rl = LonArr(28)
								 FOR j = 0,27 DO BEGIN
								 	IF rv[j] EQ 1 THEN BEGIN
			                     		self.rl[j] = self.rl[j] + (self.conLineSet)[0]
			                     	ENDIF
			                     	IF rv[j] EQ 0 THEN BEGIN
			                     		self.rl[j] = self.rl[j] + (self.conLineSet)[1]
			                     	ENDIF
			                     ENDFOR
							 	 self.sContour -> SetProperty, C_Linestyle=self.rl
							END
						ELSE :
						ENDCASE
						self.preWindow->Draw,self.preView
					ENDIF
				ENDFOR
			ENDIF
		END
		'Text1':BEGIN
			IF Tag_Names(event, /Structure_Name) EQ 'WIDGET_TEXT_CH' THEN BEGIN
				Return
			ENDIF
			IF event.enter EQ 0 THEN BEGIN
				IF Obj_Valid(self.sContour) THEN BEGIN
				Widget_Control, event.id, Get_Value = value
				value = ((20000>value)<80000)
;				self.tenThousand = value
				self.calibrat = value
				value = Strtrim(String(value),2)
				Widget_Control, event.id, Set_Value = value
				ENDIF
			ENDIF
		END
		'Text2':BEGIN
			IF Tag_Names(event, /Structure_Name) EQ 'WIDGET_TEXT_CH' THEN BEGIN
				Return
			ENDIF
			IF event.enter EQ 0 THEN BEGIN
				IF Obj_Valid(self.sContour) THEN BEGIN
				Widget_Control, event.id, Get_Value = value
				value = 89. >(99.<value)
				self.Ct = value
				value = Strtrim(String(value),2)
				Widget_Control, event.id, Set_Value = value
				ENDIF
			ENDIF
		END
		ELSE:BEGIN
		ENDELSE
	ENDCASE
END
;+
;StartXmanager
;+
PRO sesCalibrat::StartXmanager

	COMPILE_OPT IDL2

	XManager, 'SunEle'                              , $
	           self.preBase                         , $
	           /No_Block                            , $
	           Event_Handler = 'sesFrame_Event'     , $
  			   Cleanup = 'sesFrame_Cleanup'
END
;+
;CreateGraphics
;+
PRO sesCalibrat::CreateGraphics

	COMPILE_OPT IDL2

	;主虚拟窗口
	self.preView = Obj_New('IDLgrView'						, $
							Location=[0,0]	 				, $
							Dimension = [640,480]           , $
							Viewplane_rec=[0.,0.,640.,480]	, $
							Color=[128,128,128] 			  )
	;放大用view
	self.showView = Obj_New('IDLgrView'						, $
							Location=[0,0]					, $
							Dim=[120,120]					, $
							Viewplane_rec=[0.,0.,120.,120.]	, $
							Color = [128,128,128]			  )
	self.preModel = Obj_New('IDLgrModel',Name='preModel')
	self.backModel = Obj_New('IDLgrModel',Name='backModel')
	self.preView->Add,self.preModel
	self.preView->Add,self.backModel
	self.calContainer->Add,self.preView
	self.calContainer->Add,self.showView
	Widget_Control,self.preDraw,Get_Value=preWindow
	self.preWindow = preWindow
	Widget_Control,self.showDraw,Get_Value=showWindow
	self.showWindow = showWindow
	self.showWindow->Draw,self.showView
	self.preWindow->Draw,self.preView
END
;+
;remove contour property
;+
PRO Calibrat_CleanupEvent,prop

	COMPILE_OPT IDL2

	Widget_Control, prop, Get_UValue=prop_value
	FOR i=0,1 DO BEGIN
		Obj_Destroy, (prop_value.ContourlevelComp)[i]
		Obj_Destroy, (prop_value.oComp)[i]
	ENDFOR
END
;+
;CreateWidget
;+
PRO sesCalibrat::CreateWidget
	COMPILE_OPT IDL2

	self.preBase = Widget_Base(Group_Leader = self.mainBase				, $
				                UName      = 'Pretreat' 	    		, $
				                UValue	   = self						, $
				                Title      = 'Data Process'			, $
				                Space      = 2          				, $
;				                XSize	   = self.xsize					, $
;				                YSize	   = self.ysize					, $
				                XOffSet    = self.xOff					, $
				                YOffSet    = self.yOff					, $
				                /Modal									, $
				                /Toolbar								, $
				                /Column		                 			, $
				                /TLB_KILL_REQUEST_EVENTS				, $
				                /Floating               			  	  )

	predrawBase = Widget_Base(self.preBase,yPad=2)

	self.preDraw = Widget_Draw(predrawBase				, $
								XOffset=3				, $
								YOffset=0				, $
								XSize=self.drawX		, $
								YSize=self.drawY		, $
								Renderer=1				, $
								Retain=2				, $
								UName='PreDraw'			, $
								Frame=1					, $
								/Motion_Events			, $
								/Button_Events			, $
								/Expose_Events			, $
								UValue  =''             , $
								GRAPHICS_LEVEL=2 		  )

	preRowBase = Widget_Base(self.preBase,Column=2,Space=2)

	preShow = Widget_Base(preRowBase)

	osver=StrUpCase(!Version.OS_Family)


	self.preShowBase = Widget_Base(preShow				, $
							  XPad=2					, $
							  Frame=1					, $
							  Map = 1					)
;							  XSize=(self.drawX)*0.5	, $
;							  YSize=(self.ysize)*0.23	  )

	IF osver EQ 'WINDOWS' THEN BEGIN
		self.preText = Widget_Text(self.preshowBase       	, $
				                    value     = ''        	, $
				                   	XSize=55             	, $
				                   	YSize=10	  )
	ENDIF ELSE BEGIN
		self.preText = Widget_Text(self.preshowBase       	, $
				                    value     = ''        	, $
				                   	XSize=49             	, $
				                   	YSize=10	  )
	ENDELSE

	self.preShowBase1 = Widget_Base(preShow				, $
							   XPad=2					, $
;							   Frame=1					, $
;							   XSize=(self.drawX)*0.5	, $
;							   YSize=(self.ysize)*0.23	, $
							   Map=0					  )

	self.showDraw = Widget_Draw(self.preShowBase1		, $
							XSize=120					, $
							YSize=120					, $
							Retain=2					, $
							UName='showDraw'			, $
							Frame=1						, $
							XOffset=100					, $
							/Expose_Events				, $
							UValue  =''             	, $
							GRAPHICS_LEVEL=2 		  	  )




	preControlBase = Widget_Base(preRowBase,Row=2)

	levelSet_bs = Widget_Base(preControlBase,Frame=1)

    oComp = ObjArr(2)
    ContourlevelComp = ObjArr(2)
 	FOR i=0, 1 DO BEGIN
		oComp[i] = Obj_New('IDLitvisContour')
		self.calContainer->Add,oComp[i]
	ENDFOR
    arr = Transpose(self.conColor)
 	FOR i=0, 1 DO BEGIN
    	ContourlevelComp[i] = Obj_New('IDLitVisContourlevel'                 , $
								 	  name='Level'+Strtrim(String(i+1),2)    , $
								 	  uvalue='level'+Strtrim(String(i+1),2)  , $
								      _contour=oComp[i]						   )
	    ContourlevelComp[i]->SetPropertyAttribute, 'MY_LABEL_COLOR', /HIDE
        ContourlevelComp[i]->SetPropertyAttribute, 'MY_LABEL_NOGAPS', /HIDE
        ContourlevelComp[i]->SetPropertyAttribute, 'MY_LABEL_SYMBOL', /HIDE
    	ContourlevelComp[i]->SetPropertyAttribute, 'MY_LABEL_TEXT', /HIDE
    	ContourlevelComp[i]->SetPropertyAttribute, 'MY_LABELLING', /HIDE
    	ContourlevelComp[i]->SetPropertyAttribute, 'MY_SYMBOL_SIZE', /HIDE
    	ContourlevelComp[i]->SetPropertyAttribute, 'MY_USE_LABEL_COLOR', /HIDE
    	ContourlevelComp[i]->SetPropertyAttribute, 'TICKFORMAT', /HIDE
    	ContourlevelComp[i]->SetPropertyAttribute, 'TICK_DEFINEDFORMAT', /HIDE
    	ContourlevelComp[i]->SetPropertyAttribute, 'FONT_INDEX', /HIDE
    	ContourlevelComp[i]->SetPropertyAttribute, 'FONT_STYLE', /HIDE
    	ContourlevelComp[i]->SetPropertyAttribute, 'FONT_SIZE', /HIDE
    	ContourlevelComp[i]->SetPropertyAttribute, 'MY_VALUE', /HIDE
    	ContourlevelComp[i]->SetPropertyAttribute, 'MY_COLOR', NAME=' Color'
        ContourlevelComp[i]->SetPropertyAttribute, 'MY_LINESTYLE', NAME=' Line Style'
        ContourlevelComp[i]->SetPropertyAttribute, 'MY_THICK',/HIDE
        ContourlevelComp[i]->SetPropertyAttribute, 'MY_LABEL_INTERVAL',/HIDE
        ContourlevelComp[i]->setproperty, MY_COLOR=arr[*,i]
        ContourlevelComp[i]->setproperty, MY_LINESTYLE=self.conLineSet[i]
        self.calContainer->Add,ContourlevelComp[i]
 	ENDFOR

    h_laber = Widget_label(LevelSet_bs           , $
                           Value=''  			 , $
                           /Align_Center         , $
                           /Dynamic_Resize       , $
                           yOffSet=0             , $
                           xOffSet=0               )

   	prop = WIDGET_PROPERTYSHEET(levelSet_bs                              , $
  								/SUNKEN_FRAME                            , $
  								XSIZE = 45                               , $
  								YSize = 2								 , $
  								UNAME = 'LevelSheet'                     , $
			   					VALUE = ContourlevelComp                 , $
			   					KILL_NOTIFY='Calibrat_CleanupEvent'        )

    self.prop = prop
	Widget_Control, prop, set_UValue={ContourlevelComp :  ContourlevelComp , $
	                                  oComp            :  oComp              }



	preButtonBase = Widget_Base(preControlBase			, $
								XPad=0					, $
								Column=2				, $
								XSize=286				, $
;							  	YSize=(self.ysize)*0.2	, $
								Space=0	  				  )

	textBase = Widget_Base(preButtonBase				, $
						   Row=2						   )
;						   YSize=(self.ysize)*0.1		  )

	parameter1 = Widget_Label(textBase					, $
;							  YSize = 10				, $
							  Value='Calibrat '			  )

	self.preText1 = Widget_Text(textBase       		 	, $
		                       value     = '50000'      , $
		                       UName  = 'Text1'	    	, $
		                       /EditAble           	 	, $
	                           /No_NewLine         		, $
	                           /Kbrd_Focus_Events		, $
		                   	   XSize=10				 	  )

	parameter2 = Widget_Label(textBase					, $
;							  YSize = 10				, $
							  Value='Ct(93.7) '			  )

	self.preText2 = Widget_Text(textBase       		 	, $
		                       value     = '93.7'       , $
		                       UName  = 'Text2'	    	, $
		                       /EditAble           		, $
	                           /No_NewLine         		, $
	                           /Kbrd_Focus_Events		, $
		                   	   XSize=10				 	  )

	buttonBase = Widget_Base(preButtonBase				, $
;							 YSize=(self.ysize)*0.1		, $
							 Space =1					, $
							 XPad =6					, $
							 YPad = 0					, $
							 Row =2						  )

	readButton = Widget_Button(buttonBase				, $
							   Value='Read'				, $
							   UName='Read'				, $
;							   YSize = 21				, $
							   XSize=70	   				  )

	self.saveButton = Widget_Button(buttonBase			, $
								   Value='Save'			, $
								   UName='Save'			, $
								   SENSITIVE=0			, $
;								   YSize = 21			, $
								   XSize=70			  	  )

	self.coalignButton = Widget_Button(buttonBase		, $
									  Value='Coalign'	, $
									  UName='Coalign'	, $
									  SENSITIVE=0		, $
;									  YSize = 21		, $
									  XSize=70			  )

	self.calibrateButton = Widget_Button(buttonBase			, $
									    Value='Calibrate'	, $
									    UName='Calibrate'	, $
									    SENSITIVE=0			, $
;									    YSize = 21			, $
									    XSize=70			  )

	Widget_Control,self.preBase,/Realize
END
;+
;clean up
;+
PRO sesCalibrat::CleanUp

	COMPILE_OPT IDL2

	Obj_Destroy , self.calContainer
END
;+
;initialize
;+
FUNCTION sesCalibrat::Init  , oSystem = oSystem

	COMPILE_OPT IDL2

	Device, Get_Screen_Size = screenSize
	yOff = (screenSize[1]-(oSystem.baseSize)[1])/2+5
	self.oSystem = oSystem
	self.mainBase = oSystem.mBase
	self.rootDir =oSystem.rootDir

	self.xSize = oSystem.baseSize[0]*0.64
	self.ySize = oSystem.baseSize[1]*0.91
	self.xOff = (oSystem.baseSize[0]-self.xSize)/2
	self.yOff = yOff
	self.drawX = 640
	self.drawY = 480

	self.click = 0
	self.havesaved = 0

	vi=[10.,20.,40.,80.,160.,320.,640.,960.,1280.,1600.,1920.,2240.,2560.,2880.]
	rvi=[10.,20.,40.,80.,160.,280.,424.,556.,677.,788.,890.,984.,1071.,1152.]
	self.rv=[-Reverse(rvi),rvi]
	self.conColor = [[255,127],[255,127],[255,127]]
	self.rc[0,*,*] = (self.rv LT 0)*128+127
	self.rc[1,*,*] = (self.rv LT 0)*128+127
	self.rc[2,*,*] = (self.rv LT 0)*128+127
	self.conLineSet = [1,0]
	self.rl = (self.rv LE 0.)

	self.tenthousand = 10000.
	self.Ct = 93.7
	self.calibrat = 25000
	self.calContainer = Obj_New('IDL_Container')
	self.font = Obj_New('IDLgrFont', 'Helvetica', Size=12)
	self.calContainer->Add,self.font
	self->CreateWidget
	self->CreateGraphics
	self->StartXmanager

	Return,1
END
;+
;Title class name
;+
PRO sesCalibrat__Define
	COMPILE_OPT IDL2
	void = { sesCalibrat                          , $
	         ;system parameter
	         mainBase           :    0L           , $
	         preBase            :    0L           , $
	         preDraw            :    0L           , $
	         showDraw			:	 0L			  , $
	         preShowBase		:	 0L			  , $
	         preShowBase1		:	 0L			  , $
	         preText            :    0L           , $
	         saveButton         :    0L           , $
	         coalignButton      :    0L           , $
	         calibrateButton    :    0L           , $
	         conLineSet	   		:	 IntArr(2)	  , $
	         conColor			:	 IntArr(2,3)  , $
	         rv					:	 FltArr(28)	  , $
	         rc					:	 BytArr(3,28) , $
	         rl					:	 LonArr(28)   , $
	         prop          		:    0L           , $
	         rootDir            :    ''           , $
	         xSize              :    0.           , $
	         ySize              :    0.           , $
	         xOff               :    0.           , $
	         yOff               :    0.           , $
	         drawX              :    0.           , $
	         drawY              :    0.           , $
	         click              :    0            , $
	         havesaved          :    0            , $
	         Mousestat          :    ''           , $
	         x1					:	0			  , $
			 y1					:	0			  , $
			 x2					:	0			  , $
			 y2					:	0			  , $
			 preText1			:	0			  , $
			 preText2			:	0			  , $
			 tenthousand		:	0.			  , $
			 Ct					:	0.			  , $
			 calibrat			:	0.			  , $
			 ;system objct

			 calContainer       :    Obj_New()    , $
			 font               :    Obj_New()    , $
			 oPolyGon			:	 Obj_New()	  , $
			 oPolyGon1			:	 Obj_New()	  , $
			 preView            :    Obj_New()    , $
			 preModel           :    Obj_New()    , $
			 showView			:	 Obj_New()	  , $
			 backModel			:	 Obj_New()	  , $
			 magModel			:	 Obj_New()	  , $
			 magImage			:	 Obj_New()	  , $
			 sImage             :    Obj_New()    , $
			 sContour           :    Obj_New()    , $
			 showWindow			:	 Obj_New()	  , $
			 preWindow          :    Obj_New()    , $
	         oSystem            :    Obj_New()      $

	        }
END