;+
; NAME:
;	SMEI_SEQUENCE::MAKE_MCAV
;
;
; PURPOSE:
;	Generates a movie from a SMEI sequence, using mencoder
;
;
; CATEGORY:
;	SMEI_SEQUENCE
;
;
; CALLING SEQUENCE:
;	seqref -> make_mcav, file
;
;
; INPUTS:
;	file	string	The name of the file to which to write the movie
;
;
; KEYWORD PARAMETERS:
;	frame_rate	(float)	The frame rate desired (fps)
;	codec		string	For quicktime and ffmpeg, specify the
;				codec to use for the movie.
;	/no_progress	If set, then disable the progress bars (useful
;			if slow network means the progress bars are
;			slowing operation).
;	/no_delete		If set, then don't delete the PNG files.
;
; RESTRICTIONS:
;	Requires that transcode be installed on the system.
;
;
; MODIFICATION HISTORY:
;	Original (from MAKE_AVMV): 19/12/12; SJT
;-

pro smei_sequence::make_mcav, mpegfilename, frame_rate = frame_rate, $
                              codec = codec, no_progress $
                              = no_progress, no_delete = no_delete


; Verify existence of transcode
  if not have_command("mencoder") then begin
     smei_msg, /alert, ['mencoder was not found', $
                        'please install it if you', $
                        'wish to use it to make avi movies']
     return
  endif


  sz = (self -> get_first()) -> get_size()
  nframes = self -> get_count()

  ndigits = 1+fix(alog10(nframes))
  formatstring = string(ndigits, ndigits, format = "('(i',i0,'.',i0,')')")

; Load current color table into byte arrays

  red = self -> get_colour_map(/red)
  green = self -> get_colour_map(/green)
  blue = self -> get_colour_map(/blue)

  on_ioerror, badwrite

  write = file_test('./', /write)
  if (write ne 1) then dir = '/tmp/' else dir = './'

  tmpdir = dir+'idl2mpeg.frames'+string(systime(1), format = "('_',I0)")
  file_mkdir, tmpdir
  listfile = tmpdir+'/PNG.lis'
  openw, ilu, /get, listfile

; write each frame into tmpdir as an 8-bit .png image file

  namelist = strarr(nframes)

  im = self -> get_first()
  framenum = 0
  owindow = self -> get_window()
  window, /free, /pixmap, xsize = sz[0], ysize = sz[1]
  pwindow = !d.window

  if not widget_info(/active) or keyword_set(no_progress) then $
     isprog = 0b $
  else isprog = 1b

  if isprog then $
     pid = cw_progress(/column, $
                       title = 'Saving frames', $
                       xsize = 200, $
                       ysize = 20, $
                       value = 0., $
                       max = nframes) $
  else pid = 0l

  ispid = widget_info(/valid, pid)

  while obj_valid(im) do begin
     if not im -> get_pflags(/skip) then begin
        namelist[framenum] = 'frame.' + string(framenum, format = $
                                               formatstring) + '.png'
        filename = tmpdir + '/'+namelist[framenum]
        printf, ilu, filename
        im -> show, window = pwindow
        wset, pwindow
        if !d.n_colors le 256 then begin
           img = tvrd()
           write_png, filename, img, red, green, blue
        endif else begin
           img =  tvrd(true = 1)
           write_png, filename, img
        endelse
        framenum = framenum+1
        if ispid then widget_control, pid, set_value = framenum
     endif else nframes = nframes-1
     im = im -> get_next()
  endwhile
  wdelete, pwindow
  free_lun, ilu
  namelist = namelist[0:nframes-1]

  if ispid then widget_control, pid, /destroy

  device, window_state = wstat
  if owindow ne -1 && wstat[owindow] then wset, owindow

  if isprog then $
     pid = cw_progress(/column, $
                       title = 'Encoding movie', $
                       xsize = 200, $
                       ysize = 20, $
                       value = 0., $
                       max = nframes) $
  else pid = 0l

  ispid = widget_info(/valid, pid)



  if ~keyword_set(codec) then codec = 'mpeg4'
  if not keyword_set(frame_rate) then frame_rate = 10
; mencoder mf://\*.png -mf w=996:h=504:type=png:fps=4 -ovc lavc -lavcopts vcodec=mpeg4:mbd=2:trell -oac copy -o test4.avi

  cmd = string(listfile, sz, frame_rate, codec,  mpegfilename, $ $
               format = "('mencoder mf://@',A,' -mf w=',i0,':h=',"+ $
               "i0,':type=png:fps=',i0,' -ovc lavc -lavcopts '," + $
               "'vcodec=',a,':mbd=2 -oac copy -o ',a,'.avi')")
  
  print, cmd

; spawn a shell to process the mencoder command
  if ispid then begin
     spawn, cmd, unit = ilu
     inln = ''
     while not eof(ilu) do begin
        readf, ilu, inln
        if strpos(inln, 'Pos:') eq 0 then begin
           nos = stregex(inln, '[0-9]+f', /extract)
           ifr = strmid(nos[0], 0, strlen(nos[0]-1))
           widget_control, pid, set_value = $
                           1+ifr
        endif
     endwhile
     free_lun, ilu
  endif else spawn, cmd

; clean temp dir
  if (~keyword_set(no_delete)) then begin
     file_delete, tmpdir + '/'+namelist, listfile
     file_delete, tmpdir
  endif

  if ispid then widget_control, pid, /destroy

  return

badwrite:
  smei_msg, /alert, 'Unable to write Movie file!'

end
