pro make_xrt_channel, config, xrt_channel=xrt_channel, debug=debug, $
                      caldir=caldir, overwrite=overwrite, infodir=infodir
; =========================================================================
;+
; PROJECT:
;       Solar-B / XRT 
;
; NAME:
;       MAKE_XRT_CHANNEL
;
; CATEGORY:
;       Calibration
;
; PURPOSE:
;       Generate the XRT CHANNEL structure.
;
; CALLING SEQUENCE:
;       MAKE_XRT_CHANNEL, config [,xrt_channel=xrt_channel] [,/debug] 
;                         [,caldir=caldir] [,/overwrite]
;
; INPUTS:
;       CONFIG: [Mandatory] Variable containing config file to use.
;
; KEYWORDS:
;        DEBUG: [Optional] enables debugging
;       CALDIR: [Optional] location of $SSW/hinode/xrt/calibration
;    OVERWRITE: [Optional] enables output file to be overwritten.
;      INFODIR: Directory for info file.  Should be set to local copy
;      of hinode/xrt/idl/response/channels/
;
; OUTPUTS:
;      XRT_CHANNEL_Vnnnn.GENY: (RESTGENX file) Saved copy of fully populated
;                              channel structure. The version number nnnn
;                              corresponds to the config file.
;      XRT_CHANNEL: The XRT channel structure array that is saved to
;                   "xrt_channel_vNNNN.geny". Contains relevant parameters
;                   for each telescope element pertaining to that XRT channel.
;
; EXAMPLES:
;      Make the output file.
;      make_xrt_channel, config='./xrt_config_v0011.pro'
;
;      Make the file and return the output in IDL.
;      xrt_channel=1
;      make_xrt_channel, config='./xrt_config_v0011.pro', xrt_channel=xrt_channel
;      help, xrt_channel
;
; COMMON BLOCKS:
;       None.
;
; NOTES:
;      Uses routine multifilt, now in file multifilt.pro
;      Code and logic reuse from calc_xrt_chn_trans.pro / get_xrt_channel.pro.
;      Calls make_xrt_ccd.pro, make_xrt_filter.pro, make_xrt_geometry.pro and
;      make_xrt_mirror.pro, to calculate channel structure components. Call
;      make_xrt_chn_trans.pro to generate transmission for each channel.
;
; MODIFICATION HISTORY:
;  progver = 'v2008.Sep.15' ; --- (Alisdair Davey/Mark Weber)
;                                 First debugged version. Derived from
;                                 <get_xrt_channel.pro>.
;  progver = 'v2008.Oct.01'      ; --- (M.Weber) Added xrt_channel output.
;                                 Switched savefile to geny file.
  progver = 'v2010.sept.13'      ; --- (K. Reeves) Added history output to text file
;
;
;-
; =========================================================================

  if not keyword_set(config) then begin
    print, 'make_xrt_channel: did not specify config file'
    return
  end

; read config file

  if not file_test(config) then begin
    print, 'make_xrt_channel: config file does not exist'
    return
  end

  config_s = strsplit(config,'/',/extract,count=count)
  config = (strsplit(config_s[count-1],'.pro',/extract,/regex))[0]
  version = strmid(config, rstrpos(config,'_'), strlen(config))

  call_procedure, config, observatory, instrument, ccd, filter, geometry, $
		  mirror, channel
  
  if keyword_set(debug) then $
      help, ccd, filter, geometry, mirror, channel, /str

; How many channels to populate
  
  n_channel = n_elements(channel)

  if keyword_set(debug) then $
      print, 'Processing '+strtrim(string(n_channel),2),' channels'

; First define XRT_geometry, XRT_ccd, XRT_filter, XRT_mirror so that
; we can define and replicate the channel config.
    
  make_xrt_filter, XRT_filter, /define
  make_xrt_ccd, XRT_ccd, /define
  make_xrt_mirror, XRT_mirror, /define
  make_xrt_geometry, XRT_geometry, /define

;   Define and replicate channel config  

  def_name = 'XRT_CHN_CONFIG'+strupcase(version)
  XRT_channel_def = create_struct(name=def_name,                $
                                 'type', '',                    $
                      'chn_str_version', '',                    $
                        'chn_str_descr', '',                    $
                                 'name', '',                    $
                            'long_name', '',                    $
                          'observatory', observatory,           $
                           'instrument', instrument,            $
                                 'geom', XRT_geometry,          $
                            'en_filter', XRT_filter,            $
                              'mirror1', XRT_mirror,            $
                              'mirror2', XRT_mirror,            $
                           'fp_filter1', XRT_filter,            $
                           'fp_filter2', XRT_filter,            $
                               'contam', XRT_filter,            $
                                  'ccd', XRT_ccd,               $
                                 'wave', fltarr(5000),          $
                           'wave_units', 'Angstroms',           $
                                'trans', fltarr(5000),          $
                               'length', 0L,                    $
                      'config_filename', config,                $
                              'history', strarr(3),             $
                             'comments', strarr(5)               )


  XRT_channel_def.type = 'XRT_CHN_CONFIG'
  XRT_channel_def.history[0] = 'MAKE_XRT_CHANNEL '+progver+timestamp()
  XRT_channel_def.chn_str_version = 'XRT_CHN_CONFIG'+strupcase(version)
  XRT_channel_def.chn_str_descr = 'Specifies an XRT instrument ' $
                  + 'configuration, without the transmission function.'

  XRT_channel = replicate (XRT_channel_def, n_channel)

  XRT_channel.name = channel.name
  XRT_channel.long_name = channel.long_name
    
; Now make the channels

  for i=0, n_channel-1 do begin

; Populate the structures
;
; ccd - only need to call it once

    print, 'Processing channel: '+channel[i].name

    if XRT_ccd.history[0] eq '' then begin
      make_xrt_ccd, XRT_ccd, ccd, qabort, debug=debug, caldir=caldir
    
      if qabort then begin
	print, 'make_xrt_channel: call to make_xrt_ccd failed: '+qabort
	return
      end
    end

    XRT_channel[i].ccd = XRT_ccd

; en_filter
    
    make_xrt_filter, XRT_filter, filter, channel[i].en_filter, qabort, $
		     debug=debug, caldir=caldir

    if qabort then begin
      print, 'make_xrt_channel: call to make_xrt_filter failed: '+qabort
      return
    end

    XRT_channel[i].en_filter = XRT_filter

; fp_filter1
    
    make_xrt_filter, XRT_filter, filter, channel[i].fp_filter1, qabort, $
		     debug=debug, caldir=caldir

    if qabort then begin
      print, 'make_xrt_channel: call to make_xrt_filter failed: '+qabort
      return
    end

    XRT_channel[i].fp_filter1 = XRT_filter


; fp_filter2

    make_xrt_filter, XRT_filter, filter, channel[i].fp_filter2, qabort, $
		     debug=debug, caldir=caldir

    if qabort then begin
      print, 'make_xrt_channel: call to make_xrt_filter failed: '+qabort
      return
    end

    XRT_channel[i].fp_filter2 = XRT_filter

; mirror1 and mirror2 - only need to call it once
    
    if XRT_mirror.history[0] eq '' then begin
      make_xrt_mirror, XRT_mirror, mirror, qabort, caldir=caldir
    
      if qabort then begin
	print, 'make_xrt_channel: call to make_xrt_mirror failed: '+qabort
	return
      end
    end
    
    XRT_channel[i].mirror1 = XRT_mirror
    XRT_channel[i].mirror2 = XRT_mirror

; geom - only need to call it once

    if XRT_geometry.history[0] eq '' then begin      
      make_xrt_geometry, XRT_geometry, geometry, qabort
    
      if qabort then begin
	print, 'make_xrt_channel: call to make_xrt_geometry failed '+qabort
	return
      end
    end

    XRT_channel[i].geom = XRT_geometry

; Populate wave, trans and length for channel structure

    xrt_chn_trans = XRT_channel[i]
    make_xrt_chn_trans, xrt_chn_trans, qabort
    XRT_channel[i] = xrt_chn_trans
    
  end

; Save config structure

  outfile = 'xrt_channels' + version
  savegenx, XRT_channel, file=outfile, overwrite=overwrite
  print,'Channels saved to ' + outfile + '.geny in current directory.'

  ;; assumes you're running from hinode/xrt/calibration/directory
  ;; if infodir is not set
  if not keyword_set(infodir) then infodir = '../idl/response/channels/'
  openu, unit, concat_dir(infodir,'channels_history.txt'), /get_lun, /append
  printf, unit, outfile+'.geny', XRT_channel[0].history
  close, unit, /force

end
