; XXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXX
;
; interpolate spin phase to have same time resolution than time_scm
;
; P. Robert, CETP, January 2007
;
; XXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXX

  PRO scm_spin_interpol, time_state,spinpha,spinper,time_scm,spinpha_int

; we do nothing if the two time arrays are identical

  idiff=diff_2arrays1D(time_state,time_scm,average,sigma)
  IF (idiff EQ 0 ) THEN RETURN

  nsta=N_ELEMENTS(time_state)
  nscm=N_ELEMENTS(time_scm)
  spinpha_int=FLTARR(nscm)
  nwar=0

; interpolation between the two closest times

  FOR i=0L,nscm-1L DO BEGIN
  j=-1L
  condition=1

; look for the 2 closest time in time_state
  WHILE condition DO BEGIN
  j=j+1L
  IF(j LE nsta-2) THEN BEGIN
                  condition=NOT(time_scm(i) GE time_state(j) $
                            AND time_scm(i) LE time_state(j+1)) 
                  ENDIF ELSE BEGIN
                  PRINT, '*** scm_spin_interpol: error j+1=',j+1, $
                         ' > ndmax=',nsta-1
                  PRINT, '*** Nothing is done...'
                  RETURN
                  ENDELSE
  ENDWHILE

; computation of the interpolated value
; two estimate, from time_stae before and time_state after

  phiA= spinpha(j)   +360.D*(time_scm(i)- time_state(j))/spinper(j)
  phiB= spinpha(j+1) -360.D*(time_state(j+1) - time_scm(i))/spinper(j+1)

  phiA= phiA MOD(360.D)
  phiB= phiB MOD(360.D)

  IF(phiA LT 0.) THEN phiA= phiA +360.
  IF(phiB LT 0.) THEN phiB= phiB +360.

; difference between the two estimate

  xa=COS(phiA*!pi/180.)
  xb=COS(phiB*!pi/180.)
  ya=SIN(phiA*!pi/180.)
  yb=SIN(phiB*!pi/180.)
  
  dotpro=(xa*xb+ya*yb)/(sqrt(xa^2+ya^2)*sqrt(xb^2+yb^2))
  IF(dotpro GT  1.) THEN dotpro= 1.
  IF(dotpro LT -1.) THEN dotpro=-1.
  difpha=ACOS(dotpro)*180./!pi

; warnig if diff > 2 degres

  IF(ABS(difpha) GT 2.) THEN BEGIN
  nwar=nwar+1
  IF(nwar LT 100) THEN PRINT, $
  '*** scm_spin_interpol: bad estimate, prec.=',difpha,' degres !!!' 
  IF(nwar EQ 100) THEN PRINT, $
  '*** scm_spin_interpol: print warning limited to 100 ...'
  ENDIF

; averaging with different weight

  gdt=time_state(j+1) - time_state(j)
  WA= (time_state(j+1) - time_scm(i))/gdt
  WB= (time_scm(i)   - time_state(j))/gdt
  spinpha_int(i)=  WA*phiA + WB*phiB

  ENDFOR

  END
; XXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXX