;******************************************************************************
;* PRCEDURE
;*      PRO papco_cluster_rapid_sc_intercal, starttime, endtime,LMIN,LMAX,intercal_arr
;* DESCRIPTION:  
;*      code reads in RAPID IESSPECT spin averaged data in counts for
;*      specified L range (from LMIN,LMAX) to allow interspacecraft
;*      RAPID comparisons.
;*   
;*
;* INPUTS:       
;*      starttime and endtime strings in general papco format
;*      or just '8/01/2002 00:00:00' ie 
;*      mn/dy/year hr:mn:sc 
;*      LMIN and LMAX Lrange values.
;* KEYWORDS:
;*  
;* OUTPUT:	 
;*     intercal_arr, strucutre of 4 sc start end times for each Lrange pass
;*     with 6 averaged (over Lrange) energy channel counts. 
;*
;* MATT TAYLOR feb 2003
;******************************************************************************


PRO papco_cluster_rapid_sc_intercal, starttime, endtime,LMIN,LMAX,LUT_VALUE,intercal_arr,$
                                 HAVE_DATA = HAVE_DATA
;have left these in for testing
starttime='8/01/2002 00:00:00'
endtime='8/28/2002 00:00:00'
LUT_VALUE=0
LMIN=5
LMAX=7.5
;***************************8

;delete current plots
if !d.window ne -1 then begin
 for i=0,(!d.window) do begin
wdelete,i
endfor
endif

COMMON cluster_eph_data, input_header, input_data
COMMON cluster_rapid_slice_1, time, zmat, data, yarr, utitle, uytitle, uztit
COMMON cluster_rapid
COMMON mjdt, mjdt_start, mjdt_end
COMMON get_error, get_err_no, get_err_msg
;COMMON cluster_rapid_4sc, data4sc_timed
COMMON intercalkeep1, inbound_outbound_info, data4sc_timed,cl_lvalues_interp,ch

if keyword_set(HAVE_DATA) then goto, have_data

papco, /set_only
LMIN_VALUE=LMIN
LMAX_VALUE=LMAX
result = convert_timeToSeconds(starttime, /t90, /mjdt)
t1 = result.value
result = convert_timeToSeconds(endtime, /t90, /mjdt)
t2 = result.value
mjdt_start = t1 & mjdt_end = t2

    ;read ineph data    
    r_cluster_eph

  
; read in start and end timesand find beginning and end of whole
; orbits within that time  from apogee times;

  ;set the begin end end times. CLUSTER cdf time is in cdf epoch. 
    convert_t90_to_date, mjdt_start, yr,day_oy,hr,min,sec,mo,cmo,day_om, /mjdt
    cdf_epoch,xut1,yr,mo,day_om,hr,min,sec,0.0,/COMPUTE_EPOCH
    tai_start=UTC2TAI({YEAR:yr, MONTH:mo, DAY:day_om, HOUR:hr, MINUTE:min, $
                SECOND:sec, MILLISECOND:0});
    convert_t90_to_date, mjdt_end, yr,day_oy,hr,min,sec,mo,cmo,day_om, /mjdt
    cdf_epoch,xut2,yr,mo,day_om,hr,min,sec,0.0,/COMPUTE_EPOCH
    tai_end=UTC2TAI({YEAR:yr, MONTH:mo, DAY:day_om, HOUR:hr, MINUTE:min, $
                 SECOND:sec, MILLISECOND:0})

time_diff=tai_start-(xut1/1000.0)

   index=where((input_data.epoch ge xut1) and (input_data.epoch lt xut2),cc)
    if cc ne 0 then eph_data=input_data(index)
    ndat=n_elements(eph_data)    
    eph_epoch=eph_data.EPOCH;eph data epoch values
    eph_tai=(eph_epoch/1000.0)+time_diff


orbit_nums=eph_data.(1)
or_no_str=string(orbit_nums)
apogee_region=strpos(or_no_str,'.5')
apogee_region_idx=where(apogee_region ne -1,c)
idx_start_apogee=apogee_region_idx(0)
start_apogee=orbit_nums(idx_start_apogee)

stop_apogee=string(orbit_nums(apogee_region_idx(n_elements(apogee_region_idx)-1)))
stop_apogee=(  string(fix(stop_apogee))+'.5')
idx=strpos(or_no_str,stop_apogee)
idx_stop_apogee=where(idx ne -1)
idx_stop_apogee=idx_stop_apogee(0)


eph_data=eph_data(idx_start_apogee:idx_stop_apogee)


; now re-write start and end times from start of whole  orbit at apogee

xut1=eph_data(0).(0)
xut2=eph_data(n_elements(eph_data)-1).(0)
cdf_epoch,xut1,yr,mo,day_om,hr,min,sec,/break
start_start=strcompress(string(mo)+'/'+string(day_om)+'/'+string(yr)+string(hr)+':'+string(min)+':'+string(sec))
 tai_start=UTC2TAI({YEAR:yr, MONTH:mo, DAY:day_om, HOUR:hr, MINUTE:min, $
                SECOND:sec, MILLISECOND:0});
cdf_epoch,xut2,yr,mo,day_om,hr,min,sec,/break
end_end=strcompress(string(mo)+'/'+string(day_om)+'/'+string(yr)+' '+string(hr)+':'+string(min)+':'+string(sec))
    tai_end=UTC2TAI({YEAR:yr, MONTH:mo, DAY:day_om, HOUR:hr, MINUTE:min, $
                 SECOND:sec, MILLISECOND:0})

result = convert_timeToSeconds(start_start, /t90, /mjdt)
t1 = result.value
result = convert_timeToSeconds(end_end, /t90, /mjdt)
t2 = result.value
mjdt_start = t1 & mjdt_end = t2

time_diff=tai_start-(xut1/1000.0)
;set up dummy plotinfo and add in required parameters
 result=papco_getplotinfostruct()    
;add required plot parameters
plotinfo=result
plotinfo.typevector(2)=2;data source = RALIF
plotinfo.typevector(1)=2;data type IES_ESPCT
plotinfo.ioptions(3)=1;energy_CHANNEL
plotinfo.dataunits=0;units
plotinfo.typevector(0)=0;sc_id
plotinfo.ioptions(11)=1
plotinfo.xut1=xut1
plotinfo.xut2=xut2
plotinfo.ioptions(11)=0;force make data
;plotinfo.ioptions(5)=1;4scflag NOTE!! using 4sc read does obtain LUT values 
panelvector=[0,1,1]
orbitno=0
smooth = plotinfo.ioptions(0)
OUTPUT=2
currplotinfo=plotinfo
sc_id = plotinfo.typevector(0)
;read in RAPID data for requested  time

for i=0,3 do begin
 currPlotinfo.typevector(0)=i;sc_id
  r_cluster_rapid,currPlotinfo
    ;check if data read O.K.
    IF get_err_no ne 0 THEN BEGIN
      get_err_msg = 'can not read 4 SC data, SC missing'
      GOTO, found_error
    ENDIF
    p_cluster_rapid_spec, [-99, 0, 0], CurrplotInfo, OUTPUT=2
    ;check if any data contained for time period
    IF get_err_no ne 0 THEN BEGIN
      get_err_msg = 'can not read 4 SC data, no common data for time period'
      GOTO, found_error
    ENDIF    
   LUT=data.LUT
dummy = {time:time, zmat:zmat,LUT:LUT}
    IF i EQ 0 THEN $ ;make structure for data from 4 spacecraft
      data4sc = create_struct('cl'+varprt(i+1), dummy) $
    ELSE $ ;add spacecraft to structure
      data4sc = create_struct(data4sc,'cl'+varprt(i+1), dummy)
endfor

;now, need to obtain common time axis for data. Use the time of the
;spaceraft chosen as basis for time, interpolate all other spacraft
;data to that time
message, 'Folding data onto time of '+sc_names(sc_id), /cont

data4sc_timed = {time:data4sc.(sc_id).time,  $
                   zmat1:data4sc.(sc_id).zmat,  $
                   zmat2:data4sc.(sc_id).zmat,  $
                   zmat3:data4sc.(sc_id).zmat,  $
                   zmat4:data4sc.(sc_id).zmat,   $
                   LUT_1:data4sc.(sc_id).LUT,   $
                   LUT_2:data4sc.(sc_id).LUT,   $
                   LUT_3:data4sc.(sc_id).LUT,   $
                   LUT_4:data4sc.(sc_id).LUT }
                  
  ;get center time from reference spacraft
  t_ref = ( data4sc_timed.time(*, 0)+data4sc_timed.time(*, 1) )/2.0
  ;get number of channels in data array
  result = size(data4sc.(sc_id).zmat,  /struct)
  ch =  result.dimensions(1)
   
  FOR i = 0,  3 DO BEGIN ;loop through spacecraft
    IF i EQ sc_id THEN continue ;skip for referecne spacecraft   
    message, '...doing for Cluster '+varprt(i+1), /cont
    t_center = ( data4sc.(i).time(*, 0)+data4sc.(i).time(*, 1) )/2.0
    ;loop through channels to interpolate
    FOR j = 0, ch-1 DO $
      data4sc_timed.(i+1)(*, j)= $
        interpol(data4sc.(i).zmat(*, j), t_center, t_ref)
        data4sc_timed.(i+5)=interpol(data4sc.(i).(2),t_center,t_ref)
  ENDFOR 


 found_error:
  plotinfo.typevector(0) = sc_id 
  plotinfo.ioptions(0) = smooth

;now have RAPID data for required time period
TIME=data4sc_timed.time
RAPID_TIME=(TIME(*,0)+TIME(*,1))/2.0
RAPID_tai_time=RAPID_TIME+tai_start
RAPID_DATA=dblarr(4,n_elements(RAPID_TIME),ch)
for i=0,3 do RAPID_DATA(i,*,*)=data4sc_timed.(i+1)


eph_data=input_data    
eph_epoch=eph_data.EPOCH;eph data epoch values
eph_tai=(eph_epoch/1000.0)+time_diff

;find L_values in cluster_eph
    tags=tag_names(eph_data)
    pos=strpos(tags,'L_VALUE')
    idx =where(pos ne -1,c)

;setup loop which creates interpolated eph L values for each s/c
;interpolated to RAPID data time

;loops for each spacecraft

size_T=size(RAPID_time)
size_L=size(eph_data.(idx(0)))
CL_LVALUES=dblarr(4,size_L(1))
CL_LVALUES_INTERP=dblarr(4,size_T(1))

orbit_numbers=size_T
orbit_numbers=interpol(eph_data.(1),eph_tai,RAPID_tai_time)
 flags=bytarr(size_L(1))
 for i=0,3 do begin
    CL_LVALUES(i,*)=eph_data.(idx(i)) 
    idx1=where (CL_LVALUES(i,*) eq -1, c)
if c gt 0 then  flags(idx1)=1
    new_flags=interpol(flags,eph_tai,RAPID_tai_time)
    idx2 =where(new_flags gt 0,cc)
    CL_LVALUES_INTERP(i,*)=interpol(CL_LVALUES(i,*),eph_tai,RAPID_tai_time)

if cc gt 0 then  CL_LVALUES_INTERP(i,idx2) = -1

 endfor

;sort out data into inbound and outbound passes 
;do single orbit analysis for min value of L
  CL_ORBIT_VALUES=fltarr(size_T(1))
  CL_ORBIT_VALUES=interpol(eph_data.(1),eph_tai,RAPID_tai_time)
orbits=fix(cl_orbit_values(n_elements(cl_orbit_values)-1))-fix(cl_orbit_values(0))

;find positions of apogee's thruout orbit number values
apogee_pos=fltarr(orbits+1)
min_l=fltarr(4,orbits)
min_l_pos=fltarr(4,orbits)
apogee_pos(0)=0
apogee_pos(orbits)=(n_elements(CL_ORBIT_VALUES)-1)

;print,apogee_pos
for i=1,orbits-1 do begin
test_apogee=strpos(string(CL_ORBIT_VALUES),string(start_apogee+i))
test_apogee_real=where(test_apogee ne -1,c)
apogee_pos(i)=test_apogee_real(0)
endfor

for j=0,3 do begin
for i=1,orbits do begin
min_l(j,i-1)=min(CL_LVALUES_INTERP(j,(apogee_pos(i-1)):(apogee_pos(i))),min_pos) 
min_l_pos(j,i-1)=apogee_pos(i-1)+min_pos


endfor
endfor

;set up inbound - outbound selection

dummy_channels={in_pass:fltarr(6),out_pass:fltarr(6)}
dummy_lut={LUT_IN:fltarr(1),LUT_OUT:fltarr(1)}
dummy_11={IN_PASS:fltarr(2),OUT_PASS:fltarr(2),tai_in_pass:fltarr(2),tai_out_pass:fltarr(2),MIN_L:fltarr(1),av_ch:dummy_channels,av_ch_err:dummy_channels,LUT:dummy_lut}
dummy_22={CL1:dummy_11,CL2:dummy_11,CL3:dummy_11,CL4:dummy_11}
inbound_outbound_info=replicate(dummy_22,orbits)

;----------------------------------------------------------------------------------------------------------
for i=0,3 do begin

for j=0,(orbits-1) do begin

inbound_outbound_info(j).(i).IN_PASS(0)=apogee_pos(j)
inbound_outbound_info(j).(i).OUT_PASS(1)=apogee_pos(j+1)
inbound_outbound_info(j).(i).IN_PASS(1)=min_l_pos(i,j)
inbound_outbound_info(j).(i).OUT_PASS(0)=min_l_pos(i,j)
inbound_outbound_info(j).(i).MIN_L=min_l(i,j)
endfor

endfor

L_start_in=fltarr(4,orbits)
L_stop_in=fltarr(4,orbits)
L_index_mark_in=0
L_index_mark_out=0
new_inbound_outbound_info=inbound_outbound_info

lmin=3&lmax=10


 for k=0,orbits-1 do begin

  for j=0,3 do begin

   start_in=inbound_outbound_info(k).(j).IN_PASS(0) ;start index for inbound pass
   stop_in=inbound_outbound_info(k).(j).IN_PASS(1) ;end index for inboundpass
    ;print,start_in,stop_in

   INPASS=CL_LVALUES_INTERP(j,start_in:stop_in)  ;range of L values for given start:stopfor inbound
   L_index_in = where ((INPASS GE LMIN) and (INPASS LE LMAX),cc)
   ;assume no breaks in index,ie continuous data
   ;re-write inpass start stops in terms of L range
   inbound_outbound_info(k).(j).IN_PASS(0)=start_in+(L_index_in(0))
   inbound_outbound_info(k).(j).IN_PASS(1)=start_in+(L_index_in(n_elements(L_index_in)-1))
   inbound_outbound_info(k).(j).tai_in_pass(0)=RAPID_TAI_TIME(inbound_outbound_info(k).(j).IN_PASS(0))
   inbound_outbound_info(k).(j).tai_in_pass(1)=RAPID_TAI_TIME(inbound_outbound_info(k).(j).IN_PASS(1))
   start_out=inbound_outbound_info(k).(j).OUT_PASS(0) ;start index for inbound pass
   stop_out=inbound_outbound_info(k).(j).OUT_PASS(1) ;end index for inboundpass
   OUTPASS=CL_LVALUES_INTERP(j,start_out:stop_out);range of L values for given start:stop
   L_index_out = where ((OUTPASS GE LMIN) and (OUTPASS LE LMAX),cc)
   inbound_outbound_info(k).(j).OUT_PASS(0)=start_out+(L_index_out(0))
   inbound_outbound_info(k).(j).OUT_PASS(1)=start_out+(L_index_out(n_elements(L_index_out)-1))
   inbound_outbound_info(k).(j).tai_out_pass(0)=RAPID_TAI_TIME(inbound_outbound_info(k).(j).OUT_PASS(0))
   inbound_outbound_info(k).(j).tai_out_pass(1)=RAPID_TAI_TIME(inbound_outbound_info(k).(j).OUT_PASS(1))
   ;assume con
  endfor
endfor
;**------------------------****---------------------------****----------------------------------**


have_data:
lmin=6   &  lmax=10
lstep=0.2
lut=5
data_spike_ceiling=20000

dmy1={pass:0, in_out:0, lrange:intarr(2),av_counts:fltarr(4,6)}

found=0

for pass=0,n_elements(inbound_outbound_info)-1 do begin
for in_out =0,1 do begin

lrange=[lmin,lmin+lstep]


while lrange(1) le lmax do begin
   c=fltarr(4,n_elements(ch))
  for sc=0,3 do begin
   for channel=0,ch-1 do begin
      ir=inbound_outbound_info(pass).(sc).(in_out)
      idx=where(((CL_LVALUES_INTERP(sc,ir(0):ir(1)) ge lrange(0)) and (CL_LVALUES_INTERP(sc,ir(0):ir(1)) le lrange(1))) and $
                (data4sc_timed.(sc+5)(ir(0):ir(1)) eq lut), count)
      
       if count ne 0 then begin
          dummy=data4sc_timed.(sc+1)(ir(0):ir(1),channel)
          cnts=dummy(idx)
          ; check bad data!
          flags_data=fltarr(n_elements(cnts))
          idx_zero=where(cnts eq 0,ccc)
          idx_spike=where(cnts ge data_spike_ceiling,cccc)
        if ccc gt 0 then flags_data(idx_zero)=1
        if cccc gt 0 then flags_data(idx_spike)=1
        idx_good_data=where(flags_data eq 0,ccccc)
        cnts=cnts(idx_good_data)
        c(sc,channel)=total(cnts)/count
       endif
 
  endfor
  endfor

   idx=where(c eq 0,count)

   if count eq 0 then begin
       print,'pass ',varprt(pass),' in/out ',varprt(in_out), ', match for lut ', varprt(lut), ', L range: ',lrange
       print, c  
       dmy1.pass=pass
       dmy1.in_out=in_out
       dmy1.lrange=lrange
       dmy1.av_counts=c
       if found eq 0 then intcal_matches=[dmy1] else intcal_matches=[intcal_matches,dmy1]
       found=found+1
   endif
   lrange=lrange+lstep
endwhile

endfor
endfor

stop






;**************************************************************************************************************************
;***************************************************************strip zeros and spikes
;* need to get rid of zero data values
;* also need to handle data spikes so....
;* Search for 0 values in av_ch sub array
;* also search for 'data spikes', set abitrary ceiling over which one
;* expects data spikes to be above 
spike_ceiling=20000
;set up structure to hold flags of zeros and data spike values

    for i=0,(orbits-1) do begin
         for j=0,3 do begin
                  for k=0,(ch-1) do begin
                  data_pass_in=data4sc_timed.(1+j)( inbound_outbound_info(i).(j).(0)(0): inbound_outbound_info(i).(j).(0)(1),k)
                  data_pass_out=data4sc_timed.(1+j)( inbound_outbound_info(i).(j).(1)(0): inbound_outbound_info(i).(j).(1)(1),k)
                  flags_in=fltarr(n_elements(data_pass_in))
                  flags_out=fltarr(n_elements(data_pass_out))
                  test_non_zero_in=where(data_pass_in eq 0,c)
                  test_data_spike_in=where(data_pass_in gt spike_ceiling,cc) 
                  test_non_zero_out=where(data_pass_out eq 0,ccc)
                  test_data_spike_out=where(data_pass_out gt spike_ceiling,cccc)
                if c ne 0 then flags_in(test_non_zero_in)=1
                if cc ne 0 then flags_in(test_data_spike_in)=1
                if ccc ne 0 then flags_out(test_non_zero_out)=1
                if cccc ne 0 then flags_out(test_data_spike_out)=1
                idx_in=where(flags_in eq 0)
                idx_out=where(flags_out eq 0)
                inbound_outbound_info(i).(j).AV_CH.IN_PASS(k)=mean(data_pass_in(idx_in))
                inbound_outbound_info(i).(j).AV_CH.OUT_PASS(k)=mean(data_pass_in(idx_out))
                inbound_outbound_info(i).(j).AV_CH_ERR.IN_PASS(k)=mean(sqrt(data_pass_in(idx_in)))
                inbound_outbound_info(i).(j).AV_CH_ERR.OUT_PASS(k)=mean(sqrt(data_pass_in(idx_out)))
                endfor
         endfor
     endfor

;*************************************************************************************************************************












;------------------------------------------------------------------------------------------------------
;test to see if s/c for each pass are in same integration mode (LUT);
;takenout due to previous analysis

;test_str=strarr(2,4,orbits)

;for j=0,3 do begin
; for i=0,(orbits-1) do begin

;   LUT_check_in=data4sc_timed.(j+5)((inbound_outbound_info(i).(j).IN_PASS(0)):(inbound_outbound_info(i).(j).IN_PASS(1)))   
;   LUT_check_out=data4sc_timed.(j+5)((inbound_outbound_info(i).(j).OUT_PASS(0)):(inbound_outbound_info(i).(j).OUT_PASS(1)))  
;print,LUT_check_in(0)
;print,LUT_check_out(0)
;   test_str(0,j,i)=string(LUT_check_in(0))
;   test_str(1,j,i)=string(LUT_check_out(0))

;   result_in=strcmp(LUT_check_in,test_str(0,j,i),c)
;   result_out=strcmp(LUT_check_out,test_str(1,j,i),cc)

;   result_1=where(result_in ne 1,c)
;   result_2=where(result_out ne 1,cc)

;if c ne 0 then begin
;      print,'!!!!!!!!!!!!!!!!!!!IN BOUND LUT change!!!!!!!!!!!!!!CL',j
;      inbound_outbound_info(i).(j).LUT.LUT_IN=  -1;LUT CHANGE
;  endif

;if cc ne 0 then begin
;      print,'!!!!!!!!!!!!!!!!!!!OUT BOUND LUT change!!!!!!!!!!!!!!CL',j
;      inbound_outbound_info(i).(j).LUT.LUT_OUT= -1;LUT CHANGE
;  endif
;if c eq 0 then begin
;      inbound_outbound_info(i).(j).LUT.LUT_IN= test_str(0,j,i)
;  endif
;if cc eq 0 then begin
;      inbound_outbound_info(i).(j).LUT.LUT_OUT= test_str(1,j,i)
;  endif
;endfor
;endfor


;;;;;;;;;DIFFERENT LUT VALUES FOR DIFFERENT ORBITS or passes not handled....
;;maybe index most frequently occuring LUT?
stop
;;

;**************************************************************************************************************************
;***************************************************************strip zeros and spikes
;* need to get rid of zero data values
;* also need to handle data spikes so....
;* Search for 0 values in av_ch sub array
;* also search for 'data spikes', set abitrary ceiling over which one
;* expects data spikes to be above 
spike_ceiling=20000

;set up structure to hold flags of zeros and data spike values

for i=0,(orbits-1) do begin

for j=0,3 do begin
for k=0,(ch-1) do begin


 data_pass_in=data4sc_timed.(1+j)( inbound_outbound_info(i).(j).(0)(0): inbound_outbound_info(i).(j).(0)(1),k)
data_pass_out=data4sc_timed.(1+j)( inbound_outbound_info(i).(j).(1)(0): inbound_outbound_info(i).(j).(1)(1),k)
flags_in=fltarr(n_elements(data_pass_in))
flags_out=fltarr(n_elements(data_pass_out))

  test_non_zero_in=where(data_pass_in eq 0,c)
  test_data_spike_in=where(data_pass_in gt spike_ceiling,cc)

  test_non_zero_out=where(data_pass_out eq 0,ccc)
  test_data_spike_out=where(data_pass_out gt spike_ceiling,cccc)


if c ne 0 then flags_in(test_non_zero_in)=1
if cc ne 0 then flags_in(test_data_spike_in)=1
if ccc ne 0 then flags_out(test_non_zero_out)=1
if cccc ne 0 then flags_out(test_data_spike_out)=1

 idx_in=where(flags_in eq 0)
idx_out=where(flags_out eq 0)

inbound_outbound_info(i).(j).AV_CH.IN_PASS(k)=mean(data_pass_in(idx_in))
inbound_outbound_info(i).(j).AV_CH.OUT_PASS(k)=mean(data_pass_in(idx_out))
inbound_outbound_info(i).(j).AV_CH_ERR.IN_PASS(k)=mean(sqrt(data_pass_in(idx_in)))
inbound_outbound_info(i).(j).AV_CH_ERR.OUT_PASS(k)=mean(sqrt(data_pass_in(idx_out)))


endfor
endfor

endfor
;*************************************************************************************************************************


;index most commonly occuring LUT value or chosen LUT value******************
;have takenthis out due to L range analysis carried out previously  

;if LUT_VALUE eq 0 then begin
;LUT_check=fltarr(4,2,orbits)
;for j=0,3 do begin
;LUT_check(j,0,*)=inbound_outbound_info.(j).LUT.LUT_IN
;LUT_check(j,1,*)=inbound_outbound_info.(j).LUT.LUT_OUT
;endfor

;mode_LUT=HISTOGRAM(LUT_check,MIN=0,OMIN=O_MIN,OMAX=O_MAX)
;mode_LUT_VALUE=max(mode_LUT,max_subs)
;LUT_VALUE=max_subs+O_MIN
;endif

;LUT_INDEX=fltarr(orbits);

;for j=0,3 do begin
;LUT_check_inbound=where(inbound_outbound_info.(j).LUT.LUT_IN ne LUT_VALUE,c)
;if c ne 0 then LUT_INDEX(LUT_check_inbound)=1
;LUT_check_outbound=where(inbound_outbound_info.(j).LUT.LUT_OUT ne LUT_VALUE,cc)
;if cc ne 0 then LUT_INDEX(LUT_check_outbound)=1
;endfor


;lut_idx=where(LUT_index ne 1,countz)




new_inbound_outbound_info=inbound_outbound_info(lut_idx)

; do array with numer of 0's in LUT_INDEX
;thenmakesmaller versionof inbound_outbound_info

;cluster_rapid_sc_intercal_plot,new_inbound_outbound_info,LMIN,LMAX
stop
END

;*************************************************************************************
;* PROCEDURE
;*      PRO papco_cluster_rapid_sc_intercal_plot,inbound_outbound_info,LMIN,LMAX
;* DESCRIPTION:  
;*      code reads in cleaned data from
;*       papco_cluster_rapid_sc_intercal.pro and plots spacecraft vs
;*       spacecraft comparisons. energy channels are colour coded
;*     
;* INPUTS:       
;*      inbound_outbound_info, clean, no data spike or zero count data structure
;*      LMIN and LMAX Lrange values.
;*  
;* KEYWORDS:
;*  
;* OUTPUT:	 
;*    6 sc vs sc plots 
;****************************************************************************

pro cluster_rapid_sc_intercal_plot,inbound_outbound_info,LMIN,LMAX
common papco_color
;*************plotting sections
;ascertain max counts for scaling
max_counts=dblarr(4)
for i=0,3 do  begin
in_counts=inbound_outbound_info(*).(i).AV_CH.IN_PASS(*)
out_counts=inbound_outbound_info(*).(i).AV_CH.OUT_PASS(*)
max_counts(i)=max(max(in_counts),max(out_counts))
endfor
max_counts=max(max_counts)
if max_counts gt 1000000 then begin
 print, 'high counts'
max_counts=20000
endif
xrange=[0,max_counts]
yrange=xrange
LMIN=strcompress(string(LMIN))
LMAX=strcompress(string(LMAX))
size_arr=size(intercal_arr)
range=(size_arr(1))-1
ch=5
;***************************************************************************************************************************
window,0,title='CLUSTER 1 - CLUSTER 2 RAPID counts comparison, L range = '+LMIN+' - ' +LMAX
for i=0,ch do begin
plot,inbound_outbound_info.CL1.AV_CH.IN_PASS(i),inbound_outbound_info.CL2.AV_CH.IN_PASS(i),psym=4,xrange=xrange,yrange=yrange,xtitle='sc1',ytitle='sc2',color=(i*11)+1 
plot,inbound_outbound_info.CL1.AV_CH.OUT_PASS(i),inbound_outbound_info.CL2.AV_CH.OUT_PASS(i),psym=-3,xrange=xrange,yrange=yrange,xtitle='sc1',ytitle='sc2',color=(i*11)+1 
endfor
plots,xrange,yrange


window,1,title='CLUSTER 1 - CLUSTER 3 RAPID counts comparison, L range = '+LMIN+' - ' +LMAX
for i=0,ch do begin

plot,inbound_outbound_info.CL1.AV_CH.IN_PASS(i),inbound_outbound_info.CL3.AV_CH.IN_PASS(i),psym=4,xrange=xrange,yrange=yrange,xtitle='sc1',ytitle='sc3',color=(i*11)+1 
plot,inbound_outbound_info.CL1.AV_CH.OUT_PASS(i),inbound_outbound_info.CL3.AV_CH.OUT_PASS(i),psym=-3,xrange=xrange,yrange=yrange,xtitle='sc1',ytitle='sc3',color=(i*11)+1 


endfor
plots,xrange,yrange

window,2,title='CLUSTER 1 - CLUSTER 4 RAPID counts comparison, L range = '+LMIN+' - ' +LMAX
for i=0,ch do begin

plot,inbound_outbound_info.CL1.AV_CH.IN_PASS(i),inbound_outbound_info.CL4.AV_CH.IN_PASS(i),psym=4,xrange=xrange,yrange=yrange,xtitle='sc1',ytitle='sc4',color=(i*11)+1 
plot,inbound_outbound_info.CL1.AV_CH.OUT_PASS(i),inbound_outbound_info.CL4.AV_CH.OUT_PASS(i),psym=-3,xrange=xrange,yrange=yrange,xtitle='sc1',ytitle='sc4',color=(i*11)+1

endfor
plots,xrange,yrange


window,3,title='CLUSTER 2 - CLUSTER 3 RAPID counts comparison, L range = '+LMIN+' - ' +LMAX
for i=0,ch do begin

plot,inbound_outbound_info.CL2.AV_CH.IN_PASS(i),inbound_outbound_info.CL3.AV_CH.IN_PASS(i),psym=4,xrange=xrange,yrange=yrange,xtitle='sc2',ytitle='sc3',color=(i*11)+1 
plot,inbound_outbound_info.CL2.AV_CH.OUT_PASS(i),inbound_outbound_info.CL3.AV_CH.OUT_PASS(i),psym=-3,xrange=xrange,yrange=yrange,xtitle='sc2',ytitle='sc3',color=(i*11)+1


endfor
plots,xrange,yrange


window,4,title='CLUSTER 2 - CLUSTER 4 RAPID counts comparison, L range = '+LMIN+' - ' +LMAX
for i=0,ch do begin

plot,inbound_outbound_info.CL2.AV_CH.IN_PASS(i),inbound_outbound_info.CL4.AV_CH.IN_PASS(i),psym=4,xrange=xrange,yrange=yrange,xtitle='sc2',ytitle='sc4',color=(i*11)+1 
plot,inbound_outbound_info.CL2.AV_CH.OUT_PASS(i),inbound_outbound_info.CL4.AV_CH.OUT_PASS(i),psym=-3,xrange=xrange,yrange=yrange,xtitle='sc2',ytitle='sc4',color=(i*11)+1


endfor
plots,xrange,yrange


window,5,title='CLUSTER 3 - CLUSTER 4 RAPID counts comparison, L range = '+LMIN+' - ' +LMAX
for i=0,ch do begin

plot,inbound_outbound_info.CL3.AV_CH.IN_PASS(i),inbound_outbound_info.CL4.AV_CH.IN_PASS(i),psym=4,xrange=xrange,yrange=yrange,xtitle='sc3',ytitle='sc4',color=(i*11)+1 
plot,inbound_outbound_info.CL3.AV_CH.OUT_PASS(i),inbound_outbound_info.CL4.AV_CH.OUT_PASS(i),psym=-3,xrange=xrange,yrange=yrange,xtitle='sc3',ytitle='sc4',color=(i*11)+1

endfor
plots,xrange,yrange
;***************************************************************************************************************************

stop
END

;******************************************************************
;* PROCEDURE
;*      PRO papco_cluster_rapid_sc_intercal_fit,inbound_outbound_info,fit_values
;*
;* DESCRIPTION:  carry out an interspacecraft comparison for each IES energy.
;*
;*
;*do fitting for each energy channel for 6 sc combinations, gives 36
;*best fit lines.  
;*
;*
;*OUTPUT: fit_values, [2,sc_combinations,energy_channel,(inbound,outbound)] array
;*containing slope and intercept of
;*bestfit values
;*
;*
;*
;*********************************************************************************************

pro papco_cluster_rapid_sc_intercal_fit,inbound_outbound_info,fit_values


;***********************;***********************************************
;***********************************************


dummy11={fit_slope:0.0d,fit_intercept:0.0d}
dummy22={ch1:dummy11, ch2:dummy11,ch3:dummy11,ch4:dummy11,ch5:dummy11,ch6:dummy11}
fit_values_arr={sc1_sc2:dummy22,sc1_sc3:dummy22,sc1_sc4:dummy22,sc2_sc3:dummy22,sc2_sc4:dummy22,sc3_sc4:dummy22}

sc_1_data=new_intercal_arr.sc1.av_ch
sc_1_data_err=new_intercal_arr.sc1.av_ch_err

sc_2_data=new_intercal_arr.sc2.av_ch
sc_2_data_err=new_intercal_arr.sc2.av_ch_err

sc_3_data=new_intercal_arr.sc3.av_ch
sc_3_data_err=new_intercal_arr.sc3.av_ch_err

sc_4_data=new_intercal_arr.sc4.av_ch
sc_4_data_err=new_intercal_arr.sc4.av_ch_err


ch=6
titstr=''
n_iterations=100
;nparms=1
errorpercent=.06
; kappa_picture=1
;itime=10


for i=0,(ch-1) do begin


;-----------------------------sc1sc2
;-----------------------------------
;************************************
gen_fit_release,x=sc_1_data(i,*),sigma_x=sc_1_data_err(i,*),y=sc_2_data(i,*),sigma_y=sc_2_data_err(i,*),n_iterations=n_iterations, $
                     titstr=titstr, $ 
                     nparms=nparms, $ 
                     guess_slope=guess_slope,$   
                     errorpercent=errorpercent, $ 
                     slope=slope, intercept=intercept, $ 
                     chisq=chisq, rchisq=rchisq, $ 
                     s2=s2, $ 
                     c68=c68, c95=c95, c99=c99,$
                     ks_c68=ks_c68, ks_c95=ks_c95, ks_c99=ks_c99,$
                     force_kappa_search=force_kappa_search,$
                     ks_range_degrees= ks_range_deg, $
                     renormalize=renormalize, $
                     verbose=verbose,$ 
                     kappa_picture=kappa_picture,$
                     print=print,$ 
                     itime=itime,$ 
                     kappa_data=kappa_data,$
                     status=status, $
                     info = info

fit_values_arr.sc1_sc2.(i).fit_slope=slope
fit_values_arr.sc1_sc2.(i).fit_intercept=intercept


;***********************************


;-----------------------------sc1sc3
;-----------------------------------
;************************************
gen_fit_release,x=sc_1_data(i,*),sigma_x=sc_1_data_err(i,*),y=sc_3_data(i,*),sigma_y=sc_3_data_err(i,*),n_iterations=n_iterations, $
                     titstr=titstr, $ 
                     nparms=nparms, $ 
                     guess_slope=guess_slope,$   
                     errorpercent=errorpercent, $ 
                     slope=slope, intercept=intercept, $ 
                     chisq=chisq, rchisq=rchisq, $ 
                     s2=s2, $ 
                     c68=c68, c95=c95, c99=c99,$
                     ks_c68=ks_c68, ks_c95=ks_c95, ks_c99=ks_c99,$
                     force_kappa_search=force_kappa_search,$
                     ks_range_degrees= ks_range_deg, $
                     renormalize=renormalize, $
                     verbose=verbose,$ 
                     kappa_picture=kappa_picture,$
                     print=print,$ 
                     itime=itime,$ 
                     kappa_data=kappa_data,$
                     status=status, $
                     info = info

fit_values_arr.sc1_sc3.(i).fit_slope=slope
fit_values_arr.sc1_sc3.(i).fit_intercept=intercept


;***********************************


;-----------------------------sc1sc4
;-----------------------------------
;************************************
gen_fit_release,x=sc_1_data(i,*),sigma_x=sc_1_data_err(i,*),y=sc_4_data(i,*),sigma_y=sc_4_data_err(i,*),n_iterations=n_iterations, $
                     titstr=titstr, $ 
                     nparms=nparms, $ 
                     guess_slope=guess_slope,$   
                     errorpercent=errorpercent, $ 
                     slope=slope, intercept=intercept, $ 
                     chisq=chisq, rchisq=rchisq, $ 
                     s2=s2, $ 
                     c68=c68, c95=c95, c99=c99,$
                     ks_c68=ks_c68, ks_c95=ks_c95, ks_c99=ks_c99,$
                     force_kappa_search=force_kappa_search,$
                     ks_range_degrees= ks_range_deg, $
                     renormalize=renormalize, $
                     verbose=verbose,$ 
                     kappa_picture=kappa_picture,$
                     print=print,$ 
                     itime=itime,$ 
                     kappa_data=kappa_data,$
                     status=status, $
                     info = info

fit_values_arr.sc1_sc4.(i).fit_slope=slope
fit_values_arr.sc1_sc4.(i).fit_intercept=intercept


;***********************************


;-----------------------------sc2sc4
;-----------------------------------
;************************************
gen_fit_release,x=sc_2_data(i,*),sigma_x=sc_2_data_err(i,*),y=sc_4_data(i,*),sigma_y=sc_4_data_err(i,*),n_iterations=n_iterations, $
                     titstr=titstr, $ 
                     nparms=nparms, $ 
                     guess_slope=guess_slope,$   
                     errorpercent=errorpercent, $ 
                     slope=slope, intercept=intercept, $ 
                     chisq=chisq, rchisq=rchisq, $ 
                     s2=s2, $ 
                     c68=c68, c95=c95, c99=c99,$
                     ks_c68=ks_c68, ks_c95=ks_c95, ks_c99=ks_c99,$
                     force_kappa_search=force_kappa_search,$
                     ks_range_degrees= ks_range_deg, $
                     renormalize=renormalize, $
                     verbose=verbose,$ 
                     kappa_picture=kappa_picture,$
                     print=print,$ 
                     itime=itime,$ 
                     kappa_data=kappa_data,$
                     status=status, $
                     info = info

fit_values_arr.sc2_sc4.(i).fit_slope=slope
fit_values_arr.sc2_sc4.(i).fit_intercept=intercept


;***********************************

;-----------------------------sc2sc3
;-----------------------------------
;************************************
gen_fit_release,x=sc_2_data(i,*),sigma_x=sc_2_data_err(i,*),y=sc_3_data(i,*),sigma_y=sc_3_data_err(i,*),n_iterations=n_iterations, $
                     titstr=titstr, $ 
                     nparms=nparms, $ 
                     guess_slope=guess_slope,$   
                     errorpercent=errorpercent, $ 
                     slope=slope, intercept=intercept, $ 
                     chisq=chisq, rchisq=rchisq, $ 
                     s2=s2, $ 
                     c68=c68, c95=c95, c99=c99,$
                     ks_c68=ks_c68, ks_c95=ks_c95, ks_c99=ks_c99,$
                     force_kappa_search=force_kappa_search,$
                     ks_range_degrees= ks_range_deg, $
                     renormalize=renormalize, $
                     verbose=verbose,$ 
                     kappa_picture=kappa_picture,$
                     print=print,$ 
                     itime=itime,$ 
                     kappa_data=kappa_data,$
                     status=status, $
                     info = info

fit_values_arr.sc2_sc3.(i).fit_slope=slope
fit_values_arr.sc2_sc3.(i).fit_intercept=intercept


;***********************************

;-----------------------------sc3sc4
;-----------------------------------
;************************************
gen_fit_release,x=sc_3_data(i,*),sigma_x=sc_3_data_err(i,*),y=sc_4_data(i,*),sigma_y=sc_4_data_err(i,*),n_iterations=n_iterations, $
                     titstr=titstr, $ 
                     nparms=nparms, $ 
                     guess_slope=guess_slope,$   
                     errorpercent=errorpercent, $ 
                     slope=slope, intercept=intercept, $ 
                     chisq=chisq, rchisq=rchisq, $ 
                     s2=s2, $ 
                     c68=c68, c95=c95, c99=c99,$
                     ks_c68=ks_c68, ks_c95=ks_c95, ks_c99=ks_c99,$
                     force_kappa_search=force_kappa_search,$
                     ks_range_degrees= ks_range_deg, $
                     renormalize=renormalize, $
                     verbose=verbose,$ 
                     kappa_picture=kappa_picture,$
                     print=print,$ 
                     itime=itime,$ 
                     kappa_data=kappa_data,$
                     status=status, $
                     info = info
sc3_sc4_slope=slope
sc3_sc4_intercept=intercept

fit_values_arr.sc3_sc4.(i).fit_slope=slope
fit_values_arr.sc3_sc4.(i).fit_intercept=intercept
;***********************************
endfor

;***************************************************************************************
stop

END

