PRO xrt_read_coaldb_indexcor, org_index, c_index, res_index, cal_type

; Input:
;   org_index
;   c_index
;
; Output:
;   res_index
;   cal_type

nn=n_elements(org_index)
res_index=org_index
ref_type=intarr(nn)-1
;
; Scale
x_scl0=1.0286
g_scl0=1.0302
;
time0=anytim(org_index.date_obs)
time1=anytim(c_index.date_obs)


for i=0UL,nn-1 do begin
if min(abs(time1-time0(i)),m) le 0.1 then begin
 mm=m(0)
 res_index(i).xcen=c_index(mm).xcen
 res_index(i).ycen=c_index(mm).ycen
 res_index(i).crval1=c_index(mm).xcen
 res_index(i).crval2=c_index(mm).ycen
 res_index(i).crpix1=res_index(i).naxis1/2+.5
 res_index(i).crpix2=res_index(i).naxis2/2+.5
 if res_index(i).ec_fw2 eq 3 then scl0=g_scl0*res_index(i).chip_sum $
                             else scl0=x_scl0*res_index(i).chip_sum
 res_index(i).cdelt1=scl0
 res_index(i).cdelt2=scl0
 res_index(i).platescl=scl0
 res_index(i).xscale=scl0
 res_index(i).yscale=scl0
 ref_type(i)=c_index(mm).ref_type
endif
endfor

; Mapping : ref_type -> cal_type
cal_type=ref_type
tmp_ss=where(ref_type ge 10,tmp_nn) & if tmp_nn ne 0 then cal_type(tmp_ss)=1
tmp_ss=where(ref_type eq  1,tmp_nn) & if tmp_nn ne 0 then cal_type(tmp_ss)=2
tmp_ss=where(ref_type eq  5,tmp_nn) & if tmp_nn ne 0 then cal_type(tmp_ss)=4

END

;;;; ------- local_xrt_read_genxcat_init.pro -------------

PRO local_xrt_readgenxcat_init, topdir, $
          initialize=initialize, sublevel=sublevel, store=store

; To suppress a misleading message "FILE_LIST: No files found"
; from file_list.pro in read_genxcat.pro

common read_genxcat_blk1, last_topdir, cfiles, cfids
common read_genxcat_blk3, cftimes
common l_xrt_read_genxcat_blk1, last_topdir_l1, cfiles_l1, cfids_l1, cftimes_l1
common l_xrt_read_genxcat_blk2, last_topdir_l2, cfiles_l2, cfids_l2, cftimes_l2

if not keyword_set(store) then store=1  ; default

if data_chk(topdir,/string,/scalar) then begin
    if file_exist(topdir) then tdir=topdir else tdir=get_logenv(topdir)
endif else tdir=curdir()

if n_elements(last_topdir_l1) eq 0 then begin
last_topdir_l1=''
cfiles_l1=''
cfids_l1=''
cftimes_l1=0
endif
if n_elements(last_topdir_l2) eq 0 then begin
last_topdir_l2=''
cfiles_l2=''
cfids_l2=''
cftimes_l2=0
endif

case store of
1 : begin
     last_topdir=last_topdir_l1
     cfiles=cfiles_l1
     cfids=cfids_l1
     cftimes=cftimes_l1
    end
2 : begin
     last_topdir=last_topdir_l2
     cfiles=cfiles_l2
     cfids=cfids_l2
     cftimes=cftimes_l2
    end
endcase

if n_elements(last_topdir) eq 0 then last_topdir=''

initialize=keyword_set(initialize) or n_elements(cfiles) eq 0 or $
last_topdir ne tdir

if initialize then begin
if n_elements(sublevel) eq 0 then sublevel=0
for i=0,sublevel-1 do tdir=concat_dir(tdir,'*')
catfiles=file_list(tdir,'*.gen*',/cd)
cfiles=catfiles(sort(catfiles))
cfids=extract_fid(cfiles)
cftimes=file2time(cfids,out='sec')
if n_elements(ctimes) eq 1 then cftimes=[0,cftimes]
last_topdir=tdir
endif

case store of
1 : begin
     last_topdir_l1=last_topdir
     cfiles_l1=cfiles
     cfids_l1=cfids
     cftimes_l1=cftimes
    end
2 : begin
     last_topdir_l2=last_topdir
     cfiles_l2=cfiles
     cfids_l2=cfids
     cftimes_l2=cftimes
    end
endcase

END


;;;; ------- xrt_read_coaldb.pro -------------


FUNCTION xrt_read_coaldb, index, base_dir=base_dir, aia_cc=aia_cc, $
           calibration_type=calibration_type, db_ver=db_ver

;+
; PROJECT:
;       Solar-B / XRT
;
; NAME:
;       XRT_READ_COALDB
;
; CATEGORY:
;       Data calibration
;
; PURPOSE:
;       Correct XRT index structure for co-alignment
;
;
; CALLING SEQUENCE:
;       new_index=XRT_READ_COALDB(index [,/aia_cc]
;                   [,base_dir=base_dir] [,calibration_type=calibration_type])
;
; INPUTS:
;       index   - [Mandatory] (structure array)
;                  The XRT index structure
; OUTPUTS:
;       NEW_INDEX - The updated XRT structure
;
; OPTIONAL INPUT KEYWORD PARAMETERS:
;       /AIA_CC   - (Boolean) Set = 1 to utilize the calibration results
;                   from Cross Correlation between XRT thin-filter images
;                   and AIA 335A images. It is expected that you can get better
;                   results with this option, especially in the coalignment with
;                   data from SDO. This option is not the default, since
;                   sometimes you get "wrong" results with it due to some
;                   failures in cross correlation process.
;
;       BASE_DIR  - The directory where XRT Coalignment Databases Directories
;                   (coaldb_u, coaldb_c) should be found.
;
; OPTIONAL OUTPUT KEYWORD PARAMETERS:
;       DB_VER    - Version of the coalignment database
;       CALIBRATION_TYPE  - Resources for the calibration
;                           See below:
;  [CALIBRATION_TYPE]
;   -1 : (No Correction)
;    1 : Cross Correlation results (AIA and XRT)
;    2 : Limb fitting results (G-band)
;    3 : UFSS data
;    4 : Limb fitting results (X-ray)
;    6 : Other methods
;
; RESTRICTIONS:
;  This procedure assumes there has been no spatial modification to the data 
;  array (e.g., no shift, no rotation, no enlarge/shrink,...)
;  If the data are already modified, you may need some extra processing.
;  
; REFERENCES FOR FURTHER INFORMATION:
;
;  [XRT Analysis Guide]
;   http://xrt.cfa.harvard.edu/resources/documents/XAG/XAG.pdf
;
;  [XRT coalignment webpage at MSU]
;   http://ylstone.physics.montana.edu/yosimura/hinode/coalignment/
;
; MODIFICATION HISTORY:
;
;progver = 'v2014.11.08' ;--- (KY) Released
;progver = 'v2015.05.11' ;--- (KY) fixed bugs, updated the plate scale value
;                        ;         of X-ray images to the latest one
;progver = 'v2015.08.03' ;--- (Zarro (ADNET) and KY) initialized u_stat, c_stat
                        ;         to trap cases of missing/corrupt DB files
;progver = 'v2015.08.30' ;--- (KY) slightly widen the time range for DB search
                        ;         to handle small modified DATE_OBS case
progver = 'v2016.07.06' ;--- (KY) corrected position of a closing parenthesis
;
;-

if not keyword_set(base_dir) then $
              base_dir=getenv('SSWDB') + '/hinode/xrt/xrt_msu_coalign/'
if strmid(base_dir,strlen(base_dir)-1) ne '/' then base_dir=base_dir+'/'
db_dir_u=base_dir+'coaldb_u/'
db_dir_c=base_dir+'coaldb_c/'
db_ver_f=base_dir+'db_version.txt'
u_stat=0
c_stat=0

tt=anytim(minmax(anytim(index.date_obs))+[-1, 1]*0.1,/yoh)
nn0=n_elements(index)
res_in=index
time0=anytim(index.date_obs)

calibration_type=intarr(nn0)-1
db_found=0

; DB version
v_str=rd_text(db_ver_f,err=err0)
if err0 ne 0 then begin
print,'[warning] DB version file not found'
db_ver='0000.00.00'
endif else begin
v_num=n_elements(v_str)
db_ver=strmid(v_str(v_num-1),0,10)
endelse

if keyword_set(aia_cc) then begin
;;;; CoalDB_AIACC ;;;;
if file_test(db_dir_c,/directory,/read) then begin
 local_xrt_readgenxcat_init,db_dir_c,store=1
 read_genxcat,tt(0),tt(1),c_in,top=db_dir_c,status=c_stat
endif else begin
 print,'[warning] coaldb_c Not Found'
 c_stat=0
endelse
;
if c_stat eq 1 then begin
 db_found=1
 xrt_read_coaldb_indexcor, index,c_in, c_res_in,c_cal_type
 res_in=c_res_in
 calibration_type=c_cal_type
endif ;(c_stat eq 1)
;
c_ss=where(calibration_type eq -1,c_nn)
if c_nn ne 0 then begin
 tt1=anytim(minmax(anytim(index(c_ss).date_obs)),/yoh)
 if file_test(db_dir_u,/directory,/read) then begin
  local_xrt_readgenxcat_init,db_dir_u,store=2
  read_genxcat,tt1(0),tt1(1),u_in,top=db_dir_u,status=u_stat
 endif else begin
  print,'[warning] coaldb_u Not Found'
  u_stat=0
 endelse
 if u_stat eq 1 then begin
  db_found=1
  xrt_read_coaldb_indexcor,index(c_ss),u_in, u_res_in,u_cal_type
  res_in(c_ss)=u_res_in
  calibration_type(c_ss)=u_cal_type
 endif ; (u_stat eq 1)
endif ;(c_nn ne 0)
endif else begin ; keyword_set(aia_cc)

;;;; CoalDB_UFSS ;;;;
if file_test(db_dir_u,/directory,/read) then begin
 local_xrt_readgenxcat_init,db_dir_u,store=2
 read_genxcat,tt(0),tt(1),u_in,top=db_dir_u,status=u_stat
endif else begin
 print,'[warning] coaldb_u Not Found'
 u_stat=0
endelse
if u_stat eq 1 then begin
 db_found=1
 xrt_read_coaldb_indexcor, index,u_in, u_res_in,u_cal_type
 res_in=u_res_in
 calibration_type=u_cal_type
endif

endelse

; Rotation angle correction
x_ang=xrt_rollangle(index)
res_in.crota1=x_ang
res_in.crota2=x_ang

; Update index.history
if db_found eq 1 then begin
hist_prefix = 'XRT_READ_COALDB ' + progver + ': (' + systim() + ') '
hist_entry = hist_prefix + ' DB_VERSION = '+ db_ver + $
                          ' CAL_TYPE = '+strtrim(string(calibration_type),2)
if not tag_exist(res_in,'history') then h_num=0 $
                               else h_num=n_elements(res_in(0).history)
update_history, res_in, hist_entry(0), /noroutine
for i=1L,nn0-1 do res_in(i).history(h_num)=hist_entry(i)
endif

return,res_in

END