	pro yp_save_results

;******************************************************
;	SAVE COORDINATES OF THE SOLAR DISK
;******************************************************


Common Exch_yp,ID,SC,Moment,Data,Ini,Rec,Stokes,SSRT, $
	SpotCoord,SUN,Par,EW_line_save,SN_line_save,P_save,Factor,Output

WIDGET_CONTROL,/hour


	CASE !version.OS OF

'windows':	Delim='\'

'Win32':	Delim='\'

ELSE:		Delim='/'

	ENDCASE


a=Moment.Date

Subdirectory=strmid(a,6,2)+strmid(a,3,2)+strmid(a,0,2)

Name=strmid(a,0,2)+strmid(a,3,2)+strmid(a,6,2)

Filename=getenv('optics_dir')+Delim+Subdirectory+Delim+	$
	;strcompress(a,/rem)+'.crd'
	Name+'.crd'

a=''
xquestion,a,sel=['OK','Cancel'],text= $
['The center and radius are to be saved into the file','         '+Filename]

	IF strlowcase(a) ne 'ok' THEN BEGIN
kb_in_text,Filename,prompt='Input file name'
xquestion,a,sel=['OK','Cancel'],text= $
['The center and radius are to be saved into the file','         '+Filename]
	if strlowcase(a) ne 'ok' then return
	ENDIF

	if (findfile(Filename))(0) eq '' then $
	openw,lun,Filename,/get_lun else $
	openu,lun,Filename,/get_lun

		a=fstat(lun)
		point_lun,lun,a.size

aa=(name_extract(Data.Optics))(1)

	if strmid(aa,6,1) eq 'y' then Number=', '+Data.Number else Number=''

printf,lun,(name_extract(Data.Optics))(0)+Number
printf,lun,strtrim(Moment.Date,2)
printf,lun,strtrim(Moment.Time,2)
printf,lun,Output

	free_lun,lun

	end



	pro yp_input_image,cancel


;	This routine loads image into the window ID.Win(4)
;	and sets clipping rectangle in system variable !P corresponding
;	to disable clipping


Common Exch_yp,ID,SC,Moment,Data,Ini,Rec,Stokes,SSRT, $
	SpotCoord,SUN,Par,EW_line_save,SN_line_save,P_save,Factor,Output

cancel=0


Data.Map=(Num=0)


	if Data.Optics eq '' then path=getenv('optics_dir') $
		else path=subdir(Data.Optics)

	filename=pickfile(path=path,/read,file=Data.Optics)
	if filename eq '' then return

	WIDGET_CONTROL,/hour

Data.Optics=filename
aa=strlowcase((name_extract(Filename))(1))

	IF strmid(aa,6,1) eq 'y' THEN BEGIN

Inf1=(Inf2=(Number=(N_size='')))

openr,lun,Filename,/get_lun

Descr=fstat(lun)

readf,lun,Inf1
readf,lun,Number
readf,lun,Inf2
readf,lun,N_size

Inf1=Inf1+string(Number)
Inf2=Inf2+string(N_size)+'x'+strtrim(N_size,2)

Info_strings=strarr(Number)
readf,lun,Info_strings

Num=xselect(Info_strings,info=[Inf1,Inf2],tit='Please select a record')

	WIDGET_CONTROL,/hour

Offset=Descr.size-1L*N_size*N_size*Number
temp=assoc(lun,bytarr(N_size,N_size),Offset)
Y_data=temp(Num)

	free_lun,lun

Sz=(Size(Y_data))([1,2])
N_sc=((Sz(0) lt 400) and (Sz(1) lt 400))+1

X_shift=(!d.x_size-512)/2

if N_sc gt 1 then tvscl,rebin(Y_data,512,512),X_shift,X_shift $
else tvscl,Y_data,X_shift,X_shift


Moment.Date=strmid(aa,4,2)+' '+strmid(aa,2,2)+' '+strmid(aa,0,2)
aa=strtrim(strcompress(Info_strings(Num)),2)
i1=strpos(aa,' ',0)
i2=strpos(aa,' ',i1+1)
i3=strpos(aa,' ',i2+1)

Moment.Time=strmid(aa,i2+1,i3-i2-1)

N_version=strtrim(Info_strings(Num),2)
N_version=strmid(N_version,0,2)

Rec_Number=', '+strtrim(N_version,2)

	ENDIF ELSE BEGIN

N_version=''

Y_data=rd_image(filename, type=type, header=header)

if type eq 'UNRECOGNIZED' then begin
cancel=1
return
endif

wset,ID.Win(4)	&	erase,0

Sz=(Size(Y_data))([1,2])
N_sc=((Sz(0) lt 400) and (Sz(1) lt 400))+1

X_shift=(!d.x_size-512)/2

if N_sc gt 1 then tvscl,rebin(Y_data,512,512),X_shift,X_shift $
else tvscl,Y_data,X_shift,X_shift

time=fh_r_time(header, error=err)
date=fh_r_key(header,'date-obs',/ch, error=err)
if err then date=fh_r_key(header,'date',/ch, error=err)

	xtext,text=header, iden=iden

kb_in_time, date, time, prompt=(name_extract(filename))(0)

Moment.Date=date
Moment.time=time

if widget_info(iden, /valid) then widget_control, iden, /destroy

Rec_Number=''


	ENDELSE

	WIDGET_CONTROL,/hour

Data={PosEW:[-90.,0.], PosSN:[-90.,0.], PosSUN:[0.,0.], $
	BeamEW:0D, B_EW:Data.B_EW, BeamSN:0D, B_SN:Data.B_SN, $
	DxEW:[0D,0D,0D], DyEW:[0D,0D,0D], $
	DxSN:[0D,0D,0D], DySN:[0D,0D,0D], $
	Zoom:0, Press:0, Release:0, Mode:'Follow', Mouse:0, Optics:filename, $
	ClearEW:1, ClearSN:1, ClearSUN:1,  $
	GridColor:255B-Ini.colors(8), GridType:'Heliographical', $
	Optics_data:temporary(Y_data),	$
        Point1:[0.,0.], Point2:[0.,0.], Point3:[0.,0.], Map:0, $
	Number:strtrim(N_version,2)}




WIDGET_CONTROL,ID.Label,set_val=(name_extract(Data.Optics))(0)+Rec_Number+': '+	$
	Date_string(Moment.Date)+', '+Moment.Time+' UT', /hour

xyouts,0.01,0.94,/nor,Date_string(Moment.Date)+'!C'+Moment.Time+' UT',	$
	chars=1.5,col=255-!P.background

wset,ID.Win(0)
plot,(Data.Optics_data)(*,Sz(1)/2),xst=1,yst=16
Scale,temp,/mem	&	SC.IEWmain=(SC.ZEWmain=temp)

wset,ID.Win(1)
plot,(Data.Optics_data)(Sz(0)/2,*),indgen(Sz(0)),xst=16,yst=1
Scale,temp,/mem	&	SC.ISNmain=(SC.ZSNmain=temp)



suneph,Moment.Date,Moment.Time,SUN


empty
!P.clip=[0,0,1000,1000]
		end

	pro yp_draw_win


;	This routine draws models of the quiet Sun scans
;	as well as the scans themselves if they are available
;	in two windows.
;	Accordingly, in the third window map grid is drawn.


Common Exch_yp,ID,SC,Moment,Data,Ini,Rec,Stokes,SSRT, $
	SpotCoord,SUN,Par,EW_line_save,SN_line_save,P_save,Factor,Output

Sum_chan=[180,192]

;	****** DRAW MAIN WINDOW E - W ******


	device,set_graphics_function=3


wset,Id.win(0)	&	erase
plot,indgen(10),/nod,xst=4,yst=4
Scale,temp,/mem	&	SC.IEWmain=(SC.ZEWmain=temp)


;	****** DRAW MAIN WINDOW S - N ******


wset,Id.win(1)	&	erase
plot,indgen(10),/nod,xst=4,yst=4
Scale,temp,/mem	&	SC.ISNmain=(SC.ZSNmain=temp)


;	****** DRAW SUN MAP WINDOW ******

IF Data.Optics ne ''  THEN BEGIN

yp_input_image,cancel
if cancel then return

ENDIF ELSE BEGIN

Data.GridType = 'Heliographical'
!p.multi=0
wset,Id.win(4)	&	Erase

plot,indgen(10),/nod,xst=4,yst=4

scale,MapAxes0,/mem	&	SC.MapAxes0=MapAxes0

ENDELSE
!P.clip=[0,0,1000,1000]
empty
	end


	pro Zoomed_sun

;	Draws map grid, axes and diurnal parallel in
;	the large window for zoomed Sun image.
;	Accordingly, both FWHM beam positions for
;	both SSRT interferometers are drawn if they are
;	defined.


Common Exch_yp,ID,SC,Moment,Data,Ini,Rec,Stokes,SSRT, $
	SpotCoord,SUN,Par,EW_line_save,SN_line_save,P_save,Factor,Output


;	*** ZOOM WINDOW (SUN MAP) ***

window_set,ID.win(5),mul=0

	IF Data.Zoom eq 0 THEN BEGIN

MarginY=[1.,1.]*0.8
MarginX=MarginY*!D.Y_CH_SIZE/!D.X_CH_SIZE
map_set,SUN.B0*180/!Pi,0,0,/ort,/nobor,/grid,/lab,tit=' ', glinestyle=Ini.lines(1), $
Xmar=MarginX,Ymar=MarginY,col=Data.GridColor,latd=10,lond=10, $
	latal=1.,lonal=1.

scale,MapAxesZ,/mem	&	SC.MapAxesZ=MapAxesZ

XW=!x.window	&	YW=!y.window

SC.CentreZ=(convert_coord([XW(0)+XW(1),YW(0)+YW(1)]/2.,/nor,/to_dev))([0,1])
SC.RZ=(convert_coord([XW(1)-XW(0),YW(1)-YW(0)]/2.,/nor,/to_dev))([0,1])

plotline,1e6,SC.CentreZ,/dev,col=Data.GridColor,linestyle=Ini.lines(3)
plotline,0,SC.CentreZ,/dev,col=Data.GridColor,linestyle=Ini.lines(3)
plotline,-tan(SUN.Dp),SC.CentreZ,col=Ini.colors(6),/dev,linestyle=Ini.lines(1)

xyouts,0.1,0.95,Date_string(Moment.Date),/nor,col=Ini.colors(2)
xyouts,0.8,0.95,Moment.Time+' UT',/nor,col=Ini.colors(2)
Data.Zoom=1
	ENDIF ELSE BEGIN

scale,SC.MapAxesZ,/rec

	ENDELSE

if SpotCoord(2) le -1 then goto,LZoom
sz=size(SpotCoord)
if sz(0) eq 1 then in=1 else in=sz(2)
for i=0,in-1 do plots,SpotCoord([0,1],i),/data,psym=8,syms=0.7

LZoom:

B_EW=SC.CentreZ#[1,1,1]+transpose([[Data.DxEW*SC.RZ(0)],[Data.DyEW*SC.RZ(1)]])
for i=0,2,2 do plotline,tan(!Dpi/2-Par.G_EW)*SC.RZ(1)/SC.RZ(0), $
	B_EW(*,i),col=255-Ini.colors(3),line=Ini.lines(4),/dev

B_SN=SC.CentreZ#[1,1,1]+transpose([[Data.DxSN*SC.RZ(0)],[Data.DySN*SC.RZ(1)]])
for i=0,2,2 do plotline,tan(!Dpi/2-Par.G_SN)*SC.RZ(1)/SC.RZ(0), $
	B_SN(*,i),col=255-Ini.colors(5),line=Ini.lines(2),/dev


plots,[0.91,0.99],[0.115,0.115],lin=ini.lines(4),/nor
plots,[0.91,0.99],[0.075,0.075],lin=ini.lines(2),/nor

xyouts,0.85,0.1,'W-E',/nor,charsiz=1.2,col=255-Ini.colors(3)
xyouts,0.85,0.06,'S-N',/nor,charsiz=1.2,col=255-Ini.colors(5)

	end




	pro yp_event,ev


;	Event loop for routine Yp


Common Exch_yp,ID,SC,Moment,Data,Ini,Rec,Stokes,SSRT, $
	SpotCoord,SUN,Par,EW_line_save,SN_line_save,P_save,Factor,Output


		;** PROCESS DRAWABLE EVENTS **

X_shift=(!d.x_size-512)/2
Sz=(Size(Data.Optics_data))([1,2])
N_sc=((Sz(0) lt 400) and (Sz(1) lt 400))+1

GF_COPY=3			; initial grafics function COPY
GF_RESTORE=6		; grafics function XOR

Dgf0=GF_COPY

if Data.Mode eq 'Follow' then Dgf=GF_RESTORE else Dgf=GF_COPY

			FOR j=0,5 do $
		IF ev.id eq ID.View(j) THEN BEGIN
	if ev.press ne 0 then Data.press=1 	;Pressed button?
	if ev.release ne 0 then Data.press=0	;Released button?
		ENDIF

IF ev.id eq ID.View(0) THEN BEGIN

window_set,Id.win(0),sca=SC.IEWmain
temp=(convert_coord(ev.x, ev.y, /DEVICE,  /TO_DATA))([0,1])

WIDGET_CONTROL,ID.LabelEWSN(0), 	$
	set_val=string(temp(0),temp(1),format='(F6.1,",",2X,F6.1)')

	if Data.press then begin


		CASE Data.Mode OF

'Follow':	begin

device,set_graphics_function=Dgf

	if not Data.ClearEW then $
	plots,[(convert_coord(Data.PosEW([0,0]),/to_norm))([0,0])],[0,1], $
	/norm,col=255 else Data.ClearEW=0	; Restore precedent lines

Old=Data.PosEW
Data.PosEW=[temp(0),temp(0)*N_sc+X_shift]

plots,[(convert_coord(Data.PosEW([0,0]),/to_norm))([0,0])],[0,1], $
	/norm,col=255

window_set,Id.win(4), sca=SC.MapAxes0	;SUN MAP WINDOW

if not Data.ClearSUN then $
plots, [1,1]*Old(1),[0,!d.y_vsize],/dev,col=255 else Data.ClearSUN=0

plots, [1,1]*Data.PosEW(1),[0,!d.y_vsize],/dev,col=255

device,set_graphics_function=Dgf0
empty

		end

'Scope':	begin
return
	end

		ELSE:
		ENDCASE
	endif

ENDIF

	IF ev.id eq ID.View(2) THEN BEGIN

window_set,Id.win(2),sca=SC.IEWaux

temp=(convert_coord(ev.x, ev.y, /DEVICE,  /TO_DATA))([0,1])

WIDGET_CONTROL,ID.LabelEWSN(2),set_val= $
string(temp(0),temp(1),format='(F6.1,",",2X,F6.1)')


		if (Data.press gt 0) then begin

Data.PosEW=temp	&	wait,0.2

for j=0,1 do WIDGET_CONTROL,ID.Leftbase(j),map=1-j
WIDGET_CONTROL,ID.LabelEWSN(0),set_val= $
string(Data.PosEW(0),Data.PosEW(1),format='(F6.1,",",2X,F6.1)')

		endif

	ENDIF


	IF ((ev.id eq ID.View(0))  or (ev.id eq ID.View(2))) THEN return


	IF ev.id eq ID.View(1) THEN BEGIN

window_set,Id.win(1),sca=SC.ISNmain
temp=(convert_coord(ev.x, ev.y, /DEVICE,  /TO_DATA))([0,1])

WIDGET_CONTROL,ID.LabelEWSN(1),set_val= $
string(temp(0),temp(1),format='(F6.1,",",2X,F6.1)')

	if (Data.press gt 0) then begin

		CASE Data.Mode OF

'Follow':		begin

device,set_graphics_function=Dgf

	if not Data.ClearSN then $
	plots,[0,1],[(convert_coord(Data.PosSN([0,0]),/to_norm))([1,1])], $
	/norm,col=255 else Data.clearSN=0

Old=Data.PosSN
Data.PosSN=[temp(1),temp(1)*N_sc+X_shift]

plots,[0,1],[(convert_coord(Data.PosSN([0,0]),/to_norm))([1,1])], $
	/norm,col=255

window_set,Id.win(4), sca=SC.MapAxes0

if not Data.ClearSUN then $
	plots, [0,!d.y_vsize], [1,1]*Old(1),/dev,col=255	$
		else Data.ClearSUN=0

plots, [0,!d.y_vsize], [1,1]*Data.PosSN(1),/dev,col=255

device,set_graphics_function=Dgf0
empty

			end

'Scope':		begin

		end

		ELSE:
		ENDCASE
	endif
ENDIF


	IF ((ev.id eq ID.View(1))  or (ev.id eq ID.View(3))) THEN return

	IF ev.id eq ID.View(4) THEN BEGIN

window_set,Id.win(4),sca=SC.MapAxes0		;Map Window
temp=(convert_coord(ev.x, ev.y, /DEVICE,  /TO_DATA))([0,1])

if temp(0) lt 0 then DirEW='E' else DirEW='W'
if temp(1) lt 0 then DirSN='S' else DirSN='N'

EW=strcompress(DirEW+string(abs(temp(0)),Format='(F6.1)'),/rem)
SN=strcompress(DirSN+string(abs(temp(1)),Format='(F5.1)'),/rem)

if not(Data.Map) then Map_coord=' ' else Map_coord=';  '+EW+',  '+SN

WIDGET_CONTROL,ID.MapLabel,set_val= $
		string(ev.X,ev.Y,format='(I4,",",2X,I4)')+Map_Coord

	if (ev.press ne 0) and (Data.Mouse eq 1) then begin	; Mark spot
plots,temp,/data,psym=8,syms=0.7	&	Data.Mouse=0
empty		&	return
	endif


	if (Data.press gt 0) then begin


wset,ID.Win(0)
plot,(Data.Optics_data)(*,(ev.Y-X_shift)/N_sc > 0 < (Sz(1)-1)),xst=1,yst=16
Scale,temp,/mem	&	SC.IEWmain=(SC.ZEWmain=temp)

wset,ID.Win(1)
plot,(Data.Optics_data)((ev.X-X_shift)/N_sc > 0 < (Sz(0)-1),*),indgen(Sz(0)),xst=16,yst=1
Scale,temp,/mem	&	SC.ISNmain=(SC.ZSNmain=temp)

wait,0.1
	Data.ClearEW=(Data.ClearSN=1)

		Data.ClearSUN=0
	endif
empty
	return
	ENDIF

	IF ev.id eq ID.View(5) THEN BEGIN
window_set,Id.win(5),sca=SC.MapAxesZ		;Zoom Window
Data.PosSUN=(convert_coord(ev.x, ev.y, /DEVICE,  /TO_DATA))([0,1])

WIDGET_CONTROL,ID.ZoomLabel,set_val= $
	string(Data.PosSUN(0),Data.PosSUN(1),format='(F6.1,",",2X,F6.1)')

if ev.press ne 0  then plots,Data.PosSUN,/data,psym=8,syms=0.7	; Mark spot

empty		&	return
	ENDIF




;**************** OTHER EVENTS **********************



WIDGET_CONTROL,ev.id,GET_UVALUE = wuv,/hour

	CASE wuv OF

"DONE"	:  	begin

WIDGET_CONTROL,/hour

		if ID.group_leader ne 0L then begin
if WIDGET_INFO(ID.group_leader,/valid) then $
	WIDGET_CONTROL,ID.group_leader,/show
		endif

!P=P_save

ID=(SC=(Moment=(Data=(Ini=(Rec=(Stokes=(SSRT=0)))))))
P_save=(SpotCoord=(SUN=(Par=(EW_line_save=(SN_line_save=0)))))
xyouts,0,0,'!3 ',/nor

!x.style=(!y.style=(!x.range=(!y.range=0)))

WIDGET_CONTROL,ev.top,/DEST

		end



"QuitZoom":	for j=0,1 do WIDGET_CONTROL,ID.Togglebase(j),map=1-j

"XMTool":	XMTool,group=ev.top

"XLoadct":	Xloadct,group=ev.top

"Scope":	Data.Mode='Scope'

"Follow":	Data.Mode='Follow'

"Save":		begin
	yp_save_results
	widget_control,ev.top,/show
		end

"Point_1":	Data.Point1=[Data.PosEW(1), Data.PosSN(1)]

"Point_2":	Data.Point2=[Data.PosEW(1), Data.PosSN(1)]

"Point_3":		begin

Data.Point3=[Data.PosEW(1), Data.PosSN(1)]

A=def_circle(Data.Point1,Data.Point2,Data.Point3)
Centre=A([0,1])		&	Radius=A(2)

Output=A

wset,ID.Win(4)

temp=!p.color		&	!p.color=Data.Gridcolor

	if strmid(!version.release,0,1) lt 5 then begin

!x.style=(!y.style=1)

!x.range=[-Centre(0),!d.x_size-Centre(0)]/Radius
!y.range=[-Centre(1),!d.y_size-Centre(1)]/Radius

map_set,SUN.B0*!Radeg,0,0, /grid, glinestyle=Ini.lines(1), $
        /ortho,/noerase,pos=[0,0,1,1],/nobor,latdel=10,londel=10,col=Data.Gridcolor

!x.style=(!y.style=(!x.range=(!y.range=0)))

	endif else begin

map_set,SUN.B0*!Radeg,0,0, /ortho,/noerase,pos=[0,0,1,1],/nobor

!x.s=[0.5*!d.x_size, Radius] / float(!d.x_size)
!y.s=[0.5*!d.y_size, Radius] / float(!d.y_size)

P_clip_save=!P.clip
!p.clip = [0, 0, !d.x_size, !d.y_size]

MAP_GRID, latdel=10, londel=10, col=Data.Gridcolor,  glinestyle=Ini.lines(1)

!P.clip=P_clip_save

	endelse



		!p.color=temp

!x.style=(!y.style=(!x.range=(!y.range=0)))

Data.Map=1
scale,temp,/mem
if wuv eq 'Carrington' then SC.MapAxesK=temp else SC.MapAxes0=temp


yp_save_results

	widget_control,ev.top,/show

		end

"Coordinates":	begin

kb_in_helio,H_coord

Norm_coord=(convert_coord(H_coord,/data,/to_norm))([0,1])

plots,[1,1]*Norm_coord(0),[0,1],/nor
plots,[0,1],[1,1]*Norm_coord(1),/nor

empty
		end



"Save_Image":	begin
widget_control,/hour

New_File=pickfile(path=subdir(Data.Optics), filt='*.fit', $
	file=(name_extract(Data.Optics))(1)+'.fit')

if New_File eq '' then return

if (findfile(New_File))(0) ne '' then begin
widget_control,/hour

xquestion,a,sel=['OK','Cancel'],text= ['This file already exists. Overwrite?']
	if strlowcase(a) ne 'ok' then return
endif

widget_control,/hour

struc=fh_st_ssrt(/soho)

struc.object='SUN'
struc.type_obs='FULL DISK'
struc.time_obs=Moment.Time
struc.date_obs=Moment.Date
struc.telescop='SOHO'

	name=(name_extract(Data.Optics))(1)
struc.wave=strmid(name,strlen(name)-3,3)
struc.origin='SOHO'



struc.radius=SUN.R*!radeg*60
struc.p0=SUN.dp*!radeg
struc.lat0=SUN.B0*!radeg
struc.lon0=SUN.Karr*!radeg
struc.bscale=1.
struc.bzero=0.

Centre=Output([0,1])-64
Radius=Output(2)

Sz=size(Data.Optics_data)

struc.x_origin=-(struc.radius)/Radius*Sz(1)/2
struc.y_origin=-(struc.radius)/Radius*Sz(2)/2
struc.x_obs=struc.radius/Radius*Sz(1)
struc.y_obs=struc.radius/Radius*Sz(2)
struc.center_x=Centre(0)/Sz(1)*struc.x_obs+struc.x_origin
struc.center_y=Centre(1)/Sz(2)*struc.y_obs+struc.y_origin

header=fh_mk_ssrt(Sz, struc)

openw, lun, New_File,/get_lun
writeu, lun, byte(header)
writeu, lun, Data.Optics_data
free_lun, lun


		end




"Input":	begin
kb_in_text,a,prompt='Solar center:', text='Print: Center(0), Center(1), Radius <Enter>'

	if a eq '' then return else begin

a=strcompress(a,/rem)

i1=strpos(a,',')
i2=strpos(a,',',i1+1)

Centre=[strmid(a,0,i1),strmid(a,i1+1,i2-i1-1)]
Radius=strmid(a,i2+1,10)

wset,ID.Win(4)

temp=!p.color		&	!p.color=Data.Gridcolor

	if strmid(!version.release,0,1) lt 5 then begin

!x.style=(!y.style=1)

!x.range=[-Centre(0),!d.x_size-Centre(0)]/Radius
!y.range=[-Centre(1),!d.y_size-Centre(1)]/Radius

map_set,SUN.B0*!Radeg,0,0, /grid, glinestyle=Ini.lines(1), $
        /ortho,/noerase,pos=[0,0,1,1],/nobor,latdel=10,londel=10,col=Data.Gridcolor

!x.style=(!y.style=(!x.range=(!y.range=0)))

	endif else begin

map_set,SUN.B0*!Radeg,0,0, /ortho,/noerase,pos=[0,0,1,1],/nobor

!x.s=[0.5*!d.x_size, Radius] / float(!d.x_size)
!y.s=[0.5*!d.y_size, Radius] / float(!d.y_size)

P_clip_save=!P.clip
!p.clip = [0, 0, !d.x_size, !d.y_size]

MAP_GRID, latdel=10, londel=10, col=Data.Gridcolor,  glinestyle=Ini.lines(1)

!P.clip=P_clip_save

	endelse


		!p.color=temp

Data.Map=1
scale,temp,/mem
if wuv eq 'Carrington' then SC.MapAxesK=temp else SC.MapAxes0=temp
empty
	endelse

Output=float([Centre,Radius])

		end

"Calculator":	wcalc


"Suncalc":	begin
WIDGET_CONTROL,/hourglass
suncalc,group_leader=ev.top, Moment.Date,Moment.Time,/modal

		end

"Help"	:	xtext,file='yp.hlp',group=ev.top

"VC":	spawn,'vc'

"NC":	spawn,'nc'

"DOS"	:	spawn

"Parameters":	param_ssrt,time=Moment.time, Date=Moment.Date,Rec=Rec,group=ev.top

"Clear":		begin
Data.ClearEW=(Data.ClearSN=(Data.ClearSUN=1))
Data.PosEW=(Data.PosSN=[-90.,0.])	&	Data.PosSUN=[5.,5.]
	yp_draw_win
!P.clip=[0,0,1000,1000]
		end

"E-W FWHM":	begin			;	WINDOW E-W

window_set,Id.win(0),sca=SC.IEWmain
SpacingEW=abs(tan(!Dpi/2-P(1))*Df/F0)
Pos=transpose((convert_coord([[Data.PosEW-Data.BeamEW/SpacingEW/2], $
	[Data.PosEW+Data.BeamEW/SpacingEW/2]],/to_norm))(0,*))
for i=0,1 do plots,[Pos(i),Pos(i)],[0,1], /norm,col=255B-Ini.colors(3)
empty
		end

"S-N FWHM":	begin			;	WINDOW S-N

window_set,Id.win(1),sca=SC.ISNmain
SpacingSN=abs(tan(!Dpi/2-Q(1))*Df/F0)
Pos=transpose((convert_coord([[Data.PosSN-Data.BeamSN/SpacingSN/2], $
	[Data.PosSN+Data.BeamSN/SpacingSN/2]],/to_norm))(0,*))
for i=0,1 do plots,[Pos(i),Pos(i)],[0,1], /norm,col=255B-Ini.colors(5)
empty
		end

"SUN FWHM":	begin			;	SUN MAP WINDOW

window_set,Id.win(4), sca=SC.MapAxes0
for i=0,2,2 do plotline,tan(!Dpi/2-G_EW)*SC.R0(1)/SC.R0(0), $
	Data.B_EW(*,i),col=255B-Ini.colors(3),/dev
for i=0,2,2 do plotline,tan(!Dpi/2-G_SN)*SC.R0(1)/SC.R0(0), $
	Data.B_SN(*,i),col=255B-Ini.colors(5),/dev
empty
		end

"Zoom":		begin
	for j=0,1 do WIDGET_CONTROL,ID.Togglebase(j),map=j
	Zoomed_sun
		end

"Kbrd": BEGIN

kb_in_helio,SpotCoord,prompt='Input spots coordinates', group=ev.top
window_set,Id.win(4), sca=SC.MapAxes0
if SpotCoord(2) le -1 then goto,Lkbrd
sz=size(SpotCoord)
if sz(0) eq 1 then in=1 else in=sz(2)

	FOR i=0,in-1 DO BEGIN
IF SpotCoord(2,i) EQ 1. THEN SpotCoord(*,i)=[(convert_coord(SpotCoord(*,i)*SC.R0+ $
		SC.Centre0,/dev,/to_data))([0,1]),0]
plots,SpotCoord([0,1],i),/data,psym=8,syms=0.7
	ENDFOR
Lkbrd:
WIDGET_CONTROL,ev.top,/show
	END

"File":	begin

	rspotcoord,Moment,Coord,num=in
if in eq 1 then b0=0. else b0=fltarr(1,in)
Coord=[Coord,b0]
if SpotCoord(2) le -1. then SpotCoord=Coord else SpotCoord=[[Coord],[SpotCoord]]
window_set,Id.win(4), sca=SC.MapAxes0

for i=0,in-1 do plots,SpotCoord([0,1],i),/data,psym=8,syms=0.7
WIDGET_CONTROL,ev.top,/show
	end

"Mouse": Data.Mouse=1

"Open":	begin

widget_control, /hour

yp_input_image, cancel
if cancel then return

WIDGET_CONTROL,ev.top,/show

		end

"Mild":		Data.Gridcolor=Ini.colors(7)

"Medium":	Data.Gridcolor=Ini.colors(8)

"Sharp":	Data.Gridcolor=Ini.colors(9)

"Remove":	begin
if Data.Optics eq '' then erase,255 else begin
yp_input_image, cancel
if cancel then return
endelse

	CASE Data.GridType OF
	'Carrington':	window_set,ID.Win(4),scal=SC.MapAxesK
 	'Heliographical':	window_set,ID.Win(4),scal=SC.MapAxes0
	ELSE:
	ENDCASE
		end

"Carrington":	begin
Data.GridType='Carrington'	&	Lon=SUN.Karr*!Radeg
		end

"Heliographical":begin
Data.GridType = 'Heliographical'	&	Lon=0.
		end

"Axes":		begin
temp=!p.color		&	!p.color=Data.Gridcolor
window_set,ID.Win(4);,scal=SC.MapAxes0
plotline,1e6,SC.Centre0,/dev	&	plotline,0,SC.Centre0,/dev
!p.color=temp
		end

"Diurnal parallel":	begin
temp=!p.color		&	!p.color=Data.Gridcolor
window_set,ID.Win(4);,scal=SC.MapAxes0
	plotline,-tan(SUN.Dp),SC.Centre0,/dev,linestyle=Ini.lines(1)
!p.color=temp
			end

"PS":			begin


goto,ObhPot

set_plot,'PS'

Sum_chan=[180,192]

!x.thick=(!y.thick=(!P.thick=(!P.charthick=2)))

	CASE !version.OS OF

'windows':	Delim='\'

'Win32':	Delim='\'

ELSE:		Delim='/'

	ENDCASE

PS_Filename=getenv('gr_prg')+Delim+	$
	newfilename(model=strcompress(Moment.Date,/rem),filt='*.PS')

device,file=PS_Filename,xsize=17.78,ysize=17.78,yoff=6.3

Data.GridType = 'Heliographical'
!p.multi=0
xyouts,0,0,'!3 ',/nor

map_set,SUN.B0*180/!Pi,0,0,/ortho,/nobor,/grid,/lab, glinestyle=Ini.lines(1), $
	pos=[0,0,1,1],latdel=10,londel=10

xyouts,0.02,0.95,/nor,Date_string(Moment.Date)+'!C'+Moment.Time

Centre0=[!x.window(0)+!x.window(1), !y.window(0)+!y.window(1)]/2.
R0=[!x.window(1)-!x.window(0), !y.window(1)-!y.window(0)]/2.

Centre0=(convert_coord(Centre0,/norm,/to_dev))([0,1])
R0=(convert_coord(R0,/norm,/to_dev))([0,1])

plotline,1e6,Centre0,/dev	&	plotline,0,Centre0,/dev
plotline,-tan(SUN.Dp),Centre0,/dev,linestyle=Ini.lines(1)

plotline,tan(!Dpi/2-G_EW)*R0(1)/R0(0), $
(Centre0#[1,1,1]+transpose([[Data.DxEW*R0(0)],[Data.DyEW*R0(1)]]))(*,1),/dev,linest=0

goto, First_only

ChanEWobs=Data.PosEW(0)+2

OEWobs=ORD_RECOGNIZE(ChanEWobs,NoEW,OEW,CEW)

CoordEW=acos(OEWobs*C/chanfreq(ChanEWobs,Rec)/D)
BeamEW=0.886*C/(N*F0*D*abs(sin(P(1))))*par.BeamEW(1)/par.BeamEW(0)

CoordEW=[CoordEW-BeamEW/2,CoordEW,CoordEW+BeamEW/2]
DyEW=[0D,0D,0D]
DxEW=(P(1)-coordEW)/cos(G_EW)/Rsol

KEW=tan(!Dpi/2-G_EW)
BEW=DyEW-KEW*DxEW

B_EW=Centre0#[1,1,1]+ $
	transpose([[DxEW*SC.R0(0)],[DyEW*SC.R0(1)]])

;plotline,tan(!Dpi/2-G_EW)*R0(1)/R0(0), $
;(Centre0#[1,1,1]+transpose([[DxEW*R0(0)],[DyEW*R0(1)]]))(*,1),/dev,linest=5

First_only:

device,/close

PS_Filename=newfilename(model=strcompress(Moment.Date,/rem),filt='*.PS')

device,file=PS_Filename,xsize=17.78,ysize=17.78,yoff=6.3

plot_scans, model=CHECKVIS(Rec,SSRT.NoEW,SSRT.CEW), $
	int=Stokes.IEW, pol=Stokes.VEW, Xmar=Ini.PmargX, $
		Xran=[1,Sum_chan(Rec)],Char=Ini.Char

xyouts,0.02,0.95,/nor,Date_string(Moment.Date)+'!C'+Moment.Time+'!CE-W'

plots,[(convert_coord(Data.PosEW,/to_norm))([0,0])],[0,1], /norm,linest=0

device,/close

PS_Filename=newfilename(model=strcompress(Moment.Date,/rem),filt='*.ps')

device,file=PS_Filename,xsize=17.78,ysize=17.78,yoff=6.3

plot_scans, model=CHECKVIS(Rec,SSRT.NoSN,SSRT.CSN), $
	int=Stokes.ISN, pol=Stokes.VSN, Xmar=Ini.PmargX, $
		Xran=[1,Sum_chan(Rec)],Char=Ini.Char

xyouts,0.02,0.95,/nor,Date_string(Moment.Date)+'!C'+Moment.Time+'!CS-N'

plots,[(convert_coord(Data.PosSN,/to_norm))([0,0])],[0,1], /norm,linest=0

device,/close

	CASE !version.OS OF

'windows':	Initial_device='WIN'

'Win32':	Initial_device='WIN'

ELSE:		Initial_device='X'

	ENDCASE


set_plot,Initial_device
!x.thick=(!y.thick=(!P.thick=(!P.charthick=1)))


ObhPot:
wset,ID.Win(4)
x=tvrd()

filename=newfilename(filter='*.gif', $
	path=getenv('optics_dir'),model='map')
a=''
xquestion,a,sel=['OK','Cancel'],text= $
['Image is to be saved into the file','         '+Filename]
	if strlowcase(a) ne 'ok' then begin
kb_in_text,Filename,prompt='Input file name'
xquestion,a,sel=['OK','Cancel'],text= $
['Image is to be saved into the file','         '+Filename]
	if strlowcase(a) ne 'ok' then return
	endif

	CASE !version.OS OF

'windows':	Delim='\'

'Win32':	Delim='\'

ELSE:		Delim='/'

	ENDCASE

write_gif, strcompress(getenv('optics_dir')+Delim+Filename,/rem),x

			end


ELSE:
	ENDCASE

	IF (wuv eq 'Mild') or (wuv eq 'Medium') or (wuv eq 'Sharp')  THEN BEGIN

;WIDGET_CONTROL,ID.GridTypelabel,set_val=Data.GridType,/hour
if Data.GridType eq 'Carrington' then temp=SC.MapAxesK else temp=SC.MapAxes0
window_set,ID.Win(4),scal=temp
temp=!p.color		&	!p.color=Data.Gridcolor
!P.clip=[0,0,1000,1000]
map_grid,/label,latdel=10,londel=10,col=Data.Gridcolor, glinestyle=Ini.lines(1)
!p.color=temp

	ENDIF

	IF (wuv eq 'Heliographical') or (wuv eq 'Carrington')  THEN BEGIN

;WIDGET_CONTROL,ID.GridTypelabel,set_val=Data.GridType,/hour
wset,ID.Win(4)
if Data.Optics eq '' then erase,255 else begin
yp_input_image, cancel
if cancel then return
endelse

temp=!p.color		&	!p.color=Data.Gridcolor
map_set,SUN.B0*!Radeg,Lon,0, /grid,/label, glinestyle=Ini.lines(1), $
	/ortho,/noerase,pos=[0,0,1,1],/nobor,latdel=10,londel=10,color=Data.Gridcolor
!p.color=temp		&	scale,temp,/mem
if wuv eq 'Carrington' then SC.MapAxesK=temp else SC.MapAxes0=temp

	ENDIF

empty

	end


pro yp,Centre,Radius, group_leader=group_leader,Date=Date,time=time

Common Exch_yp,ID,SC,Moment,Data,Ini,Rec,Stokes,SSRT, $
	SpotCoord,SUN,Par,EW_line_save,SN_line_save,P_save,Factor,Output

if xregistered('yp') then return

	CASE !version.OS OF

'windows':	Factor=1.

'Win32':	Factor=1.

ELSE:		Factor=1.04

	ENDCASE



Output=[0.,0.,0.]

SpotCoord=[0.,0.,-1.]

if n_elements(group_leader) le 0 then group_leader = 0L

ID={View:Lonarr(6), Win:Lonarr(6), Label:0L, ToggleBase:[0L,0L], $
Leftbase:[0L,0L], LabelEW:0L, LabelEWSN:lonarr(4), MapLabel:0L, ZoomLabel:0L, $
group_leader:group_leader}

Ax={Axes, x:{!Axis}, y:{!Axis}, z:{!Axis}, map:!Map}

SC={ZEWmain:Ax, IEWmain:Ax, VEWmain:Ax, $
ZSNmain:Ax, ISNmain:Ax, VSNmain:Ax, $
ZEWaux:Ax, IEWaux:Ax, VEWaux:Ax,    $
ZSNaux:Ax, ISNaux:Ax, VSNaux:Ax,    $
MapAxes0:Ax, R0:fltarr(2), Centre0:fltarr(2), $
MapAxesK:Ax, RK:fltarr(2), CentreK:fltarr(2), $
MapAxesZ:Ax, RZ:fltarr(2), CentreZ:fltarr(2)}

	Ax=0

WIDGET_CONTROL,/hourglass
M=strlowcase(findfile('vga_drv.rcg'))
	if equiv(M,'') then M=1 else begin
openr,lun,'vga_drv.rcg',/get_lun
readf,lun,M
free_lun,lun
	endelse		;M=0 for L-310 else M=1 (to plot lines with various styles)

Ini={Lines:indgen(5)*M(0),$
	colors:[0B, 	$		; Color Table
		255B,	$		; Background
		 0B,	$		; Main color for inscriptions
		255B,	$		; E-W
		160B,	$		; Reserved
		160B,	$		; S-N
		60B,	$		; Diurnal parallel
		200B,	$		; Mild grid
		100B,	$		; Medium grid
		0B],	$		; Sharp grid
	PmargX:[3.5,3.5], Char:1.5}

temp=make_array(2,3,val=2000D)

Data={PosEW:[-90.,0.], PosSN:[-90.,0.], PosSUN:[0.,0.], $
	BeamEW:0D, B_EW:temp, BeamSN:0D, B_SN:temp, $
	DxEW:[0D,0D,0D], DyEW:[0D,0D,0D], $
	DxSN:[0D,0D,0D], DySN:[0D,0D,0D], $
	Zoom:0, Press:0, Release:0, Mode:'Follow', Mouse:0, Optics:'', $
	ClearEW:1, ClearSN:1, ClearSUN:0,  $
	GridColor:255B-Ini.colors(8), GridType:'Heliographical', $
	Optics_data:bytarr(640,640),	$
	Point1:[0.,0.], Point2:[0.,0.], Point3:[0.,0.], Map:0, Number:''}


if n_elements(Date) le 0 then Date='01 01 00'
if n_elements(Time) le 0 then Time='00 00 00'
	Moment={Date:Date, Time:Time}

Rec=0

P_save=!P

Sum_chan=[180,192]
Fmin=chanfreq(1,Rec)
Fmax=chanfreq(Sum_chan(Rec),Rec)
F0=(Fmax+Fmin)/2
Df=(Fmax-Fmin)/(Sum_chan(Rec)-1)



	device,get_scr=scr

if scr(1) lt 500 then ZoomWin=scr*0.8 else ZoomWin=scr*0.92

if scr(1) lt 1000 then TV_size=512 else TV_size=640

TV_size=[1,1]*TV_size*Factor

Scan_size0=[(scr(0)-TV_size(0))*0.9,scr(1)/2.3]

Scan_size1=[TV_size(0),scr(1)/2.3]

	Xs=	[[[Scan_size0]#replicate(1,2)], $
		[[Scan_size1]#replicate(1,2)],	$
		[TV_size], [ZoomWin]]


;***** Drawing widget

Mainbase= widget_base(/fra, group=group_leader, $
	tit='Image preprocessing')

for j=0,1 do ID.ToggleBase(j)=widget_base(Mainbase)

;***** Left Base

if scr(1) lt 500 then Wholebase=widget_base(ID.ToggleBase(0),/row,/scroll, $
	x_scroll_size=scr(0)*0.96, y_scroll_size=scr(1)*0.91) else $
		Wholebase=widget_base(ID.ToggleBase(0),/row)
LeftTogglebase=widget_base(Wholebase)
for j=0,1 do ID.Leftbase(j)=widget_base(LeftTogglebase,/colu)

 XPdMenu,	['"DONE"			DONE',	$

		'"File"		{',		$
				'"Open"		Open',	$
				'"Save"		{',	$
					'"Results"	Save',	$
					'"Image"	Save_Image',	$
					'"Screen"	PS','}',$
							 '}',	$

		'"Tools"	{',			$

			'"Screen"{',			$
				'"Zoom"			Zoom',	$
				'"Clear"		Clear','}',$

			'"Grid"	{',			$

				'"Diurnal parallel"	Diurnal parallel',	$
				'"Axes"			Axes',		$

				'"Contrast"	{',	$
					'"Mild"		Mild',		$
					'"Medium"	Medium',	$
					'"Sharp"		Sharp','}',$

				'"Longitude"	{',	$
					'"Heliographical"	Heliographical',	$
					'"Carrington"		Carrington','}',	$

				'"Remove"	Remove',	$
						'}',	$

			'"Calculator"		Calculator', $
			'"Coord. converter"	Suncalc', $
			'"Parameters"		Parameters', $

			'"Palette"		XLoadct',	$

			'"XManager Tool"	XMTool',	$

			'"Shell"			DOS', 		$

			'"Norton Commander"	{','"NC"	NC',	$
						'"VC"	VC','}',	$

	       			'}',				$
		'"Help"			Help',			$
	   	'"Circle"		{',		$
				'"Point 1"	Point_1',	$
				'"Point 2"	Point_2',	$
				'"Point 3"	Point_3',	$
				'"Input"	Input','}'], ID.Leftbase(0)


Emptystring='            '

ID.label=WIDGET_LABEL(ID.Leftbase(0), val= $
	Emptystring+Date_string(Moment.Date)+', '+Moment.Time+' UT')

Scroll_size=480

if scr(1) gt 1000 then	ID.view(4)=WIDGET_DRAW(ID.Leftbase(0), XS=640, $
	YS=640, /motion, /button, retain=2) else $
			ID.view(4)=WIDGET_DRAW(ID.Leftbase(0), XS=640, $
	YS=640, /motion, /button, retain=2,/scroll,	$
	x_scroll=Scroll_size,y_scroll=Scroll_size)

ID.Maplabel=WIDGET_LABEL(ID.Leftbase(0), val= $
	'                ')

	for j=2,3 do begin
ID.view(j)=WIDGET_DRAW(ID.Leftbase(1), XS=Xs(0,j), YS=Xs(1,j), /motion, /button_events, retain=2)
ID.LabelEWSN(J)=WIDGET_LABEL(ID.Leftbase(1),val=Emptystring)
	endfor

ZoomBase=WIDGET_BASE(ID.ToggleBase(1),/row)
junk=WIDGET_BASE(ZoomBase,/colu)
junk1=WIDGET_BUTTON(junk,VAL='DONE',uval='QuitZoom')
junk=WIDGET_BASE(ZoomBase,/colu)
ID.view(5)=WIDGET_DRAW(junk, XS=Xs(0,5), YS=Xs(1,5), /motion, /button_events, retain=2)
ID.ZoomLabel=WIDGET_LABEL(junk,val=Emptystring)

;***** Right Base
Rightbase=widget_base(Wholebase,/colu)
	for J=0,1 do begin
ID.view(J)=WIDGET_DRAW(Rightbase, XS=Xs(0,J),YS=Xs(1,J), /motion, /button_events, retain=2)
ID.LabelEWSN(J)=WIDGET_LABEL(Rightbase,val=Emptystring)
	endfor

;*****


WIDGET_CONTROL,ID.Leftbase(1),map=0
WIDGET_CONTROL,ID.Togglebase(1),map=0

WIDGET_CONTROL,Mainbase,/real,/hour

	for J=0,5 do begin
WIDGET_CONTROL,ID.view(J),GET_VALUE=temp  &  ID.Win(J)=temp
wset,ID.Win(J)
	endfor

if scr(1) lt 1000 then WIDGET_CONTROL,ID.view(4),set_draw_view=[1,1]*(640-Scroll_size)/2

WIDGET_CONTROL,/hour

circ
yp_draw_win

xmanager,'yp',Mainbase,group=group_leader

Centre=Output([0,1])	&	Radius=Output(2)

	end