;+
; NAME:
;       EIS_MOVIE_PREP
;
; PURPOSE:
;      
;	EIS_MOVIE_PREP takes a list of EIS FITS files as input. It reads the data from each file 
;	               and srings it together in an assoc file, together with a small header 
;		       describing the data. The prupose og this is to prepare a data set to be 
;                      viewed as a movie using XIMOVIE.  
;                                                                  
;
; CATEGORY:
;       Hansteen/Wikstol Data analysis SW
;
; CALLING SEQUENCE:
;       eis_movie_prep, filelist, iwin
;
; INPUTS:
;       filelist: List of EIS FITS files whose data should be concatenated and viewed as a movie
;        iwin    : The line window nr (0 - 24)
;
; KEYWORD PARAMETERS:
;
; OUTPUTS:
; 	An assoc file containing the movie data. Opitionally XIMOVIE is launched by EIS_MOVIE_PREP
;       file name may be returned in the savefile keyword
;
; CALLS:
;       
;
; COMMON BLOCKS:
;       
;
; PROCEDURE:
;
; RESTRICTIONS:
;
;
; MODIFICATION HISTORY:
;       Version 1.0, May-2006: Oivind Wikstol and Viggo Hansteen
;-
pro eis_movie_prep, filelist, iwin,  savefile =  savefile,  ccsds =  ccsds, extraheader = extraheader

  if n_params() eq 0 then begin
    message,'eis_movie_prep, filelist, iwin, savefile = savefile', /info
    return
  endif

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

  nttot = 0
  for i = 0,n_elements(filelist)-1 do begin

; get data for iwin:
    eis_getdata, filelist[i], wd, iwin = iwin,  ccsds =  ccsds
    message, 'Prosessing file ' + filelist[i], /info
    sz = size(wd)
    dims = sz[0]
    if dims lt 2 then begin
      message, ' only 2D or 3D files are supported. Returning.'
    endif
    nxnew = sZ[1]
    nynew = sZ[2]

    if dims eq 3 then nt = sZ[3]
    datatype = sz[dims+1]

;write header to file if this is the first record: 
    if i eq 0 then begin
; create output filename:
;      file_split = strsplit(filelist[i], '.', /extract)
;      savefile = file_split[0]+'iwin_'+string3(iwin)+'.tmp'
      savefile = 'eis_movie_cube_iwin'+string3(iwin)+'.tmp'
      nx = nxnew
      ny = nynew
      openw, luw, savefile, /get_lun
      rec = assoc(luw, bytarr(nx,ny),512)
    endif

    if nxnew ne nx or nynew ne ny then begin
      message,'nx or ny different from previous image for file'+filelist[i]
    endif

    for it = 0, nt-1 do rec[it+nttot] = bytscl(wd[*, *, it])
    nttot = nttot + nt

  endfor

  rec = assoc(luw, bytarr(512))
  bheader = eis_make_movie_header(nx,ny,nttot)
  message, /info, bheader
  header = extraheader +' : ' + bheader
  rec[0] = byte(header)
  free_lun, luw
  message, 'saving data cube in file: '+savefile, /info
end
