;+
;procedure: ssl2dsl
;
;Purpose: despins (spins) THEMIS  data
;
;         SSL<-->DSL;
;
;         interpolates the spinphase, spin period
;
;inputs
;
;	name_thx_xxx_in 	... data in the input coordinate system (t-plot variable name)
;   name_thx_spinper		... spin period (t-plot variable name)
;   name_thx_spinphase   ... spin phase  (t-plot variable name)
;   name_thx_xxx_out     ... name for output  (t-plot variable name)
;
;keywords:
;   TRANSFORMATIONS
;
;   /DSL2SSL inverse transformation
;Example:
;      ssl2dsl('tha_fgl_ssl','tha_spinper','tha_spinphase','tha_fgl_dsl')
;      ssl2dsl('tha_fgl_dsl','tha_spinper','tha_spinphase','tha_fgl_ssl',/DSL2SSL)
;Notes: under construction!!
;
;Written by Hannes Schwarzl
; $LastChangedBy: kenb-mac $
; $LastChangedDate: 2007-02-02 11:35:42 -0800 (Fri, 02 Feb 2007) $
; $LastChangedRevision: 277 $
; $URL: svn+ssh://thmsvn@ambrosia.ssl.berkeley.edu/repos/ssl_general/trunk/cotrans/ssl2dsl.pro $
;-
pro ssl2dsl,name_thx_xxx_in,name_thx_spinper,name_thx_spinphase,name_thx_xxx_out,DSL2SSL=DSL2SSL


; get the data using t-plot names
get_data,name_thx_xxx_in,data=thx_xxx_in
get_data,name_thx_spinper,data=thx_spinper
get_data,name_thx_spinphase,data=thx_spinphase


thx_xxx_out=thx_xxx_in


;set a constant depending if the phase decreases with time
;phaseDir=-1.0d   ;decreasing phase
phaseDir= 1.0d  ;increasing phase

if keyword_set(DSL2SSL) then begin
	PRINT,'DSL-->SSL'
	isDSL2SSL=1
endif else begin
	PRINT,'SSL-->DSL'
	isDSL2SSL=0
endelse



count=SIZE(thx_xxx_in.X,/N_ELEMENTS)
PRINT,'number of DATA records: ',count

countPhase=SIZE(thx_spinphase.X,/N_ELEMENTS)
PRINT,'number of Phase records: ',countPhase


;interpolate phase
thx_xxx_in=thx_xxx_out
thx_spinphase_highres=thm_interpolate_state(thx_xxx_in=thx_xxx_in,thx_spinper=thx_spinper,thx_spinphase=thx_spinphase) ;--> phase constructed according to the nearest neighbor spin phase, spin period


phase=thx_spinphase_highres.Y*!dpi/180.d0



if isDSL2SSL eq 0 then begin
	;despin
	thx_xxx_out.Y[*,0]=thx_xxx_in.Y[*,0]*  cos(phase) -thx_xxx_in.Y[*,1]* sin(phase)
	thx_xxx_out.Y[*,1]=thx_xxx_in.Y[*,0]*  sin(phase) +thx_xxx_in.Y[*,1]* cos(phase)
endif else begin
	;spin
	thx_xxx_out.Y[*,0]= thx_xxx_in.Y[*,0]*  cos(phase) +thx_xxx_in.Y[*,1]* sin(phase)
	thx_xxx_out.Y[*,1]=-thx_xxx_in.Y[*,0]*  sin(phase) +thx_xxx_in.Y[*,1]* cos(phase)
endelse


store_data,name_thx_xxx_out,data=thx_xxx_out


PRINT,'done'

;RETURN, thx_xxx_out
;RETURN, phase
end



;###################################################################