;+
; NAME:
;	SMEI_SEQUENCE::MAKE_AGIF
;
;
; PURPOSE:
;	Generates an animated GIF from a SMEI sequence
;
;
; CATEGORY:
;	SMEI_SEQUENCE
;
;
; CALLING SEQUENCE:
;	seqref -> make_agif, file
;
;
; INPUTS:
;	file	string	The name stem of the file to which to write the AGIFs
;
; KEYWORD PARAMETERS:
;	frame_rate	(float)	The frame rate desired (fps)
;	/no_progress	If set, then disable the progress bars (useful
;			if slow network means the progress bars are
;			slowing operation).
;
;
; MODIFICATION HISTORY:
;	Original (after make_png): 18/3/08; SJT
;	Skip hidden frames: 13/6/03; SJT
;	Add no_progress keyword: 25/8/05; SJT
;	Fix colour maps: 19/12/12; SJT
;-

pro smei_sequence::make_agif, giffilename, frame_rate = frame_rate, $
                 no_progress = no_progress 

if n_params() eq 0 then giffilename = 'smei.gif'

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

if keyword_set(frame_rate) then delay = 100./frame_rate $
else delay = 10.

; 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


; Display each image to a pixmap window, read it and write to the GIF
; file.

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)

tvlct, indgen(256), indgen(256), indgen(256)
while obj_valid(im) do begin
    if not im -> get_pflags(/skip) then begin
        im -> show, window = pwindow
        wset, pwindow
        img = tvrd()
        write_gif, giffilename, img, red, green, blue, /multiple, $
          delay = delay, repeat_count = 0
        framenum = framenum+1
        if ispid then widget_control, pid, set_value = framenum
    endif else nframes = nframes-1
    im = im -> get_next()
endwhile
write_gif, giffilename, /close
tvlct, red, green, blue

wdelete, pwindow
if ispid then widget_control, pid, /destroy

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

return

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

end
