function[] = scorevideo(callbackname,callbackvar)

% Usage:  scorevideo; -- command line call to start program
% Usage:  scorevideo(callbackname,callbackvar); -- used by scorevideo for callbacks
% Function creates gui to view and score Shah lab mouse video behavior
% assays.
% Documentation in readme_scorevideo.doc.

%%%%%%%%%%%%%%%%%
%%% Main loop %%%
%%%%%%%%%%%%%%%%%

%%%----------------------------
%%% initial rendering of figure
%%%----------------------------
if (nargin == 0)
    
    FIGM = initmainfig;					% make main figure
    FIGM = inittimer(FIGM);				% initialize timer for playback
    setstoreddata(FIGM.thisfigh,FIGM);	% save figure handles in figure
    loadusersettings(FIGM);				% load user settings
    
    %%%----------------------------
    %%% check for availability of videoIO
    %%%----------------------------
    if (~exist('videoReader.m','file') || ...
        ~ismember('seek',methods('videoReader')))
        setmsg(FIGM,['videoIO is not available.  Some video ',...
            'types will play slowly or not at all.  If videoIO ',...
            'should be present, check the path.']);
    end

%%%------------------------------------------------------------
%%% callback functions:  commands from user via figure controls
%%%------------------------------------------------------------
else

    if (nargin < 2); callbackvar = []; end	% checking inputs
    FIGM = getstoreddata(gcf);				% get info from figure
    clearmsg(FIGM);                         % clear old message

    %%%--------------------------------------------
    %%% main switch statement:  processing callback
    %%%--------------------------------------------
    try %try to handle all errors
    switch (callbackname)		% switch on callbackname

        %%%-----------------------------------------------------------------
        %%% controls along bottom of figure: switch buttons, quit, savestate
        %%%-----------------------------------------------------------------
        case ('switch')             % switch between panels
            doswitchpanel(FIGM,callbackvar);

        case ('quit')               % quit program
            query_quit(FIGM);

        case ('savestate');         % save current graphics for programmer
            dosavestate;

        %%%------------------------------------------------------
        %%% controls in lower left boxes:  load, save, clear, etc
        %%%------------------------------------------------------
        case ('video_frominput')	% load video using video file input
            loadvideofrominput(FIGM,callbackvar);

        case ('video_fromlog')		% load video using log info
            loadvideofromlog(FIGM);

        case ('video_clear')		% clear video
            doclearvideo(FIGM);

        case ('comm_load')			% load command set from file
            loadcommandsfile(FIGM);

        case ('comm_save')			% save command set to file
            savecommandsfile(FIGM);

        case ('comm_checksave')		% update check save cmnds flag
            setboxflag(FIGM,'checksavecmnds');
            
        case ('comm_clear')			% clear command set
            doclearcommandset(FIGM);

        case ('log_load')			% load log file
            loadlogfile(FIGM);

        case ('log_save')			% save log file
            savelogfile(FIGM);

        case ('log_checksave')		% update check save log flag
            setboxflag(FIGM,'checksavelog');

        case ('log_clearall')		% clear entire log
            doclearlog(FIGM);

        %%%------------------------
        %%% controls in files panel
        %%%------------------------
        case ('files_vtype')		% update video type
            dosetvtype(FIGM);

        case ('files_browsedir')	% browse for directory
            dobrowsedir(FIGM,callbackvar);

        case ('files_browsefile')	% browse for file
            dobrowsefile(FIGM,callbackvar);

        %%%------------------------
        %%% controls in cmnds panel
        %%%------------------------
        case ('cmnds_nchar')		% set # of chars in scoring commands
            changenchar(FIGM);

        case ('cmnds_add')			% add scoring command
            addusercommand(FIGM);

        case ('cmnds_delete')		% delete selected scoring command
            deleteusercommand(FIGM);

        case ('cmnds_edit')			% edit selected scoring command
            putusercommandinentry(FIGM);

        case ('cmnds_update')		% update selected scoring command
            updateusercommand(FIGM);

        %%%------------------------
        %%% controls in behav panel
        %%%------------------------
        case ('behav_delete')		% delete selected entry from raw log
            deletefromrawlog(FIGM);

        case ('behav_overwrite')	% set overwrite behav log flag
            dosetoverwritemsg(FIGM);

        case ('behav_buildfull')	% build full log
            buildfulllog(FIGM);

        case ('behav_buildasyougo')	% update build-as-you-go flag
            setboxflag(FIGM,'buildasyougo');
            switchbuildasyougo(FIGM);

        case ('jump')				% jump to requested frame in video
            jumptoframe(FIGM,callbackvar);

        case ('getlogselection')	% get current behav log frame for jumping
            getlogframes(FIGM,callbackvar,'current');

        case ('getendoflog')		% get last behav log frame for jumping
            getlogframes(FIGM,callbackvar,'end');

        case ('behav_clearfull');	% clear full behav log
            clearfulllog(FIGM);

        case ('behav_clearraw')		% clear behav log (raw and full)
            doclearrawlog(FIGM);
            
        %%%------------------------
        %%% controls in nandm panel
        %%%------------------------
        case ('notes_add')			% add user note
            addnote(FIGM);

        case ('notes_delete')		% delete user note
            deletenote(FIGM);

        case ('notes_edit')			% edit selected user note
            editnote(FIGM);

        case ('notes_update')		% update selected user note
            updatenote(FIGM);

        case ('marks_add')			% add user mark
            addmark(FIGM);

        case ('marks_delete')		% delete user mark
            deletemark(FIGM);

        case ('marks_edit')			% edit selected user mark
            editmark(FIGM);

        case ('marks_update')		% update selected user mark
            updatemark(FIGM);

        case ('marks_setstart')		% set mark for start of analysis window
            setmark(FIGM,'start');

        case ('marks_setalign')		% set mark for alignment of analysis window
            setmark(FIGM,'align');

        case ('marks_setend')       % set mark for end of analysis window
            setmark(FIGM,'end');

        case ('marks_inclstartsbefore')
            setboxflag(FIGM,'inclstartsbefore');

        case ('marks_inclstopsafter')
            setboxflag(FIGM,'inclstopsafter');

        %%%------------------------
        %%% controls in analy panel
        %%%------------------------
        case ('analy_plots')		% plot output plot (raster and/or table)
            makeoutputplot(FIGM,callbackvar);

        case ('analy_updateparams')	% update raster panel parameters
            updateplotparams(FIGM,callbackvar);

        case ('analy_calcparams')	% calculate and show plotting parameters
            getplotparams(FIGM);

        case ('analy_updatecolor')	% update color of list selection
            updateplotcolor(FIGM);

        case ('analy_plotorder')    % change order to plot behaviors
            changeplotorder(FIGM,callbackvar);

        case ('analy_coloroption')	% change plot color
            setplotcolor(FIGM,callbackvar);

        case ('analy_colorcustom')	% specify custom color
            initcustomcolorfig(FIGM);

        case ('analy_tabletoxls')	% output scoring stats to file
            writesummarystatsxlsfile(FIGM);

            %%%------------------------------------------
            %%% controls in custom color secondary figure
            %%%------------------------------------------
        case ('color')				% process callback from custom color figure
            docustomcolorrequest(callbackvar);

    end
    catch %Errors from _any_ callback
        handle_error(FIGM,callbackname,callbackvar);
    end
end

%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
%%% Subfunctions:  Program-specific, main %%%
%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
% Listing:
% function[] = acceptloginput(FIGM,lfinput,lfdata,status)
% function[] = acceptlogvideoinput(FIGM,lfdata,status)
% function[] = acceptvideoinput(FIGM,vfinput)
% function[DAT] = addentrytofulllog(DAT,framenum,key)
% function[] = addmark(FIGM)
% function[] = addnote(FIGM)
% function[vfinput] = addvideofiles(FIGM,vfinput)
% function[] = addusercommand(FIGM,ucindex)
% function[src] = bc_changedvars(src,variableset)
% function[DAT,validlist] = bc_hiddenframes(FIGM,DAT)
% function[src] = bc_newvars(src,variableset)
% function[src] = bc_renamedvars(src,variableset)
% function[] = buildfulllog(FIGM)
% function[src] = calcvideosettings(src)
% function[] = changenchar(FIGM)
% function[] = changeplotorder(FIGM,callbackvar)
% function[vfinput] = checkfilenumbers(FIGM,vfinput)
% function[status] = checkloadlog(FIGM,lfdata)
% function[] = checkmarkslog(FIGM)
% function[] = checkncharinuclist(FIGM)
% function[vfinput] = checkvfinput(FIGM,vfinput)
% function[vfinput] = checkvideoadd(FIGM,vfinput)
% function[vfinput] = checkvideoconstants(FIGM,vfinput)
% function[msg] = checkvideomatch(FIGM,lfdata)
% function[vfinput] = checkvideoupdate(FIGM,vfinput)
% function[ucindex] = checkucagainstlog(DAT,ucindex)
% function[] = clearfulllog(FIGM)
% function[] = clearmarkslog(FIGM)
% function[] = clearmsg(FIGM)
% function[] = clearnoteslog(FIGM)
% function[] = clearrawlog(FIGM)
% function[] = clearvideo(FIGM)
% function[] = clearucentryfields(FIGM)
% function[blist] = createbehaviorlist(uc)
% function[] = deletefromrawlog(FIGM)
% function[] = deletemark(FIGM)
% function[] = deletenote(FIGM)
% function[] = deleteusercommand(FIGM)
% function[] = displayfulllog(FIGM)
% function[] = displaymarkindices(FIGM)
% function[] = displaymarkslog(FIGM)
% function[] = displaynoteslog(FIGM)
% function[] = displayrawlog(FIGM)
% function[] = displayvfinfo(FIGM)
% function[] = displayusercommands(FIGM)
% function[] = dobrowsedir(FIGM,fileset)
% function[] = dobrowsefile(FIGM,fileset)
% function[] = doclearcommandset(FIGM)
% function[] = doclearlog(FIGM)
% function[] = doclearrawlog(FIGM)
% function[] = doclearvideo(FIGM)
% function[] = docustomcolorrequest(callbackvar)
% function[] = dosavestate()
% function[] = dosetoverwritemsg(FIGM)
% function[] = dosetvtype(FIGM)
% function[] = doswitchpanel(FIGM,switchname)
% function[] = drawframe(FIGM)
% function[] = editmark(FIGM)
% function[] = editnote(FIGM)
% function[] = figurekeypressfcn(hco,user)
% function[] = finishfulllog(FIGM)
% function[s] = formatvarfortext(FIGM,varname,data)
% function[src] = generatefilenames(src)
% function[aw] = getawframes(markslog)
% function[cfinput] = getcfinput(FIGM)
% function[] = getfixedcommands(FIGM)
% function[lfinput] = getlfinput(FIGM)
% function[] = getlogframes(FIGM,whichlog,whichframes)
% function[videomethod] = getvideoreadmethod(FIGM,pathandfile)
% function[slash,codepath] = getslashandcodepath()
% function[filevars] = getvarsforlogfile(FIGM)
% function[vfinput] = getvfinput(FIGM,vfinput)
% function[vfinput,avibadflag] = getvideofiles(FIGM,vfinput)
% function[oneframe] = getvideoframe(FIGM,currframe)
% function[] = growfulllog(FIGM,startframe,endframe)
% function[] = handle_error(FIGM,varargin)
% function[markslog] = indexawframes(markslog,aw)
% function[] = initcommandset(FIGM)
% function[] = initcustomcolorfig(FIGM)
% function[FIGM] = initmainfig()
% function[] = initfixedlist(FIGM)
% function[] = initfulllog(FIGM)
% function[] = initmarkslog(FIGM)
% function[] = initnoteslog(FIGM)
% function[] = initposnlog(FIGM)
% function[] = initrawlog(FIGM)
% function[] = initvideo(FIGM)
% function[FIGM] = inittimer(FIGM)
% function[] = jumptoframe(FIGM,whichlog)
% function[] = killvobj(FIGM)
% function[] = loadcommandsfile(FIGM)
% function[] = loadlogfile(FIGM)
% function[] = loadvideofrominput(FIGM,loadmode)
% function[] = loadvideofromlog(FIGM)
% function[] = loadusersettings(FIGM)
% function[filenames,firsti,lasti] = makefilenames(prefix,startnum,endnum)
% function[DAT] = makefulllogtext(DAT,nspaces)
% function[DAT] = makemarkslogtext(DAT,nspaces)
% function[] = makeoutputplot(FIGM,plottype)
% function[DAT] = makerawlogtext(DAT,nspaces)
% function[FIGM] = makeuicontrols(FIGM,uicp)
% function[s] = makevideosettext(DAT,nspaces)
% function[DAT,FFL] = overwritelog(DAT,FFL,currframe)
% function[] = putcfinput1(FIGM,cfinput)
% function[] = putcfinput2(FIGM,cfinput,cfinput2)
% function[] = putlfinput(FIGM,lfinput)
% function[] = putstoredvalues(FIGM)
% function[] = putvfinput(FIGM,src)
% function[] = putusercommandinentry(FIGM)
% function[response] = query_loadcmndswhenlog()
% function[response] = query_loadvideowhenlog()
% function[response] = query_loadvideowhenvideo()
% function[response] = query_logvideomismatch(msg)
% function[] = query_quit(FIGM)
% function[] = quitprogramfxn(hco,user)
% function[vfinput] = retrievefilelist(FIGM,vfinput)
% function[lfinput,lfdata] = retrievelogfile(FIGM)
% function[vfinput] = retrievevfinput(FIGM,loadmode)
% function[] = savecommandsfile(FIGM)
% function[] = savelogfile(FIGM)
% function[] = savelogtextfile(FIGM)
% function[] = saveusersettings(FIGM)
% function[] = setactivepanel(FIGM,mode)
% function[] = setboxflag(FIGM,boxname,flagvalue)
% function[] = setcurrframe(FIGM,currframe)
% function[vfinput] = setfilenumbers(vfinput)
% function[] = setmark(FIGM,marktype)
% function[] = setmsg(FIGM,msgtext)
% function[] = setoverwritemsg(FIGM,overwritevalue)
% function[] = setplotcolor(FIGM,callbackvar)
% function[FIGM] = setswitchhandles(FIGM)
% function[FFL] = settimeroffplayoff(FIGM,FFL)
% function[] = setvarsforvideoload(FIGM)
% function[] = setvtype(FIGM,vtype)
% function[] = setvideoloaded(FIGM,status)
% function[] = storecfinfo(FIGM,cfinput,ucinput)
% function[] = storelfdata(FIGM,lfdata)
% function[] = storelfinfo(FIGM,lfinput)
% function[FIGM] = storeprogramdata(FIGM,CON,DAT,FFL,TFL)
% function[] = storevfinfo(FIGM,src)
% function[] = switchbuildasyougo(FIGM)
% function[] = switchnchar(FIGM,newnchars)
% function[] = timertickfcn(hco,user)
% function[] = updatecmndsflags(FIGM)
% function[] = updateframe(FIGM)
% function[] = updatefulllog(FIGM)
% function[] = updatelogemptyflags(FIGM)
% function[] = updatelogsavedflag(FIGM,logjustsavedorloaded)
% function[] = updatemark(FIGM)
% function[] = updatemarkslog(FIGM)
% function[] = updatenote(FIGM)
% function[] = updatenoteslog(FIGM)
% function[] = updateongoing(FIGM,key)
% function[] = updateplotcolor(FIGM)
% function[] = updateplotparams(FIGM,callbackvar)
% function[] = updaterawlog(FIGM)
% function[] = updateusercommand(FIGM)
% function[] = writecommandstextfile(FIGM)
% function[] = writelogtextfile(FIGM)
% function[] = writesummarystatsxlsfile(FIGM)

%======================================================
function[] = acceptloginput(FIGM,lfinput,lfdata,status)
%%%---------------------------------------------------------
%%% Function stores log file variables and updates displays.
%%% Called by:  loadlogfile
%%%---------------------------------------------------------
if (status.loadlog == 1)
    storelfinfo(FIGM,lfinput);
    storelfdata(FIGM,lfdata);
    cfinput.cpath = [];
    cfinput.cfilename = [];
    cfinput.subj1name = [];
    cfinput.subj2name = [];
    cfinput.simbehav = [];
    setstoreddata(FIGM.FFLh,[],'isfrom_cmnds','log');
    storecfinfo(FIGM,cfinput,lfdata.uc);
    putcfinput2(FIGM,lfdata.uc);
    displayusercommands(FIGM);
    clearucentryfields(FIGM);
    updaterawlog(FIGM);
    checkmarkslog(FIGM);
    updatenoteslog(FIGM);
    checkmodules('updateposnlog',FIGM);
    buildfulllog(FIGM);
    if (getstoreddata(FIGM.FFLh,'isloaded_video') == 1)
        updateframe(FIGM);
    end
    setmsg(FIGM,'log loaded');
else
    setmsg(FIGM,'load log cancelled');
end

%===================================================
function[] = acceptlogvideoinput(FIGM,lfdata,status)
%%%----------------------------------------------------------
%%% Function stores video file set information from log file.
%%% Called by:  loadlogfile
%%%----------------------------------------------------------
if (status.clearvideo == 1)
    initvideo(FIGM);					% clear video file set information
    clearvideo(FIGM);					% clear video display
end
if (status.loadvideo == 1)
    lfdata = calcvideosettings(lfdata);	% calculate video file set variables
    storevfinfo(FIGM,lfdata);			% store video file set information
    if (~isempty(lfdata.vprefixes))
        setstoreddata(FIGM.FFLh,[],'canloadfromlog',1);
    else
        setstoreddata(FIGM.FFLh,[],'canloadfromlog',0);
    end
end

%==========================================
function[] = acceptvideoinput(FIGM,vfinput)
%%%-----------------------------------------------------
%%% Function stores video file set information from user
%%% input and updates displays.
%%% Called by:  loadvideofrominput
%%%-----------------------------------------------------
if (vfinput.loadflag == 1)
    vfinput = calcvideosettings(vfinput);   % calc other video parameters
    storevfinfo(FIGM,vfinput);              % store video file set info
    displayvfinfo(FIGM);                    % update video file set info display
    putvfinput(FIGM,vfinput);               % update video file set input fields
    setvarsforvideoload(FIGM);              % set up for playing video
    setvideoloaded(FIGM,1);
    setstoreddata(FIGM.FFLh,[],'canloadfromlog',0);
    checkmarkslog(FIGM);
    drawframe(FIGM);						% draw first frame
    updatelogsavedflag(FIGM);
end
if (isempty(vfinput.msg))
    switch (vfinput.loadmode)
        case ('new')
            vfinput.msg = 'video loaded';
        case ('add')
            vfinput.msg = 'video added';
        case ('update')
            vfinput.msg = 'video settings updated';
    end
end
setmsg(FIGM,vfinput.msg);

%==================================================
function[DAT] = addentrytofulllog(DAT,framenum,key)
%%%------------------------------------------------
%%% Function adds an entry to the full score log
%%% (to DAT.fulllog.<> fields), having frame number
%%% 'framenum' and command 'key'.
%%% Called by:  growfulllog, finishfulllog
%%%------------------------------------------------
logtime = double(framenum/(DAT.vfpsoi*60));
bcharindex = strmatch(key,DAT.uc.bchar);
echarindex = strmatch(key,DAT.uc.echar);
%%%-----------------------------------------------------
%%% if begin char, if state already open, ignore command
%%%-----------------------------------------------------
if (~isempty(bcharindex))
    if (~isempty(find(DAT.openstates == bcharindex,1)))
        bcharindex = [];
    end
end
%%%-----------------------------------------------------------
%%% if begin char, end ongoing states based on DAT.uc.simbehav
%%% (flag by adding to echarindex)
%%%-----------------------------------------------------------
if (~isempty(bcharindex))
    logsubj = DAT.uc.subj{bcharindex};
    switch (DAT.uc.simbehav)
        case (1)
            closeforsubj = DAT.ucparams.subj;
        case (2)
            closeforsubj = {logsubj;'3'};
        case (3)
            closeforsubj = {};
    end
    for si = DAT.openstates
        opensubj = DAT.uc.subj{si};
        if (ismember(opensubj,closeforsubj))
            echarindex = [echarindex;si];
        end
    end
end
%%%----------------------------------
%%% for end char, add ends to fulllog
%%%----------------------------------
for ei = 1:size(echarindex,1)
    openflag = find(DAT.openstates == echarindex(ei));
    if ~isempty(openflag)
        DAT.fulllog.frame{end+1,1} = double(framenum);
        DAT.fulllog.time{end+1,1} = logtime;
        DAT.fulllog.charnum{end+1,1} = echarindex(ei);
        DAT.fulllog.type{end+1,1} = 'state';
        DAT.fulllog.action{end+1,1} = 'stop';
        DAT.fulllog.subj{end+1,1} = str2double(DAT.uc.subj{echarindex(ei)});
        keepindex = setdiff(1:size(DAT.openstates,2),openflag);
        if (size(keepindex,2) < size(keepindex,1))
            keepindex = keepindex';
        end
        DAT.openstates = DAT.openstates(keepindex);
    end
end
%%%-------------------------------------
%%% for begin char, add begin to fulllog
%%%-------------------------------------
if (~isempty(bcharindex))
    if (isempty(DAT.uc.echar{bcharindex}))
        logtype = 'event';
    else
        logtype = 'state';
        DAT.openstates = [DAT.openstates bcharindex];
    end
    DAT.fulllog.frame{end+1,1} = double(framenum);
    DAT.fulllog.time{end+1,1} = logtime;
    DAT.fulllog.charnum{end+1,1} = bcharindex;
    DAT.fulllog.type{end+1,1} = logtype;
    DAT.fulllog.action{end+1,1} = 'start';
    DAT.fulllog.subj{end+1,1} = str2double(logsubj);
end

%=========================
function[] = addmark(FIGM)
%%%-----------------------------------------------------------
%%% Function adds mark from user input to markslog.
%%% Called by:  Add BUTTON under marks log list in NANDM panel
%%%-----------------------------------------------------------
newmarkframe = str2num(get(FIGM.uic.nandm.marksframe,'string'));
newmarkname = get(FIGM.uic.nandm.marksname,'string');
if (isempty(newmarkframe))
    setmsg(FIGM,'error:  frame number is required');
elseif (isempty(newmarkname))
    setmsg(FIGM,'error:  name for mark is required');
else
    DAT = getstoreddata(FIGM.DATh);
    if (ismember(newmarkframe,DAT.markslog.framenum))
        setmsg(FIGM,'error:  mark already exists; use update button to change name');
    elseif (~isempty(strmatch(newmarkname,DAT.markslog.framename,'exact')))
        setmsg(FIGM,'error:  mark name must be unique');
    else
        aw = getawframes(DAT.markslog);
        DAT.markslog.framenum = [DAT.markslog.framenum;newmarkframe];
        DAT.markslog.framename = [DAT.markslog.framename;{newmarkname}];
        [y,yi] = sort(DAT.markslog.framenum);
        DAT.markslog.framenum = DAT.markslog.framenum(yi);
        DAT.markslog.framename = DAT.markslog.framename(yi);
        DAT.markslog = indexawframes(DAT.markslog,aw);
        setstoreddata(FIGM.DATh,DAT);
        updatemarkslog(FIGM);
        setmsg(FIGM,'mark added');
    end
end

%=========================
function[] = addnote(FIGM)
%%%-----------------------------------------------------------
%%% Function adds note from user input to noteslog.
%%% Called by:  Add BUTTON under notes log list in NANDM panel
%%%-----------------------------------------------------------
newnote = get(FIGM.uic.nandm.entrytext,'string');
if (~isempty(newnote))
    DAT = getstoreddata(FIGM.DATh);
    DAT.noteslog = [DAT.noteslog;{newnote}];
    setstoreddata(FIGM.DATh,DAT);
    displaynoteslog(FIGM);
    setmsg(FIGM,'note added');
else
    setmsg(FIGM,'error:  note entry is empty');
end

%==============================================
function[vfinput] = addvideofiles(FIGM,vfinput)
%%%--------------------------------------------------
%%% Function adds or updates video file set variables
%%% based on user input.
%%% Called by:  loadvideofrominput
%%%--------------------------------------------------
if (vfinput.loadflag == 1)
    isnew_loadmode = strcmp('new',vfinput.loadmode);
    isadd_loadmode = strcmp('add',vfinput.loadmode);
    isupdate_loadmode = strcmp('update',vfinput.loadmode);
    %%%-------------------
    %%% update subset list
    %%%-------------------
    DAT = getstoreddata(FIGM.DATh);
    DAT.videomethod = vfinput.videomethod;
    if (isnew_loadmode == 1)
        vfinput.vprefixes = {vfinput.vprefix};
        vfinput.vnumstarts = vfinput.vnumstart;
        vfinput.vnumends = vfinput.vnumend;
    else
        subsetindex = get(FIGM.uic.files.vlist,'value');
        vfinput.vprefixes = DAT.vprefixes;
        vfinput.vnumstarts = DAT.vnumstarts;
        vfinput.vnumends = DAT.vnumends;
        if (isadd_loadmode == 1)
            vfinput.vprefixes = [vfinput.vprefixes;{vfinput.vprefix}];
            vfinput.vnumstarts = [vfinput.vnumstarts;vfinput.vnumstart];
            vfinput.vnumends = [vfinput.vnumends;vfinput.vnumend];
        end
        if (isupdate_loadmode == 1)
            vfinput.vnumstarts(subsetindex) = vfinput.vnumstart;
            vfinput.vnumends(subsetindex) = vfinput.vnumend;
        end
        %%%---------------------------------------------------
        %%% reduce filelist to only include old and new subset
        %%%---------------------------------------------------
        if (isadd_loadmode == 1)
            newvnumstart = vfinput.vnumstart;
            newvnumend = vfinput.vnumend;
            vstartindex = find(vfinput.vfilenums == newvnumstart);
            vendindex = find(vfinput.vfilenums == newvnumend);
        end
        if (isupdate_loadmode == 1)
            oldvnumstart = DAT.vnumstarts(subsetindex);
            oldvnumend = DAT.vnumends(subsetindex);
            newvnumstart = vfinput.vnumstart;
            newvnumend = vfinput.vnumend;
            usevnumstart = min([oldvnumstart newvnumstart]);
            usevnumend = max([oldvnumend newvnumend]);
            vstartindex = find(vfinput.vfilenums == usevnumstart);
            vendindex = find(vfinput.vfilenums == usevnumend);
        end
        keepindex = vstartindex:vendindex;
        vfinput.vfilenames = vfinput.vfilenames(keepindex);
        vfinput.vfilenums = vfinput.vfilenums(keepindex);
        vfinput.vframenums = vfinput.vframenums(keepindex);
        vfinput.vfsrcindex = vfinput.vfsrcindex(keepindex);
        %%%----------------------------------------------
        %%% set frame numbers
        %%%----------------------------------------------
        vfinput.vframenums(:) = NaN;
        vnumstart = vfinput.vnumstart;
        vnumend = vfinput.vnumend;
        framenums = (vnumstart:vnumend) - vnumstart + 1;
        vnumstartindex = find(vfinput.vfilenums == vnumstart);
        vnumendindex = find(vfinput.vfilenums == vnumend);
        vfinput.vframenums(vnumstartindex:vnumendindex) = framenums';
        maxoldframenum = nanmax(DAT.vframenums);
        vfinput.vframenums = vfinput.vframenums + maxoldframenum;
        %%%-----------------------------------------------------------
        %%% for loadmode = 'add', increment up vfsrcindex
        %%% for loadmode = 'update', set vfsrcindex to match selection
        %%%-----------------------------------------------------------
        if (isadd_loadmode == 1)
            maxoldsrcindex = size(DAT.vprefixes,1);
            vfinput.vfsrcindex(:) = maxoldsrcindex + 1;
        end
        if (isupdate_loadmode == 1)
            vfinput.vfsrcindex(:) = subsetindex;
        end
        %%%--------------------------------------------------------
        %%% get indices for replaced items in old and new filelists
        %%%--------------------------------------------------------
        vlistids_old = cellstr([char(DAT.vfilenames),num2str(DAT.vfilenums)]);
        vlistids_new = cellstr([char(vfinput.vfilenames),num2str(vfinput.vfilenums)]);
        replindex_old = find(ismember(vlistids_old,vlistids_new));
        replindex_new = find(ismember(vlistids_new,vlistids_old));
        addindex_new = setdiff((1:size(vlistids_new,1)),replindex_new);
        if (size(addindex_new,2) < size(addindex_new,1))
            addindex_new = addindex_new';
        end
        %%%---------------------------------------------------------------
        %%% replace and append in old filelist, eliminate duplicates using
        %%% last occurrence
        %%%---------------------------------------------------------------
        temp.vfilenames = DAT.vfilenames;
        temp.vfilenums = DAT.vfilenums;
        temp.vframenums = DAT.vframenums;
        temp.vfsrcindex = DAT.vfsrcindex;
        if (~isempty(replindex_old))
            temp.vframenums(replindex_old) = vfinput.vframenums(replindex_new);
            temp.vfsrcindex(replindex_old) = vfinput.vfsrcindex(replindex_new);
        end
        if (~isempty(addindex_new))
            temp.vfilenames = [temp.vfilenames; vfinput.vfilenames(addindex_new)];
            temp.vfilenums = [temp.vfilenums; vfinput.vfilenums(addindex_new)];
            temp.vframenums = [temp.vframenums; vfinput.vframenums(addindex_new)];
            temp.vfsrcindex = [temp.vfsrcindex; vfinput.vfsrcindex(addindex_new)];
        end
        vfinput.vfilenames = temp.vfilenames;
        vfinput.vfilenums = temp.vfilenums;
        vfinput.vframenums = temp.vframenums;
        vfinput.vfsrcindex = temp.vfsrcindex;
        vlistids_new = cellstr([char(vfinput.vfilenames),num2str(vfinput.vfilenums)]);
        [vlistids_new,index] = unique(vlistids_new);    % index returns last occurrence
        vfinput.vfilenames = vfinput.vfilenames(index);
        vfinput.vfilenums = vfinput.vfilenums(index);
        vfinput.vframenums = vfinput.vframenums(index);
        vfinput.vfsrcindex = vfinput.vfsrcindex(index);
        vfinput.vnummax = size(vfinput.vfilenames,1);
        %%%----------------------------------
        %%% sort filelist and renumber frames
        %%%----------------------------------
        [vlistids_new,index] = sort(vlistids_new);
        vfinput.vfilenames = vfinput.vfilenames(index);
        vfinput.vfilenums = vfinput.vfilenums(index);
        vfinput.vframenums = vfinput.vframenums(index);
        vfinput.vfsrcindex = vfinput.vfsrcindex(index);
        fnindex = find(~isnan(vfinput.vframenums));
        vfinput.vframenums(fnindex) = (1:size(fnindex,1))';
        vfinput.vframemax = nanmax(vfinput.vframenums);
        if (isempty(vfinput.vframemax) || isnan(vfinput.vframemax))
            vfinput.vframemax = 0;
        end
        %%%---------------------------------------
        %%% adjust vfsrcindex, reorder subset list
        %%%---------------------------------------
        [uniquefsrc,index] = unique(vfinput.vfsrcindex);
        orderfsrc = zeros(size(uniquefsrc));
        for fi = 1:size(orderfsrc,1)
            x = find(vfinput.vfsrcindex == uniquefsrc(fi));
            orderfsrc(fi) = x(1);
        end
        [sortedvar,origorder] = sort(orderfsrc);
        temp.vfsrcindex = vfinput.vfsrcindex;
        for fi = 1:size(origorder,1)
            temp.vfsrcindex(vfinput.vfsrcindex == origorder(fi)) = fi;
        end
        vfinput.vfsrcindex = temp.vfsrcindex;
        vfinput.vprefixes = vfinput.vprefixes(origorder);
        vfinput.vnumstarts = vfinput.vnumstarts(origorder);
        vfinput.vnumends = vfinput.vnumends(origorder);
        %%%-------------------------------------------
        %%% get log indices, fix frame numbers in logs
        %%%-------------------------------------------
        isempty_log = getstoreddata(FIGM.FFLh,'isempty_log');
        if (isempty_log == 0)
            logchangedflag = 0;
            isempty_slog = getstoreddata(FIGM.FFLh,'isempty_slog');
            if (isempty_slog == 0)
                rlogframes = DAT.rawlogframe;
                for row = 1:size(rlogframes,1)
                    framenum_old = rlogframes(row);
                    index_old = find(DAT.vframenums == framenum_old);
                    frameid = vlistids_old{index_old};
                    index_new = strmatch(frameid,vlistids_new,'exact');
                    framenum_new = vfinput.vframenums(index_new);
                    if (framenum_old ~= framenum_new)
                        rlogframes(row) = framenum_new;
                        logchangedflag = 1;
                        if (isnan(framenum_new))
                            vfinput.loadflag = 0;
                            vfinput.msg = 'error:  update excludes frame(s) used in log(s)';
                        end
                    end
                end
                DAT.rawlogframe = rlogframes;
            end
            isempty_mlog = getstoreddata(FIGM.FFLh,'isempty_mlog');
            if (isempty_mlog == 0)
                mlogframes = DAT.markslog.framenum;
                startindex = strmatch('video start',DAT.markslog.framename);
                endindex = strmatch('video end',DAT.markslog.framename);
                startendindex = [startindex;endindex];
                for row = 1:size(mlogframes,1)
                    if (~ismember(row,startendindex))
                        framenum_old = mlogframes(row);
                        index_old = find(DAT.vframenums == framenum_old);
                        frameid = vlistids_old{index_old};
                        index_new = strmatch(frameid,vlistids_new,'exact');
                        framenum_new = vfinput.vframenums(index_new);
                        if (framenum_old ~= framenum_new)
                            mlogframes(row) = framenum_new;
                            logchangedflag = 1;
                            if (isnan(framenum_new))
                                vfinput.loadflag = 0;
                                vfinput.msg = 'error:  update excludes frame(s) used in log(s)';
                            end
                        end
                    end
                end
                DAT.markslog.framenum = mlogframes;
            end
            isempty_plog = getstoreddata(FIGM.FFLh,'isempty_plog');
            if (isempty_plog == 0)
                plogframes = DAT.posnlog(:,1);
                for row = 1:size(plogframes,1)
                    framenum_old = plogframes(row);
                    index_old = find(DAT.vframenums == framenum_old);
                    frameid = vlistids_old{index_old};
                    index_new = strmatch(frameid,vlistids_new,'exact');
                    framenum_new = vfinput.vframenums(index_new);
                    if (framenum_old ~= framenum_new)
                        plogframes(row) = framenum_new;
                        logchangedflag = 1;
                        if (isnan(framenum_new))
                            vfinput.loadflag = 0;
                            vfinput.msg = 'error:  update excludes frame(s) used in log(s)';
                        end
                    end
                end
                DAT.posnlog(:,1) = plogframes;
            end
            if (vfinput.loadflag == 1)
                if (logchangedflag == 1)
                    updaterawlog(FIGM);
                    clearfulllog(FIGM);
                    checkmarkslog(FIGM);
                    updatemarkslog(FIGM);
                    checkmodules('updateposnlog',FIGM);
                end
            end
        end
    end
    setstoreddata(FIGM.DATh,DAT);
end

%========================================
function[] = addusercommand(FIGM,ucindex)
%%%-------------------------------------------------------------
%%% Function adds user command from user input to command set.
%%% Called by:  Add BUTTON below command set list in CMNDS panel
%%%-------------------------------------------------------------
errorflag = 0;
DAT = getstoreddata(FIGM.DATh);
if (nargin < 2); ucindex = size(DAT.uc.bchar,1) + 1; end
if isempty(ucindex); ucindex = size(DAT.uc.bchar,1) + 1; end
newbchar = get(FIGM.uic.cmnds.bchar,'string');
newechar = get(FIGM.uic.cmnds.echar,'string');
newsubj = getuivalue(FIGM.uic.cmnds.subj);
newsubj = newsubj(1);
newdesc = get(FIGM.uic.cmnds.desc,'string');
if isempty(newbchar)
    errorflag = 1;
    setmsg(FIGM,'error:  character must be provided');
else
    checkreserved = strmatch(newbchar(1),DAT.fixed.char,'exact');
    if ~isempty(checkreserved)
        errorflag = 1;
        setmsg(FIGM,'error:  first character cannot overlap with fixed commands');
    else
        if (length(newbchar) ~= DAT.uc.nchars)
            errorflag = 1;
            setmsg(FIGM,'error:  command has an incorrect number of characters');
        end
    end
end
if (~isempty(newechar) && errorflag == 0)
    checkreserved = strmatch(newechar(1),DAT.fixed.char,'exact');
    if ~isempty(checkreserved)
        errorflag = 1;
        setmsg(FIGM,'error:  first character cannot overlap with fixed commands');
    else
        if (length(newechar) ~= DAT.uc.nchars)
            errorflag = 1;
            setmsg(FIGM,'error:  command has an incorrect number of characters');
        end
    end
end
if (errorflag == 0)
    bcharindex = 1:size(DAT.uc.bchar,1);
    inuseindex = setdiff(bcharindex,ucindex)';
    if (size(inuseindex,2) > size(inuseindex,1))
        inuseindex = inuseindex';
    end
    bcharinuse = DAT.uc.bchar(inuseindex);
    bcharoverlap = strmatch(newbchar,bcharinuse,'exact');
    if (~isempty(bcharoverlap))
        errorflag = 1;
        setmsg(FIGM,'error:  each start command must be unique');
    end
end
if (errorflag == 0)
    bcharinuse = [DAT.uc.bchar;{newbchar}];
    echaroverlap = strmatch(newechar,bcharinuse,'exact');
    if (~isempty(echaroverlap))
        errorflag = 1;
        setmsg(FIGM,'error:  stop commands cannot overlap with start commands');
    end
end
if (errorflag == 0)
    if (ucindex == size(DAT.uc.bchar,1) + 1)
        DAT.uc.plotorder(ucindex,1) = ucindex;
        DAT.uc.plotclr(ucindex,:) = [0 0 0];
    end
    DAT.uc.bchar{ucindex,1} = newbchar;
    DAT.uc.echar{ucindex,1} = newechar;
    DAT.uc.subj{ucindex,1} = newsubj;
    DAT.uc.desc{ucindex,1} = newdesc;
    [ordered_char,ordered_index] = sort(DAT.uc.bchar);
    DAT.uc.bchar = ordered_char;
    DAT.uc.echar = DAT.uc.echar(ordered_index);
    DAT.uc.subj = DAT.uc.subj(ordered_index);
    DAT.uc.desc = DAT.uc.desc(ordered_index);
    DAT.uc.plotorder = DAT.uc.plotorder(ordered_index);
    DAT.uc.plotclr = DAT.uc.plotclr(ordered_index,:);
    setstoreddata(FIGM.DATh,DAT);
    displayusercommands(FIGM);
    clearucentryfields(FIGM);
    setmsg(FIGM,'command set updated');
end

%==============================================
function[src] = bc_changedvars(src,variableset)
%%%-----------------------------------------------------------
%%% Function handles back compatibility for variables whose
%%% structure changed:  modifies variable in input loaded from
%%% log file or user settings file to be in current format.
%%% Called by:  loadusersettings, retrievelogfile
%%%-----------------------------------------------------------
switch (variableset)
    case ('settings')
        if (isfield(src,'vtype'))
            src.vtype = upper(src.vtype);
        end
    case ('log')
        if (isfield(src,'vtype'))
            src.vtype = upper(src.vtype);
        end
        if ((isfield(src,'vfilenames')) && (isfield(src,'vtype')))
            if sum(strcmp(src.vtype,{'AVI','MPG','WMV'}))...
                    && (size(src.vfilenames,1) == 1)
                avifilename = src.vfilenames;
                if (isfield(src,'vnummax'))
                    lengthoflist = src.vnummax;
                else
                    lengthoflist = src.vnumend;
                end
                src.vfilenames = cell(lengthoflist,1);
                src.vfilenames(:) = {avifilename};
            end
        end
end

%==================================================
function[DAT,validlist] = bc_hiddenframes(FIGM,DAT)
%%%-----------------------------
%%% Called by:  loadvideofromlog
%%%-----------------------------
validlist = 1;
CON = getstoreddata(FIGM.CONh);
if strcmpi(DAT.videomethod,'videoIO videoReader')
    navifiles = size(DAT.vprefixes,1);
    for ni = 1:navifiles
        vfilename = [DAT.vprefixes{ni},'.',DAT.vtype];
        pathandfile = [DAT.vpath,CON.slash,vfilename];
        DAT.vobj = videoReader(pathandfile);
        info = getinfo(DAT.vobj);
        if strcmpi(info.fourcc,'YV12')
            setmsg(FIGM,'Warning: MPEG-2 videos may cause errors.');
            pause(1);
        end 
        DAT.nhiddenframes = info.nHiddenFinalFrames + 1;
        if (DAT.nhiddenframes > 0)
            lastvalidframenum = info.numFrames - DAT.nhiddenframes;
            filenumindex = strmatch(vfilename,DAT.vfilenames,'exact');
            invalidindex = find(DAT.vfilenums(filenumindex) > lastvalidframenum);
            if (~isempty(invalidindex))
                if (ni == 1)
                    DAT.vfilenums(filenumindex(invalidindex)) = NaN;
                    setstoreddata(FIGM.DATh,DAT);
                    setmsg(FIGM,['note:  ',num2str(DAT.nhiddenframes), ...
                        ' frames at end of video not accessible']);
                    pause(0.5);
                else
                    validlist = 2;
                end
            end
        end
    end
end

%==========================================
function[src] = bc_newvars(src,variableset)
%%%----------------------------------------------------------
%%% Function handles back compatibility for variables that
%%% didn't used to exist:  adds variable to input loaded from
%%% log file or user settings file with a default value.
%%% Called by:  loadusersettings, retrievelogfile
%%%----------------------------------------------------------
switch (variableset)
    case ('settings')
        if (~isfield(src,'vtype'))
            src.vtype = 'JPG';
        end
        if (~isfield(src,'vnsubj'))
            src.vnsubj = 2;
        end
        if (~isfield(src,'checksavecmnds'))
            src.checksavecmnds = 0;
        end
        if (~isfield(src,'checksavelog'))
            src.checksavelog = 0;
        end
    case ('log')
        if (~isfield(src,'vtype'))
            src.vtype = 'JPG';
        end
        if (~isfield(src,'vnsubj'))
            src.vnsubj = 2;
        end
        if (~isfield(src,'vfilenames'))
            src = generatefilenames(src);
        end
        if (~isfield(src,'vnummax'))
            src.vnummax = size(src.vfilenames,1);
        end
        if (~isfield(src,'vnumstart'))
            src.vnumstart = 1;
        end
        if (~isfield(src,'vnumend'))
            src.vnumend = size(src.vfilenames,1);
        end
        if (~isfield(src,'vprefixes'))
            src.vprefixes = {src.vprefix};
        end
        if (~isfield(src,'vnumstarts'))
            src.vnumstarts = src.vnumstart;
        end
        if (~isfield(src,'vnumends'))
            src.vnumends = src.vnumend;
        end
        if (~isfield(src,'noteslog'))
            src.noteslog = {};
        end
        if (~isfield(src,'markslog'))
            src.markslog.framenum = [];
            src.markslog.framename = {};
            src.markslog.startindex = [];
            src.markslog.alignindex = [];
            src.markslog.endindex = [];
        end
        if (~isfield(src,'posnlog'))
            src.posnlog = [];
            src.posnlogtext = {};
        end
        %%%------------------------------------------------------------
        %%% if vfilenums/vframenums/vfsrcindex/vframemax aren't fields,
        %%% because this is coming from an older log file, they are
        %%% obtained by calling setfilenumbers; in this case,
        %%% vprefix/vnumstart/vnumend will be fields in src
        %%%------------------------------------------------------------
        if (~isfield(src,'vfilenums') || isempty(src.vfilenums))
            src = setfilenumbers(src);
        end
end

%==============================================
function[src] = bc_renamedvars(src,variableset)
%%%-----------------------------------------------------------
%%% Function handles back compatibility for renamed variables:
%%% adds variable to input loaded from log file or user
%%% settings file with a value of old variable.
%%% Called by:  loadusersettings, retrievelogfile
%%%-----------------------------------------------------------
switch (variableset)
    case ('settings')
        oldandnew = { ...
            'fpath','vpath'; ...
            'fpref','vprefix'; ...
            'fnumstart','vnumstart'; ...
            'fnumend','vnumend'; ...
            'ffpsoi','vfpsoi'; ...
            'ffpstp','vfpstp'; ...
            'nsubj','vnsubj'; ...
            'commpath','cpath'; ...
            'commfilename','cfilename'; ...
            'ison_checksavecmnds','checksavecmnds'; ...
            'ison_checksavelog','checksavelog'};
    case ('log')
        oldandnew = { ...
            'fpath','vpath'; ...
            'fpref','vprefix'; ...
            'fnumstart','vnumstart'; ...
            'fnumend','vnumend'; ...
            'ffpsoi','vfpsoi'; ...
            'ffpstp','vfpstp'; ...
            'nsubj','vnsubj'; ...
            'commpath','cpath'; ...
            'commfilename','cfilename'; ...
            'filenames','vfilenames'; ...
            'fulllognotes','noteslog'};
end
for row = 1:size(oldandnew,1)
    oldfieldname = oldandnew{row,1};
    newfieldname = oldandnew{row,2};
    if (isfield(src,oldfieldname))
        src.(newfieldname) = src.(oldfieldname);
    end
end

%==============================
function[] = buildfulllog(FIGM)
%%%---------------------------------------------------------
%%% Function builds full log from raw log and updates its
%%% display.
%%% Called by:  acceptloginput, makeoutputplot, savelogfile,
%%% and Build BUTTON below full log list in BEHAV panel
%%%---------------------------------------------------------
isempty_slog = getstoreddata(FIGM.FFLh,'isempty_slog');
if (isempty_slog == 0)
    setmsg(FIGM,'building full log ...');
    cfinput = getcfinput(FIGM);
    storecfinfo(FIGM,cfinput);
    initfulllog(FIGM);
    growfulllog(FIGM);
    finishfulllog(FIGM);
    updatefulllog(FIGM);
    setmsg(FIGM,'full log built');
else
    setmsg(FIGM,'error:  score log is empty');
end

%=====================================
function[src] = calcvideosettings(src)
%%%--------------------------------------------------------
%%% Function calculates duration in minutes of selected and
%%% available video file sets, frame number increment, and
%%% checks/rounds increment and fps to play as needed.
%%% Called by:  acceptlogvideoinput, acceptvideoinput
%%%--------------------------------------------------------
src.fseldur = src.vframemax/(src.vfpsoi*60);
src.favaildur = size(src.vfilenames,1)/(src.vfpsoi*60);
src.fnumincr = src.vfpsoi/src.vfpstp;
if (rem(src.fnumincr,1) ~= 0)
    src.fnumincr = round(src.fnumincr);
    if (src.fnumincr < 1)
        src.fnumincr = 1;
    end
    if (src.fnumincr > src.vfpsoi)
        src.fnumincr = src.vfpsoi;
    end
    src.vfpstp = src.vfpsoi/src.fnumincr;
    while (rem(src.vfpstp,1) ~= 0)
        src.fnumincr = src.fnumincr + 1;
        src.vfpstp = src.vfpsoi/src.fnumincr;
    end
end

%=============================
function[] = changenchar(FIGM)
%%%--------------------------------------------------------
%%% Called by:  No. of characters in command POPUP menu in
%%% CMNDS panel
%%%--------------------------------------------------------
ncharnum = str2num(getuivalue(FIGM.uic.cmnds.nchar));
isempty_slog = getstoreddata(FIGM.FFLh,'isempty_slog');
if (isempty_slog == 1)
    switchnchar(FIGM,ncharnum);
    checkncharinuclist(FIGM);
    displayusercommands(FIGM);
    clearucentryfields(FIGM);
    setmsg(FIGM,'no. of chars changed');
else
    DAT = getstoreddata(FIGM.DATh);
    ncharnum = DAT.uc.nchars;
    switchnchar(FIGM,ncharnum);
    setmsg(FIGM,'error:  no. of chars cannot be changed if score log is not empty');
end

%=============================================
function[] = changeplotorder(FIGM,callbackvar)
%%%--------------------------------------------------------
%%% Called by:  ^, v, +, and - BUTTONS in ANALY panel
%%%--------------------------------------------------------
isempty_cmnds = getstoreddata(FIGM.FFLh,'isempty_cmnds');
if (isempty_cmnds == 0)
    listvalue = get(FIGM.uic.analy.behaviorslist,'value');
    uc = getstoreddata(FIGM.DATh,'uc');
    po = uc.plotorder;
    includeindex = find(po);
    restindex = setdiff(includeindex,listvalue);
    switch (callbackvar)
        case ('^')
            if (po(listvalue) ~= 0)
                po(listvalue) = max([1 po(listvalue) - 1]);
                lowerri = find(po(restindex) == po(listvalue));
                if (~isempty(lowerri))
                    po(restindex(lowerri)) = po(restindex(lowerri)) + 1;
                end
            end
        case ('v')
            if (po(listvalue) ~= 0)
                maxpo = max(po(includeindex));
                po(listvalue) = min([maxpo po(listvalue) + 1]);
                upperri = find(po(restindex) == po(listvalue));
                if (~isempty(upperri))
                    po(restindex(upperri)) = po(restindex(upperri)) - 1;
                end
            end
        case ('+')
            if (~isempty(includeindex))
                if ~ismember(listvalue,includeindex)
                    maxpo = max(po(includeindex));
                    po(listvalue) = maxpo + 1;
                end
            else
                po(listvalue) = 1;
            end
        case ('-')
            if (po(listvalue) ~= 0)
                if ismember(listvalue,includeindex)
                    upperri = find(po(restindex) >= po(listvalue));
                    if (~isempty(upperri))
                        po(restindex(upperri)) = po(restindex(upperri)) - 1;
                    end
                    po(listvalue) = 0;
                end
            end
    end
    uc.plotorder = po;
    setstoreddata(FIGM.DATh,[],'uc',uc);
    blist = createbehaviorlist(uc);
    set(FIGM.uic.analy.behaviorslist,'string',blist);
    setmsg(FIGM,'plot order updated');
else
    setmsg(FIGM,'error:  no entries in command set');
end

%=================================================
function[vfinput] = checkfilenumbers(FIGM,vfinput)
%%%--------------------------------------
%%% Called by:  loadvideofrominput
%%%--------------------------------------
if (vfinput.loadflag == 1)
    if ~strcmp(vfinput.vtype,'NONE') % JPG or video
        if (vfinput.vnummax >= 1)
            if (isempty(vfinput.vnumstart))
                vfinput.vnumstart = 1;
            end
            if (vfinput.vnumstart < 1)
                vfinput.vnumstart = 1;
            end
            maxtouse = vfinput.vnummax;
            if (vfinput.nhiddenframes > 0)
                maxtouse = maxtouse - vfinput.nhiddenframes - 1;
                setmsg(FIGM,['note:  ',num2str(vfinput.nhiddenframes + 1), ...
                    ' frames at end of video not accessible']);
                pause(0.5);
            end
            if (isempty(vfinput.vnumend))
                vfinput.vnumend = maxtouse;
            end
            if (vfinput.vnumend > maxtouse)
                vfinput.vnumend = maxtouse;
            end
        end
    end
    %%% TO DO:  document this rounding error
    vfinput.vfpsoi = round(vfinput.vfpsoi);
    if (isempty(vfinput.vfpstp))
        vfinput.vfpstp = vfinput.vfpsoi;
    end
end

%===========================================
function[status] = checkloadlog(FIGM,lfdata)
%%%----------------------------------------------
%%% Function checks (a) for unsaved changes in existing
%%% log when loading log, and (b) if video present when loading
%%% log; for each, if so, queries user about what to do.
%%% Called by:  loadlogfile
%%%----------------------------------------------
status.loadlog = 1;
status.loadvideo = 1;
status.clearvideo = 0;
if (isempty(lfdata))
    status.loadlog = 0;
    status.loadvideo = 0;
else
    issaved_log = getstoreddata(FIGM.FFLh,'issaved_log');
    isempty_log = getstoreddata(FIGM.FFLh,'isempty_log');
    if ((issaved_log == 0) && (isempty_log == 0))
        response = questdlg( ...
            {'The current log contains unsaved changes.'; ...
            'Loading a new log will result in these changes being lost.'; ...
            'Are you sure you want to load the new log?'}, ...
            'Unsaved Changes Warning','yes','no','no');
        if (isempty(response))
            response = 'no';
        end
    else
        response = 'yes';
    end
    if (strcmp('no',response))
        status.loadlog = 0;
    end
end
if (status.loadlog == 1)
    isloaded_video = getstoreddata(FIGM.FFLh,'isloaded_video');
    if (isloaded_video == 1)
        msg = checkvideomatch(FIGM,lfdata);
        if (~isempty(msg.varname))
            response = query_logvideomismatch(msg);
            switch (response)
                case ('(a) Log and video info')
                    status.clearvideo = 1;
                case ('(b) Log only')
                    status.loadvideo = 0;
                case ('(c) Cancel')
                    status.loadlog = 0;
                    status.loadvideo = 0;
            end
        end
    end
end

%===============================
function[] = checkmarkslog(FIGM)
%%%----------------------------------------------------------
%%% Function maintains video start and end marks in the marks
%%% log, adding them if they are not present, or updating
%%% them to correspond to the first and last frame of the
%%% current video file set.
%%% Called by:  acceptloginput, addvideofiles, clearmarkslog,
%%% clearvideo
%%%----------------------------------------------------------
DAT = getstoreddata(FIGM.DATh);
isloaded_video = getstoreddata(FIGM.FFLh,'isloaded_video');
isempty_log = getstoreddata(FIGM.FFLh,'isempty_log');
if ((isloaded_video == 0) && (isempty_log == 1))
    initmarkslog(FIGM);
else
    if (isempty(DAT.markslog.framenum))
        if (isloaded_video == 1)
            DAT.markslog.framenum = [DAT.vnumstarts(1);DAT.vframemax];
            % Changed from 1 to DAT.vnumstarts(1)
            DAT.markslog.framename = {'video start';'video end'};
            DAT.markslog.startindex = 1;
            DAT.markslog.alignindex = 1;
            DAT.markslog.endindex = 2;
            setstoreddata(FIGM.DATh,DAT);
        end
    else
        vsindex = strmatch('video start',DAT.markslog.framename,'exact');
        DAT.markslog.framenum(vsindex) = DAT.vnumstarts(1);
        % Changed from 1 to DAT.vnumstarts(1)
        veindex = strmatch('video end',DAT.markslog.framename,'exact');
        DAT.markslog.framenum(veindex) = DAT.vframemax;
        setstoreddata(FIGM.DATh,DAT);
    end
end
updatemarkslog(FIGM);

%====================================
function[] = checkncharinuclist(FIGM)
%%%------------------------
%%% Called by:  changenchar
%%%------------------------
DAT = getstoreddata(FIGM.DATh);
nentries = size(DAT.uc.bchar,1);
switch (DAT.uc.nchars)
    case (1)
        for ni = 1:nentries
            switch (size(DAT.uc.bchar{ni},2))
                case (1)
                    % do nothing
                otherwise
                    DAT.uc.bchar{ni} = DAT.uc.bchar{ni}(1);
            end
            switch (size(DAT.uc.echar{ni},2))
                case (0)
                    % do nothing
                case (1)
                    % do nothing
                otherwise
                    DAT.uc.echar{ni} = DAT.uc.echar{ni}(1);
            end
        end
    case (2)
        for ni = 1:nentries
            switch (size(DAT.uc.bchar{ni},2))
                case (1)
                    DAT.uc.bchar{ni} = [DAT.uc.bchar{ni},'x'];
                case (2)
                    % do nothing
                otherwise
                    DAT.uc.bchar{ni} = DAT.uc.bchar{ni}(1:2);
            end
            switch (size(DAT.uc.echar{ni},2))
                case (0)
                    % do nothing
                case (1)
                    DAT.uc.echar{ni} = [DAT.uc.echar{ni},'x'];
                case (2)
                    % do nothing
                otherwise
                    DAT.uc.echar{ni} = DAT.uc.echar{ni}(1:2);
            end
        end
end
setstoreddata(FIGM.DATh,DAT);

%=============================================
function[vfinput] = checkvfinput(FIGM,vfinput)
%%%---------------------------------------------------
%%% Checks for valid input:  vfpsoi not empty and >= 1
%%% for vtype = 'JPG' or 'NONE'
%%% Called by:  retrievevfinput
%%%---------------------------------------------------
isvideo_vtype = ~ismember(vfinput.vtype,{'JPG','NONE'}); %Any chance of vtype not set yet?
if (isvideo_vtype == 1)
    if (isempty(vfinput.vprefix))
        vfinput.loadflag = 0;
        vfinput.msg = 'error:  filename must be provided';
    end
else
    if (isempty(vfinput.vfpsoi))
        vfinput.loadflag = 0;
        vfinput.msg = 'error:  the FPS of files must be a number and cannot be blank';
    else
        if (vfinput.vfpsoi < 1)
            vfinput.vfpsoi = 1;
        end
    end
end

%==============================================
function[vfinput] = checkvideoadd(FIGM,vfinput)
%%%----------------------------------------------------------
%%% if loadflag == 1 (no errors so far), and loadmode = 'add'
%%% 1. get DAT.<>
%%% 2. check match for vtype, vpath; if not, reject add, error msg
%%% 3. check not already in list vprefixes/vnumstarts/vnumends; if so, reject add, error msg
%%% 4. check no overlap with list vprefixes/vnumstarts/vnumends; if so, reject add, use update
%%% 5. check match vfpsoi, vfpstp, vnsubj; if not, query user for which to use
%%% Called by:  loadvideofrominput
%%%----------------------------------------------------------
isadd_loadmode = strcmp('add',vfinput.loadmode);
if ((vfinput.loadflag == 1) && (isadd_loadmode == 1))
    DAT = getstoreddata(FIGM.DATh);
    if (strcmp(vfinput.vtype,DAT.vtype) == 0)
        vfinput.loadflag = 0;
        vfinput.msg = 'error:  video file type must match existing type';
    end
    if (vfinput.loadflag == 1)
        if (strcmp(vfinput.vpath,DAT.vpath) == 0)
            vfinput.loadflag = 0;
            vfinput.msg = 'error:  video file directory must match existing directory';
        end
    end
    if (vfinput.loadflag == 1)
        maxvi = size(DAT.vprefixes,1);
        vi = 1;
        while ((vi <= maxvi) && (vfinput.loadflag == 1))
            oldvprefix = DAT.vprefixes{vi};
            oldvnumstart = DAT.vnumstarts(vi);
            oldvnumend = DAT.vnumends(vi);
            if (strcmp(vfinput.vprefix,oldvprefix))			% exact match
                if ((vfinput.vnumstart == oldvnumstart) && (vfinput.vnumend == oldvnumend))
                    vfinput.loadflag = 0;
                    vfinput.msg = 'error:  video file subset is already in video file set';
                elseif ((vfinput.vnumstart <= oldvnumend) && (vfinput.vnumend >= oldvnumstart))
                    vfinput.loadflag = 0;
                    vfinput.msg = ['error:  video file subset overlaps with an existing ', ...
                        'one; use update button'];
                end
            elseif (~isempty(strmatch(vfinput.vprefix,oldvprefix)))	% partial match
                vfinput.loadflag = 0;
                vfinput.msg = ['error:  video file prefix/filename overlaps with an existing ', ...
                    'one; use same prefix/filename, and add to or update button'];
            end
            vi = vi + 1;
        end
    end
    if (vfinput.loadflag == 1)
        vfinput = checkvideoconstants(FIGM,vfinput);
    end
end

%====================================================
function[vfinput] = checkvideoconstants(FIGM,vfinput)
%%%--------------------------
%%% Called by:  checkvideoadd
%%%--------------------------
DAT = getstoreddata(FIGM.DATh);
if (vfinput.vfpsoi ~= DAT.vfpsoi)
    response = questdlg( ...
        {'The FPS of files of this video file subset'; ...
        'does not match that of the existing video file set.'; ...
        ['   existing:  ',num2str(DAT.vfpsoi)]; ...
        ['   new:  ',num2str(vfinput.vfpsoi)]; ...
        ' '; ...
        'Which FPS would you like to use?'}, ...
        'FPS of files mismatch','existing','new','existing');
    if (strcmp('existing',response))
        vfinput.vfpsoi = DAT.vfpsoi;
    end
end
if (vfinput.vfpstp ~= DAT.vfpstp)
    response = questdlg( ...
        {'The FPS to play of this video file subset'; ...
        'does not match that for the existing video file set.'; ...
        ['   existing:  ',num2str(DAT.vfpstp)]; ...
        ['   new:  ',num2str(vfinput.vfpstp)]; ...
        ' '; ...
        'Which number would you like to use?'}, ...
        'Number of subjects mismatch','existing','new','existing');
    if (strcmp('existing',response))
        vfinput.vfpstp = DAT.vfpstp;
    end
end
if (vfinput.vnsubj ~= DAT.vnsubj)
    response = questdlg( ...
        {'The number of subjects for this video file subset'; ...
        'does not match that for the existing video file set.'; ...
        ['   existing:  ',num2str(DAT.vnsubj)]; ...
        ['   new:  ',num2str(vfinput.vnsubj)]; ...
        ' '; ...
        'Which FPS would you like to use?'}, ...
        'FPS to play mismatch','existing','new','existing');
    if (strcmp('existing',response))
        vfinput.vnsubj = DAT.vnsubj;
    end
end

%===========================================
function[msg] = checkvideomatch(FIGM,lfdata)
%%%-----------------------------------------------------------
%%% Function checks for mismatches between video file set info
%%% in the current video versus the video in the log file.
%%% Called by:  checkloadlog
%%%-----------------------------------------------------------
%%% setting which variables to check
%%%-----------------------------------------------------------
DAT = getstoreddata(FIGM.DATh);
msg.varname = {};
msg.vidvalue = {};
msg.logvalue = {};
checkvars = {'vtype';'vpath';'vfpsoi';'vnsubj';'vlist'};
varlabels = {'video type';'directory';'FPS of files'; ...
    'no. of subjects';'video file subsets'};
switch (lfdata.vtype)
    case ('NONE')
        cvindex = [1 2 3 4];
    case ('JPG')
        cvindex = [1 2 3 4 5];
    otherwise
        cvindex = [1 2 4 5];
end
%%%----------------------------------------------------------
%%% checking variables for mismatch betw DAT.<> and lfdata.<>
%%%----------------------------------------------------------
for ci = cvindex
    checkvar = checkvars{ci};
    switch (checkvar)
        case {'vtype','vpath'}				% string variables
            if (~strcmp(lfdata.(checkvar),DAT.(checkvar)))
                msg.varname = [msg.varname;{varlabels{ci}}];
                msg.vidvalue = [msg.vidvalue;{DAT.(checkvar)}];
                msg.logvalue = [msg.logvalue;{lfdata.(checkvar)}];
            end
        case {'vfpsoi','vnsubj'}				% scalar numeric variables
            if (lfdata.(checkvar) ~= DAT.(checkvar))
                msg.varname = [msg.varname;{varlabels{ci}}];
                msg.vidvalue = [msg.vidvalue;{num2str(DAT.(checkvar))}];
                msg.logvalue = [msg.logvalue;{num2str(lfdata.(checkvar))}];
            end
        case ('vlist')					% three-part list variable
            vlistn_vid = size(DAT.vprefixes,1);
            vliststr_vid = [];
            for vli = 1:vlistn_vid
                entry = [DAT.vprefixes{vli},'(', ...
                    num2str(DAT.vnumstarts(vli)),'-',num2str(DAT.vnumends(vli)),')'];
                vliststr_vid = [vliststr_vid,entry];
                if (vli ~= vlistn_vid)
                    vliststr_vid = [vliststr_vid,'; '];
                end
            end
            vlistn_log = size(lfdata.vprefixes,1);
            vliststr_log = [];
            for vli = 1:vlistn_log
                entry = [lfdata.vprefixes{vli},'(', ...
                    num2str(lfdata.vnumstarts(vli)),'-',num2str(lfdata.vnumends(vli)),')'];
                vliststr_log = [vliststr_log,entry];
                if (vli ~= vlistn_log)
                    vliststr_log = [vliststr_log,'; '];
                end
            end
            if (~strcmp(vliststr_vid,vliststr_log))
                msg.varname = [msg.varname;{varlabels{ci}}];
                msg.vidvalue = [msg.vidvalue;{vliststr_vid}];
                msg.logvalue = [msg.logvalue;{vliststr_log}];
            end
    end
end

%=================================================
function[vfinput] = checkvideoupdate(FIGM,vfinput)
%%%-----------------------------------------------------------
%%% Function checks that vnsubj has not changed if posn log
%%% is not empty, and that new vnumstart and vnumend do
%%% not overlap with other subsets, if vtype ~= 'NONE';
%%% checks video constants against pre-existing ones.
%%% Called by:  loadvideofrominput
%%%-----------------------------------------------------------
isupdate_loadmode = strcmp('update',vfinput.loadmode);
if ((vfinput.loadflag == 1) && (isupdate_loadmode == 1))
    DAT = getstoreddata(FIGM.DATh);
    if ~(ismember(vfinput.vtype,{'NONE'}))
        isempty_plog = getstoreddata(FIGM.FFLh,'isempty_plog');
        if (isempty_plog == 0)
            if (vfinput.vnsubj ~= DAT.vnsubj)
                vfinput.loadflag = 0;
                vfinput.msg = 'error:  number of subjects cannot be changed if posn log is not empty';
            end
        end
        vprefix = vfinput.vprefix;
        vnumstart = vfinput.vnumstart;
        vnumend = vfinput.vnumend;
        subsetindex = get(FIGM.uic.files.vlist,'value');
        if (vfinput.loadflag == 1)
            if (subsetindex >= 2)
                previousvprefix = DAT.vprefixes{subsetindex-1};
                if (strcmp(previousvprefix,vprefix))
                    previousvnumend = DAT.vnumends(subsetindex-1);
                    if (vnumstart <= previousvnumend)
                        vfinput.loadflag = 0;
                        vfinput.msg = 'error:  update creates overlap with another subset';
                    end
                end
            end
        end
        if (vfinput.loadflag == 1)
            if (subsetindex <= size(DAT.vprefixes,1)-1)
                nextvprefix = DAT.vprefixes{subsetindex+1};
                if (strcmp(nextvprefix,vprefix))
                    nextvnumstart = DAT.vnumstarts(subsetindex+1);
                    if (vnumend >= nextvnumstart)
                        vfinput.loadflag = 0;
                        vfinput.msg = 'error:  update creates overlap with another subset';
                    end
                end
            end
        end
    end
    if (vfinput.loadflag == 1)
        vfinput = checkvideoconstants(FIGM,vfinput);
    end
end

%=================================================
function[ucindex] = checkucagainstlog(DAT,ucindex)
%%%-------------------------------------------------
%%% Called by:  deleteusercommand, updateusercommand
%%%-------------------------------------------------
if (size(DAT.rawlog,1) ~= 0)
    bchartochange = DAT.uc.bchar{ucindex};
    bcharleft = DAT.uc.bchar([1:ucindex-1 ucindex+1:end]);
    bchangeinlog = strmatch(bchartochange,DAT.rawlog,'exact');
    bchangeinleft = strmatch(bchartochange,bcharleft,'exact');
    if (~isempty(bchangeinlog) && isempty(bchangeinleft))
        ucindex = [];
    else
        echartochange = DAT.uc.echar{ucindex};
        echarleft = DAT.uc.echar([1:ucindex-1 ucindex+1:end]);
        echangeinlog = strmatch(echartochange,DAT.rawlog,'exact');
        echangeinleft = strmatch(echartochange,echarleft,'exact');
        if (~isempty(echangeinlog) && isempty(echangeinleft))
            ucindex = [];
        end
    end
end

%==============================
function[] = clearfulllog(FIGM)
%%%--------------------------------------------------------------
%%% Function clears the full score log and updates its display.
%%% Called by:  addvideofiles, deletefromrawlog, doclearlog,
%%% doclearrawlog, figurekeypressfcn, and subject names input
%%% FIELDS and No. of simult. behaviors POPUP menu in CMNDS panel
%%%--------------------------------------------------------------
initfulllog(FIGM);
updatefulllog(FIGM);

%===============================
function[] = clearmarkslog(FIGM)
%%%-----------------------------
%%% Called by:  doclearlog
%%%-----------------------------
initmarkslog(FIGM);
checkmarkslog(FIGM);

%==========================
function[] = clearmsg(FIGM)
%%%----------------------------------------------------
%%% Called by:  scorevideo (main loop of this function)
%%%----------------------------------------------------
if (~isfield(FIGM,'mainfigh'))			% if callback is from main figure
    setmsg(FIGM,'');				% clear old message
end

%===============================
function[] = clearnoteslog(FIGM)
%%%-----------------------------
%%% Called by:  doclearlog
%%%-----------------------------
initnoteslog(FIGM);
updatenoteslog(FIGM);

%=============================
function[] = clearrawlog(FIGM)
%%%--------------------------------------
%%% Called by:  doclearlog, doclearrawlog
%%%--------------------------------------
initrawlog(FIGM);
updaterawlog(FIGM);

%============================
function[] = clearvideo(FIGM)
%%%--------------------------------------------
%%% Called by:  acceptlogvideoinput, doclearlog
%%%--------------------------------------------
setvideoloaded(FIGM,0);
set(FIGM.uic.files.vcurrdir,'string','');
set(FIGM.uic.files.vtotsel,'string','');
set(FIGM.uic.files.vtotavail,'string','');
set(FIGM.uic.files.vfps,'string','');
set(FIGM.uic.files.vlist,'string','','value',1);
set(FIGM.uic.score.realdur,'string','');
set(FIGM.uic.score.playdur,'string','');
set(FIGM.uic.score.currframe,'string','');
set(FIGM.uic.score.currtime,'string','');
checkmodules('clearnsubj',FIGM);
isempty_log = getstoreddata(FIGM.FFLh,'isempty_log');
if (isempty_log == 1)
    checkmarkslog(FIGM);
end
drawframe(FIGM);
updatelogsavedflag(FIGM);

%====================================
function[] = clearucentryfields(FIGM)
%%%-------------------------------------------------
%%% Called by:  acceptloginput, addusercommand,
%%% changenchar, doclearcommandset, loadcommandsfile
%%%-------------------------------------------------
set(FIGM.uic.cmnds.bchar,'string','');
set(FIGM.uic.cmnds.echar,'string','');
setuivalue(FIGM.uic.cmnds.subj,'0  (either)');
set(FIGM.uic.cmnds.desc,'string','');

%=======================================
function[blist] = createbehaviorlist(uc)
%%%---------------------------------------------------------------
%%% Called by:  changeplotcolor, displayusercommands, setplotcolor
%%%---------------------------------------------------------------
uclisttxt = createlistboxtext(uc,1);
clrlisttxt = num2str(uc.plotclr,'%3.2f ');
potext = num2str(uc.plotorder);
poi = find(uc.plotorder == 0);
if (~isempty(poi))
    potext(poi,:) = '-';
end
blist = {};
for bi = 1:size(uclisttxt,1)
    s = uclisttxt{bi};
    s = s(1:min([14 length(s)]));
    s2 = blanks(16);
    s2(1:length(s)) = s;
    blist{bi} = [s2,' ',potext(bi,:),'  ',clrlisttxt(bi,:)];
end

%==================================
function[] = deletefromrawlog(FIGM)
%%%------------------------------------------------------------
%%% Called by:  Delete BUTTON below raw log list in BEHAV panel
%%%------------------------------------------------------------
isempty_slog = getstoreddata(FIGM.FFLh,'isempty_slog');
if (isempty_slog == 0)
    DAT = getstoreddata(FIGM.DATh);
    rawindex = get(FIGM.uic.behav.rawlog,'value');
    rawindexleft = setdiff(1:size(DAT.rawlog,1),rawindex);
    if (isempty(rawindexleft))
        initrawlog(FIGM);
    else
        DAT.rawlog = DAT.rawlog(rawindexleft);
        DAT.rawlogframe = DAT.rawlogframe(rawindexleft);
    end
    setstoreddata(FIGM.DATh,DAT);
    updaterawlog(FIGM);
    clearfulllog(FIGM);
    setmsg(FIGM,'entry removed');
else
    setmsg(FIGM,'error:  score log is empty');
end

%============================
function[] = deletemark(FIGM)
%%%--------------------------------------------------------------
%%% Called by:  Delete BUTTON below marks log list in NANDM panel
%%%--------------------------------------------------------------
marksindex = get(FIGM.uic.nandm.markslog,'value');
DAT = getstoreddata(FIGM.DATh);
framename = DAT.markslog.framename{marksindex};
frameisfixed = ~isempty(strmatch(framename,{'video start';'video end'},'exact'));
if (frameisfixed == 1)
    setmsg(FIGM,'error:  video start and end marks cannot be deleted');
else
    aw = getawframes(DAT.markslog);
    marksleft = setdiff(1:size(DAT.markslog.framenum,1),marksindex);
    DAT.markslog.framenum = DAT.markslog.framenum(marksleft);
    DAT.markslog.framename = DAT.markslog.framename(marksleft);
    DAT.markslog = indexawframes(DAT.markslog,aw);
    setstoreddata(FIGM.DATh,DAT);
    updatemarkslog(FIGM);
    setmsg(FIGM,'mark removed');
end

%============================
function[] = deletenote(FIGM)
%%%--------------------------------------------------------------
%%% Called by:  Delete BUTTON below notes log list in NANDM panel
%%%--------------------------------------------------------------
isempty_nlog = getstoreddata(FIGM.FFLh,'isempty_nlog');
if (isempty_nlog == 0)
    DAT = getstoreddata(FIGM.DATh);
    notesindex = get(FIGM.uic.nandm.noteslog,'value');
    notesleft = setdiff(1:size(DAT.noteslog,1),notesindex);
    if (isempty(notesleft))
        DAT.noteslog = {};
    else
        DAT.noteslog = DAT.noteslog(notesleft);
    end
    setstoreddata(FIGM.DATh,DAT);
    displaynoteslog(FIGM);
    setmsg(FIGM,'note removed');
else
    setmsg(FIGM,'error:  notes log is empty');
end

%===================================
function[] = deleteusercommand(FIGM)
%%%----------------------------------------------------------------
%%% Called by:  Delete BUTTON below command set list in CMNDS panel
%%%----------------------------------------------------------------
ucindex = get(FIGM.uic.cmnds.uclist,'value');
DAT = getstoreddata(FIGM.DATh);
ucindex = checkucagainstlog(DAT,ucindex);
if (~isempty(ucindex))
    ucindexleft = setdiff(1:size(DAT.uc.bchar,1),ucindex);
    DAT.uc.bchar = DAT.uc.bchar(ucindexleft,1);
    DAT.uc.echar = DAT.uc.echar(ucindexleft,1);
    DAT.uc.subj = DAT.uc.subj(ucindexleft,1);
    DAT.uc.desc = DAT.uc.desc(ucindexleft,1);
    DAT.uc.plotorder = DAT.uc.plotorder(ucindexleft,1);
    po = find(DAT.uc.plotorder ~= 0);
    if (~isempty(po))
        [po2,pi2] = sort(DAT.uc.plotorder(po));
        DAT.uc.plotorder(po(pi2)) = (1:length(po))';
    end
    DAT.uc.plotclr = DAT.uc.plotclr(ucindexleft,:);
    setstoreddata(FIGM.DATh,DAT);
    displayusercommands(FIGM);
    setmsg(FIGM,'entry removed');
else
    setmsg(FIGM,'error:  command cannot be removed while used in score log');
end

%================================
function[] = displayfulllog(FIGM)
%%%----------------------------------------
%%% Called by:  timertickfcn, updatefulllog
%%%----------------------------------------
DAT = getstoreddata(FIGM.DATh);
flval = get(FIGM.uic.behav.fulllog,'value');
flmax = size(DAT.fulllogtext,1);
newflval = max([min([flval flmax]) 1]);
set(FIGM.uic.behav.fulllog,'string',DAT.fulllogtext,'value',newflval);

%====================================
function[] = displaymarkindices(FIGM)
%%%---------------------------
%%% Called by:  updatemarkslog
%%%---------------------------
DAT = getstoreddata(FIGM.DATh);
set(FIGM.uic.nandm.marksstart,'string',num2str(DAT.markslog.framenum(DAT.markslog.startindex)));
set(FIGM.uic.nandm.marksalign,'string',num2str(DAT.markslog.framenum(DAT.markslog.alignindex)));
set(FIGM.uic.nandm.marksend,'string',num2str(DAT.markslog.framenum(DAT.markslog.endindex)));

%=================================
function[] = displaymarkslog(FIGM)
%%%---------------------------
%%% Called by:  updatemarkslog
%%%---------------------------
DAT = getstoreddata(FIGM.DATh);
nlval = get(FIGM.uic.nandm.markslog,'value');
nlmax = size(DAT.markslog.framenum,1);
newnlval = max([min([nlval nlmax]) 1]);
set(FIGM.uic.nandm.markslog,'string',DAT.markslogtext,'value',newnlval);
updatelogemptyflags(FIGM);
updatelogsavedflag(FIGM);

%=================================
function[] = displaynoteslog(FIGM)
%%%------------------------------------------------------------
%%% Called by:  addnote, deletenote, updatenote, updatenoteslog
%%%------------------------------------------------------------
DAT = getstoreddata(FIGM.DATh);
nlval = get(FIGM.uic.nandm.noteslog,'value');
nlmax = size(DAT.noteslog,1);
newnlval = max([min([nlval nlmax]) 1]);
set(FIGM.uic.nandm.noteslog,'string',DAT.noteslog,'value',newnlval);
updatelogemptyflags(FIGM);
updatelogsavedflag(FIGM);

%===============================
function[] = displayrawlog(FIGM)
%%%---------------------------------------
%%% Called by:  timertickfcn, updaterawlog
%%%---------------------------------------
DAT = getstoreddata(FIGM.DATh);
rlval = get(FIGM.uic.behav.rawlog,'value');
rlmax = size(DAT.rawlogtext,1);
newrlval = max([min([rlval rlmax]) 1]);
lastframeadded = getstoreddata(FIGM.FFLh,'val_lastframeadded');
if (~isempty(lastframeadded))
    rlindex = find(DAT.rawlogframe == lastframeadded);
    if (~isempty(rlindex))
        newrlval = rlindex;
    end
end
if (~isempty(newrlval))
    newrlval = newrlval(end);		% for bug 10/12/07, #2
end
lbval = max([newrlval-5 1]);
set(FIGM.uic.behav.rawlog,'string',DAT.rawlogtext,'value',newrlval, ...
    'listboxtop',lbval);
updatelogemptyflags(FIGM);
updatelogsavedflag(FIGM);

%===============================
function[] = displayvfinfo(FIGM)
%%%-----------------------------------------------
%%% Called by:  acceptvideoinput, loadvideofromlog
%%%-----------------------------------------------
DAT = getstoreddata(FIGM.DATh);
switch (DAT.vtype)
    case ('NONE')
        set(FIGM.uic.files.vcurrdir,'string',DAT.vpath);
        set(FIGM.uic.files.vtotsel,'string','');
        set(FIGM.uic.files.vtotavail,'string','');
        s = ['files ',num2str(DAT.vfpsoi),', playback ',num2str(DAT.vfpstp)];
        set(FIGM.uic.files.vfps,'string',s);
        set(FIGM.uic.files.vlist,'string','','value',1);
    case ('JPG')
        set(FIGM.uic.files.vcurrdir,'string',DAT.vpath);
        s = [num2str(DAT.vframemax),' files (',mintominsec(DAT.fseldur),' min:sec)'];
        set(FIGM.uic.files.vtotsel,'string',s);
        s = [num2str(DAT.vnummax),' files (',mintominsec(DAT.favaildur),' min:sec)'];
        set(FIGM.uic.files.vtotavail,'string',s);
        s = ['files ',num2str(DAT.vfpsoi),', playback ',num2str(DAT.vfpstp)];
        set(FIGM.uic.files.vfps,'string',s);
        s = makevideosettext(DAT);
        vlval = get(FIGM.uic.files.vlist,'value');
        vlmax = size(s,1);
        newvlval = max([min([vlval vlmax]) 1]);
        set(FIGM.uic.files.vlist,'string',s,'value',newvlval);
    otherwise
        set(FIGM.uic.files.vcurrdir,'string',DAT.vpath);
        s = [num2str(DAT.vframemax),' frames (',mintominsec(DAT.fseldur),' min:sec)'];
        set(FIGM.uic.files.vtotsel,'string',s);
        s = [num2str(DAT.vnummax),' frames (',mintominsec(DAT.favaildur),' min:sec)'];
        set(FIGM.uic.files.vtotavail,'string',s);
        s = ['files ',num2str(DAT.vfpsoi),', playback ',num2str(DAT.vfpstp)];
        set(FIGM.uic.files.vfps,'string',s);
        s = makevideosettext(DAT);
        vlval = get(FIGM.uic.files.vlist,'value');
        vlmax = size(s,1);
        newvlval = max([min([vlval vlmax]) 1]);
        set(FIGM.uic.files.vlist,'string',s,'value',newvlval);
end
checkmodules('dispnsubj',FIGM,DAT.vnsubj);
set(FIGM.uic.score.realdur,'string','');
set(FIGM.uic.score.playdur,'string','');

%=====================================
function[] = displayusercommands(FIGM)
%%%---------------------------------------------------------
%%% Called by:  acceptloginput, addusercommand, changenchar,
%%% deleteusercommand, doclearcommandset, loadcommandsfile
%%%---------------------------------------------------------
DAT = getstoreddata(FIGM.DATh);
if (~isfield(DAT.uc,'plotorder'))
    isempty_cmnds = isempty(DAT.uc.bchar);		% can't use flag, hasn't been updated yet
    if (isempty_cmnds == 0)
        ncmnds = size(DAT.uc.bchar,1);
        DAT.uc.plotorder = (1:ncmnds)';
        DAT.uc.plotclr = zeros(ncmnds,3);
        setstoreddata(FIGM.DATh,DAT);
    else
        DAT.uc.plotorder = [];
        DAT.uc.plotclr = [];
    end
end
uc = DAT.uc;
spacebchar = strmatch(' ',uc.bchar);
for si = 1:size(spacebchar,1)
    origchar = uc.bchar{spacebchar(si)};
    sindex = find(origchar == ' ');
    if (~isempty(sindex))
        origchar(sindex) = '_';
        uc.bchar(spacebchar(si)) = {origchar};
    end
end
spaceechar = strmatch(' ',uc.echar);
for si = 1:size(spaceechar,1)
    origchar = uc.echar{spaceechar(si)};
    sindex = find(origchar == ' ');
    if (~isempty(sindex))
        origchar(sindex) = '_';
        uc.echar(spaceechar(si)) = {origchar};
    end
end
echarindex = cellfun('isempty',uc.echar);
blankchar = blanks(uc.nchars);
uc.echar(echarindex) = {blankchar};
uclisttxt = createlistboxtext(uc);
ulval = get(FIGM.uic.cmnds.uclist,'value');
ulmax = size(uclisttxt,1);
newulval = max([min([ulval ulmax]) 1]);
set(FIGM.uic.cmnds.uclist,'string',uclisttxt,'value',newulval);
blist = createbehaviorlist(uc);
set(FIGM.uic.analy.behaviorslist,'string',blist,'value',newulval);
currclr = uc.plotclr(newulval,:);
set(FIGM.uic.analy.colordisplay,'backgroundcolor',currclr);
updatecmndsflags(FIGM);
updatelogsavedflag(FIGM);

%=====================================
function[] = dobrowsedir(FIGM,fileset)
%%%---------------------------------------------
%%% Called by:  Directory BUTTONS in FILES panel
%%%---------------------------------------------
switch (fileset)
    case ('video')
        fname = 'vinputpath';
    case ('cmnds')
        fname = 'cinputpath';
    case ('log')
        fname = 'linputpath';
end
startingdir = get(FIGM.uic.files.(fname),'string');
if (isempty(startingdir)); startingdir = ''; end
sdir = uigetdir(startingdir,'Select directory');
if (sdir ~= 0)
    set(FIGM.uic.files.(fname),'string',sdir);
end

%======================================
function[] = dobrowsefile(FIGM,fileset)
%%%-------------------------------------------------
%%% Called by:  File prefix/Filename and File suffix
%%% BUTTONS in FILES panel
%%%-------------------------------------------------
dosearch = 1;
msg = '';
omitstring = [];
switch (fileset)
    case ('video')
        fdirname = 'vinputpath';
        ffilename = 'vinputprefix';
        vtype = getstoreddata(FIGM.FFLh,'val_videotype');
        switch (vtype)
            case ('NONE')
                dosearch = 0;
            case ('JPG')
                ffilter = '*.jpg';
                msg = 'note:  edit filename to be file prefix';
            otherwise
                ffilter = ['*.',lower(vtype)];
        end
    case ('cmnds')
        fdirname = 'cinputpath';
        ffilename = 'cinputsuffix';
        ffilter = 'commands*.mat';
        omitstring = 'commands';
    case ('log')
        fdirname = 'linputpath';
        ffilename = 'linputsuffix';
        ffilter = 'log*.mat';
        omitstring = 'log';
end
if (dosearch == 1)
    startingdir = get(FIGM.uic.files.(fdirname),'string');
    if (isempty(startingdir));
        startingdir = ffilter;
    else
        startingdir = [startingdir,'/',ffilter];
    end
    [sfile,sdir] = uigetfile(startingdir,'Find a file');
    if (sfile ~= 0)
        speriod = find(sfile == '.');
        if (~isempty(speriod))
            sfile = sfile(1:speriod(1)-1);
        end
        omitindex = strfind(sfile,omitstring);
        if (~isempty(omitindex))
            omitindex = omitindex(1)+(0:length(omitstring)-1);
            keepindex = setdiff((1:length(sfile)),omitindex);
            sfile = sfile(keepindex);
        end
        set(FIGM.uic.files.(fdirname),'string',sdir);
        set(FIGM.uic.files.(ffilename),'string',sfile);
    end
end
setmsg(FIGM,msg);

%===================================
function[] = doclearcommandset(FIGM)
%%%-------------------------------------------------------------
%%% Called by:  Clear BUTTON for command set in left-hand panels
%%%-------------------------------------------------------------
isempty_cmnds = getstoreddata(FIGM.FFLh,'isempty_cmnds');
isempty_slog = getstoreddata(FIGM.FFLh,'isempty_slog');
clearpermission = 0;
if (isempty_cmnds == 1)
    clearpermission = 1;
else
    clearpermission = 1;
    if (isempty_slog == 0)
        clearpermission = 0;
        response = questdlg( ...
            {'The score log is not empty.  Clearing the command'; ...
            'set is a bad idea if you intend to resave this log.'; ...
            ' '; ...
            'Do you still want to clear it?'}, ...
            'Clear Command Set Check','yes','no','no');
        if (strcmp('yes',response))
            clearpermission = 1;
        end
    end
end
if (clearpermission == 1)
    initcommandset(FIGM);
    setstoreddata(FIGM.FFLh,[],'isfrom_cmnds',[]);
    cfinput = getcfinput(FIGM);
    cfinput.cpath = [];
    cfinput.cfilename = [];
    DAT = getstoreddata(FIGM.DATh);
    storecfinfo(FIGM,cfinput,DAT.uc);
    putcfinput2(FIGM,DAT.uc);
    displayusercommands(FIGM);
    clearucentryfields(FIGM);
    setmsg(FIGM,'command set cleared');
else
    setmsg(FIGM,'clear command set cancelled');
end

%============================
function[] = doclearlog(FIGM)
%%%-----------------------------------------------------
%%% Called by:  Clear BUTTON for log in left-hand panels
%%%-----------------------------------------------------
isempty_log = getstoreddata(FIGM.FFLh,'isempty_log');
clearpermission = 0;
if (isempty_log == 1)
    clearpermission = 1;
else
    response = questdlg( ...
        {'Are you sure you want to clear the entire log?'}, ...
        'Clear Log Check','yes','no','no');
    if (strcmp('yes',response))
        clearpermission = 1;
    end
end
if (clearpermission == 1)
    setmsg(FIGM,'clearing log ...');
    isloaded_video = getstoreddata(FIGM.FFLh,'isloaded_video');
    if (isloaded_video == 0)				% if no video loaded
        initvideo(FIGM);					% clear video file set information
    end
    setstoreddata(FIGM.FFLh,[],'canloadfromlog',0);
    lfinput.lpath = [];					% clear log file info display
    lfinput.lfilename = [];
    storelfinfo(FIGM,lfinput);
    set(FIGM.uic.files.lcurrinfo,'string','');
    setstoreddata(FIGM.FFLh,[],'isfrom_cmnds',[]);	% clear command file info display
    cfinput = getcfinput(FIGM);
    cfinput.cpath = [];
    cfinput.cfilename = [];
    storecfinfo(FIGM,cfinput);
    clearrawlog(FIGM);
    clearfulllog(FIGM);
    clearmarkslog(FIGM);
    clearnoteslog(FIGM);
    checkmodules('clearposnlog',FIGM);
    setmsg(FIGM,'log cleared');
else
    setmsg(FIGM,'clear log cancelled');
end

%===============================
function[] = doclearrawlog(FIGM)
%%%--------------------------------------------------
%%% Called by:  Clear score log BUTTON in BEHAV panel
%%%--------------------------------------------------
isempty_slog = getstoreddata(FIGM.FFLh,'isempty_slog');
clearpermission = 0;
if (isempty_slog == 1)
    clearpermission = 1;
else
    response = questdlg( ...
        {'Are you sure you want to clear the score log?'}, ...
        'Clear Log Check','yes','no','no');
    if (strcmp('yes',response))
        clearpermission = 1;
    end
end
if (clearpermission == 1)
    setmsg(FIGM,'clearing score log ...');
    clearrawlog(FIGM);
    clearfulllog(FIGM);
    setmsg(FIGM,'score log cleared');
else
    setmsg(FIGM,'clear score log cancelled');
end

%==============================
function[] = doclearvideo(FIGM)
%%%-------------------------------------------------------
%%% Called by:  Clear BUTTON for video in left-hand panels
%%%-------------------------------------------------------
isloaded_video = getstoreddata(FIGM.FFLh,'isloaded_video');
clearpermission = 0;
if (isloaded_video == 0)
    clearpermission = 1;
else
    response = questdlg( ...
        {'Are you sure you want to clear the video?'}, ...
        'Clear Video Check','yes','no','no');
    if (strcmp('yes',response))
        clearpermission = 1;
    end
end
if (clearpermission == 1)
    setmsg(FIGM,'clearing video ...');
    isempty_log = getstoreddata(FIGM.FFLh,'isempty_log');
    if (isempty_log == 1)
        initvideo(FIGM);					% clear video file set information
    end
    clearvideo(FIGM);					% clear video display
    setmsg(FIGM,'video cleared');
else
    setmsg(FIGM,'clear video cancelled');
end

%=============================================
function[] = docustomcolorrequest(callbackvar)
%%%---------------------------------------------------------------------
%%% Called by:  all SLIDERS and BUTTONS in secondary CUSTOM COLOR figure
%%%---------------------------------------------------------------------
FIGC = getstoreddata(gcf);				% get info from custom color figure
r = get(FIGC.uic.sliderred,'value');
g = get(FIGC.uic.slidergrn,'value');
b = get(FIGC.uic.sliderblu,'value');
currclr = get(FIGC.uic.axes,'color');
switch (callbackvar)					% switch on second input
    case ('red')						% update change in red value
        currclr(1) = r;
        set(FIGC.uic.axes,'color',currclr);
    case ('green')						% update change in green value
        currclr(2) = g;
        set(FIGC.uic.axes,'color',currclr);
    case ('blue')						% update change in blue value
        currclr(3) = b;
        set(FIGC.uic.axes,'color',currclr);
    case ('accept')						% get current color and close this window
        close(FIGC.thisfigh);
        FIGM = getstoreddata(FIGC.mainfigh);
        setplotcolor(FIGM,round([r g b]*100)/100);
end

%=========================
function[] = dosavestate()
%%%-------------------------------------------------------
%%% Called by:  Save state BUTTON at bottom of main figure
%%%-------------------------------------------------------
allgraphics = get(0,'children');
savename = ['currentstate',datestr(clock,30)];
hgsave(allgraphics,savename,'all');
msgbox({'The current graphics state has been saved in the file'; ...
    ''; ...
    ['       ',savename,'.fig']; ...
    ''; ...
    'in the directory'; ...
    ''; ...
    ['       ',pwd]; ...
    ''; ...
    'If you are saving this file for the programmer, attach'; ...
    'it to an email in which you describe the problem.  Thanks!'});

%===================================
function[] = dosetoverwritemsg(FIGM)
%%%--------------------------------------------------------
%%% Called by:  Overwrite score log CHECKBOX in BEHAV panel
%%%--------------------------------------------------------
isloaded_video = getstoreddata(FIGM.FFLh,'isloaded_video');
if (isloaded_video == 1)
    setoverwritemsg(FIGM);
else
    setoverwritemsg(FIGM,0);
end

%============================
function[] = dosetvtype(FIGM)
%%%------------------------------------------------
%%% Called by:  File type POPUP menu in FILES panel
%%%------------------------------------------------
isloaded_video = getstoreddata(FIGM.FFLh,'isloaded_video');
oldvtype = getstoreddata(FIGM.FFLh,'val_videotype');
vtype = getuivalue(FIGM.uic.files.vtype);
if (isloaded_video == 1)
    setuivalue(FIGM.uic.files.vtype,oldvtype);
    setmsg(FIGM,'error:  video must be cleared before video type can be changed');
else
    setvtype(FIGM,vtype);
end

%==========================================
function[] = doswitchpanel(FIGM,switchname)
%%%--------------------------------------------------
%%% Called by:  Files, Cmnds, Behav, Nandm, Posns,
%%% Analy, and Score BUTTONS at bottom of main figure
%%%--------------------------------------------------
settimeroffplayoff(FIGM);				% stop playback
if (strcmp(switchname,'score'))				% if score button pressed
    cfinput = getcfinput(FIGM);				% update stored command set
    storecfinfo(FIGM,cfinput);
end
setactivepanel(FIGM,switchname);			% switch to requested panel

%===========================
function[] = drawframe(FIGM)
%%%-----------------------------------------------------------
%%% Called by:  acceptvideoinput, clearvideo, loadvideofromlog
%%%-----------------------------------------------------------
cla(FIGM.uic.score.axes_image);
DAT = getstoreddata(FIGM.DATh);
CON = getstoreddata(FIGM.CONh);
currframe = str2num(get(FIGM.uic.score.currframe,'string'));
if (~isempty(currframe) && ~strcmp('NONE',DAT.vtype))
    setmsg(FIGM,'rendering image ...');
    oneframe = getvideoframe(FIGM,currframe);
    FIGM.uic.score.image = imagesc(oneframe);
    aspectratio = [size(oneframe,2) size(oneframe,1) 1];
    set(FIGM.uic.score.axes_image,'xlim',[0,aspectratio(1)]);
    set(FIGM.uic.score.axes_image,'ylim',[0,aspectratio(2)]);
    set(FIGM.uic.score.axes_image,'plotboxaspectratio',aspectratio);
    set(FIGM.uic.score.image,'erasemode','none');
    FIGM = checkmodules('plotposns',FIGM,currframe);
    setstoreddata(FIGM.thisfigh,FIGM);
else
    x=get(FIGM.uic.score.axes_image,'xlim');
    y=get(FIGM.uic.score.axes_image,'ylim');
    setmsg(FIGM,'clearing image ...');
    fill([x(1) x(2) x(2) x(1)],[y(1) y(1) y(2) y(2)],CON.clr.frame1);
    cla(FIGM.uic.score.axes_image);
end
drawnow;

%==========================
function[] = editmark(FIGM)
%%%------------------------------------------------------------
%%% Called by:  Edit BUTTON below marks log list in NANDM panel
%%%------------------------------------------------------------
marksindex = get(FIGM.uic.nandm.markslog,'value');
DAT = getstoreddata(FIGM.DATh);
if ((size(DAT.markslog.framenum,1) > 0) && (marksindex > 0))
    set(FIGM.uic.nandm.marksframe,'string',num2str(DAT.markslog.framenum(marksindex)));
    set(FIGM.uic.nandm.marksname,'string',DAT.markslog.framename{marksindex});
end

%==========================
function[] = editnote(FIGM)
%%%------------------------------------------------------------
%%% Called by:  Edit BUTTON below notes log list in NANDM panel
%%%------------------------------------------------------------
isempty_nlog = getstoreddata(FIGM.FFLh,'isempty_nlog');
if (isempty_nlog == 0)
    notesindex = get(FIGM.uic.nandm.noteslog,'value');
    if (notesindex > 0)
        %%% TO DO:  why would notesindex == 0?
        DAT = getstoreddata(FIGM.DATh);
        set(FIGM.uic.nandm.entrytext,'string',DAT.noteslog{notesindex});
    end
end

%=======================================
function[] = figurekeypressfcn(hco,user)
%%%-----------------------------------------------------------------
%%% Called by:  KeyPressFcn property of main figure (called whenever
%%% a keystroke occurs)
%%%-----------------------------------------------------------------
FIGM = getstoreddata(gcf);
FFL = getstoreddata(FIGM.FFLh);
if ((get(FIGM.uic.swtch.score,'value') == 1) && (FFL.isloaded_video == 1))
    dologdisplays = 0;		% flag to update log displays at end of this fxn
    FFL.val_lastframeadded = [];
    key = get(FIGM.thisfigh,'currentcharacter');
    DAT = getstoreddata(FIGM.DATh);
    if (DAT.uc.nchars == 2)
        if (isempty(FFL.val_holdchar))		% first of two keys entered
            if (isempty(strmatch(key,DAT.fixed.char,'exact')))	% if not a playback command
                FFL.val_holdchar = key;
                key = nan;
            end
        else					% second of two keys entered
            key = [FFL.val_holdchar,key];
            FFL.val_holdchar = [];
        end
    end
    if ~isnan(key)
        currframe = str2num(get(FIGM.uic.score.currframe,'string'));
        bcharindex = strmatch(key,DAT.uc.bchar,'exact');
        echarindex = strmatch(key,DAT.uc.echar,'exact');
        fcharindex = strmatch(key,DAT.fixed.char,'exact');
        if (FFL.ison_overwrite == 1)
            if (~isempty(bcharindex) || ~isempty(echarindex) || ~isempty(fcharindex))
                [DAT,FFL] = overwritelog(DAT,FFL,currframe);
            end
        end
        if (~isempty(bcharindex) || ~isempty(echarindex))
            DAT.rawlog{end+1,1} = key;
            DAT.rawlogframe(end+1,1) = currframe;
            FFL.val_lastframeadded = currframe;
            dologdisplays = 1;
        elseif (~isempty(fcharindex))
            switch (key)
                case (DAT.fixed.charlookup.playstoptoggle)
                    if (FFL.isplaying == 0)
                        FFL.val_startframe = currframe + DAT.fnumincr;
                        set(FIGM.uic.score.realdur,'string','');
                        set(FIGM.uic.score.playdur,'string','');
                        set(FIGM.uic.score.playing,'string','playing');
                        FFL.val_holdchar = [];
                        FFL.isplaying = 1;
                        turntimeron(FIGM.tim);
                    else
                        FFL = settimeroffplayoff(FIGM,FFL);
                        if ((FFL.ison_overwrite == 1) || (FFL.ison_bayg == 1))
                            dologdisplays = 1;
                        end
                    end
                case (DAT.fixed.charlookup.backtostart)
                    currframe = 1;
                    setcurrframe(FIGM,currframe);
                    if (FFL.isplaying == 0); updateframe(FIGM); end
                    if (FFL.ison_bayg == 1); FFL.val_lastbgframe = 1; dologdisplays = 1; end
                case (DAT.fixed.charlookup.back1minute)
                    currframe = currframe - round(60*DAT.vfpsoi);
                    if (currframe < 1); currframe = 1; end
                    setcurrframe(FIGM,currframe);
                    if (FFL.isplaying == 0); updateframe(FIGM); end
                    if (FFL.ison_bayg == 1); FFL.val_lastbgframe = 1; dologdisplays = 1; end
                case (DAT.fixed.charlookup.back1second)
                    currframe = currframe - round(DAT.vfpsoi);
                    if (currframe < 1); currframe = 1; end
                    setcurrframe(FIGM,currframe);
                    if (FFL.isplaying == 0); updateframe(FIGM); end
                    if (FFL.ison_bayg == 1); FFL.val_lastbgframe = 1; dologdisplays = 1; end
                case (DAT.fixed.charlookup.back1frame)
                    currframe = currframe - 1;
                    if (currframe < 1); currframe = 1; end
                    setcurrframe(FIGM,currframe);
                    if (FFL.isplaying == 0); updateframe(FIGM); end
                    if (FFL.ison_bayg == 1); FFL.val_lastbgframe = 1; dologdisplays = 1; end
                case (DAT.fixed.charlookup.forward1frame)
                    currframe = currframe + 1;
                    if (currframe > DAT.vframemax); currframe = DAT.vframemax; end
                    setcurrframe(FIGM,currframe);
                    if (FFL.isplaying == 0); updateframe(FIGM); end
                    if (FFL.ison_bayg == 1); dologdisplays = 1; end
                case (DAT.fixed.charlookup.forward1second)
                    currframe = currframe + round(DAT.vfpsoi);
                    if (currframe > DAT.vframemax); currframe = DAT.vframemax; end
                    setcurrframe(FIGM,currframe);
                    if (FFL.isplaying == 0); updateframe(FIGM); end
                    if (FFL.ison_bayg == 1); dologdisplays = 1; end
                case (DAT.fixed.charlookup.forward1minute)
                    currframe = currframe + round(60*DAT.vfpsoi);
                    if (currframe > DAT.vframemax); currframe = DAT.vframemax; end
                    setcurrframe(FIGM,currframe);
                    if (FFL.isplaying == 0); updateframe(FIGM); end
                    if (FFL.ison_bayg == 1); dologdisplays = 1; end
                case (DAT.fixed.charlookup.forwardtoend)
                    currframe = DAT.vframemax;
                    if currframe==inf
                        setmsg(FIGM,'End of video does not exist in this mode.');
                    else
                        setcurrframe(FIGM,currframe);
                    end
                    if (FFL.isplaying == 0); updateframe(FIGM); end
                    if (FFL.ison_bayg == 1); dologdisplays = 1; end
                case (DAT.fixed.charlookup.playspeedtoggle)
                    if (FFL.isplaying == 0)
                        normalrate = 1/DAT.vfpstp;
                        switch (FFL.val_playspeed)
                            case ('normal')
                                FFL.val_playspeed = 'fastx1.5';
                                newrate = normalrate/1.5;
                                set(FIGM.uic.score.playspeed,'string','fast x1.5');
                            case ('fastx1.5')
                                FFL.val_playspeed = 'fastx2';
                                newrate = normalrate/2;
                                set(FIGM.uic.score.playspeed,'string','fast x2');
                            case ('fastx2')
                                FFL.val_playspeed = 'fastx3';
                                newrate = normalrate/3;
                                set(FIGM.uic.score.playspeed,'string','fast x3');
                            case ('fastx3')
                                FFL.val_playspeed = 'fastx5';
                                newrate = normalrate/5;
                                set(FIGM.uic.score.playspeed,'string','fast x5');
                            case ('fastx5')
                                FFL.val_playspeed = 'slowx2';
                                newrate = normalrate*2;
                                set(FIGM.uic.score.playspeed,'string','slow x2');
                            case ('slowx2')
                                FFL.val_playspeed = 'normal';
                                newrate = normalrate;
                                set(FIGM.uic.score.playspeed,'string','normal');
                        end
                        newrate = round(1000*newrate)/1000;
                        set(FIGM.tim,'period',newrate);
                    end
            end			% end switch on key
            if (FFL.ison_overwrite == 1)
                FFL.val_lastovframe = currframe;	% if jump, overwrite from new spot
            end
        else			% an invalid key was pressed
            updateongoing(FIGM,key);
        end			% end if fcharindex not empty
    end				% end if ~isnan(key)
    setstoreddata(FIGM.DATh,DAT);
    setstoreddata(FIGM.FFLh,FFL);
    if (dologdisplays == 1)
        updaterawlog(FIGM);
        if (FFL.ison_bayg == 1)
            growfulllog(FIGM,FFL.val_lastbgframe,currframe);
            updatefulllog(FIGM);
        else
            if (size(DAT.fulllogtext,1) > 0)
                clearfulllog(FIGM);
            end
        end
        updateongoing(FIGM,key);
    end
end				% end if score == 1 & isloaded_video == 1

%===============================
function[] = finishfulllog(FIGM)
%%%--------------------------------------------
%%% Called by:  addentrytofulllog, buildfulllog
%%%--------------------------------------------
DAT = getstoreddata(FIGM.DATh);
if (~isempty(DAT.openstates))
    framenum = DAT.vnumends(end);
    keystoclose = unique(DAT.uc.echar(DAT.openstates));
    for ki = 1:length(keystoclose)
        key = keystoclose{ki};
        DAT = addentrytofulllog(DAT,framenum,key);
    end
    setstoreddata(FIGM.DATh,DAT);
end

%================================================
function[s] = formatvarfortext(FIGM,varname,data)
%%%---------------------------------------------------------
%%% Function formats variables for text display.
%%% Called by:  settimeroffplayoff, storecfinfo, storelfdata
%%%---------------------------------------------------------
switch (varname)
    case {'realdur','playdur'}
        s = num2str(data,'%3.2f');
    case ('ccurrinfo')
        s = ['1 ',data.uc.subj1name];
        if (~isempty(data.uc.subj2name))
            s = [s,', 1 ',data.uc.subj2name];
        end
        s = [s,'; ',num2str(size(data.uc.bchar,1)),' behaviors; ', ...
            num2str(data.uc.nchars),' chars/cmd; '];
        switch(data.uc.simbehav)
            case (1)
                s = [s,'1 sim behav'];
            case (2)
                s = [s,'1 sim behav/subj'];
            case (3)
                s = [s,'mult sim behav'];
        end
    case ('lcurrinfo')
        s = [num2str(size(data.rawlog,1)),' score log entries; ', ...
            num2str(size(data.noteslog,1)),' notes; ', ...
            num2str(size(data.markslog.framenum,1)),' marks'];
        ispresent_posnmodule = getstoreddata(FIGM.FFLh,'ispresent_posnmodule');
        if (ispresent_posnmodule == 1)
            s = [s,'; ',num2str(size(data.posnlog,1)),' frames with positions'];
        end
    otherwise
        s = '';
end

%=====================================
function[src] = generatefilenames(src)
%%%-----------------------
%%% Called by:  bc_newvars
%%%-----------------------
FIGM = getstoreddata(gcf);
CON = getstoreddata(FIGM.CONh);
filenamefilter = [src.vpath,CON.slash,src.vprefix,'*.jpg'];
setmsg(FIGM,'log file from previous version; getting file list ...');
[vfilenames,n] = getfilenames(filenamefilter);
if (n < 1)
    [vfilenames,firstfileindex,lastfileindex] = ...
        makefilenames(src.vprefix,src.fsuffstart_txt,src.fsuffend_txt);
else
    firstfilename = [src.vprefix,src.fsuffstart_txt,'.jpg'];
    lastfilename = [src.vprefix,src.fsuffend_txt,'.jpg'];
    firstfileindex = strmatch(firstfilename,vfilenames);
    lastfileindex = strmatch(lastfilename,vfilenames);
    if (isempty(firstfileindex) || isempty(lastfileindex))
        [vfilenames,firstfileindex,lastfileindex] = ...
            makefilenames(src.vprefix,src.fsuffstart_txt,src.fsuffend_txt);
    else
        if (firstfileindex > 1)
            framedifference = firstfileindex - 1;
            src.rawlogframe = src.rawlogframe + framedifference;
        end
    end
end
src.vnumstart = firstfileindex;
src.vnumend = lastfileindex;
src.vfilenames = vfilenames;

%===================================
function[aw] = getawframes(markslog)
%%%--------------------------------------------
%%% Called by:  addmark, deletemark, updatemark
%%%--------------------------------------------
aw.start = markslog.framenum(markslog.startindex);
aw.align = markslog.framenum(markslog.alignindex);
aw.end = markslog.framenum(markslog.endindex);

%===================================
function[cfinput] = getcfinput(FIGM)
%%%------------------------------------------------------------------------
%%% Called by:  buildfulllog, doclearcommandset, doclearlog, doswitchpanel,
%%% loadcommandsfile, savecommandsfile, switchbuildasyougo
%%%------------------------------------------------------------------------
cfinput.cpath = get(FIGM.uic.files.cinputpath,'string');
cfinput.cfilename = get(FIGM.uic.files.cinputsuffix,'string');
cfinput.subj1name = get(FIGM.uic.cmnds.subj1name,'string');
cfinput.subj2name = get(FIGM.uic.cmnds.subj2name,'string');
cfinput.simbehav = get(FIGM.uic.cmnds.simbehav,'value');
if (isempty(cfinput.cpath))
    cfinput.cpath = pwd;
end

%==================================
function[] = getfixedcommands(FIGM)
%%%--------------------------
%%% Called by:  initfixedlist
%%%--------------------------
DAT = getstoreddata(FIGM.DATh);
fixed.char = {'0';'1';'2';'3';'4';'6';'7';'8';'9';'='};
fixed.desc = {'play/stop toggle';'back to start';'back 1 minute';'back 1 second'; ...
    'back 1 frame';'forward 1 frame';'forward 1 second';'forward 1 minute'; ...
    'forward to end';'play speed toggle'};
fixed.charlookup = [];
for row = 1:size(fixed.char,1)
    fname = fixed.desc{row};
    notspaceindex = find(fname ~= ' ');
    fname = fname(notspaceindex);
    notslashindex = find(fname ~= '/');
    fname = fname(notslashindex);
    fixed.charlookup.(fname) = fixed.char{row};
end
DAT.fixed = fixed;
setstoreddata(FIGM.DATh,DAT);

%===================================
function[lfinput] = getlfinput(FIGM)
%%%-----------------------------------------
%%% Called by:  retrievelogfile, savelogfile
%%%-----------------------------------------
lfinput.lpath = get(FIGM.uic.files.linputpath,'string');
if (isempty(lfinput.lpath))
    lfinput.lpath = pwd;
end
lfinput.lfilename = get(FIGM.uic.files.linputsuffix,'string');

%===================================================
function[] = getlogframes(FIGM,whichlog,whichframes)
%%%------------------------------------------------------------
%%% Called by:  Log selection and End of log BUTTONS in Display
%%% subpanel of BEHAV and POSNS panels
%%%------------------------------------------------------------
DAT = getstoreddata(FIGM.DATh);
framenum = [];
switch (whichlog)
    case ('score')
        isempty_thislog = getstoreddata(FIGM.FFLh,'isempty_slog');
        logframes = DAT.rawlogframe;
        fieldhandle = FIGM.uic.behav.jumpfnum;
        loghandle = FIGM.uic.behav.rawlog;
    case ('posn')
        isempty_thislog = getstoreddata(FIGM.FFLh,'isempty_plog');
        logframes = DAT.posnlog;
        fieldhandle = FIGM.uic.posns.jumpfnum;
        loghandle = FIGM.uic.posns.posnlog;
end
if (isempty_thislog == 0)
    msg = 'log frame number retrieved';
    switch (whichframes)
        case ('end')
            framenum = max(logframes(:,1));
        case ('current')
            logindex = get(loghandle,'value');
            if ((logindex >= 1) && (logindex <= size(logframes,1)))
                framenum = logframes(logindex,1);
            else
                msg = 'error:  unable to apply current index to log';
            end
    end
    set(fieldhandle,'string',num2str(framenum));
else
    msg = 'error:  this log is empty';
end
setmsg(FIGM,msg);
%===============================================
function videomethod = getvideoreadmethod(FIGM,pathandfile)
%%%------------------------------------------------------------
%%% Called by: getvideofiles, loadvideofromlog
%%%------------------------------------------------------------
% What Matlab function can be used to play a video file depends on the
% platform, the Matlab release, the presence of 3rd party software such
% as the videoIO package, and the type of file.
% Preference order would be:
% 1. videoIO videoReader - fastest, Windows only, requires installation
% 2. aviread - slow, deprecated or absent in R2010b, Mac uncompressed AVIs only, Windows
%   uncompressed or Indeo5
% 3. Matlab videoReader - probably slow, Mac or Windows, R2010b+
% 4. mmreader - slow, 2007b-2010a Windows, 2008a-2010a Mac, 2009a-2010a Linux
% 5. unsupported
%
% Possibly mmreader/videoReader is slower than aviread.  If not, priority
% should be changed.
%
% Author: Eleanor Fraser
% Date: September 30, 2010

CON = getstoreddata(FIGM.CONh);
extension = lower(pathandfile(find(pathandfile=='.',1,'last'):end));
if ismember(extension,{'.jpg'})
    videomethod = 'JPEG';
else
    ispresent_videoReader = (exist('videoReader.m','file') == 2);
    if ispresent_videoReader
        ispresent_videoIO = ismember('seek',methods('videoReader'));
    else
        ispresent_videoIO = false;
    end
    ispresent_mmreader = (exist('mmreader.m','file') == 2);
    ispresent_aviread = (exist('mmreader.m','file') == 2);

    if ispc()
        platform = 'PC';
    else
        if isunix()
            platform = 'Unix';
        else
            platform = 'Mac';
        end
    end
    vidType = upper(extension(2:end));
    is_AVI = strcmpi(extension,'.avi');
    is_videoIOMovie = ismember(vidType,CON.videoIOMovie);
    is_WindowsMovie = ismember(vidType,CON.WindowsMovie);
    is_MacMovie = ismember(vidType,CON.MacMovie);
    is_UnixMovie = ismember(vidType,CON.UnixMovie);
    if is_AVI
        warning('off','MATLAB:aviinfo:FunctionToBeRemoved');
        info = aviinfo(pathandfile);
        is_WinCompr = ismember(info.VideoCompression,...
            {'Indeo3','Indeo5','Cinepak','MSVC','RLE','None'}); %?
        is_MacCompr = ismember(info.VideoCompression,{'None'});
        clear info
    end

    if ispresent_videoIO && strcmpi(computer,'PCWIN') && is_videoIOMovie % all versions?
            videomethod = 'videoIO videoReader';
            warning('off','MATLAB:fileparts:VersionToBeRemoved');
    else
        if is_AVI && ispresent_aviread && ...
                ((ismember(platform,{'Mac','Unix'}) && is_MacCompr)...
                || (strcmpi(platform,'PC') && is_WinCompr))
            videomethod = 'aviread';
        else
            if (strcmpi(platform,'PC')   && is_WindowsMovie) || ...
                    (strcmpi(platform,'Mac')  && is_MacMovie)     || ...
                    (strcmpi(platform,'Unix') && is_UnixMovie)
                if ispresent_videoReader
                    videomethod = 'VideoReader';
                else
                    if ispresent_mmreader
                        videomethod = 'mmreader';
                    else
                        videomethod = 'unsupported';
                    end
                end
            else
                videomethod = 'unsupported';
            end
        end
    end
end
%===============================================

function[slash,codepath] = getslashandcodepath()
%%%------------------------
%%% Called by:  getdefaults
%%%------------------------
codefilename = mfilename;
codepathandfile = mfilename('fullpath');
codepath = codepathandfile(1:end-(length(codefilename)));
slash = codepath(end);
codepath = codepath(1:end-1);

%===========================================
function[filevars] = getvarsforlogfile(FIGM)
%%%--------------------------------------------------------------
%%% Function gets set of variables to save in log file and places
%%% them in the structure filevars, by doing the following:
%%% (a) info.<infofields> = DAT.<infofields>
%%% (b) filevars.info = info
%%% (c) filevars.<dtfields> = DAT.<dtfields>
%%% Called by:  savelogfile
%%%--------------------------------------------------------------
DAT = getstoreddata(FIGM.DATh);
CON = getstoreddata(FIGM.CONh);
infofields = CON.set.vfields;
info = [];
for ifi = 1:size(infofields,1)
    info.(infofields{ifi}) = DAT.(infofields{ifi});
end
filevars.info = info;
dtfields = {'ucparams';'uc';'rawlog';'rawlogframe';'posnlog'; ...
    'fulllog';'noteslog';'markslog'};
for ifi = 1:size(dtfields,1)
    filevars.(dtfields{ifi}) = DAT.(dtfields{ifi});
end

%===========================================
function[vfinput] = getvfinput(FIGM,vfinput)
%%%----------------------------
%%% Called by:  retrievevfinput
%%%----------------------------
vfinput.vtype = getstoreddata(FIGM.FFLh,'val_videotype');
vfinput.vpath = get(FIGM.uic.files.vinputpath,'string');
if ~isempty(vfinput.vpath) && ismember(vfinput.vpath(end),{'/','\'})
    vfinput.vpath = vfinput.vpath(1:end-1);
end
vfinput.vprefix = get(FIGM.uic.files.vinputprefix,'string');
vfinput.vnumstart = str2num(get(FIGM.uic.files.vinputnumstart,'string'));
vfinput.vnumend = str2num(get(FIGM.uic.files.vinputnumend,'string'));
vfinput.vfpsoi = str2num(get(FIGM.uic.files.vinputfpsoi,'string'));
vfinput.vfpstp = str2num(get(FIGM.uic.files.vinputfpstp,'string'));
vfinput = checkmodules('getnsubj',FIGM,vfinput);
if (isempty(vfinput.vpath)); vfinput.vpath = pwd; end
switch (vfinput.vtype)
    case ('NONE')
        vfinput.vprefix = [];
        vfinput.vnumstart = 1;
        vfinput.vnumend = inf;
    case ('JPEG')
    otherwise
        vfinput.vfpsoi = 24;
end
ison_inclall = get(FIGM.uic.files.vinputinclall,'value');
if (ison_inclall == 1)
    vfinput.vnumstart = [];
    vfinput.vnumend = [];
end

%=========================================================
function[vfinput,avibadflag] = getvideofiles(FIGM,vfinput)
%%%----------------------------
%%% Called by:  retrievevfinput
%%%----------------------------
avibadflag = 0;
CON = getstoreddata(FIGM.CONh);
vfinput.videomethod = 'None';
switch (vfinput.vtype)
    case ('NONE')
        vfilenames = [];
        n = inf;
    case ('JPG')
        vfinput.videomethod = 'JPEG';
        filefilter = [vfinput.vpath,CON.slash,vfinput.vprefix,'*.jpg'];
        setmsg(FIGM,'getting file list ...');
        [vfilenames,n] = getfilenames(filefilter);
    otherwise
        vfilename = [vfinput.vprefix,'.',vfinput.vtype];
        pathandfile = [vfinput.vpath,CON.slash,vfilename];
        if (exist(pathandfile,'file'))
            vfinput.videomethod = getvideoreadmethod(FIGM,pathandfile);
            if ismember(vfinput.videomethod,{'aviread','VideoReader','mmreader'})
                setmsg(FIGM,'Video play will probably be slow without videoIO.');
                pause(0.5);
            end
            switch vfinput.videomethod
                case 'unsupported'
                    avibadflag = 1;
                    vfilenames = {};
                    n = 0;
                case 'aviread'
                    fileinfo = aviinfo(pathandfile);
                    n = fileinfo.NumFrames;
                    vfilenames = cell(n,1);
                    vfilenames(:) = {vfilename};
                    vfinput.vfpsoi = fileinfo.FramesPerSecond;
                case 'videoIO videoReader'
                    DAT.vobj = videoReader(pathandfile);
                    info = getinfo(DAT.vobj);
                    if strcmpi(info.fourcc,'YV12')
                        setmsg(FIGM,'Warning: MPEG-2 videos may cause errors.');
                        pause(1)
                    end 
                    vfinput.nhiddenframes = info.nHiddenFinalFrames;
                    n = info.numFrames;
                    vfilenames = cell(n,1);
                    vfilenames(:) = {vfilename};
                    vfinput.vfpsoi = info.fps;
                case 'VideoReader'
                    DAT.vobj = VideoReader(pathandfile);
                    n = get(DAT.vobj,'NumberOfFrames');
                    if isempty(n) % Variable frame rate; can't find # frames
                        avibadflag = 2;
                    end
                    vfilenames = cell(n,1);
                    vfilenames(:) = {vfilename};
                    vfinput.vfpsoi = get(DAT.vobj,'FrameRate');
                case 'mmreader'
                    DAT.vobj = mmreader(pathandfile);
                    n = get(DAT.vobj,'NumberOfFrames');
                    if isempty(n) % Variable frame rate; can't find # frames
                        avibadflag = 2;
                    end
                    vfilenames = cell(n,1);
                    vfilenames(:) = {vfilename};
                    vfinput.vfpsoi = get(DAT.vobj,'FrameRate');
            end
        else
            vfilenames = {};
            n = 0;
        end
end
vfinput.vfilenames = vfilenames;
vfinput.vnummax = n;

%=================================================
function[oneframe] = getvideoframe(FIGM,currframe)
%%%-----------------------------------------------------------------
%%% Called by:  buildavgimage, calcpositions, drawframe, updateframe
%%%-----------------------------------------------------------------
DAT = getstoreddata(FIGM.DATh);
CON = getstoreddata(FIGM.CONh);
currindex = find(DAT.vframenums == currframe);
pathandfile = [DAT.vpath,CON.slash,DAT.vfilenames{currindex}];
switch (DAT.videomethod)
    case ('JPEG')
        oneframe = imread(pathandfile,'jpeg');
    case ('avireader')
        oneframe = aviread(pathandfile,DAT.vfilenums(currindex));
        oneframe = oneframe.cdata;
    case 'videoIO videoReader';
        if (isempty(DAT.vobj))
            status = 0;
        else
            info = getinfo(DAT.vobj);
            if ~strcmp(pathandfile,info.url)
                %i.e. if jumping to a different video file
                setmsg(FIGM,'switching video files...');
                DAT.vobj = videoReader(pathandfile);
                setstoreddata(FIGM.DATh,DAT);
                setmsg(FIGM,'done.');
            end
            status = seek(DAT.vobj,DAT.vfilenums(currindex));
        end
        if (status == 0)         
            DAT.vobj = videoReader(pathandfile);
            setstoreddata(FIGM.DATh,DAT);
            status = seek(DAT.vobj,DAT.vfilenums(currindex));
        end
        oneframe = getframe(DAT.vobj);
    case 'VideoReader'
        if (isempty(DAT.vobj))
            DAT.vobj = VideoReader(pathandfile);
            setstoreddata(FIGM.DATh,DAT);
        else
            info = get(DAT.vobj);
            if ~strcmp(pathandfile,[info.Path,CON.slash,info.Name])
                %i.e. if jumping to a different video file
                setmsg(FIGM,'switching video files...');
                DAT.vobj = VideoReader(pathandfile);
                setstoreddata(FIGM.DATh,DAT);
                setmsg(FIGM,'done.');
            end
        end
        oneframe = read(DAT.vobj,DAT.vfilenums(currindex));
    case 'mmreader'
        if (isempty(DAT.vobj))
            DAT.vobj = mmreader(pathandfile);
            setstoreddata(FIGM.DATh,DAT);
        else
            info = get(DAT.vobj);
            if ~strcmp(pathandfile,[info.Path,CON.slash,info.Name])
                %i.e. if jumping to a different video file
                setmsg(FIGM,'switching video files...');
                DAT.vobj = mmreader(pathandfile);
                setstoreddata(FIGM.DATh,DAT);
                setmsg(FIGM,'done.');
            end
        end
        oneframe = read(DAT.vobj,DAT.vfilenums(currindex));
end

%=================================================
function[] = growfulllog(FIGM,startframe,endframe)
%%%----------------------------------------------------------------
%%% Called by:  addentrytofulllog, buildfulllog, figurekeypressfcn,
%%% switchbuildasyougo
%%%----------------------------------------------------------------
if (nargin < 2); startframe = []; end
if (nargin < 3); endframe = []; end
DAT = getstoreddata(FIGM.DATh);
if (isempty(startframe))
    startframe = 1;
end
if (isempty(endframe))
    endframe = DAT.vframemax;
end
if endframe == inf
    if DAT.markslog.framenum(DAT.markslog.endindex) == inf
        tmp1 = 50000;
    else
        tmp1 = DAT.markslog.framenum(DAT.markslog.endindex);
    end
    if isempty(DAT.rawlogframe)
        tmp2 = 50000;
    else
        tmp2 = max(DAT.rawlogframe);
    end
    endframe = max(tmp1,tmp2);
end
if (isempty(startframe) || isempty(endframe))
    setstoreddata(FIGM.FFLh,[],'val_lastbgframe',0);
else
    if (startframe == 1)
        initfulllog(FIGM);
        DAT = getstoreddata(FIGM.DATh);
    end
    frameindex = (startframe:endframe)';
    rawlogindex = find(ismember(DAT.rawlogframe,frameindex));
    if (~isempty(rawlogindex))
        for row = rawlogindex'
            framenum = DAT.rawlogframe(row);
            key = DAT.rawlog{row};
            DAT = addentrytofulllog(DAT,framenum,key);
        end
        setstoreddata(FIGM.DATh,DAT);
    end
    setstoreddata(FIGM.FFLh,[],'val_lastbgframe',endframe+1);
end

%==============================================
function [] = handle_error(FIGM,varargin)
%%%--------------------------------------------
%%% Called by:  main loop
%%%--------------------------------------------
% Saves information about the last error for a programmer
err = lasterror;
CON = getstoreddata(FIGM.CONh);
suffix = datestr(clock,'yyyymmdd-HHMM');
system_info.computer = computer;
system_info.OS = getenv('OS');
system_info.version = version;
% Check for common videoIO errors
knownerrors = find(...
    [~isempty(findstr('No combination of intermediate filters',err.message)),...
    ~isempty(findstr('Perhaps the file does not exist',err.message)),...
    ~isempty(findstr('invalid media type',err.message))]);
if isempty(knownerrors); knownerrors = 0; end
switch knownerrors
    case 1
        setmsg(FIGM,'VideoIO cannot load video.  Required codec appears to be missing.');
    case 2
        setmsg(FIGM,'DirectShowIVideo failed to load video: thinks file does not exist.  Restart Matlab.');
    case 3
        setmsg(FIGM,'DirectShowIVideo failed to load video: claims invalid media type.  Restart Matlab.');
    otherwise
        % No common errors found
        % Save information on last error:
        errlogfilename = ['scorevideoErrorLog',suffix,'.mat'];
        errlogpathandfile = [CON.codepath,CON.slash,errlogfilename];
        save(errlogpathandfile,'err','system_info','varargin');
        % Save information about program's current state
        figsavefilename = ['scorevideoSaveState',suffix,'.fig'];
        figsavepathandfile = [CON.codepath,CON.slash,figsavefilename];
            allgraphics = get(0,'children');
            hgsave(allgraphics,figsavepathandfile,'all');
            % Tell user to send the information to me
            errordlg({'An error has occurred:',...
                err.message,'','Please send',errlogpathandfile,...
                figsavepathandfile,...
                'and any files that may have caused the error',...
                'to a programmer for debugging'});
end
%==============================================
function[markslog] = indexawframes(markslog,aw)
%%%--------------------------------------------
%%% Called by:  addmark, deletemark, updatemark
%%%--------------------------------------------
startindex = find(markslog.framenum == aw.start);
if isempty(startindex)
    startindex = strmatch('video start',markslog.framename,'exact');
end
markslog.startindex = startindex;
alignindex = find(markslog.framenum == aw.align);
if isempty(alignindex)
    alignindex = strmatch('video start',markslog.framename,'exact');
end
markslog.alignindex = alignindex;
endindex = find(markslog.framenum == aw.end);
if isempty(endindex)
    endindex = strmatch('video end',markslog.framename,'exact');
end
markslog.endindex = endindex;

%================================
function[] = initcommandset(FIGM)
%%%-------------------------------------------
%%% Called by:  doclearcommandset, initmainfig
%%%-------------------------------------------
DAT = getstoreddata(FIGM.DATh);
DAT.cpath = [];
DAT.cfilename = [];
DAT.ucparams.subj = {'0';'1';'2';'3'};
DAT.ucparams.simbehav = {'one';'one per subject';'multiple'};
DAT.uc.nchars = 1;
DAT.uc.subj1name = 'subject1';
DAT.uc.subj2name = 'subject2';
DAT.uc.bchar = {};
DAT.uc.echar = {};
DAT.uc.subj = {};
DAT.uc.desc = {};
DAT.uc.simbehav = 1;
setstoreddata(FIGM.DATh,DAT);

%====================================
function[] = initcustomcolorfig(FIGM)
%%%-----------------------------------------
%%% Called by:  Custom BUTTON in ANALY panel
%%%-----------------------------------------
%%% TO DO:  decompose just like initmainfig
CON = getstoreddata(FIGM.CONh);
FIGC.mainfigh = FIGM.thisfigh;
FIGC.thisfigh = makefig('customcolor','Custom color selector', ...
    CON.fontsize.ax,CON.fontsize.ui);
FIGC.uic.axes = axes('position',[.10 .50 .80 .40],'xtick',[],'ytick',[]);
FIGC.uic.sliderredlabel = uicontrol('style','text', ...
    'position',[.10 .40 .10 .04], ...
    'string','Red', ...
    'backgroundcolor',CON.clr.fig);
FIGC.uic.sliderred = uicontrol('style','slider', ...
    'position',[.10 .35 .80 .05], ...
    'callback','scorevideo(''color'',''red'');', ...
    'min',0,'max',1,'sliderstep',[.01 .1]);
FIGC.uic.slidergrnlabel = uicontrol('style','text', ...
    'position',[.10 .30 .15 .04], ...
    'string','Green', ...
    'backgroundcolor',CON.clr.fig);
FIGC.uic.slidergrn = uicontrol('style','slider', ...
    'position',[.10 .25 .80 .05], ...
    'callback','scorevideo(''color'',''green'');', ...
    'min',0,'max',1,'sliderstep',[.01 .1]);
FIGC.uic.sliderblulabel = uicontrol('style','text', ...
    'position',[.10 .20 .10 .04], ...
    'string','Blue', ...
    'backgroundcolor',CON.clr.fig);
FIGC.uic.sliderblu = uicontrol('style','slider', ...
    'position',[.10 .15 .80 .05], ...
    'callback','scorevideo(''color'',''blue'');', ...
    'min',0,'max',1,'sliderstep',[.01 .1]);
FIGC.uic.cancel = uicontrol('style','pushbutton', ...
    'position',[.10 .05 .20 .08], ...
    'string','Cancel', ...
    'backgroundcolor',CON.clr.button1, ...
    'callback','close;');
FIGC.uic.accept = uicontrol('style','pushbutton', ...
    'position',[.70 .05 .20 .08], ...
    'string','Accept', ...
    'backgroundcolor',CON.clr.button1, ...
    'callback','scorevideo(''color'',''accept'');');
rgb = get(FIGM.uic.analy.colordisplay,'backgroundcolor');
set(FIGC.uic.axes,'color',rgb);
set(FIGC.uic.sliderred,'value',rgb(1));
set(FIGC.uic.slidergrn,'value',rgb(2));
set(FIGC.uic.sliderblu,'value',rgb(3));
setstoreddata(FIGC.thisfigh,FIGC);

%=============================
function[FIGM] = initmainfig()
%%%----------------------------------------------------
%%% Called by:  scorevideo (main loop of this function)
%%%----------------------------------------------------
%%% getting constants and graphics parameters
%%%------------------------------------------
[CON,DAT,FFL,TFL] = getdefaults;
uicp = getuicparams(FFL,CON);

%%%----------------------
%%% making program window
%%%----------------------
FIGM.thisfigh = makefig('main','scorevideo', ...
    CON.fontsize.ax,CON.fontsize.ui,CON.clr.fig);
FIGM = makeuicontrols(FIGM,uicp);
FIGM = storeprogramdata(FIGM,CON,DAT,FFL,TFL);
FIGM = setswitchhandles(FIGM);

%%%-------------------------------------------------
%%% configuring program window and setting variables
%%%-------------------------------------------------
setactivepanel(FIGM,'files');
initvideo(FIGM);
initfixedlist(FIGM);
initcommandset(FIGM);
initrawlog(FIGM);
initfulllog(FIGM);
initmarkslog(FIGM);
initnoteslog(FIGM);
initposnlog(FIGM);
putstoredvalues(FIGM);
axes(FIGM.uic.score.axes_image);				% setting current axes

%===============================
function[] = initfixedlist(FIGM)
%%%------------------------
%%% Called by:  initmainfig
%%%------------------------
getfixedcommands(FIGM);
DAT = getstoreddata(FIGM.DATh);
fixedlist = createlistboxtext(DAT.fixed);
set(FIGM.uic.cmnds.fixedlist,'string',fixedlist);

%=============================
function[] = initfulllog(FIGM)
%%%-----------------------------------------------------------------
%%% Called by:  buildfulllog, clearfulllog, growfulllog, initmainfig
%%%-----------------------------------------------------------------
DAT = getstoreddata(FIGM.DATh);
DAT.fulllog.frame = {};
DAT.fulllog.time = {};
DAT.fulllog.charnum = {};
DAT.fulllog.type = {};
DAT.fulllog.action = {};
DAT.fulllog.subj = {};
DAT.fulllogtext = {};
DAT.openstates = [];
setstoreddata(FIGM.DATh,DAT);
setstoreddata(FIGM.FFLh,[],'val_lastbgframe',1);

%==============================
function[] = initmarkslog(FIGM)
%%%------------------------------------------------------
%%% Called by:  checkmarkslog, clearmarkslog, initmainfig
%%%------------------------------------------------------
DAT = getstoreddata(FIGM.DATh);
DAT.markslog.framenum = [];
DAT.markslog.framename = {};
DAT.markslog.startindex = [];
DAT.markslog.alignindex = [];
DAT.markslog.endindex = [];
setstoreddata(FIGM.DATh,DAT);

%==============================
function[] = initnoteslog(FIGM)
%%%--------------------------------------
%%% Called by: clearnoteslog, initmainfig
%%%--------------------------------------
DAT = getstoreddata(FIGM.DATh);
DAT.noteslog = {};
setstoreddata(FIGM.DATh,DAT);

%=============================
function[] = initposnlog(FIGM)
%%%--------------------------------------
%%% Called by: clearposnlog, initmainfig
%%%--------------------------------------
DAT = getstoreddata(FIGM.DATh);
DAT.posnlog = [];
DAT.posnlogtext = {};
setstoreddata(FIGM.DATh,DAT);

%============================
function[] = initrawlog(FIGM)
%%%------------------------------------------------------
%%% Called by: clearrawlog, deletefromrawlog, initmainfig
%%%------------------------------------------------------
DAT = getstoreddata(FIGM.DATh);
DAT.lpath = [];
DAT.lfilename = [];
DAT.rawlog = {};
DAT.rawlogframe = [];
DAT.rawlogtext = {};
setstoreddata(FIGM.DATh,DAT);

%===========================
function[] = initvideo(FIGM)
%%%-----------------------------------------------------------------------
%%% Called by:  acceptlogvideoinput, doclearlog, doclearvideo, initmainfig
%%%-----------------------------------------------------------------------
DAT = getstoreddata(FIGM.DATh);
vtype = getstoreddata(FIGM.FFLh,'val_videotype');
DAT.vtype = vtype;
DAT.vobj = [];
DAT.vpath = [];
DAT.vprefix = [];
DAT.vnumstart = [];
DAT.vnumend = [];
DAT.vprefixes = {};
DAT.vnumstarts = [];
DAT.vnumends = [];
DAT.vfpsoi = 24;
DAT.vfpstp = 24;
DAT.vnsubj = 2;
DAT.vfilenames = {};
DAT.vfilenums = [];
DAT.vframenums = [];
DAT.vfsrcindex = [];
DAT.vframemax = 0;
DAT.vnummax = 0;
DAT.fseldur = 0;
DAT.favaildur = 0;
DAT.fnumincr = 1;
DAT.nhiddenframes = 0;
setstoreddata(FIGM.DATh,DAT);
setvideoloaded(FIGM,0);

%===============================
function[FIGM] = inittimer(FIGM)
%%%----------------------------------------------------
%%% Called by:  scorevideo (main loop of this function)
%%%----------------------------------------------------
TH.fig = FIGM.thisfigh;
TH.tim = timer( ...
    'ExecutionMode','fixedRate', ...
    'TimerFcn', {@timertickfcn}, ...
    'BusyMode', 'drop', ...
    'TasksToExecute', inf, ...
    'StartDelay', 0.1);
FIGM.tim = TH.tim;
TH.TFLh = FIGM.TFLh;
TH.DATh = FIGM.DATh;
TH.FFLh = FIGM.FFLh;
setstoreddata(TH.tim,TH);

%======================================
function[] = jumptoframe(FIGM,whichlog)
%%%---------------------------------------------------
%%% Called by:  Jump BUTTONS in BEHAV and POSNS panels
%%%---------------------------------------------------
isloaded_video = getstoreddata(FIGM.FFLh,'isloaded_video');
isnone_vtype = strcmp('NONE',getstoreddata(FIGM.DATh,'vtype'));
if (isloaded_video == 1)
    if (isnone_vtype == 0)
        jumpfnum = str2num(get(FIGM.uic.(whichlog).jumpfnum,'string'));
        if (~isempty(jumpfnum))
            DAT = getstoreddata(FIGM.DATh);
            if ((jumpfnum >= 1) && (jumpfnum <= DAT.vframemax))
                setcurrframe(FIGM,jumpfnum);
                updateframe(FIGM);
                setmsg(FIGM,'jump completed');
            else
                setmsg(FIGM,'error:  invalid frame number');
            end
        else
            setmsg(FIGM,'error:  frame number needed');
        end
    else
        setmsg(FIGM,'error:  jump functions not applicable when video type is none');
    end
else
    setmsg(FIGM,'error:  video must be loaded');
end

%==========================
function[] = killvobj(FIGM)
%%%---------------------------------------------------------
%%% Called by:  retrievevfinput, quitprogramfxn, updateframe
%%%---------------------------------------------------------
DAT = getstoreddata(FIGM.DATh);
if (~isempty(DAT.vobj))
    if strcmp(DAT.videomethod,'videoIO videoReader')
        close(DAT.vobj);
    end
    DAT.vobj = [];
    setstoreddata(FIGM.DATh,DAT);
end

%==================================
function[] = loadcommandsfile(FIGM)
%%%------------------------------------------------------------
%%% Called by:  Load BUTTON for command set in left-hand panels
%%%------------------------------------------------------------
cfinput = getcfinput(FIGM);
response = 'yes';
isempty_slog = getstoreddata(FIGM.FFLh,'isempty_slog');
if (isempty_slog == 0)
    response = query_loadcmndswhenlog;
end
if (strcmp('yes',response))
    CON = getstoreddata(FIGM.CONh);
    filename = ['commands',cfinput.cfilename];
    pathandfile = [cfinput.cpath,CON.slash,filename];
    if (exist([pathandfile,'.mat'],'file'))
        setmsg(FIGM,'loading commands file ...');
        filevars = load(pathandfile);
        setstoreddata(FIGM.FFLh,[],'isfrom_cmnds','cmd');
        storecfinfo(FIGM,cfinput,filevars.uc);
        DAT = getstoreddata(FIGM.DATh);
        putcfinput1(FIGM,DAT);
        putcfinput2(FIGM,DAT.uc);
        displayusercommands(FIGM);
        clearucentryfields(FIGM);
        setmsg(FIGM,'commands file loaded');
    else
        setmsg(FIGM,['error: ',pathandfile,'.mat not found']);
    end
else
    setmsg(FIGM,'commands file load cancelled');
end

%=============================
function[] = loadlogfile(FIGM)
%%%----------------------------------------------------
%%% Called by:  Load BUTTON for log in left-hand panels
%%%----------------------------------------------------
[lfinput,lfdata] = retrievelogfile(FIGM);
status = checkloadlog(FIGM,lfdata);
acceptlogvideoinput(FIGM,lfdata,status);
acceptloginput(FIGM,lfinput,lfdata,status);
if (status.loadlog == 1)
    updatelogsavedflag(FIGM,1);
end

%=============================================
function[] = loadvideofrominput(FIGM,loadmode)
%%%----------------------------------------------------------
%%% Called by:  Load new, Add to and Update BUTTONS for video
%%% in left-hand panels
%%%----------------------------------------------------------
setmsg(FIGM,'checking user input ...');
vfinput = retrievevfinput(FIGM,loadmode);
vfinput = checkfilenumbers(FIGM,vfinput);			% check that inputs are valid
vfinput = setfilenumbers(vfinput);				% apply starting and ending frame #s
vfinput = checkvideoadd(FIGM,vfinput);				% check valid inputs for add
vfinput = checkvideoupdate(FIGM,vfinput);			% check valid inputs for update
vfinput = addvideofiles(FIGM,vfinput);				% add/update video file set w/ vfinput
acceptvideoinput(FIGM,vfinput);					% store input, update displays, etc

%==================================
function[] = loadvideofromlog(FIGM)
%%%----------------------------------------------------------
%%% Called by:  From log BUTTON for video in left-hand panels
%%%----------------------------------------------------------
canloadfromlog = getstoreddata(FIGM.FFLh,'canloadfromlog');
if (canloadfromlog == 1)
    setmsg(FIGM,'loading video from log ...');
    DAT = getstoreddata(FIGM.DATh);
    CON = getstoreddata(FIGM.CONh);
    validlist = 1;
    if ismember(DAT.vpath(end),{'/','\'})
        DAT.vpath = DAT.vpath(1:end-1);
    end
    pathandfile = [DAT.vpath,CON.slash,DAT.vfilenames{1}];
    if (~exist(pathandfile,'file'))
        validlist = 0;
    end
    pathandfile = [DAT.vpath,CON.slash,DAT.vfilenames{end}];
    if (~exist(pathandfile,'file'))
        validlist = 0;
    end
    if (validlist == 1)
        DAT.videomethod = getvideoreadmethod(FIGM,pathandfile); % in case of change in system or old log
        [DAT,validlist] = bc_hiddenframes(FIGM,DAT);
    end
    if (validlist == 1)
        DAT.vprefix = DAT.vprefixes{1};
        DAT.vnumstart = DAT.vnumstarts(1);
        DAT.vnumend = DAT.vnumends(1);
        setstoreddata(FIGM.DATh,DAT);
        displayvfinfo(FIGM);					% update video file set info display
        putvfinput(FIGM,DAT);					% update video file set input fields
        setvarsforvideoload(FIGM);				% set up for playing video
        setvideoloaded(FIGM,1);
        drawframe(FIGM);						% draw first frame
        setmsg(FIGM,'video loaded; first video file subset placed in input fields');
    elseif (validlist == 0)
        setmsg(FIGM,['error:  video cannot be loaded from log -- ', ...
            'one or more video files not found']);
    elseif (validlist == 2)
        setmsg(FIGM,'error:  this log is not compatible with current version of program; contact programmer');
    end
else
    setmsg(FIGM,['error:  video cannot be loaded from log -- ', ...
        'video file set info either absent or replaced']);
end

%==================================
function[] = loadusersettings(FIGM)
%%%----------------------------------------------------
%%% Called by:  scorevideo (main loop of this function)
%%%----------------------------------------------------
CON = getstoreddata(FIGM.CONh);
filename = 'scorevideosettings';
pathandfile = [CON.codepath,CON.slash,filename];
if (exist([pathandfile,'.mat'],'file'))
    filevars = load(pathandfile);
    settings = filevars.settings;
    settings = bc_renamedvars(settings,'settings');
    settings = bc_changedvars(settings,'settings');
    settings = bc_newvars(settings,'settings');
    putvfinput(FIGM,settings);
    putcfinput1(FIGM,settings);
    putcfinput2(FIGM,settings.uc);
    putlfinput(FIGM,settings);
    %%% TO DO:  incorporate these checks into other functions
    setboxflag(FIGM,'checksavecmnds',settings.checksavecmnds);
    setboxflag(FIGM,'checksavelog',settings.checksavelog);
end

%=======================================================================
function[filenames,firsti,lasti] = makefilenames(prefix,startnum,endnum)
%%%------------------------------
%%% Called by:  generatefilenames
%%%------------------------------
fsufflen = size(startnum,2);
fsufftemplate = blanks(fsufflen);
fsufftemplate(1:end) = '0';
startnum_num = str2num(startnum);
endnum_num = str2num(endnum);
ftot = endnum_num - startnum_num + 1;
filenames = cell(ftot,1);
for fi = 1:ftot
    thisfsuff = fsufftemplate;
    thisfsuffnum = startnum_num + fi - 1;
    thisfsuffnum_txt = num2str(thisfsuffnum);
    sufftxtlen = size(thisfsuffnum_txt,2);
    thisfsuff(end-sufftxtlen+1:end) = thisfsuffnum_txt;
    filename = [prefix,thisfsuff,'.jpg'];
    filenames{fi} = filename;
end
firsti = 1;
lasti = ftot;

%===========================================
function[DAT] = makefulllogtext(DAT,nspaces)
%%%--------------------------------------------
%%% Called by:  updatefulllog, writelogtextfile
%%%--------------------------------------------
if (nargin < 2); nspaces = 2; end
DAT.fulllogtext = {};
if (~isempty(DAT.fulllog.frame))
    subjnames = {'either';DAT.uc.subj1name;DAT.uc.subj2name;'both'};
    t = cell2mat(DAT.fulllog.time);
    ts = mintominsec(t);
    if (~iscell(ts)); ts = {ts}; end
    eventindex = strmatch('event',DAT.fulllog.type,'exact');
    if (~isempty(eventindex))
        DAT.fulllog.action(eventindex) = {' '};
    end
    col1 = num2str(cell2mat(DAT.fulllog.frame));
    col2 = char(ts);
    col3 = char(DAT.uc.desc{cell2mat(DAT.fulllog.charnum)});
    col4 = char(subjnames{cell2mat(DAT.fulllog.subj)+1});
    col5 = char(DAT.fulllog.action);
    filler = ones(size(col1,1),1)*blanks(nspaces);
    DAT.fulllogtext = [col1,filler,col2,filler,col3,filler,col4,filler,col5];
    DAT.fulllogtext = cellstr(DAT.fulllogtext);
end

%============================================
function[DAT] = makemarkslogtext(DAT,nspaces)
%%%---------------------------------------------
%%% Called by:  updatemarkslog, writelogtextfile
%%%---------------------------------------------
if (nargin < 2); nspaces = 2; end
DAT.markslogtext = {};
if (~isempty(DAT.markslog.framenum))
    t = DAT.markslog.framenum/(DAT.vfpsoi*60);
    ts = mintominsec(t);
    if (~iscell(ts)); ts = {ts}; end
    col1 = num2str(DAT.markslog.framenum);
    col2 = char(ts);
    col3 = char(DAT.markslog.framename);
    filler = ones(size(col1,1),1)*blanks(nspaces);
    DAT.markslogtext = [col1,filler,col2,filler,col3];
    DAT.markslogtext = cellstr(DAT.markslogtext);
end

%=========================================
function[] = makeoutputplot(FIGM,plottype)
%%%--------------------------------------------------------
%%% Called by:  Raster, Raster and table, and Table BUTTONS
%%% in ANALY panels
%%%--------------------------------------------------------
isempty_slog = getstoreddata(FIGM.FFLh,'isempty_slog');
if (isempty_slog == 0)
    buildfulllog(FIGM);
    switch (plottype)
        case ('raster')
            plotraster(FIGM);
        case ('rasterandtable')
            plotrasterandtable(FIGM);
        case ('table')
            plottable(FIGM);
    end
    setmsg(FIGM,'figure(s) complete');
else
    setmsg(FIGM,'error:  log is empty; no data to plot');
end

%==========================================
function[DAT] = makerawlogtext(DAT,nspaces)
%%%-------------------------------------------
%%% Called by:  updaterawlog, writelogtextfile
%%%-------------------------------------------
if (nargin < 2); nspaces = 2; end
DAT.rawlogtext = {};
if (~isempty(DAT.rawlogframe))
    t = DAT.rawlogframe/(DAT.vfpsoi*60);
    ts = mintominsec(t);
    if (~iscell(ts)); ts = {ts}; end
    col1 = num2str(DAT.rawlogframe);
    col2 = char(ts);
    col3 = char(DAT.rawlog);
    filler = ones(size(col1,1),1)*blanks(nspaces);
    DAT.rawlogtext = [col1,filler,col2,filler,col3];
    DAT.rawlogtext = cellstr(DAT.rawlogtext);
end

%=========================================
function[FIGM] = makeuicontrols(FIGM,uicp)
%%%------------------------
%%% Called by:  initmainfig
%%%------------------------
elimprops = {'type','position','style','xdata','ydata','sdata'};
setnames = fieldnames(uicp);
for seti = 1:size(setnames,1)
    objnames = fieldnames(uicp.(setnames{seti}));
    for obji = 1:size(objnames,1)
        p = uicp.(setnames{seti}).(objnames{obji});
        switch (p.type)
            case ('uipanel')
                objh = uipanel('position',p.position);
            case ('uicontrol')
                objh = uicontrol('style',p.style,'position',p.position);
            case ('axes')
                objh = axes('position',p.position);
            case ('plot')
                objh = plot(p.xdata,p.ydata,p.sdata);
        end
        propnames = fieldnames(p);
        index = find(ismember(propnames,elimprops) == 0);
        propnames = propnames(index);
        for pni = 1:size(propnames,1)
            switch (propnames{pni})
                case ('xlabel')
                    xlabel(p.(propnames{pni}));
                otherwise
                    set(objh,propnames{pni},p.(propnames{pni}));
            end
        end
        FIGM.uic.(setnames{seti}).(objnames{obji}) = objh;
    end
end

%==========================================
function[s] = makevideosettext(DAT,nspaces)
%%%--------------------------
%%% Called by:  displayvfinfo
%%%--------------------------
if (nargin < 2); nspaces = 2; end
s = {};
if (~isempty(DAT.vprefixes))
    col1 = char(DAT.vprefixes);
    col2 = num2str(DAT.vnumstarts);
    col3 = num2str(DAT.vnumends);
    filler = ones(size(col1,1),1)*blanks(nspaces);
    s = [col1,filler,col2,filler,col3];
end

%==================================================
function[DAT,FFL] = overwritelog(DAT,FFL,currframe)
%%%------------------------------
%%% Called by:  figurekeypressfcn
%%%------------------------------
if (FFL.val_lastovframe > 0)
    logindex1 = find(DAT.rawlogframe > FFL.val_lastovframe);
    logindex2 = find(DAT.rawlogframe <= currframe);
    logindex = intersect(logindex1,logindex2);
    if (~isempty(logindex))
        keepindex = setdiff(1:size(DAT.rawlogframe,1),logindex);
        DAT.rawlog = DAT.rawlog(keepindex);
        DAT.rawlogframe = DAT.rawlogframe(keepindex);
    end
    FFL.val_lastovframe = currframe;
end

%=====================================
function[] = putcfinput1(FIGM,cfinput)
%%%----------------------------------------------------------------
%%% Called by:  acceptloginput, loadcommandsfile, loadusersettings,
%%% putstoredvalues, savecommandsfile
%%%----------------------------------------------------------------
set(FIGM.uic.files.cinputpath,'string',cfinput.cpath);
set(FIGM.uic.files.cinputsuffix,'string',cfinput.cfilename);

%==============================================
function[] = putcfinput2(FIGM,cfinput,cfinput2)
%%%-----------------------------------------------------------------
%%% Called by:  acceptloginput, doclearcommandset, loadcommandsfile,
%%% loadusersettings, putstoredvalues, savecommandsfile
%%%-----------------------------------------------------------------
if (nargin > 2)
    set(FIGM.uic.cmnds.simbehav,'string',cfinput2);
end
set(FIGM.uic.cmnds.subj1name,'string',cfinput.subj1name);
set(FIGM.uic.cmnds.subj2name,'string',cfinput.subj2name);
set(FIGM.uic.cmnds.simbehav,'value',cfinput.simbehav);
if (isfield(cfinput,'nchars'))
    switchnchar(FIGM,cfinput.nchars);
end

%====================================
function[] = putlfinput(FIGM,lfinput)
%%%-----------------------------
%%% Called by:  loadusersettings
%%%-----------------------------
set(FIGM.uic.files.linputpath,'string',lfinput.lpath);
set(FIGM.uic.files.linputsuffix,'string',lfinput.lfilename);

%=================================
function[] = putstoredvalues(FIGM)
%%%------------------------
%%% Called by:  initmainfig
%%%------------------------
DAT = getstoreddata(FIGM.DATh);
putvfinput(FIGM,DAT);
putcfinput1(FIGM,DAT);
putcfinput2(FIGM,DAT.uc,DAT.ucparams.simbehav);

%================================
function[] = putvfinput(FIGM,src)
%%%----------------------------------------------------
%%% Called by:  acceptlogvideoinput, acceptvideoinput,
%%% loadvideofromlog, loadusersettings, putstoredvalues
%%%----------------------------------------------------
if (nargin < 2)
    src.vpath = [];
    src.vprefix = [];
    src.vnumstart = [];
    src.vnumend = [];
    src.vfpsoi = 24;
    src.vfpstp = 24;
    src.vnsubj = 2;
end
if (isfield(src,'vtype'))
    setvtype(FIGM,src.vtype);
end
set(FIGM.uic.files.vinputpath,'string',src.vpath);
set(FIGM.uic.files.vinputprefix,'string',src.vprefix);
set(FIGM.uic.files.vinputnumstart,'string',num2str(src.vnumstart));
set(FIGM.uic.files.vinputnumend,'string',num2str(src.vnumend));
set(FIGM.uic.files.vinputfpsoi,'string',num2str(src.vfpsoi));
set(FIGM.uic.files.vinputfpstp,'string',num2str(src.vfpstp));
checkmodules('setnsubj',FIGM,src.vnsubj);

%=======================================
function[] = putusercommandinentry(FIGM)
%%%--------------------------------------------------------------
%%% Called by:  Edit button below command set list in CMNDS panel
%%%--------------------------------------------------------------
ucindex = get(FIGM.uic.cmnds.uclist,'value');
DAT = getstoreddata(FIGM.DATh);
set(FIGM.uic.cmnds.echar,'string',DAT.uc.echar{ucindex});
set(FIGM.uic.cmnds.bchar,'string',DAT.uc.bchar{ucindex});
set(FIGM.uic.cmnds.subj,'value',str2num(DAT.uc.subj{ucindex})+1);
set(FIGM.uic.cmnds.desc,'string',DAT.uc.desc{ucindex});

%============================================
function[response] = query_loadcmndswhenlog()
%%%-----------------------------
%%% Called by:  loadcommandsfile
%%%-----------------------------
response = questdlg( ...
    {'The score log is not empty.  If you load this command set'; ...
    'but it is not the one used to create the log, it is'; ...
    'recommended that you clear the log so that it is not resaved'; ...
    'with the wrong command set.'; ...
    '  '; ...
    'Do you still want to load this command set?'}, ...
    'Data Integrity Warning','yes','no','no');
if (isempty(response))
    response = 'no';
end

%============================================
function[response] = query_loadvideowhenlog()
%%%----------------------------
%%% Called by:  retrievevfinput
%%%----------------------------
response = questdlg( ...
    {'There is currently a log loaded in the program.'; ...
    'Loading a new video will replace the video file'; ...
    'set information from the log.'; ...
    '  '; ...
    'If you choose to load this video, (a) if you'; ...
    'resave the log, data integrity may be compromised;'; ...
    '(b) it is recommended that you clear the log'; ...
    'after loading the video to avoid this risk.'; ...
    '  '; ...
    'To load the video stored with the log, don''t load'; ...
    'this video; use the FROM LOG button.'; ...
    '  '; ...
    'Do you still want to load a new video?'}, ...
    'Data Integrity Warning','yes','no','no');
if (isempty(response))
    response = 'no';
end

%==============================================
function[response] = query_loadvideowhenvideo()
%%%----------------------------
%%% Called by:  retrievevfinput
%%%----------------------------
response = questdlg( ...
    {'There is currently a video loaded in the program.'; ...
    'Loading a new video will replace it.'; ...
    '  '; ...
    'To add to or update the current video file set,'; ...
    'use the ADD TO and UPDATE buttons.  To avoid'; ...
    'getting this warning in the future, clear the'; ...
    'video before loading a new one.'; ...
    '  '; ...
    'Do you still want to load a new video?'}, ...
    'Data Integrity Warning','yes','no','no');
if (isempty(response))
    response = 'no';
end

%===============================================
function[response] = query_logvideomismatch(msg)
%%%-------------------------
%%% Called by:  checkloadlog
%%%-------------------------
list1 = {};
for vli = 1:size(msg.varname,1)
    list1 = [list1;'   ',msg.varname{vli},': ',msg.vidvalue{vli},' vs. ',msg.logvalue{vli}];
end
dlgmsg1 = ...
    {'The video in the log does not match the currently loaded video.'; ...
    'Variables that do not match (video vs. log):'};
dlgmsg2 = ...
    {'  '; ...
    'Please tell the program what to load.'; ...
    '[SAFE]   (a) Log and video info'; ...
    '         - The current video will be cleared.  Video file set'; ...
    '           info from the log will be loaded.  This video can be'; ...
    '           loaded using the FROM LOG button.'; ...
    '[RISKY]  (b) Log only'; ...
    '         - The current video will remain.  Video file set info'; ...
    '           from the log will not be loaded.  If the log is later'; ...
    '           resaved, data integrity may be compromised.'; ...
    '[SAFE]   (c) Cancel'; ...
    '         - The log will not be loaded.  No changes will be made.'; ...
    '  '};
dlgmsg = [dlgmsg1;list1;dlgmsg2];
response = questdlg(dlgmsg,'Log-Video Mismatch', ...
    '(a) Log and video info','(b) Log only','(c) Cancel', ...
    '(a) Log and video info');
if (isempty(response))
    response = '(c) Cancel';
end

%============================
function[] = query_quit(FIGM)
%%%----------------------------------------------------
%%% Called by:  Quit BUTTON at bottom of program window
%%%----------------------------------------------------
issaved_log = getstoreddata(FIGM.FFLh,'issaved_log');
isempty_log = getstoreddata(FIGM.FFLh,'isempty_log');
isloaded_video = getstoreddata(FIGM.FFLh,'isloaded_video');
somethingtosave = ((isempty_log == 0) || ((isempty_log == 1) && (isloaded_video == 1)));
if ((issaved_log == 0) && (somethingtosave == 1))
    response = questdlg( ...
        {'The current log contains unsaved changes.'; ...
        'Are you sure you want to quit?'}, ...
        'Unsaved Changes Warning','yes','no','no');
    if (isempty(response))
        response = 'no';
    end
else
    response = 'yes';
end
if (strcmp('yes',response))
    close;
end

%====================================
function[] = quitprogramfxn(hco,user)
%%%-----------------------------------------------
%%% Function terminates variables and saves
%%% user settings.
%%% Called by:  DeleteFcn property of main figure,
%%% called whenever figure is closed
%%%-----------------------------------------------
FIGM = getstoreddata(hco);
turntimeroff(FIGM.tim);
delete(FIGM.tim);
killvobj(FIGM);
saveusersettings(FIGM);
% Turn back on warnings that were turned off
% Assumes you didn't have them off before running scorevideo, but it's not
% worth keeping track of that.
warning('on','MATLAB:fileparts:VersionToBeRemoved');
warning('on','MATLAB:aviinfo:FunctionToBeRemoved');

%=================================================
function[vfinput] = retrievefilelist(FIGM,vfinput)
%%%---------------------------------------------
%%% Function retrieves filelist for subset being
%%% updated from existing video file set.
%%% Called by:  retrievevfinput
%%%---------------------------------------------
DAT = getstoreddata(FIGM.DATh);
vfinput.vtype = DAT.vtype;
vfinput.vpath = DAT.vpath;
subsetindex = get(FIGM.uic.files.vlist,'value');
vfinput.vprefix = DAT.vprefixes{subsetindex};
vfinput.videomethod = DAT.videomethod;
switch (vfinput.vtype)
    case ('NONE')
        vfinput.vfilenames = [];
        vfinput.vnummax = inf;
    otherwise
        index = find(strmatch(vfinput.vprefix,DAT.vfilenames));
        vfinput.vfilenames = DAT.vfilenames(index);
        vfinput.vnummax = size(vfinput.vfilenames,1);
        if ~strcmp(vfinput,'JPG')
            vfinput.vfpsoi = DAT.vfpsoi;
        end
        vfinput.nhiddenframes = DAT.nhiddenframes;
end

%===============================================
function[lfinput,lfdata] = retrievelogfile(FIGM)
%%%------------------------
%%% Called by:  loadlogfile
%%%------------------------
lfinput = getlfinput(FIGM);
CON = getstoreddata(FIGM.CONh);
filename = ['log',lfinput.lfilename];
pathandfile = [lfinput.lpath,CON.slash,filename];
if (exist([pathandfile,'.mat'],'file'))
    setmsg(FIGM,'loading log file ...');
    filevars = load(pathandfile);
    lfdata = filevars.info;
    fvfields = fieldnames(filevars);
    fvfields = setdiff(fvfields,'info');
    if (size(fvfields,2) > size(fvfields,1))
        fvfields = fvfields';
    end
    for fvi = 1:size(fvfields,1)
        lfdata.(fvfields{fvi}) = filevars.(fvfields{fvi});
    end
    lfdata = bc_renamedvars(lfdata,'log');
    lfdata = bc_changedvars(lfdata,'log');
    lfdata = bc_newvars(lfdata,'log');
else
    lfdata = [];
    setmsg(FIGM,['error:  ',pathandfile,'.mat not found']);
end

%=================================================
function[vfinput] = retrievevfinput(FIGM,loadmode)
%%%-------------------------------
%%% Called by:  loadvideofrominput
%%%-------------------------------
vfinput.loadflag = 1;
vfinput.loadmode = loadmode;
vfinput.msg = [];
vfinput.nhiddenframes = 0;		% this may be changed in getvideofiles, so init'd here
%%%---------------
%%% check loadmode
%%%---------------
isnew_loadmode = strcmp(loadmode,'new');
isloaded_video = getstoreddata(FIGM.FFLh,'isloaded_video');
isempty_log = getstoreddata(FIGM.FFLh,'isempty_log');
if ((isloaded_video == 0) && (isnew_loadmode == 0))
    vfinput.loadflag = 0;
    vfinput.msg = 'error:  no video loaded; use load new button';
end
if ((isempty_log == 0) && (isnew_loadmode == 1))
    response = query_loadvideowhenlog;
    if (strcmp('no',response))
        vfinput.loadflag = 0;
        vfinput.msg = 'video load cancelled';
    end
end
if ((isloaded_video == 1) && (isnew_loadmode == 1))
    response = query_loadvideowhenvideo;
    if (strcmp('no',response))
        vfinput.loadflag = 0;
        vfinput.msg = 'video load cancelled';
    end
end
%%%-------------------------
%%% get video file set input
%%%-------------------------
if (vfinput.loadflag == 1)
    %%% DEBUG
    vfinput = getvfinput(FIGM,vfinput);
    vfinput = checkvfinput(FIGM,vfinput);
end
if (vfinput.loadflag == 1)
    killvobj(FIGM);
    switch (loadmode)
        case {'new','add'}
            [vfinput,avibadflag] = getvideofiles(FIGM,vfinput);
            if (avibadflag == 1)
                vfinput.loadflag = 0;
                vfinput.msg = ['error:  matlab cannot load video files ', ...
                    'of this type on this system'];
            elseif (avibadflag == 2) % Variable frame rate; can't find # frames
                vfinput.loadflag = 0;
                vfinput.msg = ['error:  matlab cannot load video files ', ...
                    'of this type without videoIO'];
            elseif (vfinput.vnummax == 0)
                vfinput.loadflag = 0;
                vfinput.msg = 'error:  video file(s) not found';
            end
        case ('update')
            vfinput = retrievefilelist(FIGM,vfinput);
    end
end

%==================================
function[] = savecommandsfile(FIGM)
%%%---------------------------------------------------------
%%% Called by:  Save BUTTON for commands in left-hand panels
%%%---------------------------------------------------------
isempty_cmnds = getstoreddata(FIGM.FFLh,'isempty_cmnds');
if (isempty_cmnds == 0)
    cfinput = getcfinput(FIGM);
    CON = getstoreddata(FIGM.CONh);
    filename = ['commands',cfinput.cfilename];
    pathandfile = [cfinput.cpath,CON.slash,filename];
    ison_checksavecmnds = getstoreddata(FIGM.FFLh,'ison_checksavecmnds');
    permissiontosave = 1 - ison_checksavecmnds;
    if (permissiontosave == 0)
        if (exist([pathandfile,'.mat'],'file'))
            response = questdlg( ...
                {'Overwrite existing commands file?'}, ...
                'File Overwrite Warning','yes','no','yes');
            if (strcmp('yes',response))
                permissiontosave = 1;
            end
        else
            permissiontosave = 1;
        end
    end
    if (permissiontosave == 1)
        setmsg(FIGM,'saving commands file ...');
        setstoreddata(FIGM.FFLh,[],'isfrom_cmnds','cmd');
        storecfinfo(FIGM,cfinput);
        putcfinput1(FIGM,cfinput);
        putcfinput2(FIGM,cfinput);
        filevars.uc = getstoreddata(FIGM.DATh,'uc');
        try
            eval(['save ''',pathandfile,''' -STRUCT filevars;'])
            writecommandstextfile(FIGM);
            setmsg(FIGM,'commands file saved');
        catch
            err = lasterror;
            switch err.identifier
                case 'MATLAB:m_unterminated_string'
                    setmsg(FIGM,['Commands file did not save.  Do not include ',...
                        'single or double quotes in path or file name.']);
                case 'MATLAB:save:couldNotWriteFile'
                    setmsg(FIGM,'Commands file did not save.  Could not write file.');
                case 'MATLAB:save:permissionDenied'
                    setmsg(FIGM,['Commands file did not save. ',...
                        'You do not have permission to write to this directory.']);
                otherwise
                    setmsg(FIGM,['Commands file did not save.  ',err.message]);
            end
        end
    else
        setmsg(FIGM,'save commands file cancelled');
    end
else
    setmsg(FIGM,'error:  command set is empty');
end

%=============================
function[] = savelogfile(FIGM)
%%%----------------------------------------------------
%%% Called by:  Save BUTTON for log in left-hand panels
%%%----------------------------------------------------
isempty_log = getstoreddata(FIGM.FFLh,'isempty_log');
lfinput = getlfinput(FIGM);
%buildfulllog(FIGM);
filevars = getvarsforlogfile(FIGM);
CON = getstoreddata(FIGM.CONh);
filename = ['log',lfinput.lfilename];
pathandfile = [lfinput.lpath,CON.slash,filename];
ison_checksavelog = getstoreddata(FIGM.FFLh,'ison_checksavelog');
permissiontosave = 1 - ison_checksavelog;
if (permissiontosave == 0)
    if (exist([pathandfile,'.mat'],'file'))
        response = questdlg( ...
            {'Overwrite existing log?'}, ...
            'File Overwrite Warning','yes','no','yes');
        if (strcmp('yes',response))
            permissiontosave = 1;
        end
    else
        permissiontosave = 1;
    end
end
if (permissiontosave == 1)
    setmsg(FIGM,'saving log file ...');
    try
        eval(['save ''',pathandfile,''' -STRUCT filevars;']);
        updatelogsavedflag(FIGM,1);
        storelfinfo(FIGM,lfinput);
        storelfdata(FIGM,filevars);
        writelogtextfile(FIGM);
        setmsg(FIGM,'log file saved');
    catch
        err = lasterror;
        switch err.identifier
            case 'MATLAB:m_unterminated_string'
                setmsg(FIGM,['Log file did not save.  Do not include ',...
                    'single or double quotes in path or file name.']);
            case 'MATLAB:save:couldNotWriteFile'
                setmsg(FIGM,'Log file did not save.  Could not write file.');
            case 'MATLAB:save:permissionDenied'
                setmsg(FIGM,['Log file did not save. ',...
                    'You do not have permission to write to this directory.']);
            otherwise
                setmsg(FIGM,['Log file did not save.  ',err.message]);
        end
    end
else
    setmsg(FIGM,'save log file cancelled');
end

%==================================
function[] = saveusersettings(FIGM)
%%%---------------------------
%%% Called by:  quitprogramfxn
%%%---------------------------
settings.vtype = getstoreddata(FIGM.FFLh,'val_videotype');
settings.vpath = get(FIGM.uic.files.vinputpath,'string');
settings.vprefix = get(FIGM.uic.files.vinputprefix,'string');
settings.vnumstart = str2num(get(FIGM.uic.files.vinputnumstart,'string'));
settings.vnumend = str2num(get(FIGM.uic.files.vinputnumend,'string'));
settings.vfpsoi = str2num(get(FIGM.uic.files.vinputfpsoi,'string'));
settings.vfpstp = str2num(get(FIGM.uic.files.vinputfpstp,'string'));
settings = checkmodules('getnsubj',FIGM,settings);
settings.cpath = get(FIGM.uic.files.cinputpath,'string');
settings.cfilename = get(FIGM.uic.files.cinputsuffix,'string');
settings.uc.subj1name = get(FIGM.uic.cmnds.subj1name,'string');
settings.uc.subj2name = get(FIGM.uic.cmnds.subj2name,'string');
settings.uc.simbehav = get(FIGM.uic.cmnds.simbehav,'value');
uc = getstoreddata(FIGM.DATh,'uc');
settings.uc.nchars = uc.nchars;
settings.lpath = get(FIGM.uic.files.linputpath,'string');
settings.lfilename = get(FIGM.uic.files.linputsuffix,'string');
settings.ison_checksavelog = getstoreddata(FIGM.FFLh,'ison_checksavelog');
settings.ison_checksavecmnds = getstoreddata(FIGM.FFLh,'ison_checksavecmnds');
filename = 'scorevideosettings';
CON = getstoreddata(FIGM.CONh);
pathandfile = [CON.codepath,CON.slash,filename];
eval(['save ''',pathandfile,''' settings;'])

%=====================================
function[] = setactivepanel(FIGM,mode)
%%%---------------------------------------
%%% Called by:  doswitchpanel, initmainfig
%%%---------------------------------------
swh = FIGM.swh;
if (strcmp('score',mode))					% if activating score panel
    enablestatus = 'off';					% disable other uicontrols
else								% if activating another panel
    enablestatus = 'on';						% enable other uicontrols
    for si = 1:size(swh.names,1)					% for each panel
        vistochange = swh.visible.(swh.names{si});
        if (~isempty(vistochange))
            if (strcmp(mode,swh.names{si}))			% set visible status
                visstatus = 'on';
            else
                visstatus = 'off';
            end
            set(swh.visible.(swh.names{si}),'visible',visstatus);	% update visibility
        end
    end
end
set(swh.enable,'enable',enablestatus);				% update enable status
for si = 1:size(swh.names,1)					% for each panel
    if (strcmp(mode,swh.names{si}))				% set visible status
        buttonvalue = 1;
    else
        buttonvalue = 0;
    end
    set(FIGM.uic.swtch.(swh.names{si}),'value',buttonvalue);
end

%==============================================
function[] = setboxflag(FIGM,boxname,flagvalue)
%%%------------------------------------------------------------------------
%%% Called by:  Check CHECKBOXES for commands and log files in left-hand
%%% panels, Build as you go CHECKBOX in BEHAV panel, Include starts before
%%% and Include stops after CHECKBOXES in NANDM panel, and loadusersettings
%%%------------------------------------------------------------------------
switch (boxname)
    case ('checksavecmnds')
        boxhandle = FIGM.uic.score.checksavecmnds;
        flagname = 'ison_checksavecmnds';
    case ('checksavelog')
        boxhandle = FIGM.uic.score.checksavelog;
        flagname = 'ison_checksavelog';
    case ('buildasyougo')
        boxhandle = FIGM.uic.behav.buildasyougo;
        flagname = 'ison_bayg';
    case ('inclstartsbefore')
        boxhandle = FIGM.uic.nandm.marksinclstartsbefore;
        flagname = 'val_inclstartsbefore';
    case ('inclstopsafter')
        boxhandle = FIGM.uic.nandm.marksinclstopsafter;
        flagname = 'val_inclstopsafter';
end
if (nargin < 3)
    flagvalue = get(boxhandle,'value');
else
    set(boxhandle,'value',flagvalue);
end
setstoreddata(FIGM.FFLh,[],flagname,flagvalue);

%========================================
function[] = setcurrframe(FIGM,currframe)
%%%-----------------------------------------------------------------
%%% Called by:  figurekeypressfcn, jumptoframe, setvarsforvideoload,
%%% timertickfcn
%%%-----------------------------------------------------------------
DAT = getstoreddata(FIGM.DATh);
set(FIGM.uic.score.currframe,'string',num2str(currframe));
currtime = currframe/(DAT.vfpsoi*60);
set(FIGM.uic.score.currtime,'string',mintominsec(currtime));

%==========================================
function[vfinput] = setfilenumbers(vfinput)
%%%-------------------------------------------
%%% Called by:  bc_newvars, loadvideofrominput
%%%-------------------------------------------
if (~isfield(vfinput,'loadflag'))
    vfinput.loadflag = 1;
end
if (vfinput.loadflag == 1)
    switch (vfinput.vtype)
        case ('NONE')
            %%% TO DO:  does vtype='NONE' ever try to access these variables?
            vfinput.vfilenums = [];
            vfinput.vframenums = [];
            vfinput.vframemax = vfinput.vnumend - vfinput.vnumstart + 1; % Inf
            vfinput.vfsrcindex = [];
        otherwise
            vfinput.vfilenums = (1:vfinput.vnummax)';
            framenums = (vfinput.vnumstart:vfinput.vnumend) - vfinput.vnumstart + 1;
            vfinput.vframenums = ones(vfinput.vnummax,1)*nan;
            vfinput.vframenums(vfinput.vnumstart:vfinput.vnumend) = framenums';
            vfinput.vframemax = nanmax(vfinput.vframenums);
            if (isempty(vfinput.vframemax) || isnan(vfinput.vframemax))
                vfinput.vframemax = 0;
            end
            vfinput.vfsrcindex = ones(size(vfinput.vfilenums,1),1);
    end
end

%==================================
function[] = setmark(FIGM,marktype)
%%%---------------------------------------
%%% Called by:  Set BUTTONS in NANDM panel
%%%---------------------------------------
DAT = getstoreddata(FIGM.DATh);
if (size(DAT.markslog.framenum,1) > 0)
    marksindex = get(FIGM.uic.nandm.markslog,'value');
    switch (marktype)
        case ('start')
            DAT.markslog.startindex = marksindex;
        case ('align')
            DAT.markslog.alignindex = marksindex;
        case ('end')
            DAT.markslog.endindex = marksindex;
    end
    setstoreddata(FIGM.DATh,DAT);
    updatemarkslog(FIGM);
    setmsg(FIGM,'mark set');
else
    setmsg(FIGM,'no marks present');
end

%================================
function[] = setmsg(FIGM,msgtext)
%%%--------------------------------
%%% Called by:  (many subfunctions)
%%%--------------------------------
set(FIGM.uic.score.msg,'string',msgtext);
drawnow;

%================================================
function[] = setoverwritemsg(FIGM,overwritevalue)
%%%------------------------------
%%% Called by:  dosetoverwritemsg
%%%------------------------------
if (nargin < 2)
    overwritevalue = get(FIGM.uic.behav.overwrite,'value');
end
switch (overwritevalue)
    case (0)
        set(FIGM.uic.score.overwritemsg,'string','');
        lastovframe = 0;
    case (1)
        set(FIGM.uic.score.overwritemsg,'string','OVERWRITE LOG IS ON');
        currframe = str2num(get(FIGM.uic.score.currframe,'string'));
        lastovframe = currframe;
end
setstoreddata(FIGM.FFLh,[],'ison_overwrite',overwritevalue);
setstoreddata(FIGM.FFLh,[],'val_lastovframe',lastovframe);

%==========================================
function[] = setplotcolor(FIGM,callbackvar)
%%%---------------------------------------------------------------------
%%% Called by:  Colored BUTTONS in ANALY panel, and docustomcolorrequest
%%%---------------------------------------------------------------------
isempty_cmnds = getstoreddata(FIGM.FFLh,'isempty_cmnds');
if (isempty_cmnds == 0)
    listvalue = get(FIGM.uic.analy.behaviorslist,'value');
    uc = getstoreddata(FIGM.DATh,'uc');
    uc.plotclr(listvalue,:) = callbackvar;
    setstoreddata(FIGM.DATh,[],'uc',uc);
    blist = createbehaviorlist(uc);
    set(FIGM.uic.analy.behaviorslist,'string',blist);
    currclr = uc.plotclr(listvalue,:);
    set(FIGM.uic.analy.colordisplay,'backgroundcolor',currclr);
    setmsg(FIGM,'plot color updated');
end

%======================================
function[FIGM] = setswitchhandles(FIGM)
%%%------------------------
%%% Called by:  initmainfig
%%%------------------------
disabletypes = {'pushbutton';'togglebutton';'edit';'checkbox'};
swh.names = fieldnames(FIGM.uic.swtch);
swh.enable = [];
for si = 1:size(swh.names,1)
    section = FIGM.uic.(swh.names{si});
    sectionfields = fieldnames(section);
    allinsection = [];
    for fi = 1:size(sectionfields,1)
        allinsection = [allinsection;section.(sectionfields{fi})];
    end
    if (strcmp('score',swh.names{si}))
        visibleset = [];
    else
        visibleset = allinsection;
        ax_index = strmatch('axes',get(allinsection,'type'),'exact');
        if (~isempty(ax_index))
            axinsection = allinsection(ax_index);
            for ai = 1:size(axinsection,1)
                axobjs = get(axinsection(ai),'children');
                visibleset = [visibleset; axobjs];
            end
        end
    end
    swh.visible.(swh.names{si}) = visibleset;
    ui_index = strmatch('uicontrol',get(allinsection,'type'),'exact');
    uiinsection = allinsection(ui_index);
    for di = 1:size(disabletypes,1)
        di_index = strmatch(disabletypes{di},get(uiinsection,'style'),'exact');
        swh.enable = [swh.enable;uiinsection(di_index)];
    end
end
FIGM.swh = swh;

%===========================================
function[FFL] = settimeroffplayoff(FIGM,FFL)
%%%-----------------------------------------------------------
%%% Called by:  doswitchpanel, figurekeypressfcn, timertickfcn
%%%-----------------------------------------------------------
if (nargin < 2); FFL = getstoreddata(FIGM.FFLh); end
oldplaystatus = FFL.isplaying;
FFL.isplaying = 0;
setstoreddata(FIGM.FFLh,FFL);
turntimeroff(FIGM.tim);
if (oldplaystatus == 1)
    updateframe(FIGM);
    DAT = getstoreddata(FIGM.DATh);
    playtime = toc;
    playtime = playtime - 1/DAT.vfpstp;
    endframe = str2num(get(FIGM.uic.score.currframe,'string'));
    realtime = (endframe-FFL.val_startframe)/(DAT.vfpstp*DAT.fnumincr);
    s = formatvarfortext(FIGM,'realdur',realtime);
    set(FIGM.uic.score.realdur,'string',s);
    s = formatvarfortext(FIGM,'playdur',playtime);
    set(FIGM.uic.score.playdur,'string',s);
    set(FIGM.uic.score.playing,'string','stopped');
    setstoreddata(FIGM.TFLh,[],'do_dispraw',0);
    setstoreddata(FIGM.TFLh,[],'do_dispfull',0);
end

%=====================================
function[] = setvarsforvideoload(FIGM)
%%%---------------------------------------------------
%%% Function sets period for timer, current frame = 1,
%%% and video-loaded flag = 1.
%%% Called by:  acceptvideoinput, loadvideofromlog
%%%---------------------------------------------------
DAT = getstoreddata(FIGM.DATh);
set(FIGM.tim,'period',(round(1000/DAT.vfpstp)/1000));
set(FIGM.uic.score.playspeed,'string','normal');
FFL = getstoreddata(FIGM.FFLh);
FFL.val_playspeed = 'normal';
setstoreddata(FIGM.FFLh,FFL);
setcurrframe(FIGM,1);

%================================
function[] = setvtype(FIGM,vtype)
%%%-----------------------------------
%%% Called by:  dosetvtype, putvfinput
%%%-----------------------------------
oldvtype = getstoreddata(FIGM.FFLh,'val_videotype');
CON = getstoreddata(FIGM.CONh);
if (~strcmp(vtype,oldvtype))
    switch (vtype)
        case ('NONE')
            set(FIGM.uic.files.vinputpathlabel,'string','Source desc.');
            set(FIGM.uic.files.vinputprefixlabel,'style','text');
            set(FIGM.uic.files.vinputprefixlabel,'string','');
            set(FIGM.uic.files.vinputprefixlabel,'backgroundcolor',CON.clr.frame2);
            set(FIGM.uic.files.vinputprefix,'style','text','foregroundcolor','w');
            set(FIGM.uic.files.vinputfpsoilabel,'string','FPS of files');
            set(FIGM.uic.files.vinputfpsoi,'position',[.265 .665 .03 .03]);
            set(FIGM.uic.files.vinputnumstartlabel,'string','');
            set(FIGM.uic.files.vinputnumstart,'style','text','foregroundcolor','w');
            set(FIGM.uic.files.vinputnumendlabel,'string','');
            set(FIGM.uic.files.vinputnumend,'style','text','foregroundcolor','w');
            set(FIGM.uic.files.vinputinclall,'style','text');
            set(FIGM.uic.files.vinputinclalllabel,'foregroundcolor','w');
        case ('JPG')
            set(FIGM.uic.files.vinputpathlabel,'string','Directory');
            set(FIGM.uic.files.vinputprefixlabel,'style','pushbutton');
            set(FIGM.uic.files.vinputprefixlabel,'string','File prefix');
            set(FIGM.uic.files.vinputprefixlabel,'backgroundcolor',CON.clr.button1);
            set(FIGM.uic.files.vinputprefix,'style','edit','foregroundcolor','k');
            set(FIGM.uic.files.vinputfpsoilabel,'string','FPS of files');
            set(FIGM.uic.files.vinputfpsoi,'position',[.265 .665 .03 .03]);
            set(FIGM.uic.files.vinputnumstartlabel,'string','Include files');
            set(FIGM.uic.files.vinputnumstart,'style','edit','foregroundcolor','k');
            set(FIGM.uic.files.vinputnumendlabel,'string','to');
            set(FIGM.uic.files.vinputnumend,'style','edit','foregroundcolor','k');
            set(FIGM.uic.files.vinputinclall,'style','checkbox');
            set(FIGM.uic.files.vinputinclalllabel,'foregroundcolor','k');
        otherwise
            set(FIGM.uic.files.vinputpathlabel,'string','Directory');
            set(FIGM.uic.files.vinputprefixlabel,'style','pushbutton');
            set(FIGM.uic.files.vinputprefixlabel,'string','File name');
            set(FIGM.uic.files.vinputprefixlabel,'backgroundcolor',CON.clr.button1);
            set(FIGM.uic.files.vinputprefix,'style','edit','foregroundcolor','k');
            set(FIGM.uic.files.vinputfpsoilabel,'string','');
            set(FIGM.uic.files.vinputfpsoi,'position',[.265 -.665 .03 .03]);
            set(FIGM.uic.files.vinputnumstartlabel,'string','Include frames');
            set(FIGM.uic.files.vinputnumstart,'style','edit','foregroundcolor','k');
            set(FIGM.uic.files.vinputnumendlabel,'string','to');
            set(FIGM.uic.files.vinputnumend,'style','edit','foregroundcolor','k');
            set(FIGM.uic.files.vinputinclall,'style','checkbox');
            set(FIGM.uic.files.vinputinclalllabel,'foregroundcolor','k');
    end
    checkmodules('setvtype',FIGM,vtype);
    setstoreddata(FIGM.FFLh,[],'val_videotype',vtype);
end
setuivalue(FIGM.uic.files.vtype,vtype);

%=======================================
function[] = setvideoloaded(FIGM,status)
%%%----------------------------------------------------------------------
%%% Called by:  acceptvideoinput, clearvideo, initvideo, loadvideofromlog
%%%----------------------------------------------------------------------
setstoreddata(FIGM.FFLh,[],'isloaded_video',status);
CON = getstoreddata(FIGM.CONh);
if (status == 1)
    clr = CON.clr.loaded;
elseif (status == 0)
    clr = CON.clr.none;
end
set(FIGM.uic.score.videobuttonsflag,'foregroundcolor',clr);

%=============================================
function[] = storecfinfo(FIGM,cfinput,ucinput)
%%%-------------------------------------------------------------------------
%%% Called by:  acceptloginput, buildfulllog, doclearcommandset, doclearlog,
%%% doswitchpanel, loadcommandsfile, savecommandsfile, switchbuildasyougo
%%%-------------------------------------------------------------------------
DAT = getstoreddata(FIGM.DATh);
DAT.cpath = cfinput.cpath;
DAT.cfilename = cfinput.cfilename;
DAT.uc.subj1name = cfinput.subj1name;
DAT.uc.subj2name = cfinput.subj2name;
DAT.uc.simbehav = cfinput.simbehav;
setstoreddata(FIGM.DATh,DAT);
if (nargin >= 3)
    DAT.uc.subj1name = ucinput.subj1name;
    DAT.uc.subj2name = ucinput.subj2name;
    DAT.uc.bchar = ucinput.bchar;
    DAT.uc.echar = ucinput.echar;
    DAT.uc.subj = ucinput.subj;
    DAT.uc.desc = ucinput.desc;
    DAT.uc.simbehav = ucinput.simbehav;
    if (isfield(ucinput,'plotorder'))
        DAT.uc.plotorder = ucinput.plotorder;
        DAT.uc.plotclr = ucinput.plotclr;
    end
    setstoreddata(FIGM.DATh,DAT);
    switchnchar(FIGM,ucinput.nchars);
    DAT = getstoreddata(FIGM.DATh);
end
isfrom_cmnds = getstoreddata(FIGM.FFLh,'isfrom_cmnds');
if (strmatch('log',isfrom_cmnds,'exact'))
    set(FIGM.uic.files.ccurrfile,'string','(from log file)');
    s = formatvarfortext(FIGM,'ccurrinfo',DAT);
    set(FIGM.uic.files.ccurrinfo,'string',s);
elseif (strmatch('cmd',isfrom_cmnds,'exact'))
    CON = getstoreddata(FIGM.CONh);
    filename = ['commands',cfinput.cfilename];
    pathandfile = [cfinput.cpath,CON.slash,filename];
    set(FIGM.uic.files.ccurrfile,'string',[pathandfile,'.mat']);
    s = formatvarfortext(FIGM,'ccurrinfo',DAT);
    set(FIGM.uic.files.ccurrinfo,'string',s);
else
    set(FIGM.uic.files.ccurrfile,'string','');
    set(FIGM.uic.files.ccurrinfo,'string','');
end

%====================================
function[] = storelfdata(FIGM,lfdata)
%%%----------------------------------------
%%% Called by:  acceptloginput, savelogfile
%%%----------------------------------------
DAT = getstoreddata(FIGM.DATh);
DAT.rawlog = lfdata.rawlog;
DAT.rawlogframe = lfdata.rawlogframe;
DAT.fulllog = lfdata.fulllog;
DAT.noteslog = lfdata.noteslog;
DAT.markslog = lfdata.markslog;
DAT.posnlog = lfdata.posnlog;
setstoreddata(FIGM.DATh,DAT);
s = formatvarfortext(FIGM,'lcurrinfo',lfdata);
set(FIGM.uic.files.lcurrinfo,'string',s);

%=====================================
function[] = storelfinfo(FIGM,lfinput)
%%%----------------------------------------------------
%%% Called by:  acceptloginput, doclearlog, savelogfile
%%%----------------------------------------------------
CON = getstoreddata(FIGM.CONh);
DAT = getstoreddata(FIGM.DATh);
DAT.lpath = lfinput.lpath;
DAT.lfilename = lfinput.lfilename;
setstoreddata(FIGM.DATh,DAT);
if (~isempty(lfinput.lpath))
    filename = ['log',lfinput.lfilename];
    pathandfile = [lfinput.lpath,CON.slash,filename];
    set(FIGM.uic.files.lcurrfile,'string',[pathandfile,'.mat']);
else
    set(FIGM.uic.files.lcurrfile,'string','');
end

%======================================================
function[FIGM] = storeprogramdata(FIGM,CON,DAT,FFL,TFL)
%%%------------------------
%%% Called by:  initmainfig
%%%------------------------
objh = [];
uicsets = fieldnames(FIGM.uic);
uicsetindex = 1;
subsetindex = 1;
while (size(objh,1) < 4)
    if (subsetindex == 1)
        setnames = fieldnames(FIGM.uic.(uicsets{uicsetindex}));
        maxindex = size(setnames,1);
    end
    objh = [objh;FIGM.uic.(uicsets{uicsetindex}).(setnames{subsetindex})];
    subsetindex = subsetindex + 1;
    if (subsetindex > maxindex)
        subsetindex = 1;
        uicsetindex = uicsetindex + 1;
    end
end
FIGM.CONh = objh(1);
FIGM.DATh = objh(2);
FIGM.FFLh = objh(3);
FIGM.TFLh = objh(4);
setstoreddata(FIGM.CONh,CON);
setstoreddata(FIGM.DATh,DAT);
setstoreddata(FIGM.FFLh,FFL);
setstoreddata(FIGM.TFLh,TFL);

%=================================
function[] = storevfinfo(FIGM,src)
%%%--------------------------------------------------
%%% Function copies src.<> to DAT.<>, thereby
%%% storing video file set info in data structure.
%%% Called by:  acceptlogvideoinput, acceptvideoinput
%%%--------------------------------------------------
DAT = getstoreddata(FIGM.DATh);
CON = getstoreddata(FIGM.CONh);
vfields = CON.set.vfields;			% input "src" should have these fields
for vi = 1:size(vfields,1)
    DAT.(vfields{vi}) = src.(vfields{vi});
end
if isfield(src,'nhiddenframes')
    DAT.nhiddenframes = src.nhiddenframes;
else
    DAT.nhiddenframes = 0;
end
setstoreddata(FIGM.DATh,DAT);

%====================================
function[] = switchbuildasyougo(FIGM)
%%%----------------------------------------------------
%%% Called by:  Build as you go CHECKBOX in BEHAV panel
%%%----------------------------------------------------
ison_bayg = getstoreddata(FIGM.FFLh,'ison_bayg');
switch (ison_bayg)
    case (1)
        currframe = str2num(get(FIGM.uic.score.currframe,'string'));
        set(FIGM.uic.score.ongoinglabel,'string','Ongoing behavior:');
        set(FIGM.uic.score.ongoing,'string','');
        setstoreddata(FIGM.FFLh,[],'val_lastbgframe',currframe + 1);
        cfinput = getcfinput(FIGM);
        storecfinfo(FIGM,cfinput);
        initfulllog(FIGM);
        growfulllog(FIGM,1,currframe);
        updatefulllog(FIGM);
    case (0)
        set(FIGM.uic.score.ongoinglabel,'string','Last command:');
        set(FIGM.uic.score.ongoing,'string','');
end

%=======================================
function[] = switchnchar(FIGM,newnchars)
%%%--------------------------------------------------
%%% Called by:  changenchar, putcfinput2, storecfinfo
%%%--------------------------------------------------
DAT = getstoreddata(FIGM.DATh);
if (nargin > 1)
    DAT.uc.nchars = newnchars;
    setstoreddata(FIGM.DATh,DAT);
end
setuivalue(FIGM.uic.cmnds.nchar,num2str(DAT.uc.nchars));

%==================================
function[] = timertickfcn(hco,user)
%%%-----------------------------------------------------
%%% Called by:  Matlab whenever timer is running, once
%%% every period of the timer; timer object handle is
%%% FIGM.tim/TH.tim, property 'period' determines period
%%%-----------------------------------------------------
try
TH = getstoreddata(hco);
FIGM = getstoreddata(TH.fig);
DAT = getstoreddata(TH.DATh);
currframe = str2num(get(FIGM.uic.score.currframe,'string'));
if (currframe + DAT.fnumincr <= DAT.vframemax)
    currframe = currframe + DAT.fnumincr;
    setcurrframe(FIGM,currframe);
    updateframe(FIGM);
    if (currframe == getstoreddata(TH.FFLh,'val_startframe'))
        tic;
    end
else
    settimeroffplayoff(FIGM);
end
TFL = getstoreddata(TH.TFLh);
if ((TFL.do_dispraw == 1) || (TFL.do_dispfull == 1))
    if (TFL.do_dispraw == 1)
        displayrawlog(FIGM);
        TFL = setstoreddata(TH.TFLh,TFL,'do_dispraw',0);
    end
    if (TFL.do_dispfull == 1)
        displayfulllog(FIGM);
        setstoreddata(TH.TFLh,TFL,'do_dispfull',0);
    end
end
catch
    disp('Error in timer tick!');
    le=lasterror();
    disp(le.message);
end
%==================================
function[] = updatecmndsflags(FIGM)
%%%--------------------------------
%%% Called by:  displayusercommands
%%%--------------------------------
DAT = getstoreddata(FIGM.DATh);
isempty_cmnds = isempty(DAT.uc.bchar);
setstoreddata(FIGM.FFLh,[],'isempty_cmnds',isempty_cmnds);
CON = getstoreddata(FIGM.CONh);
if (isempty_cmnds == 1)
    set(FIGM.uic.score.cmndsbuttonsflag,'foregroundcolor',CON.clr.none);
elseif (isempty_cmnds == 0)
    set(FIGM.uic.score.cmndsbuttonsflag,'foregroundcolor',CON.clr.loaded);
end

%=============================
function[] = updateframe(FIGM)
%%%------------------------------------------------------------
%%% Called by:  acceptloginput, figurekeypressfcn, jumptoframe,
%%% settimeroffplayoff, timertickfcn
%%%------------------------------------------------------------
DAT = getstoreddata(FIGM.DATh);
currframe = str2num(get(FIGM.uic.score.currframe,'string'));
if (~strcmp('NONE',DAT.vtype))
    oneframe = [];
    if (~isempty(currframe))
        oneframe = getvideoframe(FIGM,currframe);
    else
        killvobj(FIGM);
    end
    set(FIGM.uic.score.image,'cdata',oneframe);
    checkmodules('updateposns',FIGM,currframe);
    drawnow;
end

%===============================
function[] = updatefulllog(FIGM)
%%%------------------------------------------------------------------------------
%%% Called by:  buildfulllog, clearfulllog, figurekeypressfcn, switchbuildasyougo
%%%------------------------------------------------------------------------------
DAT = getstoreddata(FIGM.DATh);
DAT = makefulllogtext(DAT);
setstoreddata(FIGM.DATh,DAT);
isplaying = getstoreddata(FIGM.FFLh,'isplaying');
if (isplaying == 1)
    setstoreddata(FIGM.TFLh,[],'do_dispfull',1);
else
    displayfulllog(FIGM);
end

%=====================================
function[] = updatelogemptyflags(FIGM)
%%%----------------------------------------------------------------------------
%%% Called by:  displaymarkslog, displaynoteslog, displayposnlog, displayrawlog
%%%----------------------------------------------------------------------------
DAT = getstoreddata(FIGM.DATh);
isempty_slog = isempty(DAT.rawlogframe);
isempty_nlog = isempty(DAT.noteslog);
isempty_mlog = (size(DAT.markslog.framenum,1) <= 2);
isempty_plog = isempty(DAT.posnlog);
isempty_log = min([isempty_slog isempty_nlog isempty_mlog isempty_plog]);
setstoreddata(FIGM.FFLh,[],'isempty_slog',isempty_slog);
setstoreddata(FIGM.FFLh,[],'isempty_nlog',isempty_nlog);
setstoreddata(FIGM.FFLh,[],'isempty_mlog',isempty_mlog);
setstoreddata(FIGM.FFLh,[],'isempty_plog',isempty_plog);
setstoreddata(FIGM.FFLh,[],'isempty_log',isempty_log);
CON = getstoreddata(FIGM.CONh);
if (isempty_log == 1)
    set(FIGM.uic.score.logbuttonsflag,'foregroundcolor',CON.clr.none);
elseif (isempty_log == 0)
    set(FIGM.uic.score.logbuttonsflag,'foregroundcolor',CON.clr.loaded);
end

%=========================================================
function[] = updatelogsavedflag(FIGM,logjustsavedorloaded)
%%%-----------------------------------------------------------------------------
%%% Called by:  acceptvideoinput, clearvideo, displaymarkslog, displaynoteslog,
%%% displayposnlog, displayrawlog, displayusercommands, loadlogfile, savelogfile
%%% Note:  should always be called after isemptyflags are updated
%%%-----------------------------------------------------------------------------
if (nargin < 2); logjustsavedorloaded = 0; end
if isempty(logjustsavedorloaded); logjustsavedorloaded = 0; end
issaved_log = logjustsavedorloaded;
isloaded_video = getstoreddata(FIGM.FFLh,'isloaded_video');
isempty_cmnds = getstoreddata(FIGM.FFLh,'isempty_cmnds');
isempty_log = getstoreddata(FIGM.FFLh,'isempty_log');
if ((isloaded_video == 0) && (isempty_cmnds == 1) && (isempty_log == 1))
    issaved_log = 1;
end
setstoreddata(FIGM.FFLh,[],'issaved_log',issaved_log);

%============================
function[] = updatemark(FIGM)
%%%--------------------------------------------------------------
%%% Called by:  Update BUTTON below marks log list in NANDM panel
%%%--------------------------------------------------------------
marksindex = get(FIGM.uic.nandm.markslog,'value');
DAT = getstoreddata(FIGM.DATh);
framename = DAT.markslog.framename{marksindex};
frameisfixed = ~isempty(strmatch(framename,{'video start';'video end'},'exact'));
if (frameisfixed == 1)
    setmsg(FIGM,'error:  video start and end marks cannot be changed');
else
    newmarkframe = str2num(get(FIGM.uic.nandm.marksframe,'string'));
    newmarkname = get(FIGM.uic.nandm.marksname,'string');
    if (ismember(newmarkframe,DAT.markslog.framenum([1:marksindex-1,marksindex+1:end])))
        setmsg(FIGM,'error:  mark at this frame already exists');
    elseif (~isempty(strmatch(newmarkname,DAT.markslog.framename([1:marksindex-1,marksindex+1:end]),'exact')))
        setmsg(FIGM,'error:  mark name must be unique');
    else
        DAT.markslog.framenum(marksindex) = newmarkframe;
        DAT.markslog.framename{marksindex} = newmarkname;
        aw = getawframes(DAT.markslog);
        [y,yi] = sort(DAT.markslog.framenum);
        DAT.markslog.framenum = DAT.markslog.framenum(yi);
        DAT.markslog.framename = DAT.markslog.framename(yi);
        DAT.markslog = indexawframes(DAT.markslog,aw);
        setstoreddata(FIGM.DATh,DAT);
        updatemarkslog(FIGM);
        setmsg(FIGM,'mark updated');
    end
end

%================================
function[] = updatemarkslog(FIGM)
%%%---------------------------------------------------
%%% Called by:  addmark, addvideofiles, checkmarkslog,
%%% deletemark, setmark, updatemark
%%%---------------------------------------------------
DAT = getstoreddata(FIGM.DATh);
DAT = makemarkslogtext(DAT);
setstoreddata(FIGM.DATh,DAT);
displaymarkslog(FIGM);
displaymarkindices(FIGM);

%============================
function[] = updatenote(FIGM)
%%%--------------------------------------------------------------
%%% Called by:  Update BUTTON below notes log list in NANDM panel
%%%--------------------------------------------------------------
isempty_nlog = getstoreddata(FIGM.FFLh,'isempty_nlog');
if (isempty_nlog == 0)
    notesindex = get(FIGM.uic.nandm.noteslog,'value');
    if (notesindex > 0)
        DAT = getstoreddata(FIGM.DATh);
        newnote = get(FIGM.uic.nandm.entrytext,'string');
        DAT.noteslog{notesindex} = newnote;
        setstoreddata(FIGM.DATh,DAT);
        displaynoteslog(FIGM);
        setmsg(FIGM,'note updated');
    end
end

%================================
function[] = updatenoteslog(FIGM)
%%%------------------------------------------
%%% Called by:  acceptloginput, clearnoteslog
%%%------------------------------------------
displaynoteslog(FIGM);

%===================================
function[] = updateongoing(FIGM,key)
%%%------------------------------
%%% Called by:  figurekeypressfcn
%%%------------------------------
if (nargin < 2); key = ''; end
DAT = getstoreddata(FIGM.DATh);
isbchar = (~isempty(strmatch(key,DAT.uc.bchar,'exact')));
isechar = (~isempty(strmatch(key,DAT.uc.echar,'exact')));
isfchar = (~isempty(strmatch(key,DAT.fixed.char,'exact')));
if ((isbchar == 1) || (isechar == 1))
    ison_bayg = getstoreddata(FIGM.FFLh,'ison_bayg');
    if (ison_bayg == 1)
        ongoingchars = DAT.uc.bchar(DAT.openstates);
        n = size(ongoingchars,1);
        if (n > 0)
            ongoingtext = reshape([cell2mat(ongoingchars)';blanks(n)],1,n*2);
        else
            ongoingtext = '';
        end
        set(FIGM.uic.score.ongoing,'string',ongoingtext);
    else
        set(FIGM.uic.score.ongoing,'string',key);
    end
    set(FIGM.uic.score.ongoing2,'string','');
elseif (isfchar == 1)
    % do nothing
else
    set(FIGM.uic.score.ongoing2,'string',['unknown command:  ',key]);
end

%=================================
function[] = updateplotcolor(FIGM)
%%%--------------------------------------------------------
%%% Called by:  Behaviors list in ANALY panel (selecting an
%%% item in list, scrolling in list)
%%%--------------------------------------------------------
listvalue = get(FIGM.uic.analy.behaviorslist,'value');
uc = getstoreddata(FIGM.DATh,'uc');
currclr = uc.plotclr(listvalue,:);
set(FIGM.uic.analy.colordisplay,'backgroundcolor',currclr);

%==============================================
function[] = updateplotparams(FIGM,callbackvar)
%%%------------------------------------------------------------
%%% Called by:  # of panels, # of pages and # of minutes FIELDS
%%% in ANALY panels (changes to inputs in these fields)
%%%------------------------------------------------------------
varnames = {'npanels';'npages';'nmins'};
vari = strmatch(callbackvar,varnames,'exact');
flag_npanels = getstoreddata(FIGM.uic.analy.npanels) + 1;
flag_npages = getstoreddata(FIGM.uic.analy.npages) + 1;
flag_nmins = getstoreddata(FIGM.uic.analy.nmins) + 1;
vars = [flag_npanels flag_npages flag_nmins];
vars(vari) = 1;
sortedvars = sort(vars);
for col = 1:3
    index = find(vars == sortedvars(col));
    vars(index) = col;
end
flag_npanels = vars(1);
flag_npages = vars(2);
flag_nmins = vars(3);
setstoreddata(FIGM.uic.analy.npanels,flag_npanels);
setstoreddata(FIGM.uic.analy.npages,flag_npages);
setstoreddata(FIGM.uic.analy.nmins,flag_nmins);

%==============================
function[] = updaterawlog(FIGM)
%%%--------------------------------------------------------
%%% Called by:  acceptloginput, addvideofiles, clearrawlog,
%%% deletefromrawlog, figurekeypressfcn
%%%--------------------------------------------------------
DAT = getstoreddata(FIGM.DATh);
isempty_slog = getstoreddata(FIGM.FFLh,'isempty_slog');
if (isempty_slog == 0)
    [temp,rawindex] = sort(DAT.rawlogframe);
    DAT.rawlog = DAT.rawlog(rawindex);
    DAT.rawlogframe = DAT.rawlogframe(rawindex);
end
DAT = makerawlogtext(DAT);
setstoreddata(FIGM.DATh,DAT);
isplaying = getstoreddata(FIGM.FFLh,'isplaying');
if (isplaying == 1)
    setstoreddata(FIGM.TFLh,[],'do_dispraw',1);
else
    displayrawlog(FIGM);
end

%===================================
function[] = updateusercommand(FIGM)
%%%----------------------------------------------------------------
%%% Called by:  Update BUTTON below command set list in CMNDS panel
%%%----------------------------------------------------------------
ucindex = get(FIGM.uic.cmnds.uclist,'value');
DAT = getstoreddata(FIGM.DATh);
bchartochange = DAT.uc.bchar{ucindex};
echartochange = DAT.uc.echar{ucindex};
newbchar = get(FIGM.uic.cmnds.bchar,'string');
newechar = get(FIGM.uic.cmnds.echar,'string');
if (~strcmp(bchartochange,newbchar) || ~strcmp(echartochange,newechar))
    ucindex = checkucagainstlog(DAT,ucindex);
end
if (~isempty(ucindex))
    addusercommand(FIGM,ucindex);
else
    setmsg(FIGM,'error:  command cannot be changed while used in score log');
end

%=======================================
function[] = writecommandstextfile(FIGM)
%%%-----------------------------
%%% Called by:  savecommandsfile
%%%-----------------------------
CON = getstoreddata(FIGM.CONh);
DAT = getstoreddata(FIGM.DATh);
filename = ['commands',DAT.cfilename];
pathandfile = [DAT.cpath,CON.slash,filename];
fid = fopen([pathandfile,'.txt'],'wt');
fprintf(fid,'%s\n','scorevideo COMMAND SET AND SETTINGS');
fprintf(fid,'%s\n',['File:  ',filename,'.mat']);
fprintf(fid,'\n');
fprintf(fid,'%s\n','VIDEO PLAY COMMANDS (fixed)');
fprintf(fid,'%s\n','-------------------------------');
fprintf(fid,'%s\n','command|description');
fprintf(fid,'%s\n','-------------------------------');
for row = 1:size(DAT.fixed.char,1)
    fprintf(fid,'%s\n',[DAT.fixed.char{row},'       ',DAT.fixed.desc{row}]);
end
fprintf(fid,'%s\n','-------------------------------');
fprintf(fid,'\n');
fprintf(fid,'%s\n','SCORING COMMANDS (user-defined)');
fprintf(fid,'%s\n','-------------------------------');
fprintf(fid,'%s\n','start|stop|subject|description');
fprintf(fid,'%s\n','-------------------------------');
uc = DAT.uc;
echarindex = find(cellfun('isempty',uc.echar));
blankchar = blanks(uc.nchars);
uc.echar(echarindex) = {blankchar};
uclisttxt = createlistboxtext(uc,6);
for row = 1:size(uclisttxt,1)
    fprintf(fid,'%s\n',uclisttxt{row});
end
fprintf(fid,'%s\n','-------------------------------');
fprintf(fid,'%s\n',['subject 1:  ',DAT.uc.subj1name]);
fprintf(fid,'%s\n',['subject 2:  ',DAT.uc.subj2name]);
fprintf(fid,'%s\n','subj#:  0=either  1=subject1  2=subject2  3=both');
fprintf(fid,'%s\n',['No. of simultaneous behaviors:  ', ...
    DAT.ucparams.simbehav{DAT.uc.simbehav}]);
fclose(fid);

%==================================
function[] = writelogtextfile(FIGM)
%%%------------------------
%%% Called by:  savelogfile
%%%------------------------
CON = getstoreddata(FIGM.CONh);
DAT = getstoreddata(FIGM.DATh);
filename = ['log',DAT.lfilename];
pathandfile = [DAT.lpath,CON.slash,filename];
fid = fopen([pathandfile,'.txt'],'wt');
fprintf(fid,'%s\n','scorevideo LOG');
fprintf(fid,'%s\n',['File:  ',filename,'.mat']);
fprintf(fid,'\n');
fprintf(fid,'%s\n','VIDEO FILE SET');
fprintf(fid,'%s\n',['Videotype:  ',DAT.vtype]);
fprintf(fid,'%s\n',['Directory:  ',DAT.vpath]);
fprintf(fid,'%s\n','Video file set:');
for vi = 1:size(DAT.vprefixes,1)
    fprintf(fid,'%s\n',['   ',DAT.vprefixes{vi},' ', ...
        num2str(DAT.vnumstarts(vi)),'-',num2str(DAT.vnumends(vi))]);
end
fprintf(fid,'%s\n',['Play duration (min):  ',num2str(DAT.fseldur,'%3.3f')]);
fprintf(fid,'%s\n',['Frames/sec of files:  ',num2str(DAT.vfpsoi)]);
fprintf(fid,'%s\n',['No. of subjects:  ',num2str(DAT.vnsubj)]);
fprintf(fid,'\n');
fprintf(fid,'%s\n','COMMAND SET AND SETTINGS');
fprintf(fid,'%s\n','-------------------------------');
fprintf(fid,'%s\n','start|stop|subject|description');
fprintf(fid,'%s\n','-------------------------------');
uc = DAT.uc;
echarindex = find(cellfun('isempty',uc.echar));
blankchar = blanks(uc.nchars);
uc.echar(echarindex) = {blankchar};
uclisttxt = createlistboxtext(uc,6);
for row = 1:size(uclisttxt,1)
    fprintf(fid,'%s\n',uclisttxt{row});
end
fprintf(fid,'%s\n','-------------------------------');
fprintf(fid,'%s\n',['subject 1:  ',DAT.uc.subj1name]);
fprintf(fid,'%s\n',['subject 2:  ',DAT.uc.subj2name]);
fprintf(fid,'%s\n','subj#:  0=either  1=subject1  2=subject2  3=both');
fprintf(fid,'%s\n',['No. of simultaneous behaviors:  ',DAT.ucparams.simbehav{DAT.uc.simbehav}]);
fprintf(fid,'\n');
fprintf(fid,'%s\n','RAW LOG');
fprintf(fid,'%s\n','------------------------------------------');
fprintf(fid,'%s\n','frame|time(min:sec)|command');
fprintf(fid,'%s\n','------------------------------------------');
DAT = makerawlogtext(DAT,5);
for row = 1:size(DAT.rawlogtext,1)
    fprintf(fid,'%s\n',DAT.rawlogtext{row});
end
fprintf(fid,'%s\n','------------------------------------------');
fprintf(fid,'\n');
fprintf(fid,'%s\n','FULL LOG');
fprintf(fid,'%s\n','------------------------------------------');
fprintf(fid,'%s\n','frame|time(min:sec)|description|action|subject');
fprintf(fid,'%s\n','------------------------------------------');
DAT = makefulllogtext(DAT,4);
for row = 1:size(DAT.fulllogtext,1)
    fprintf(fid,'%s\n',DAT.fulllogtext{row});
end
fprintf(fid,'%s\n','------------------------------------------');
fprintf(fid,'\n');
fprintf(fid,'%s\n','NOTES');
fprintf(fid,'%s\n','------------------------------------------');
for row = 1:size(DAT.noteslog,1)
    fprintf(fid,'%s\n',DAT.noteslog{row});
end
fprintf(fid,'%s\n','------------------------------------------');
fprintf(fid,'\n');
fprintf(fid,'%s\n','MARKS');
fprintf(fid,'%s\n','------------------------------------------');
fprintf(fid,'%s\n','frame|time(min:sec)|mark name');
fprintf(fid,'%s\n','------------------------------------------');
DAT = makemarkslogtext(DAT,4);
for row = 1:size(DAT.markslogtext,1)
    fprintf(fid,'%s\n',DAT.markslogtext{row});
end
fprintf(fid,'%s\n','------------------------------------------');
fclose(fid);

%==========================================
function[] = writesummarystatsxlsfile(FIGM)
%%%-------------------------------------------------
%%% Called by:  Table to Excel BUTTON in ANALY panel
%%%-------------------------------------------------
isempty_slog = getstoreddata(FIGM.FFLh,'isempty_slog');
if (isempty_slog == 0)
    CON = getstoreddata(FIGM.CONh);
    DAT = getstoreddata(FIGM.DATh);
    plotparams = getplotparams(FIGM);
    [timedata,summarystats] = calcsummarydata(DAT,plotparams);
    subjnames = {'either';DAT.uc.subj1name;DAT.uc.subj2name;'both'};
    ncommands = size(summarystats,1);
    statsdata = cell(ncommands+1,8);
    statsdata{1,1} = 'behavior';
    statsdata{1,2} = 'subject';
    statsdata{1,3} = 'count';
    statsdata{1,4} = '1st occ.';
    statsdata{1,5} = 'mean dur';
    statsdata{1,6} = 'total dur';
    statsdata{1,7} = 'std dur';
    statsdata{1,8} = 'mean isi';
    for ni = 1:ncommands
        statsdata{ni+1,1} = DAT.uc.desc{ni};
        statsdata{ni+1,2} = subjnames{str2double(DAT.uc.subj{ni})+1};
        statsdata{ni+1,3} = num2str(summarystats(ni,1));
        statsdata{ni+1,4} = num2str(summarystats(ni,2),'%3.2f');
        statsdata{ni+1,5} = num2str(summarystats(ni,3),'%3.2f');
        statsdata{ni+1,6} = num2str(summarystats(ni,4),'%3.2f');
        statsdata{ni+1,7} = num2str(summarystats(ni,5),'%3.2f');
        statsdata{ni+1,8} = num2str(summarystats(ni,6),'%3.2f');
    end
    filename = ['stats',DAT.lfilename];
    pathandfile = [DAT.lpath,CON.slash,filename];
    fid = fopen([pathandfile,'.xls'],'wt');
    fprintf(fid,'%s\t\t\t\t\t\t\t%s\n',['SUMMARY STATS for log',DAT.lfilename,'.mat'],'times in sec');
    fprintf(fid,'\n');
    for row = 1:size(statsdata,1)
        fprintf(fid,'%s\t%s\t%s\t%s\t%s\t%s\t%s\t%s\n', ...
            statsdata{row,1},statsdata{row,2},statsdata{row,3},statsdata{row,4}, ...
            statsdata{row,5},statsdata{row,6},statsdata{row,7},statsdata{row,8});
    end
    fclose(fid);
    setmsg(FIGM,[filename,'.xls saved in log directory']);
else
    setmsg(FIGM,'error:  log is empty');
end

%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
%%% Subfunctions:  Program-specific, plotting secondary figures %%%
%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
% Listing:
% function[] = addpagelabel(pagenum,totalpages)
% function[timedata,summarystats] = calcsummarydata(DAT,plotparams)
% function[] = drawrasters(FIGM,timedata,xwidth)
% function[] = drawtable(FIGM,summarystats,plotparams,spnum)
% function[plotparams] = getplotparams(FIGM)
% function[] = plotraster(FIGM)
% function[] = plotrasterandtable(FIGM)
% function[] = plottable(FIGM)

%============================================
function[] = addpagelabel(pagenum,totalpages)
%%%-------------------------------------------
%%% Called by:  plotraster, plotrasterandtable
%%%-------------------------------------------
axes('position',[.05 .03 .9 .03]);
set(gca,'xlim',[0 1],'ylim',[0 1]);
text('position',[1 0],'string',['page ',num2str(pagenum),' of ',num2str(totalpages)], ...
    'horizontalalignment','right');
axis off;

%================================================================
function[timedata,summarystats] = calcsummarydata(DAT,plotparams)
%%%----------------------------------------------------
%%% Called by:  writesummarystatsxlsstable, plotraster,
%%% plotrasterandtable, plottable
%%%----------------------------------------------------
pp = plotparams;
uc = DAT.uc;
blankindex = strmatch(' ',DAT.fulllog.action,'exact');
if (~isempty(blankindex))
    DAT.fulllog.action(blankindex) = {'start'};
end
actions = DAT.fulllog.action;
frames = cell2mat(DAT.fulllog.frame);
charnums = DAT.fulllog.charnum;
types = DAT.fulllog.type;
startindex = strmatch('start',actions,'exact');
stopindex = strmatch('stop',actions,'exact');
allindex = union(startindex,stopindex);
awindex1 = find(frames >= pp.aw_startframe);
awindex2 = find(frames <= pp.aw_endframe);
awindex = intersect(awindex1,awindex2);
allindex = intersect(allindex,awindex);
nbehavs = size(allindex,1);
nlogentries = size(frames,1);
ncommands = size(uc.bchar,1);
timedata = ones(nbehavs,4)*nan;					% cols:  charnum, starttime, stoptime, dur
summarystats = ones(ncommands,6)*nan;				% cols:  count, 1ststart, meandur, totdur, stddur, isidur
for ti = 1:nbehavs						% for each behavior that occurred
    logrow = allindex(ti);					% get fulllog row of start of behavior
    if (~isnan(logrow))
        actiontype = actions{logrow};
        switch (actiontype)
            case ('start')
                timedata(ti,1) = charnums{logrow};			% store index of command (which behavior)
                relframe = frames(logrow) - pp.aw_alignframe + 1;
                reltime = relframe/(pp.fpsoi*60);
                timedata(ti,2) = reltime;				% store start time relative to align mark
                if (strcmp('state',types{logrow}))			% if it's a state, find stop time
                    stoptime = nan;
                    stoprow = logrow + 1;
                    while ((stoprow <= nlogentries) && isnan(stoptime))	% search rows of log for matching stop
                        charsmatch = (charnums{logrow} == charnums{stoprow});
                        charisstop = strcmp(actions{stoprow},'stop');
                        if ((charsmatch == 1) && (charisstop == 1))		% if match
                            stopinallindex = find(allindex == stoprow);
                            if (~isempty(stopinallindex))
                                allindex(stopinallindex) = NaN;
                                timedata(stopinallindex,1) = NaN;
                            end
                            if (pp.inclstopsafter == 0)
                                if (frames(stoprow) > pp.aw_endframe)
                                    timedata(ti,1) = NaN;
                                    stoptime = 0;
                                end
                            end
                            if (isnan(stoptime))
                                relframe = frames(stoprow) - pp.aw_alignframe + 1;
                                reltime = relframe/(pp.fpsoi*60);
                                stoptime = reltime;				% pull stop time relative to align mark
                            end
                        end
                        stoprow = stoprow + 1;
                    end
                    timedata(ti,3) = stoptime;				% store stop time
                end
            case ('stop')
                timedata(ti,1) = charnums{logrow};			% store index of command (which behavior)
                relframe = frames(logrow) - pp.aw_alignframe + 1;
                reltime = relframe/(pp.fpsoi*60);
                timedata(ti,3) = reltime;				% store stop time relative to align mark
                if (strcmp('state',types{logrow}))			% if it's a state, find start time
                    starttime = nan;
                    startrow = logrow - 1;
                    while ((startrow >= 1) && isnan(starttime))		% search rows of log for matching start
                        charsmatch = (charnums{logrow} == charnums{startrow});
                        charisstart = strcmp(actions{startrow},'start');
                        if ((charsmatch == 1) && (charisstart == 1))	% if match
                            if (pp.inclstartsbefore == 0)
                                if (frames(startrow) < pp.aw_startframe)
                                    timedata(ti,1) = NaN;
                                    starttime = 0;
                                end
                            end
                            if (isnan(starttime))
                                relframe = frames(startrow) - pp.aw_alignframe + 1;
                                reltime = relframe/(pp.fpsoi*60);
                                starttime = reltime;				% pull start time relative to align mark
                            end
                        end
                        startrow = startrow - 1;
                    end
                    timedata(ti,2) = starttime;				% store start time
                end
        end
    end
end
removeindex = find(isnan(timedata(:,1)));
if (~isempty(removeindex))
    keepindex = find(~isnan(timedata(:,1)));
    timedata = timedata(keepindex,:);
end
timedata(:,4) = timedata(:,3) - timedata(:,2);			% calculate duration of behavior
for ni = 1:ncommands						% for each behavior in command list
    starts = find(timedata(:,1) == ni);
    if (~isempty(starts))
        numstarts = length(starts);
        earlieststart = min(timedata(starts,2));
        meandur = nanmean(timedata(starts,4));
        totdur = nansum(timedata(starts,4));
        stddur = nanstd(timedata(starts,4));
        if (numstarts > 1)
            isis = timedata(starts(2:end),2) - timedata(starts(1:end-1),3);
            meanisi = nanmean(isis);
        else
            meanisi = NaN;
        end
    else
        numstarts = 0;
        earlieststart = NaN;
        meandur = 0;
        totdur = 0;
        stddur = NaN;
        meanisi = NaN;
    end
    summarystats(ni,1) = numstarts;
    summarystats(ni,2) = earlieststart;
    summarystats(ni,3) = meandur;
    summarystats(ni,4) = totdur;
    summarystats(ni,5) = stddur;
    summarystats(ni,6) = meanisi;
end
summarystats(:,2:6) = summarystats(:,2:6)*60;			% converting times to sec

%============================================================
function[] = drawrasters(FIGM,timedata,plotparams,panelindex)
%%%-------------------------------------------
%%% Called by:  plotraster, plotrasterandtable
%%%-------------------------------------------
DAT = getstoreddata(FIGM.DATh);
subjnames = {'either';DAT.uc.subj1name;DAT.uc.subj2name;'both'};
yticklabels = {};
ncommands = size(plotparams.inclindex,1);
for ui = 1:ncommands
    ucrow = plotparams.inclindex(ui);
    if (plotparams.inclsubjname == 1)
        yticklabels{ui,1} = [DAT.uc.desc{ucrow},'/',subjnames{str2double(DAT.uc.subj{ucrow})+1}];
    elseif (plotparams.inclsubjname == 0)
        yticklabels{ui,1} = DAT.uc.desc{ucrow};
    end
end
nbehavs = size(timedata,1);
xwidth = plotparams.nmins;
xoffset = (plotparams.aw_startframe - plotparams.aw_alignframe)/(plotparams.fpsoi*60);
ny = plotparams.npanels;
for si = 1:ny
    thispanelindex = panelindex(si);
    if (~isnan(thispanelindex))
        subplot(ny,1,si);
        axesposition = get(gca,'position');
        if (thispanelindex == 1)
            if (plotparams.usepanelht == 0)
                set(FIGM.uic.analy.panelht,'string',num2str(axesposition(4),'%3.3f'));
            end
            tempfilename = DAT.lfilename;
            x = find(tempfilename == '_');
            while (~isempty(x))
                tempfilename = [tempfilename(1:x(1)-1),'_-',tempfilename(x(1)+1:end)];
                x = find(tempfilename == '_');
                y = find(tempfilename == '-') - 1;
                x = setdiff(x,y);
            end
            titletext = ['RASTER for log',tempfilename,'.mat'];
            title(titletext);
            text('position',[xwidth+xoffset -1],'string', ...
                ['time 0 = ',DAT.markslog.framename{DAT.markslog.alignindex}], ...
                'horizontalalignment','right');
        end
        xlimits = [xwidth*(thispanelindex-1) xwidth*(thispanelindex)] + xoffset;
        set(gca,'xlim',xlimits);
        set(gca,'ydir','reverse')
        set(gca,'ylim',[0 ncommands+1],'ytick',1:ncommands,'yticklabel',yticklabels);
        if (si == ny); xlabel('time (min)'); end
        if (plotparams.usepanelht == 1)
            axesposition = [axesposition(1) axesposition(2)+axesposition(4)-plotparams.panelht ...
                axesposition(3) plotparams.panelht];
        end
        for ni = 1:nbehavs
            ci = timedata(ni,1);
            yi = find(plotparams.inclindex == ci);
            if (~isempty(yi))
                if (~isnan(timedata(ni,3)))
                    fill([timedata(ni,2)*[1 1] timedata(ni,3)*[1 1]], ...
                        yi+(.3)*[1 -1 -1 1],plotparams.clrs(ci,:),'edgecolor',plotparams.clrs(ci,:));
                else
                    plot(timedata(ni,2),yi,'d','markersize',5,'color',plotparams.clrs(ci,:));
                end
            end
        end
        plot([1 1]* plotparams.aw_relstarttime,[0 ncommands+1],'k:');
        plot([1 1]* plotparams.aw_relendtime,[0 ncommands+1],'k:');
        set(gca,'position',axesposition+[.06 0 -.06 0]);
    end
end

%=========================================================
function[] = drawtable(FIGM,summarystats,plotparams,spnum)
%%%------------------------------------------
%%% Called by:  plotrasterandtable, plottable
%%%------------------------------------------
DAT = getstoreddata(FIGM.DATh);
subplot(2,1,spnum)
set(gca,'xlim',[0 1],'ylim',[0 1])
subjnames = {'either';DAT.uc.subj1name;DAT.uc.subj2name;'both'};
tempfilename = DAT.lfilename;
x = find(tempfilename == '_');
while (~isempty(x))
    tempfilename = [tempfilename(1:x(1)-1),'_-',tempfilename(x(1)+1:end)];
    x = find(tempfilename == '_');
    y = find(tempfilename == '-') - 1;
    x = setdiff(x,y);
end
titletext = ['SUMMARY STATISTICS for log',tempfilename,'.mat'];
title(titletext);
xoffsets = [-.1 .15 .33 .47 .61 .75 .89 1.03];
yoffset = .82;
yinc = .08;
text('position',[xoffsets(end) 1],'string', ...
    'all times in sec','horizontalalignment','right');
text('position',[xoffsets(end) 0.94],'string', ...
    ['time 0 = ',DAT.markslog.framename{DAT.markslog.alignindex}], ...
    'horizontalalignment','right');
text('position',[xoffsets(1) yoffset],'string','behavior');
text('position',[xoffsets(2) yoffset],'string','subject');
text('position',[xoffsets(3) yoffset],'string','count','horizontalalignment','right');
text('position',[xoffsets(4) yoffset],'string','1st occ.','horizontalalignment','right');
text('position',[xoffsets(5) yoffset],'string','mean dur','horizontalalignment','right');
text('position',[xoffsets(6) yoffset],'string','total dur','horizontalalignment','right');
text('position',[xoffsets(7) yoffset],'string','std dur','horizontalalignment','right');
text('position',[xoffsets(8) yoffset],'string','mean isi','horizontalalignment','right');
yoffset = yoffset - yinc;
for ni = plotparams.inclindex'
    text('position',[xoffsets(1) yoffset],'string',DAT.uc.desc{ni});
    text('position',[xoffsets(2) yoffset],'string',subjnames{str2double(DAT.uc.subj{ni})+1});
    text('position',[xoffsets(3) yoffset],'string',num2str(summarystats(ni,1)), ...
        'horizontalalignment','right');
    text('position',[xoffsets(4) yoffset],'string',num2str(summarystats(ni,2),'%3.2f'), ...
        'horizontalalignment','right');
    text('position',[xoffsets(5) yoffset],'string',num2str(summarystats(ni,3),'%3.2f'), ...
        'horizontalalignment','right');
    text('position',[xoffsets(6) yoffset],'string',num2str(summarystats(ni,4),'%3.2f'), ...
        'horizontalalignment','right');
    text('position',[xoffsets(7) yoffset],'string',num2str(summarystats(ni,5),'%3.2f'), ...
        'horizontalalignment','right');
    text('position',[xoffsets(8) yoffset],'string',num2str(summarystats(ni,6),'%3.2f'), ...
        'horizontalalignment','right');
    yoffset = yoffset - yinc;
end
axis off

%=========================================
function[plotparams] = getplotparams(FIGM)
%%%------------------------------------------------------------------
%%% Called by:  Calc BUTTON in ANALY panel, writesummarystatsxlsfile,
%%% plotraster, plotrasterandtable, plottable
%%%------------------------------------------------------------------
plotparams = [];
isempty_slog = getstoreddata(FIGM.FFLh,'isempty_slog');
if (isempty_slog == 0)
    DAT = getstoreddata(FIGM.DATh);
    plotparams.fpsoi = DAT.vfpsoi;
    plotparams.aw_startframe = DAT.markslog.framenum(DAT.markslog.startindex);
    plotparams.aw_alignframe = DAT.markslog.framenum(DAT.markslog.alignindex);
    plotparams.aw_endframe = DAT.markslog.framenum(DAT.markslog.endindex);
    plotparams.aw_totframes = plotparams.aw_endframe - plotparams.aw_startframe + 1;
    plotparams.aw_totdur = plotparams.aw_totframes/(plotparams.fpsoi*60);
    plotparams.aw_relstartframe = plotparams.aw_startframe - plotparams.aw_alignframe + 1;
    plotparams.aw_relstarttime = plotparams.aw_relstartframe/(plotparams.fpsoi*60);
    plotparams.aw_relendframe = plotparams.aw_endframe - plotparams.aw_alignframe + 1;
    plotparams.aw_relendtime = plotparams.aw_relendframe/(plotparams.fpsoi*60);
    npanels = str2num(get(FIGM.uic.analy.npanels,'string'));
    npages = str2num(get(FIGM.uic.analy.npages,'string'));
    nmins = str2num(get(FIGM.uic.analy.nmins,'string'));
    flag_npanels = getstoreddata(FIGM.uic.analy.npanels);
    flag_npages = getstoreddata(FIGM.uic.analy.npages);
    flag_nmins = getstoreddata(FIGM.uic.analy.nmins);
    if (isempty(npanels) && (flag_npanels ~= 3)); npanels = 4; end
    if (isempty(npages) && (flag_npages ~= 3)); npages = 1; end
    if (isempty(nmins) && (flag_nmins ~= 3)); nmins = 15; end
    if (flag_nmins == 3)
        npanels = floor(npanels);
        if (npanels < 1); npanels = 1; end
        npages = floor(npages);
        if (npages < 1); npages = 1; end
        npanelstot = npanels * npages;
        nmins = ceil(plotparams.aw_totdur/npanelstot);
    elseif (flag_npages == 3)
        npanels = floor(npanels);
        if (npanels < 1); npanels = 1; end
        nmins = floor(nmins);
        if (nmins < 1); nmins = 1; end
        npanelstot = ceil(plotparams.aw_totdur/nmins);
        npages = ceil(npanelstot/npanels);
    elseif (flag_npanels == 3)
        npages = floor(npages);
        if (npages < 1); npages = 1; end
        nmins = floor(nmins);
        if (nmins < 1); nmins = 1; end
        npanelstot = ceil(plotparams.aw_totdur/nmins);
        npanels = ceil(npanelstot/npages);
    end
    set(FIGM.uic.analy.npanels,'string',num2str(npanels));
    set(FIGM.uic.analy.npages,'string',num2str(npages));
    set(FIGM.uic.analy.nmins,'string',num2str(nmins));
    plotparams.npanels = npanels;
    plotparams.npages = npages;
    plotparams.npanelstot = npanelstot;
    plotparams.nmins = nmins;
    plotparams.usepanelht = get(FIGM.uic.analy.setpanelht,'value');
    plotparams.panelht = str2num(get(FIGM.uic.analy.panelht,'string'));
    plotparams.inclsubjname = get(FIGM.uic.analy.inclsubjname,'value');
    uc = getstoreddata(FIGM.DATh,'uc');
    [y,yi] = sort(uc.plotorder);
    yinclude = find(y);
    yi = yi(yinclude);
    plotparams.inclindex = yi;
    plotparams.clrs = uc.plotclr;
    plotparams.fontsize = str2num(getuivalue(FIGM.uic.analy.fontsize));
    FFL = getstoreddata(FIGM.FFLh);
    plotparams.inclstartsbefore = FFL.val_inclstartsbefore;
    plotparams.inclstopsafter = FFL.val_inclstopsafter;
    setmsg(FIGM,'plot parameters calculated');
else
    setmsg(FIGM,'error:  log is empty (info in log required)');
end

%============================
function[] = plotraster(FIGM)
%%%---------------------------
%%% Called by:  makeoutputplot
%%%---------------------------
setmsg(FIGM,'generating figure ...');
DAT = getstoreddata(FIGM.DATh);
plotparams = getplotparams(FIGM);
if (size(DAT.rawlog,1) ~= 0)
    timedata = calcsummarydata(DAT,plotparams);
    for pagei = 1:plotparams.npages
        panelindex = (1:plotparams.npanels) + (pagei-1)*plotparams.npanels;
        figh = makefig('data','log summary:  raster',plotparams.fontsize);
        drawrasters(FIGM,timedata,plotparams,panelindex);
        addpagelabel(pagei,plotparams.npages);
        setprintformat(figh);
        if (pagei > 1)
            figposition = get(gcf,'position');
            set(gcf,'position',figposition + (.5)*(pagei-1)*[1 0 0 0]);
        end
    end
end

%====================================
function[] = plotrasterandtable(FIGM)
%%%---------------------------
%%% Called by:  makeoutputplot
%%%---------------------------
setmsg(FIGM,'generating figure ...');
DAT = getstoreddata(FIGM.DATh);
plotparams = getplotparams(FIGM);
plotparams.npanelsp1 = floor(plotparams.npanels/2);
plotparams.npages = plotparams.npages + 1;
lastpanel = plotparams.npanels*(plotparams.npages - 1);
if (size(DAT.rawlog,1) ~= 0)
    [timedata,summarystats] = calcsummarydata(DAT,plotparams);
    for pagei = 1
        panelindex = ones(1,plotparams.npanels)*nan;
        panelindex(end-plotparams.npanelsp1+1:end) = 1:plotparams.npanelsp1;
        figh = makefig('data','log summary:  raster and table',plotparams.fontsize);
        drawtable(FIGM,summarystats,plotparams,1);
        drawrasters(FIGM,timedata,plotparams,panelindex);
        addpagelabel(pagei,plotparams.npages);
        setprintformat(figh);
    end
    for pagei = 2:plotparams.npages
        panelindex = (1:plotparams.npanels) + plotparams.npanelsp1 + (pagei-2)*plotparams.npanels;
        lindex = find(panelindex > lastpanel);
        if (~isempty(lindex))
            panelindex(lindex) = nan;
        end
        figh = makefig('data','log summary:  raster and table',plotparams.fontsize);
        drawrasters(FIGM,timedata,plotparams,panelindex);
        addpagelabel(pagei,plotparams.npages);
        setprintformat(figh);
        figposition = get(gcf,'position');
        set(gcf,'position',figposition + (.5)*(pagei-1)*[1 0 0 0]);
    end
end

%===========================
function[] = plottable(FIGM)
%%%---------------------------
%%% Called by:  makeoutputplot
%%%---------------------------
setmsg(FIGM,'generating figure ...');
DAT = getstoreddata(FIGM.DATh);
plotparams = getplotparams(FIGM);
if (size(DAT.rawlog,1) ~= 0)
    figh = makefig('data','log summary:  table',plotparams.fontsize);
    [timedata,summarystats] = calcsummarydata(DAT,plotparams);
    drawtable(FIGM,summarystats,plotparams,1);
    setprintformat(figh);
end

%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
%%% SUBFUNCTIONS:  Generic %%%
%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
% Listing:
% function[textlist] = createlistboxtext(celllist,nspaces)
% function[filenames,n] = getfilenames(filenamefilter)
% function[dataorval] = getstoreddata(handletohdata,fieldname)
% function[val] = getuivalue(uihandle)
% function[fighandle] = makefig(figtype,figname,afontsize,ufontsize,figcolor)
% function[strminsec] = mintominsec(valmin)
% function[] = setprintformat(fighandle)
% function[hdata] = setstoreddata(handletohdata,hdata,fieldname,fieldvalue)
% function[] = setuivalue(uihandle,strval)
% function[] = turntimeroff(timerhandle)
% function[] = turntimeron(timerhandle)

%=======================================================
function[textlist] = createlistboxtext(celllist,nspaces)
if (nargin < 2); nspaces = 2; end
cfields = fieldnames(celllist);
for ci = 1:size(cfields,1)
    if ~iscell(celllist.(cfields{ci}))
        celllist = rmfield(celllist,cfields{ci});
    end
end
cfields = fieldnames(celllist);
nentries = size(celllist.(cfields{1}),1);
if (nentries > 0)
    textlist = cell(nentries,1);
    for ci = 1:size(cfields,1)
        cfield = celllist.(cfields{ci});
        for ni = 1:nentries
            textlist{ni} = [textlist{ni},cfield{ni}];
            if (ci ~= size(cfields,1))
                textlist{ni} = [textlist{ni},blanks(nspaces)];
            end
        end
    end
else
    textlist = [];
end

%===================================================
function[filenames,n] = getfilenames(filenamefilter)
filenames = dir(filenamefilter);
n = size(filenames,1);
if (n >= 1)
    filenames = rmfield(filenames,'date');
    filenames = rmfield(filenames,'bytes');
    filenames = rmfield(filenames,'isdir');
    tempfilenames = {filenames(1:end).name}';
    filenames = tempfilenames;
end

%===========================================================
function[dataorval] = getstoreddata(handletohdata,fieldname)
hdata = get(handletohdata,'userdata');
if (nargin < 2)
    dataorval = hdata;
else
    dataorval = hdata.(fieldname);
end

%===================================
function[val] = getuivalue(uihandle)
numval = get(uihandle,'value');
strvals = get(uihandle,'string');
val = strvals{numval};

%==========================================================================
function[fighandle] = makefig(figtype,figname,afontsize,ufontsize,figcolor)
if (nargin < 4); ufontsize = afontsize; end
if (nargin < 5); figcolor = [.8 .8 .8]; end
fighandle = figure;
set(fighandle,'Name',figname,'NumberTitle','off','Toolbar','none')
set(fighandle,'Color',figcolor)
set(fighandle,'Units','normalized')
set(fighandle,'DefaultAxesNextPlot','add','DefaultAxesBox','off')
set(fighandle,'DefaultAxesFontName','Helvetica','DefaultAxesFontSize',afontsize)
set(fighandle,'DefaultAxesTickDir','out')
set(fighandle,'DefaultAxesUnits','normalized')
set(fighandle,'DefaultUicontrolUnits','normalized')
set(fighandle,'DefaultUicontrolFontName','Helvetica','DefaultUicontrolFontSize',ufontsize)
set(fighandle,'DefaultTextFontName','Helvetica','DefaultTextFontSize',ufontsize)
switch (figtype)
    case ('main')
        set(fighandle,'Position',[.08 .14 .88 .76])
        set(fighandle,'DefaultUicontrolHorizontalAlignment','left')
        set(fighandle,'DefaultUipanelBorderType','beveledin')
        set(fighandle,'DefaultUipanelHighlightColor',[.8 .8 .8])
        set(fighandle,'Backingstore','off','Doublebuffer','off')
        set(fighandle,'KeyPressFcn',@figurekeypressfcn)
        set(fighandle,'DeleteFcn',@quitprogramfxn);
        colormap('gray');
    case ('data')
        set(fighandle,'Position',[.10 .05 .48 .80])
    case ('customcolor')
        set(fighandle,'Menubar','none')
        set(fighandle,'Position',[.45 .12 .25 .40])
        set(fighandle,'DefaultUicontrolHorizontalAlignment','center')
end

%========================================
function[strminsec] = mintominsec(valmin)
m = fix(valmin);
s = round(100*abs(60*rem(valmin,1)))/100;
if (length(valmin) == 1)
    lz = []; ls = [];
    if (s < 10); lz = '0'; end
    if (m < 10); ls = ' '; end
    strminsec = [ls,num2str(m),':',lz,num2str(s,'%3.2f')];
else
    strminsec = {};
    for vi = 1:length(valmin)
        lz = []; ls = [];
        if (s(vi) < 10); lz = '0'; end
        if (m(vi) < 10); ls = ' '; end
        strminsec{vi,1} = [ls,num2str(m(vi)),':',lz,num2str(s(vi),'%3.2f')];
    end
end

%=====================================
function[] = setprintformat(fighandle)
set(fighandle,'Units','inches');
set(fighandle,'PaperPosition',[.5 .5 8 10.5]);

%========================================================================
function[hdata] = setstoreddata(handletohdata,hdata,fieldname,fieldvalue)
if (isempty(hdata))
    hdata = get(handletohdata,'userdata');
end
if (nargin > 2)
    hdata.(fieldname) = fieldvalue;
end
set(handletohdata,'userdata',hdata);

%=======================================
function[] = setuivalue(uihandle,strval)
strvals = get(uihandle,'string');
numval = strmatch(strval,strvals,'exact');
if (~isempty(numval))
    set(uihandle,'value',numval);
end

%=====================================
function[] = turntimeroff(timerhandle)
if (strcmp(get(timerhandle,'Running'),'on'))
    stop(timerhandle);
end

%====================================
function[] = turntimeron(timerhandle)
if (strcmp(get(timerhandle,'Running'),'off'))
    start(timerhandle);
end

%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
%%% SUBFUNCTIONS:  Setting constants %%%
%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
% Listing:
% function[CON,DAT,FFL,TFL] = getdefaults()
% function[uicp] = getuicparams(FFL,CON)
% function[varout] = checkmodules(opname,FIGM,varin1,varin2)

%========================================
function[CON,DAT,FFL,TFL] = getdefaults()
CON = [];
DAT = [];
FFL = [];
TFL = [];
[slash,codepath] = getslashandcodepath;
CON.codepath = codepath;
CON.slash = slash;
switch (slash)				% set fontsizes by computer type
    case ('/')				% Mac
        CON.fontsize.sm = 8;
        CON.fontsize.lg = 14;
        CON.fontsize.ax = 9;
        CON.fontsize.ui = 9;
        CON.fontsize.uilg = 12;
        CON.fontsize.xlg = 28;
    case ('\')				% PC
        CON.fontsize.sm = 7;
        CON.fontsize.lg = 12;
        CON.fontsize.ax = 8;
        CON.fontsize.ui = 8;
        CON.fontsize.uilg = 10;
        CON.fontsize.xlg = 24;
    otherwise				% other
        CON.fontsize.sm = 7;
        CON.fontsize.lg = 12;
        CON.fontsize.ax = 8;
        CON.fontsize.ui = 8;
        CON.fontsize.uilg = 10;
        CON.fontsize.xlg = 24;
end
CON.videoIOMovie = {'ASF';'ASX';'AVI';'MPG';'WMV'};
CON.WindowsMovie = {'ASF';'ASX';'AVI';'MJ2';'MPG';'WMV'};
CON.MacMovie = {'AVI';'MJ2';'MP4';'M4V';'MOV';'MPG'};
CON.UnixMovie =  {'AVI';'MJ2';'OGG'}; % Actual list?
switch (ispc() - isunix())
    case (1) %PC
        CON.videoTypes = CON.WindowsMovie;
    case (0) %Mac
        CON.videoTypes = CON.MacMovie;
    otherwise
        CON.videoTypes = CON.UnixMovie;
end
CON.clr.fig = [.90 .90 .94];
CON.clr.frame1 = [.97 .94 .84];
CON.clr.frame2 = [1 1 1];
CON.clr.frame3 = [.7 .7 .7];
CON.clr.frame4 = [.9 .9 .9];
CON.clr.frame5 = [1 1 .91];
CON.clr.uitext = [1 1 1];
CON.clr.listbox = [.98 .98 .98];
CON.clr.button1 = [.96 .96 .96];
CON.clr.button2 = [.2 .2 1];
CON.clr.button3 = [.7 0 .8];
CON.clr.button4 = [0 .5 0];
CON.clr.none = [.8 .8 .8];
CON.clr.loaded = [0 0 0];
CON.clr.textlow = [.4 .4 .4];
CON.clr.textalert = [.4 0 .7];
CON.clr.posns = ...			% colors for subject posn markers
    [0 .8 1;				% subject 1
    1 0 1];				% subject 2
CON.clr.plots = ...			% ready-to-use colors for plots
    [1 0 0;				% red
    1 .5 0;				% orange
    0 .9 0;				% green
    0 1 1;				% cyan
    .1 .1 1;				% blue
    .6 0 1;				% purple
    1 0 1;				% magenta
    0 0 0];				% black
CON.set.vfields = ...
    {'vtype';'vpath';'vprefixes';'vnumstarts';'vnumends'; ...
    'vfilenames';'vfilenums';'vframenums';'vfsrcindex'; ...
    'vnummax';'vframemax';'vfpsoi';'vfpstp'; ...
    'vnsubj';'fseldur';'favaildur';'fnumincr'};
FFL.val_videotype = 'AVI';		% values:  JPG, AVI, MPG, NONE, ... (other vid types)
FFL.isloaded_video = 0;
%FFL.ispresent_videoIO = (exist('videoReader.m','file') == 2);
FFL.ispresent_posnmodule = (exist('posnmodule.m','file') == 2);
FFL.isempty_cmnds = 1;
FFL.isfrom_cmnds = [];
FFL.isempty_slog = 1;
FFL.isempty_nlog = 1;
FFL.isempty_mlog = 1;
FFL.isempty_plog = 1;
FFL.isempty_log = 1;
FFL.issaved_log = 0;
FFL.canloadfromlog = 0;
FFL.val_lastframeadded = [];
FFL.isplaying = 0;
FFL.val_playspeed = 'normal';
FFL.val_holdchar = [];
FFL.val_startframe = -1;
FFL.ison_overwrite = 0;
FFL.val_lastovframe = 0;
FFL.ison_bayg = 0;
FFL.val_lastbgframe = 0;
FFL.ison_checksavecmnds = 0;
FFL.ison_checksavelog = 0;
FFL.ison_showposns = 1;
FFL.val_inclstartsbefore = 0;
FFL.val_inclstopsafter = 1;
TFL.do_dispraw = 0;
TFL.do_dispfull = 0;

%=====================================
function[uicp] = getuicparams(FFL,CON)
panel.score.type = 'uipanel';
panel.score.position = [.40 .11 .58 .87];
panel.score.backgroundcolor = CON.clr.frame1;
panel.switch2.type = 'uipanel';
panel.switch2.position = [.40 .04 .121 .071];
panel.switch2.backgroundcolor = CON.clr.frame1;
panel.switch3.type = 'uipanel';
panel.switch3.position = [.52 .04 .12 .071];
panel.switch3.backgroundcolor = CON.clr.frame2;
panel.switch4.type = 'uicontrol';
panel.switch4.position = [.402 .105 .118 .01];
panel.switch4.style = 'text';
panel.switch4.backgroundcolor = CON.clr.frame1;
panel.switch1.type = 'uipanel';
panel.switch1.position = [.02 .04 .381 .94];
panel.switch1.backgroundcolor = CON.clr.frame2;
panel.settings.type = 'uipanel';
panel.settings.position = [.03 .11 .12 .126];
panel.settings.backgroundcolor = CON.clr.frame2;
panel.settings2.type = 'uipanel';
panel.settings2.position = [.15 .11 .121 .126];
panel.settings2.backgroundcolor = CON.clr.frame2;
panel.settings3.type = 'uipanel';
panel.settings3.position = [.271 .11 .12 .126];
panel.settings3.backgroundcolor = CON.clr.frame2;
uicp.panel = panel;
swtch.files.type = 'uicontrol';
swtch.files.position = [.03 .05 .06 .05];
swtch.files.style = 'togglebutton';
swtch.files.string = 'FILES';
swtch.files.backgroundcolor = CON.clr.button1;
swtch.files.horizontalalignment = 'center';
swtch.files.fontsize = CON.fontsize.sm;
swtch.files.callback = 'scorevideo(''switch'',''files'');';
swtch.cmnds.type = 'uicontrol';
swtch.cmnds.position = [.105 .05 .06 .05];
swtch.cmnds.style = 'togglebutton';
swtch.cmnds.string = 'COMMANDS';
swtch.cmnds.backgroundcolor = CON.clr.button1;
swtch.cmnds.horizontalalignment = 'center';
swtch.cmnds.fontsize = CON.fontsize.sm;
swtch.cmnds.callback = 'scorevideo(''switch'',''cmnds'');';
swtch.behav.type = 'uicontrol';
swtch.behav.position = [.18 .05 .06 .05];
swtch.behav.style = 'togglebutton';
swtch.behav.string = 'BEHAV';
swtch.behav.backgroundcolor = CON.clr.button1;
swtch.behav.horizontalalignment = 'center';
swtch.behav.fontsize = CON.fontsize.sm;
swtch.behav.callback = 'scorevideo(''switch'',''behav'');';
swtch.nandm.type = 'uicontrol';
swtch.nandm.position = [.255 .05 .06 .05];
swtch.nandm.style = 'togglebutton';
swtch.nandm.string = 'N & M';
swtch.nandm.backgroundcolor = CON.clr.button1;
swtch.nandm.horizontalalignment = 'center';
swtch.nandm.fontsize = CON.fontsize.sm;
swtch.nandm.callback = 'scorevideo(''switch'',''nandm'');';
swtch.analy.type = 'uicontrol';
swtch.analy.position = [.33 .05 .06 .05];
swtch.analy.style = 'togglebutton';
swtch.analy.string = 'ANALYSIS';
swtch.analy.backgroundcolor = CON.clr.button1;
swtch.analy.horizontalalignment = 'center';
swtch.analy.fontsize = CON.fontsize.sm;
swtch.analy.callback = 'scorevideo(''switch'',''analy'');';
swtch.score.type = 'uicontrol';
swtch.score.position = [.43 .05 .06 .05];
swtch.score.style = 'togglebutton';
swtch.score.string = 'SCORE';
swtch.score.backgroundcolor = CON.clr.button1;
swtch.score.horizontalalignment = 'center';
swtch.score.fontsize = CON.fontsize.sm;
swtch.score.callback = 'scorevideo(''switch'',''score'');';
uicp.swtch = swtch;
score.title.type = 'uicontrol';
score.title.position = [.43 .94 .53 .025];
score.title.style = 'text';
score.title.backgroundcolor = CON.clr.frame1;
score.title.string = 'SCORE';
score.title.horizontalalignment = 'center';
score.title.fontweight = 'bold';
score.title.fontsize = CON.fontsize.lg;
score.msglabel.type = 'uicontrol';
score.msglabel.position = [.02 .01 .06 .021];
score.msglabel.style = 'text';
score.msglabel.backgroundcolor = CON.clr.fig;
score.msglabel.string = 'Message';
score.msg.type = 'uicontrol';
score.msg.position = [.08 .01 .80 .022];
score.msg.style = 'text';
score.msg.backgroundcolor = CON.clr.fig;
score.msg.foregroundcolor = CON.clr.textalert;
score.msg.fontweight = 'bold';
score.msg.fontsize = CON.fontsize.uilg;
score.axes_image.type = 'axes';
score.axes_image.position = [.43 .26 .53 .65];
score.axes_image.color = CON.clr.frame1;
score.axes_image.ydir = 'reverse';
score.axes_image.drawmode = 'fast';
score.axes_image.xlim = [0 720];
score.axes_image.xtick = score.axes_image.xlim(1):120:score.axes_image.xlim(2);
score.axes_image.xlabel = 'pixels';
score.axes_image.ylim = [0 480];
score.axes_image.ytick = score.axes_image.ylim(1):120:score.axes_image.ylim(2);
score.axes_image.ticklength = [.005 .025];
score.playinglabel.type = 'uicontrol';
score.playinglabel.position = [.43 .17 .05 .022];
score.playinglabel.style = 'text';
score.playinglabel.backgroundcolor = CON.clr.frame1;
score.playinglabel.string = 'Video:';
score.playing.type = 'uicontrol';
score.playing.position = [.48 .17 .08 .022];
score.playing.style = 'text';
score.playing.backgroundcolor = CON.clr.frame1;
score.playing.string = 'stopped';
score.playspeedlabel.type = 'uicontrol';
score.playspeedlabel.position = [.43 .145 .05 .022];
score.playspeedlabel.style = 'text';
score.playspeedlabel.backgroundcolor = CON.clr.frame1;
score.playspeedlabel.string = 'Speed:';
score.playspeed.type = 'uicontrol';
score.playspeed.position = [.48 .145 .08 .022];
score.playspeed.style = 'text';
score.playspeed.backgroundcolor = CON.clr.frame1;
score.playspeed.string = 'normal';
score.currframelabel.type = 'uicontrol';
score.currframelabel.position = [.55 .17 .05 .022];
score.currframelabel.style = 'text';
score.currframelabel.backgroundcolor = CON.clr.frame1;
score.currframelabel.string = 'Frame:';
score.currframe.type = 'uicontrol';
score.currframe.position = [.62 .17 .05 .022];
score.currframe.style = 'text';
score.currframe.backgroundcolor = CON.clr.frame1;
score.currframe.horizontalalignment = 'center';
score.currtimelabel.type = 'uicontrol';
score.currtimelabel.position = [.55 .145 .07 .022];
score.currtimelabel.style = 'text';
score.currtimelabel.backgroundcolor = CON.clr.frame1;
score.currtimelabel.string = 'Time (min:sec):';
score.currtime.type = 'uicontrol';
score.currtime.position = [.62 .145 .05 .022];
score.currtime.style = 'text';
score.currtime.backgroundcolor = CON.clr.frame1;
score.currtime.horizontalalignment = 'center';
score.ongoinglabel.type = 'uicontrol';
score.ongoinglabel.position = [.70 .17 .08 .022];
score.ongoinglabel.style = 'text';
score.ongoinglabel.backgroundcolor = CON.clr.frame1;
score.ongoinglabel.string = 'Last command:';
score.ongoing.type = 'uicontrol';
score.ongoing.position = [.78 .17 .18 .03];
score.ongoing.style = 'text';
score.ongoing.backgroundcolor = CON.clr.frame1;
score.ongoing.foregroundcolor = CON.clr.textalert;
score.ongoing.fontsize = CON.fontsize.lg;
score.ongoing2.type = 'uicontrol';
score.ongoing2.position = [.78 .145 .18 .03];
score.ongoing2.style = 'text';
score.ongoing2.backgroundcolor = CON.clr.frame1;
score.ongoing2.foregroundcolor = CON.clr.textalert;
score.ongoing2.fontsize = CON.fontsize.lg;
score.overwritemsg.type = 'uicontrol';
score.overwritemsg.position = [.70 .12 .20 .022];
score.overwritemsg.style = 'text';
score.overwritemsg.backgroundcolor = CON.clr.frame1;
score.overwritemsg.foregroundcolor = CON.clr.textalert;
score.overwritemsg.fontweight = 'bold';
score.quit.type = 'uicontrol';
score.quit.position = [.55 .053 .06 .04];
score.quit.style = 'pushbutton';
score.quit.string = 'QUIT';
score.quit.backgroundcolor = CON.clr.button1;
score.quit.horizontalalignment = 'center';
score.quit.fontsize = CON.fontsize.sm;
score.quit.callback = 'scorevideo(''quit'');';
score.lastplaylabel.type = 'uicontrol';
score.lastplaylabel.position = [.70 .07 .15 .02];
score.lastplaylabel.style = 'text';
score.lastplaylabel.backgroundcolor = CON.clr.fig;
score.lastplaylabel.foregroundcolor = CON.clr.textlow;
score.lastplaylabel.fontsize = CON.fontsize.sm;
score.lastplaylabel.string = 'Duration of last sequence (sec):';
score.realdurlabel.type = 'uicontrol';
score.realdurlabel.position = [.70 .05 .04 .02];
score.realdurlabel.style = 'text';
score.realdurlabel.backgroundcolor = CON.clr.fig;
score.realdurlabel.foregroundcolor = CON.clr.textlow;
score.realdurlabel.fontsize = CON.fontsize.sm;
score.realdurlabel.string = 'Video time';
score.realdur.type = 'uicontrol';
score.realdur.position = [.74 .05 .06 .02];
score.realdur.style = 'text';
score.realdur.backgroundcolor = CON.clr.fig;
score.realdur.foregroundcolor = CON.clr.textlow;
score.realdur.fontsize = CON.fontsize.sm;
score.realdur.horizontalalignment = 'center';
score.playdurlabel.type = 'uicontrol';
score.playdurlabel.position = [.80 .05 .04 .02];
score.playdurlabel.style = 'text';
score.playdurlabel.backgroundcolor = CON.clr.fig;
score.playdurlabel.foregroundcolor = CON.clr.textlow;
score.playdurlabel.fontsize = CON.fontsize.sm;
score.playdurlabel.string = 'Play time';
score.playdur.type = 'uicontrol';
score.playdur.position = [.84 .05 .06 .02];
score.playdur.style = 'text';
score.playdur.backgroundcolor = CON.clr.fig;
score.playdur.foregroundcolor = CON.clr.textlow;
score.playdur.fontsize = CON.fontsize.sm;
score.playdur.horizontalalignment = 'center';
score.savestate.type = 'uicontrol';
score.savestate.position = [.92 .05 .06 .037];
score.savestate.style = 'pushbutton';
score.savestate.string = 'Save state';
score.savestate.backgroundcolor = CON.clr.button1;
score.savestate.horizontalalignment = 'center';
score.savestate.fontsize = CON.fontsize.sm;
score.savestate.callback = 'scorevideo(''savestate'');';
score.videobuttonstitle.type = 'uicontrol';
score.videobuttonstitle.position = [.05 .202 .05 .022];
score.videobuttonstitle.style = 'text';
score.videobuttonstitle.backgroundcolor = CON.clr.frame2;
score.videobuttonstitle.fontweight = 'bold';
score.videobuttonstitle.string = 'VIDEO';
score.videobuttonsflag.type = 'uicontrol';
score.videobuttonsflag.position = [.035 .205 .015 .026];     % good for PC
score.videobuttonsflag.style = 'text';
score.videobuttonsflag.backgroundcolor = CON.clr.frame2;
score.videobuttonsflag.foregroundcolor = CON.clr.none;
score.videobuttonsflag.fontsize = CON.fontsize.xlg;
score.videobuttonsflag.tooltipstring = ' Star indicates a video is loaded ';
score.videobuttonsflag.string = '*';
score.videoclear.type = 'uicontrol';
score.videoclear.position = [.095 .194 .05 .032];
score.videoclear.style = 'pushbutton';
score.videoclear.backgroundcolor = CON.clr.button1;
score.videoclear.foregroundcolor = CON.clr.button4;
score.videoclear.horizontalalignment = 'center';
score.videoclear.string = 'Clear';
score.videoclear.tooltipstring = ' Clear existing video file set ';
score.videoclear.callback = 'scorevideo(''video_clear'')';
score.videoload.type = 'uicontrol';
score.videoload.position = [.04 .156 .05 .032];
score.videoload.style = 'pushbutton';
score.videoload.backgroundcolor = CON.clr.button1;
score.videoload.foregroundcolor = CON.clr.button2;
score.videoload.horizontalalignment = 'center';
score.videoload.string = 'Load new';
score.videoload.tooltipstring = ' Start new video file set; replaces any existing video file set ';
score.videoload.callback = 'scorevideo(''video_frominput'',''new'')';
score.videofromlog.type = 'uicontrol';
score.videofromlog.position = [.04 .118 .05 .032];
score.videofromlog.style = 'pushbutton';
score.videofromlog.backgroundcolor = CON.clr.button1;
score.videofromlog.foregroundcolor = CON.clr.button2;
score.videofromlog.horizontalalignment = 'center';
score.videofromlog.string = 'From log';
score.videofromlog.tooltipstring = ' Load video file set from current log ';
score.videofromlog.callback = 'scorevideo(''video_fromlog'')';
score.videoadd.type = 'uicontrol';
score.videoadd.position = [.095 .156 .05 .032];
score.videoadd.style = 'pushbutton';
score.videoadd.backgroundcolor = CON.clr.button1;
score.videoadd.foregroundcolor = CON.clr.button2;
score.videoadd.horizontalalignment = 'center';
score.videoadd.string = 'Add to';
score.videoadd.tooltipstring = ' Add video file subset to existing video file set ';
score.videoadd.callback = 'scorevideo(''video_frominput'',''add'')';
score.videoupdate.type = 'uicontrol';
score.videoupdate.position = [.095 .118 .05 .032];
score.videoupdate.style = 'pushbutton';
score.videoupdate.backgroundcolor = CON.clr.button1;
score.videoupdate.foregroundcolor = CON.clr.button2;
score.videoupdate.horizontalalignment = 'center';
score.videoupdate.string = 'Update';
score.videoupdate.tooltipstring = ' Update settings for video file subset; skips getting file list ';
score.videoupdate.callback = 'scorevideo(''video_frominput'',''update'')';
score.cmndsbuttonstitle.type = 'uicontrol';
score.cmndsbuttonstitle.position = [.17 .202 .05 .022];
score.cmndsbuttonstitle.style = 'text';
score.cmndsbuttonstitle.backgroundcolor = CON.clr.frame2;
score.cmndsbuttonstitle.fontweight = 'bold';
score.cmndsbuttonstitle.string = 'CMNDS';
score.cmndsbuttonsflag.type = 'uicontrol';
score.cmndsbuttonsflag.position = [.155 .205 .015 .026];     % good for PC
score.cmndsbuttonsflag.style = 'text';
score.cmndsbuttonsflag.backgroundcolor = CON.clr.frame2;
score.cmndsbuttonsflag.foregroundcolor = CON.clr.none;
score.cmndsbuttonsflag.fontsize = CON.fontsize.xlg;
score.cmndsbuttonsflag.tooltipstring = ' Star indicates a command set is present ';
score.cmndsbuttonsflag.string = '*';
score.cmndsclear.type = 'uicontrol';
score.cmndsclear.position = [.216 .194 .05 .032];
score.cmndsclear.style = 'pushbutton';
score.cmndsclear.backgroundcolor = CON.clr.button1;
score.cmndsclear.foregroundcolor = CON.clr.button4;
score.cmndsclear.horizontalalignment = 'center';
score.cmndsclear.string = 'Clear';
score.cmndsclear.tooltipstring = ' Clear current command set ';
score.cmndsclear.callback = 'scorevideo(''comm_clear'')';
score.cmndsload.type = 'uicontrol';
score.cmndsload.position = [.159 .156 .05 .032];
score.cmndsload.style = 'pushbutton';
score.cmndsload.backgroundcolor = CON.clr.button1;
score.cmndsload.foregroundcolor = CON.clr.button2;
score.cmndsload.horizontalalignment = 'center';
score.cmndsload.string = 'Load';
score.cmndsload.tooltipstring = ' Load command set from commands file; replaces any existing command set ';
score.cmndsload.callback = 'scorevideo(''comm_load'')';
score.cmndssave.type = 'uicontrol';
score.cmndssave.position = [.159 .118 .05 .032];
score.cmndssave.style = 'pushbutton';
score.cmndssave.backgroundcolor = CON.clr.button1;
score.cmndssave.foregroundcolor = CON.clr.button3;
score.cmndssave.horizontalalignment = 'center';
score.cmndssave.string = 'Save';
score.cmndssave.tooltipstring = ' Save current command set to commands file ';
score.cmndssave.callback = 'scorevideo(''comm_save'')';
score.checksavecmnds.type = 'uicontrol';
score.checksavecmnds.position = [.216 .123 .015 .025];
score.checksavecmnds.style = 'checkbox';
score.checksavecmnds.backgroundcolor = CON.clr.uitext;
score.checksavecmnds.tooltipstring = ' Save commands will query user before overwriting any existing commands file';
score.checksavecmnds.callback = 'scorevideo(''comm_checksave'')';
score.checksavecmndslabel.type = 'uicontrol';
score.checksavecmndslabel.position = [.237 .12 .03 .018];
score.checksavecmndslabel.style = 'text';
score.checksavecmndslabel.backgroundcolor = CON.clr.frame2;
score.checksavecmndslabel.fontsize = CON.fontsize.sm;
score.checksavecmndslabel.string = 'Check';
score.logbuttonstitle.type = 'uicontrol';
score.logbuttonstitle.position = [.29 .202 .05 .022];
score.logbuttonstitle.style = 'text';
score.logbuttonstitle.backgroundcolor = CON.clr.frame2;
score.logbuttonstitle.fontweight = 'bold';
score.logbuttonstitle.string = 'LOG';
score.logbuttonsflag.type = 'uicontrol';
score.logbuttonsflag.position = [.275 .205 .015 .026];     % good for PC
score.logbuttonsflag.style = 'text';
score.logbuttonsflag.backgroundcolor = CON.clr.frame2;
score.logbuttonsflag.foregroundcolor = CON.clr.none;
score.logbuttonsflag.fontsize = CON.fontsize.xlg;
score.logbuttonsflag.tooltipstring = ' Star indicates a log is present ';
score.logbuttonsflag.string = '*';
score.logclear.type = 'uicontrol';
score.logclear.position = [.337 .194 .05 .032];
score.logclear.style = 'pushbutton';
score.logclear.backgroundcolor = CON.clr.button1;
score.logclear.foregroundcolor = CON.clr.button4;
score.logclear.horizontalalignment = 'center';
score.logclear.string = 'Clear';
score.logclear.tooltipstring = ' Clear current log file ';
score.logclear.callback = 'scorevideo(''log_clearall'')';
score.logload.type = 'uicontrol';
score.logload.position = [.28 .156 .05 .032];
score.logload.style = 'pushbutton';
score.logload.backgroundcolor = CON.clr.button1;
score.logload.foregroundcolor = CON.clr.button2;
score.logload.horizontalalignment = 'center';
score.logload.string = 'Load';
score.logload.tooltipstring = ' Load log from log file ';
score.logload.callback = 'scorevideo(''log_load'')';
score.logsave.type = 'uicontrol';
score.logsave.position = [.28 .118 .05 .032];
score.logsave.style = 'pushbutton';
score.logsave.backgroundcolor = CON.clr.button1;
score.logsave.foregroundcolor = CON.clr.button3;
score.logsave.horizontalalignment = 'center';
score.logsave.string = 'Save';
score.logsave.tooltipstring = ' Save current log to log file ';
score.logsave.callback = 'scorevideo(''log_save'')';
score.checksavelog.type = 'uicontrol';
score.checksavelog.position = [.337 .123 .015 .025];
score.checksavelog.style = 'checkbox';
score.checksavelog.backgroundcolor = CON.clr.uitext;
score.checksavelog.tooltipstring = ' Save log will query user before overwriting any existing log file';
score.checksavelog.callback = 'scorevideo(''log_checksave'')';
score.checksaveloglabel.type = 'uicontrol';
score.checksaveloglabel.position = [.357 .12 .03 .018];
score.checksaveloglabel.style = 'text';
score.checksaveloglabel.backgroundcolor = CON.clr.frame2;
score.checksaveloglabel.fontsize = CON.fontsize.sm;
score.checksaveloglabel.string = 'Check';
uicp.score = score;
files.title.type = 'uicontrol';
files.title.position = [.03 .94 .36 .025];
files.title.style = 'text';
files.title.backgroundcolor = CON.clr.frame2;
files.title.horizontalalignment = 'center';
files.title.fontsize = CON.fontsize.lg;
files.title.fontweight = 'bold';
files.title.string = 'FILES';
files.subpanel1.type = 'uicontrol';
files.subpanel1.position = [.026 .768 .368 .165];
files.subpanel1.style = 'text';
files.subpanel1.backgroundcolor = CON.clr.frame1;
files.subpanel1a.type = 'uicontrol';
files.subpanel1a.position = [.24 .735 .154 .04];
files.subpanel1a.style = 'text';
files.subpanel1a.backgroundcolor = CON.clr.frame1;
files.vtitle.type = 'uicontrol';
files.vtitle.position = [.03 .89 .15 .03];
files.vtitle.style = 'text';
files.vtitle.backgroundcolor = CON.clr.frame1;
files.vtitle.fontweight = 'bold';
files.vtitle.string = 'VIDEO FILE SET';
files.vcurrdirlabel.type = 'uicontrol';
files.vcurrdirlabel.position = [.03 .864 .05 .035];
files.vcurrdirlabel.style = 'text';
files.vcurrdirlabel.backgroundcolor = CON.clr.frame1;
files.vcurrdirlabel.string = 'Saved in:';
files.vcurrdir.type = 'uicontrol';
files.vcurrdir.position = [.08 .864 .30 .035];
files.vcurrdir.style = 'text';
files.vcurrdir.backgroundcolor = CON.clr.frame1;
files.vcurrdir.fontname = 'courier';
files.vcurrdir.fontsize = CON.fontsize.ax;
files.vtotsellabel.type = 'uicontrol';
files.vtotsellabel.position = [.03 .84 .05 .02];
files.vtotsellabel.style = 'text';
files.vtotsellabel.backgroundcolor = CON.clr.frame1;
files.vtotsellabel.string = 'Selected:';
files.vtotsel.type = 'uicontrol';
files.vtotsel.position = [.08 .84 .22 .02];
files.vtotsel.style = 'text';
files.vtotsel.backgroundcolor = CON.clr.frame1;
files.vtotsel.fontname = 'courier';
files.vtotsel.fontsize = CON.fontsize.ax;
files.vtotavaillabel.type = 'uicontrol';
files.vtotavaillabel.position = [.03 .82 .05 .02];
files.vtotavaillabel.style = 'text';
files.vtotavaillabel.backgroundcolor = CON.clr.frame1;
files.vtotavaillabel.string = 'Available:';
files.vtotavail.type = 'uicontrol';
files.vtotavail.position = [.08 .82 .22 .02];
files.vtotavail.style = 'text';
files.vtotavail.backgroundcolor = CON.clr.frame1;
files.vtotavail.fontname = 'courier';
files.vtotavail.fontsize = CON.fontsize.ax;
files.vfpslabel.type = 'uicontrol';
files.vfpslabel.position = [.03 .80 .05 .02];
files.vfpslabel.style = 'text';
files.vfpslabel.backgroundcolor = CON.clr.frame1;
files.vfpslabel.string = 'FPS:';
files.vfps.type = 'uicontrol';
files.vfps.position = [.08 .80 .17 .02];
files.vfps.style = 'text';
files.vfps.backgroundcolor = CON.clr.frame1;
files.vfps.fontname = 'courier';
files.vfps.fontsize = CON.fontsize.ax;
files.vtypelabel.type = 'uicontrol';
files.vtypelabel.position = [.03 .732 .04 .022];
files.vtypelabel.style = 'text';
files.vtypelabel.backgroundcolor = CON.clr.frame2;
files.vtypelabel.string = 'File type';
files.vtype.type = 'uicontrol';
files.vtype.position = [.08 .73 .06 .03];
files.vtype.style = 'popup';
files.vtype.backgroundcolor = CON.clr.button1;
files.vtype.fontsize = CON.fontsize.sm;
files.vtype.string = [CON.videoTypes;'JPEG';'NONE'];
files.vtype.value = 1;
files.vtype.callback = 'scorevideo(''files_vtype'')';
files.vlistlabel.type = 'uicontrol';
files.vlistlabel.position = [.20 .77 .06 .04];                  % good for PC
files.vlistlabel.style = 'text';
files.vlistlabel.backgroundcolor = CON.clr.frame1;
files.vlistlabel.string = 'Contents (subsets):';
files.vlist.type = 'uicontrol';
files.vlist.position = [.245 .745 .145 .075];
files.vlist.style = 'listbox';
files.vlist.backgroundcolor = CON.clr.listbox;
files.vlist.fontname = 'courier';
files.vlist.fontsize = CON.fontsize.ax;
files.vlist.tooltipstring = 'COLUMNS:  prefix or filename  |  from  |  to';
files.vinputpathlabel.type = 'uicontrol';
files.vinputpathlabel.position = [.03 .70 .06 .03];
files.vinputpathlabel.style = 'pushbutton';
files.vinputpathlabel.backgroundcolor = CON.clr.button1;
files.vinputpathlabel.string = 'Directory';
files.vinputpathlabel.callback = 'scorevideo(''files_browsedir'',''video'');';
files.vinputpath.type = 'uicontrol';
files.vinputpath.position = [.10 .70 .29 .03];
files.vinputpath.style = 'edit';
files.vinputpath.backgroundcolor = CON.clr.uitext;
files.vinputprefixlabel.type = 'uicontrol';
files.vinputprefixlabel.position = [.03 .665 .06 .03];
files.vinputprefixlabel.style = 'pushbutton';
files.vinputprefixlabel.backgroundcolor = CON.clr.button1;
files.vinputprefixlabel.string = 'File prefix';
files.vinputprefixlabel.callback = 'scorevideo(''files_browsefile'',''video'');';
files.vinputprefix.type = 'uicontrol';
files.vinputprefix.position = [.10 .665 .08 .03];
files.vinputprefix.style = 'edit';
files.vinputprefix.backgroundcolor = CON.clr.uitext;
files.vinputprefix.horizontalalignment = 'center';
files.vinputfpsoilabel.type = 'uicontrol';
files.vinputfpsoilabel.position = [.215 .665 .06 .022];
files.vinputfpsoilabel.style = 'text';
files.vinputfpsoilabel.backgroundcolor = CON.clr.frame2;
files.vinputfpsoilabel.string = 'FPS of files';
files.vinputfpsoi.type = 'uicontrol';
files.vinputfpsoi.position = [.265 .665 .03 .03];
files.vinputfpsoi.style = 'edit';
files.vinputfpsoi.backgroundcolor = CON.clr.uitext;
files.vinputfpsoi.horizontalalignment = 'center';
files.vinputfpstplabel.type = 'uicontrol';
files.vinputfpstplabel.position = [.305 .665 .06 .022];         % good for PC
files.vinputfpstplabel.style = 'text';
files.vinputfpstplabel.backgroundcolor = CON.clr.frame2;
files.vinputfpstplabel.string = 'FPS to play';
files.vinputfpstp.type = 'uicontrol';
files.vinputfpstp.position = [.36 .665 .03 .03];
files.vinputfpstp.style = 'edit';
files.vinputfpstp.backgroundcolor = CON.clr.uitext;
files.vinputfpstp.horizontalalignment = 'center';
files.vinputnumstartlabel.type = 'uicontrol';
files.vinputnumstartlabel.position = [.03 .63 .07 .022];
files.vinputnumstartlabel.style = 'text';
files.vinputnumstartlabel.backgroundcolor = CON.clr.frame2;
files.vinputnumstartlabel.string = 'Include files';
files.vinputnumstart.type = 'uicontrol';
files.vinputnumstart.position = [.10 .63 .04 .03];
files.vinputnumstart.style = 'edit';
files.vinputnumstart.backgroundcolor = CON.clr.uitext;
files.vinputnumstart.horizontalalignment = 'center';
files.vinputnumendlabel.type = 'uicontrol';
files.vinputnumendlabel.position = [.145 .63 .015 .022];
files.vinputnumendlabel.style = 'text';
files.vinputnumendlabel.backgroundcolor = CON.clr.frame2;
files.vinputnumendlabel.string = 'to';
files.vinputnumend.type = 'uicontrol';
files.vinputnumend.position = [.16 .63 .04 .03];
files.vinputnumend.style = 'edit';
files.vinputnumend.backgroundcolor = CON.clr.uitext;
files.vinputnumend.horizontalalignment = 'center';
files.vinputinclall.type = 'uicontrol';
files.vinputinclall.position = [.206 .627 .015 .03];            % good for PC
files.vinputinclall.style = 'checkbox';
files.vinputinclall.value = 1;
files.vinputinclall.backgroundcolor = CON.clr.uitext;
files.vinputinclalllabel.type = 'uicontrol';
files.vinputinclalllabel.position = [.222 .628 .04 .022];       % good for PC
files.vinputinclalllabel.style = 'text';
files.vinputinclalllabel.backgroundcolor = CON.clr.frame2;
files.vinputinclalllabel.fontsize = CON.fontsize.sm;
files.vinputinclalllabel.string = 'all';
files.subpanel2.type = 'uicontrol';
files.subpanel2.position = [.026 .51 .368 .107];
files.subpanel2.style = 'text';
files.subpanel2.backgroundcolor = CON.clr.frame1;
files.ctitle.type = 'uicontrol';
files.ctitle.position = [.03 .576 .15 .03];
files.ctitle.style = 'text';
files.ctitle.backgroundcolor = CON.clr.frame1;
files.ctitle.fontweight = 'bold';
files.ctitle.string = 'COMMANDS FILE';
files.ccurrfilelabel.type = 'uicontrol';
files.ccurrfilelabel.position = [.03 .55 .05 .035];
files.ccurrfilelabel.style = 'text';
files.ccurrfilelabel.backgroundcolor = CON.clr.frame1;
files.ccurrfilelabel.string = 'Saved in:';
files.ccurrfile.type = 'uicontrol';
files.ccurrfile.position = [.08 .55 .30 .035];
files.ccurrfile.style = 'text';
files.ccurrfile.backgroundcolor = CON.clr.frame1;
files.ccurrfile.fontname = 'courier';
files.ccurrfile.fontsize = CON.fontsize.ax;
files.ccurrinfolabel.type = 'uicontrol';
files.ccurrinfolabel.position = [.03 .51 .05 .035];
files.ccurrinfolabel.style = 'text';
files.ccurrinfolabel.backgroundcolor = CON.clr.frame1;
files.ccurrinfolabel.string = 'Contents:';
files.ccurrinfo.type = 'uicontrol';
files.ccurrinfo.position = [.08 .51 .30 .035];
files.ccurrinfo.style = 'text';
files.ccurrinfo.backgroundcolor = CON.clr.frame1;
files.ccurrinfo.fontname = 'courier';
files.ccurrinfo.fontsize = CON.fontsize.ax;
files.cinputpathlabel.type = 'uicontrol';
files.cinputpathlabel.position = [.03 .472 .06 .03];
files.cinputpathlabel.style = 'pushbutton';
files.cinputpathlabel.backgroundcolor = CON.clr.button1;
files.cinputpathlabel.string = 'Directory';
files.cinputpathlabel.callback = 'scorevideo(''files_browsedir'',''cmnds'');';
files.cinputpath.type = 'uicontrol';
files.cinputpath.position = [.10 .472 .29 .03];
files.cinputpath.style = 'edit';
files.cinputpath.backgroundcolor = CON.clr.uitext;
files.cinputsuffixlabel.type = 'uicontrol';
files.cinputsuffixlabel.position = [.03 .437 .06 .03];
files.cinputsuffixlabel.style = 'pushbutton';
files.cinputsuffixlabel.backgroundcolor = CON.clr.button1;
files.cinputsuffixlabel.string = 'File suffix';
files.cinputsuffixlabel.callback = 'scorevideo(''files_browsefile'',''cmnds'');';
files.cinputsuffix.type = 'uicontrol';
files.cinputsuffix.position = [.10 .437 .08 .03];
files.cinputsuffix.style = 'edit';
files.cinputsuffix.backgroundcolor = CON.clr.uitext;
files.cinputsuffix.horizontalalignment = 'center';
files.subpanel3.type = 'uicontrol';
files.subpanel3.position = [.026 .321 .368 .107];
files.subpanel3.style = 'text';
files.subpanel3.backgroundcolor = CON.clr.frame1;
files.ltitle.type = 'uicontrol';
files.ltitle.position = [.03 .387 .15 .03];
files.ltitle.style = 'text';
files.ltitle.backgroundcolor = CON.clr.frame1;
files.ltitle.fontweight = 'bold';
files.ltitle.string = 'LOG FILE';
files.lcurrfilelabel.type = 'uicontrol';
files.lcurrfilelabel.position = [.03 .362 .05 .035];
files.lcurrfilelabel.style = 'text';
files.lcurrfilelabel.backgroundcolor = CON.clr.frame1;
files.lcurrfilelabel.string = 'Saved in:';
files.lcurrfile.type = 'uicontrol';
files.lcurrfile.position = [.08 .362 .30 .035];
files.lcurrfile.style = 'text';
files.lcurrfile.backgroundcolor = CON.clr.frame1;
files.lcurrfile.fontname = 'courier';
files.lcurrfile.fontsize = CON.fontsize.ax;
files.lcurrinfolabel.type = 'uicontrol';
files.lcurrinfolabel.position = [.03 .332 .05 .025];
files.lcurrinfolabel.style = 'text';
files.lcurrinfolabel.backgroundcolor = CON.clr.frame1;
files.lcurrinfolabel.string = 'Contents:';
files.lcurrinfo.type = 'uicontrol';
files.lcurrinfo.position = [.08 .327 .30 .03];
files.lcurrinfo.style = 'text';
files.lcurrinfo.backgroundcolor = CON.clr.frame1;
files.lcurrinfo.fontname = 'courier';
files.lcurrinfo.fontsize = CON.fontsize.ax;
files.linputpathlabel.type = 'uicontrol';
files.linputpathlabel.position = [.03 .283 .06 .03];
files.linputpathlabel.style = 'pushbutton';
files.linputpathlabel.backgroundcolor = CON.clr.button1;
files.linputpathlabel.string = 'Directory';
files.linputpathlabel.callback = 'scorevideo(''files_browsedir'',''log'');';
files.linputpath.type = 'uicontrol';
files.linputpath.position = [.10 .283 .29 .03];
files.linputpath.style = 'edit';
files.linputpath.backgroundcolor = CON.clr.uitext;
files.linputsuffixlabel.type = 'uicontrol';
files.linputsuffixlabel.position = [.03 .248 .06 .03];
files.linputsuffixlabel.style = 'pushbutton';
files.linputsuffixlabel.backgroundcolor = CON.clr.button1;
files.linputsuffixlabel.string = 'File suffix';
files.linputsuffixlabel.callback = 'scorevideo(''files_browsefile'',''log'');';
files.linputsuffix.type = 'uicontrol';
files.linputsuffix.position = [.10 .248 .08 .03];
files.linputsuffix.style = 'edit';
files.linputsuffix.backgroundcolor = CON.clr.uitext;
files.linputsuffix.horizontalalignment = 'center';
uicp.files = files;
cmnds.title.type = 'uicontrol';
cmnds.title.position = [.03 .94 .36 .025];
cmnds.title.style = 'text';
cmnds.title.backgroundcolor = CON.clr.frame2;
cmnds.title.horizontalalignment = 'center';
cmnds.title.fontsize = CON.fontsize.lg;
cmnds.title.fontweight = 'bold';
cmnds.title.string = 'COMMANDS';
cmnds.subpanel1.type = 'uicontrol';
cmnds.subpanel1.position = [.025 .64 .152 .288];
cmnds.subpanel1.style = 'text';
cmnds.subpanel1.backgroundcolor = CON.clr.frame1;
cmnds.fixedlistlabel.type = 'uicontrol';
cmnds.fixedlistlabel.position = [.031 .90 .14 .022];
cmnds.fixedlistlabel.style = 'text';
cmnds.fixedlistlabel.backgroundcolor = CON.clr.frame1;
cmnds.fixedlistlabel.horizontalalignment = 'center';
cmnds.fixedlistlabel.fontweight = 'bold';
cmnds.fixedlistlabel.string = 'PLAYBACK';
cmnds.fixedlistlabel2.type = 'uicontrol';
cmnds.fixedlistlabel2.position = [.031 .88 .14 .022];
cmnds.fixedlistlabel2.style = 'text';
cmnds.fixedlistlabel2.backgroundcolor = CON.clr.frame1;
cmnds.fixedlistlabel2.horizontalalignment = 'center';
cmnds.fixedlistlabel2.fontweight = 'bold';
cmnds.fixedlistlabel2.string = '(fixed)';
cmnds.fixedlist.type = 'uicontrol';
cmnds.fixedlist.position = [.031 .65 .14 .23];
cmnds.fixedlist.style = 'text';
cmnds.fixedlist.backgroundcolor = CON.clr.frame1;
cmnds.fixedlist.fontname = 'courier';
cmnds.fixedlist.fontsize = CON.fontsize.ax;
cmnds.settingstitle.type = 'uicontrol';
cmnds.settingstitle.position = [.031 .58 .14 .03];
cmnds.settingstitle.style = 'text';
cmnds.settingstitle.backgroundcolor = CON.clr.frame2;
cmnds.settingstitle.horizontalalignment = 'center';
cmnds.settingstitle.fontweight = 'bold';
cmnds.settingstitle.string = 'SETTINGS';
cmnds.subjnameslabel.type = 'uicontrol';
cmnds.subjnameslabel.position = [.031 .56 .12 .025];
cmnds.subjnameslabel.style = 'text';
cmnds.subjnameslabel.backgroundcolor = CON.clr.frame2;
cmnds.subjnameslabel.tooltipstring = 'Identity of each subject';
cmnds.subjnameslabel.string = 'Subject names';
cmnds.subj1namelabel.type = 'uicontrol';
cmnds.subj1namelabel.position = [.041 .52 .06 .03];
cmnds.subj1namelabel.style = 'text';
cmnds.subj1namelabel.backgroundcolor = CON.clr.frame2;
cmnds.subj1namelabel.fontsize = CON.fontsize.sm;
cmnds.subj1namelabel.string = 'Subject 1';
cmnds.subj1name.type = 'uicontrol';
cmnds.subj1name.position = [.091 .525 .07 .03];
cmnds.subj1name.style = 'edit';
cmnds.subj1name.backgroundcolor = CON.clr.uitext;
cmnds.subj1name.horizontalalignment = 'center';
cmnds.subj1name.callback = 'scorevideo(''behav_clearfull'');';
cmnds.subj2namelabel.type = 'uicontrol';
cmnds.subj2namelabel.position = [.041 .48 .06 .03];
cmnds.subj2namelabel.style = 'text';
cmnds.subj2namelabel.backgroundcolor = CON.clr.frame2;
cmnds.subj2namelabel.fontsize = CON.fontsize.sm;
cmnds.subj2namelabel.string = 'Subject 2';
cmnds.subj2name.type = 'uicontrol';
cmnds.subj2name.position = [.091 .485 .07 .03];
cmnds.subj2name.style = 'edit';
cmnds.subj2name.backgroundcolor = CON.clr.uitext;
cmnds.subj2name.horizontalalignment = 'center';
cmnds.subj2name.callback = 'scorevideo(''behav_clearfull'');';
cmnds.ncharlabel.type = 'uicontrol';
cmnds.ncharlabel.position = [.031 .404 .085 .05];
cmnds.ncharlabel.style = 'text';
cmnds.ncharlabel.backgroundcolor = CON.clr.frame2;
cmnds.ncharlabel.string = 'No. of characters in scoring commands';
cmnds.nchar.type = 'uicontrol';
cmnds.nchar.position = [.121 .415 .04 .035];
cmnds.nchar.style = 'popup';
cmnds.nchar.backgroundcolor = CON.clr.uitext;
cmnds.nchar.string = {1;2};
cmnds.nchar.value = 1;
cmnds.nchar.callback = 'scorevideo(''cmnds_nchar'');';
cmnds.simbehavlabel.type = 'uicontrol';
cmnds.simbehavlabel.position = [.031 .34 .09 .05];
cmnds.simbehavlabel.style = 'text';
cmnds.simbehavlabel.backgroundcolor = CON.clr.frame2;
cmnds.simbehavlabel.string = 'No. of simultaneous behaviors';
cmnds.simbehav.type = 'uicontrol';
cmnds.simbehav.position = [.071 .315 .09 .035];
cmnds.simbehav.style = 'popup';
cmnds.simbehav.backgroundcolor = CON.clr.uitext;
cmnds.simbehav.callback = 'scorevideo(''behav_clearfull'');';
cmnds.uclistlabel.type = 'uicontrol';
cmnds.uclistlabel.position = [.184 .90 .205 .022];
cmnds.uclistlabel.style = 'text';
cmnds.uclistlabel.backgroundcolor = CON.clr.frame2;
cmnds.uclistlabel.horizontalalignment = 'center';
cmnds.uclistlabel.fontweight = 'bold';
cmnds.uclistlabel.string = 'SCORING';
cmnds.uclistlabel2.type = 'uicontrol';
cmnds.uclistlabel2.position = [.184 .88 .205 .022];
cmnds.uclistlabel2.style = 'text';
cmnds.uclistlabel2.backgroundcolor = CON.clr.frame2;
cmnds.uclistlabel2.horizontalalignment = 'center';
cmnds.uclistlabel2.fontweight = 'bold';
cmnds.uclistlabel2.string = '(user-defined command set)';
cmnds.uclist.type = 'uicontrol';
cmnds.uclist.position = [.184 .45 .205 .43];
cmnds.uclist.style = 'listbox';
cmnds.uclist.backgroundcolor = CON.clr.listbox;
cmnds.uclist.fontname = 'courier';
cmnds.uclist.fontsize = CON.fontsize.ax;
cmnds.uclist.tooltipstring = 'COLUMNS: start | stop | subject | description';
cmnds.ucentrylabel.type = 'uicontrol';
cmnds.ucentrylabel.position = [.184 .41 .14 .025];
cmnds.ucentrylabel.style = 'text';
cmnds.ucentrylabel.backgroundcolor = CON.clr.frame2;
cmnds.ucentrylabel.string = 'Scoring command entry';
cmnds.bcharlabel.type = 'uicontrol';
cmnds.bcharlabel.position = [.184 .39 .03 .02];
cmnds.bcharlabel.style = 'text';
cmnds.bcharlabel.backgroundcolor = CON.clr.frame2;
cmnds.bcharlabel.fontsize = CON.fontsize.sm;
cmnds.bcharlabel.string = 'Start';
cmnds.bchar.type = 'uicontrol';
cmnds.bchar.position = [.184 .359 .025 .03];
cmnds.bchar.style = 'edit';
cmnds.bchar.backgroundcolor = CON.clr.uitext;
cmnds.bchar.horizontalalignment = 'center';
cmnds.echarlabel.type = 'uicontrol';
cmnds.echarlabel.position = [.214 .39 .03 .02];
cmnds.echarlabel.style = 'text';
cmnds.echarlabel.backgroundcolor = CON.clr.frame2;
cmnds.echarlabel.fontsize = CON.fontsize.sm;
cmnds.echarlabel.string = 'Stop';
cmnds.echar.type = 'uicontrol';
cmnds.echar.position = [.214 .359 .025 .03];
cmnds.echar.style = 'edit';
cmnds.echar.backgroundcolor = CON.clr.uitext;
cmnds.echar.horizontalalignment = 'center';
cmnds.subjlabel.type = 'uicontrol';
cmnds.subjlabel.position = [.244 .39 .03 .02];
cmnds.subjlabel.style = 'text';
cmnds.subjlabel.backgroundcolor = CON.clr.frame2;
cmnds.subjlabel.fontsize = CON.fontsize.sm;
cmnds.subjlabel.string = 'Subj #';
cmnds.subj.type = 'uicontrol';
cmnds.subj.position = [.246 .357 .04 .03];              % width good for PC
cmnds.subj.style = 'popup';
cmnds.subj.backgroundcolor = CON.clr.uitext;
cmnds.subj.string = {'0  (either)';'1  (subj #1)';'2  (subj #2)';'3  (both)'};
cmnds.desclabel.type = 'uicontrol';
cmnds.desclabel.position = [.294 .39 .095 .02];
cmnds.desclabel.style = 'text';
cmnds.desclabel.backgroundcolor = CON.clr.frame2;
cmnds.desclabel.fontsize = CON.fontsize.sm;
cmnds.desclabel.string = 'Description';
cmnds.desc.type = 'uicontrol';
cmnds.desc.position = [.294 .359 .095 .03];
cmnds.desc.style = 'edit';
cmnds.desc.backgroundcolor = CON.clr.uitext;
cmnds.desc.horizontalalignment = 'center';
cmnds.add.type = 'uicontrol';
cmnds.add.position = [.184 .319 .045 .03];
cmnds.add.style = 'pushbutton';
cmnds.add.backgroundcolor = CON.clr.button1;
cmnds.add.horizontalalignment = 'center';
cmnds.add.string = 'Add';
cmnds.add.callback = 'scorevideo(''cmnds_add'');';
cmnds.delete.type = 'uicontrol';
cmnds.delete.position = [.235 .319 .045 .03];
cmnds.delete.style = 'pushbutton';
cmnds.delete.backgroundcolor = CON.clr.button1;
cmnds.delete.foregroundcolor = CON.clr.button4;
cmnds.delete.horizontalalignment = 'center';
cmnds.delete.string = 'Delete';
cmnds.delete.callback = 'scorevideo(''cmnds_delete'');';
cmnds.edit.type = 'uicontrol';
cmnds.edit.position = [.288 .319 .045 .03];
cmnds.edit.style = 'pushbutton';
cmnds.edit.backgroundcolor = CON.clr.button1;
cmnds.edit.horizontalalignment = 'center';
cmnds.edit.string = 'Edit';
cmnds.edit.callback = 'scorevideo(''cmnds_edit'');';
cmnds.update.type = 'uicontrol';
cmnds.update.position = [.339 .319 .05 .03];
cmnds.update.style = 'pushbutton';
cmnds.update.backgroundcolor = CON.clr.button1;
cmnds.update.horizontalalignment = 'center';
cmnds.update.string = 'Update';
cmnds.update.callback = 'scorevideo(''cmnds_update'');';
uicp.cmnds = cmnds;
behav.title.type = 'uicontrol';
behav.title.position = [.03 .94 .36 .025];
behav.title.style = 'text';
behav.title.backgroundcolor = CON.clr.frame2;
behav.title.horizontalalignment = 'center';
behav.title.fontsize = CON.fontsize.lg;
behav.title.fontweight = 'bold';
behav.title.string = 'SCORED BEHAVIORS';
behav.rawloglabel.type = 'uicontrol';
behav.rawloglabel.position = [.03 .88 .14 .025];
behav.rawloglabel.style = 'text';
behav.rawloglabel.backgroundcolor = CON.clr.frame2;
behav.rawloglabel.horizontalalignment = 'center';
behav.rawloglabel.fontweight = 'bold';
behav.rawloglabel.string = 'RAW SCORE LOG';
behav.rawlog.type = 'uicontrol';
behav.rawlog.position = [.03 .53 .14 .35];
behav.rawlog.style = 'listbox';
behav.rawlog.backgroundcolor = CON.clr.listbox;
behav.rawlog.fontname = 'courier';
behav.rawlog.fontsize = CON.fontsize.ax;
behav.rawlog.tooltipstring = 'COLUMNS:  frame | time(min:sec) | command';
behav.delete.type = 'uicontrol';
behav.delete.position = [.04 .49 .08 .03];
behav.delete.style = 'pushbutton';
behav.delete.backgroundcolor = CON.clr.button1;
behav.delete.foregroundcolor = CON.clr.button4;
behav.delete.horizontalalignment = 'center';
behav.delete.string = 'Delete entry';
behav.delete.callback = 'scorevideo(''behav_delete'');';
behav.overwrite.type = 'uicontrol';
behav.overwrite.position = [.13 .49 .018 .025];
behav.overwrite.style = 'checkbox';
behav.overwrite.backgroundcolor = CON.clr.uitext;
behav.overwrite.callback = 'scorevideo(''behav_overwrite'');';
behav.overwritelabel.type = 'uicontrol';
behav.overwritelabel.position = [.15 .48 .05 .035];
behav.overwritelabel.style = 'text';
behav.overwritelabel.backgroundcolor = CON.clr.frame2;
behav.overwritelabel.fontsize = CON.fontsize.sm;
behav.overwritelabel.string = 'Overwrite score log';
behav.fullloglabel.type = 'uicontrol';
behav.fullloglabel.position = [.18 .88 .21 .025];
behav.fullloglabel.style = 'text';
behav.fullloglabel.backgroundcolor = CON.clr.frame2;
behav.fullloglabel.horizontalalignment = 'center';
behav.fullloglabel.fontweight = 'bold';
behav.fullloglabel.string = 'FULL SCORE LOG';
behav.fulllog.type = 'uicontrol';
behav.fulllog.position = [.18 .53 .21 .35];
behav.fulllog.style = 'listbox';
behav.fulllog.backgroundcolor = CON.clr.listbox;
behav.fulllog.fontname = 'courier';
behav.fulllog.fontsize = CON.fontsize.ax;
behav.fulllog.tooltipstring = 'COLUMNS:  frame | time(min:sec) | description | action | subject';
behav.build.type = 'uicontrol';
behav.build.position = [.23 .49 .08 .03];
behav.build.style = 'pushbutton';
behav.build.backgroundcolor = CON.clr.button1;
behav.build.horizontalalignment = 'center';
behav.build.string = 'Build full log';
behav.build.callback = 'scorevideo(''behav_buildfull'');';
behav.buildasyougo.type = 'uicontrol';
behav.buildasyougo.position = [.32 .49 .015 .025];
behav.buildasyougo.style = 'checkbox';
behav.buildasyougo.backgroundcolor = CON.clr.uitext;
behav.buildasyougo.callback = 'scorevideo(''behav_buildasyougo'');';
behav.buildasyougolabel.type = 'uicontrol';
behav.buildasyougolabel.position = [.34 .48 .04 .035];
behav.buildasyougolabel.style = 'text';
behav.buildasyougolabel.backgroundcolor = CON.clr.frame2;
behav.buildasyougolabel.fontsize = CON.fontsize.sm;
behav.buildasyougolabel.string = 'Build as you go';
behav.subpanel2.type = 'uicontrol';
behav.subpanel2.position = [.245 .325 .14 .135];
behav.subpanel2.style = 'text';
behav.subpanel2.backgroundcolor = CON.clr.button1;
behav.jumplabel.type = 'uicontrol';
behav.jumplabel.position = [.25 .41 .06 .04];
behav.jumplabel.style = 'text';
behav.jumplabel.backgroundcolor = CON.clr.button1;
behav.jumplabel.fontweight = 'bold';
behav.jumplabel.string = 'Displayed frame';
behav.jump.type = 'uicontrol';
behav.jump.position = [.31 .42 .07 .03];
behav.jump.style = 'pushbutton';
behav.jump.backgroundcolor = CON.clr.button1;
behav.jump.horizontalalignment = 'center';
behav.jump.string = 'Jump';
behav.jump.callback = 'scorevideo(''jump'',''behav'');';
behav.jumpfnumlabel.type = 'uicontrol';
behav.jumpfnumlabel.position = [.25 .37 .06 .025];
behav.jumpfnumlabel.style = 'text';
behav.jumpfnumlabel.backgroundcolor = CON.clr.button1;
behav.jumpfnumlabel.fontsize = CON.fontsize.sm;
behav.jumpfnumlabel.string = 'Frame number:';
behav.jumpfnum.type = 'uicontrol';
behav.jumpfnum.position = [.31 .37 .07 .034];
behav.jumpfnum.style = 'edit';
behav.jumpfnum.backgroundcolor = CON.clr.uitext;
behav.jumpfnum.horizontalalignment = 'center';
behav.logselection.type = 'uicontrol';
behav.logselection.position = [.25 .33 .06 .03];
behav.logselection.style = 'pushbutton';
behav.logselection.backgroundcolor = CON.clr.button1;
behav.logselection.horizontalalignment = 'center';
behav.logselection.fontsize = CON.fontsize.sm;
behav.logselection.string = 'Log selection';
behav.logselection.callback = 'scorevideo(''getlogselection'',''score'');';
behav.endoflog.type = 'uicontrol';
behav.endoflog.position = [.32 .33 .06 .03];
behav.endoflog.style = 'pushbutton';
behav.endoflog.backgroundcolor = CON.clr.button1;
behav.endoflog.horizontalalignment = 'center';
behav.endoflog.fontsize = CON.fontsize.sm;
behav.endoflog.string = 'End of log';
behav.endoflog.callback = 'scorevideo(''getendoflog'',''score'');';
behav.logclearraw.type = 'uicontrol';
behav.logclearraw.position = [.04 .33 .08 .03];
behav.logclearraw.style = 'pushbutton';
behav.logclearraw.backgroundcolor = CON.clr.button1;
behav.logclearraw.foregroundcolor = CON.clr.button4;
behav.logclearraw.horizontalalignment = 'center';
behav.logclearraw.string = 'Clear score log';
behav.logclearraw.callback = 'scorevideo(''behav_clearraw'');';
uicp.behav = behav;
nandm.title.type = 'uicontrol';
nandm.title.position = [.03 .94 .36 .025];
nandm.title.style = 'text';
nandm.title.backgroundcolor = CON.clr.frame2;
nandm.title.horizontalalignment = 'center';
nandm.title.fontsize = CON.fontsize.lg;
nandm.title.fontweight = 'bold';
nandm.title.string = 'NOTES & MARKS';
nandm.notesloglabel.type = 'uicontrol';
nandm.notesloglabel.position = [.04 .88 .34 .025];
nandm.notesloglabel.style = 'text';
nandm.notesloglabel.backgroundcolor = CON.clr.frame2;
nandm.notesloglabel.horizontalalignment = 'center';
nandm.notesloglabel.fontweight = 'bold';
nandm.notesloglabel.string = 'NOTES LOG';
nandm.noteslog.type = 'uicontrol';
nandm.noteslog.position = [.04 .72 .34 .16];
nandm.noteslog.style = 'listbox';
nandm.noteslog.backgroundcolor = CON.clr.listbox;
nandm.noteslog.fontname = 'courier';
nandm.noteslog.fontsize = CON.fontsize.ax;
nandm.entrytextlabel.type = 'uicontrol';
nandm.entrytextlabel.position = [.04 .69 .06 .02];
nandm.entrytextlabel.style = 'text';
nandm.entrytextlabel.backgroundcolor = CON.clr.frame2;
nandm.entrytextlabel.fontsize = CON.fontsize.sm;
nandm.entrytextlabel.string = 'Notes entry';
nandm.entrytext.type = 'uicontrol';
nandm.entrytext.position = [.04 .65 .34 .03];
nandm.entrytext.style = 'edit';
nandm.entrytext.backgroundcolor = CON.clr.uitext;
nandm.notesadd.type = 'uicontrol';
nandm.notesadd.position = [.04 .61 .04 .03];
nandm.notesadd.style = 'pushbutton';
nandm.notesadd.backgroundcolor = CON.clr.button1;
nandm.notesadd.horizontalalignment = 'center';
nandm.notesadd.string = 'Add';
nandm.notesadd.callback = 'scorevideo(''notes_add'');';
nandm.notesdelete.type = 'uicontrol';
nandm.notesdelete.position = [.085 .61 .05 .03];
nandm.notesdelete.style = 'pushbutton';
nandm.notesdelete.backgroundcolor = CON.clr.button1;
nandm.notesdelete.foregroundcolor = CON.clr.button4;
nandm.notesdelete.horizontalalignment = 'center';
nandm.notesdelete.string = 'Delete';
nandm.notesdelete.callback = 'scorevideo(''notes_delete'');';
nandm.notesedit.type = 'uicontrol';
nandm.notesedit.position = [.14 .61 .04 .03];
nandm.notesedit.style = 'pushbutton';
nandm.notesedit.backgroundcolor = CON.clr.button1;
nandm.notesedit.horizontalalignment = 'center';
nandm.notesedit.string = 'Edit';
nandm.notesedit.callback = 'scorevideo(''notes_edit'');';
nandm.notesupdate.type = 'uicontrol';
nandm.notesupdate.position = [.185 .61 .05 .03];
nandm.notesupdate.style = 'pushbutton';
nandm.notesupdate.backgroundcolor = CON.clr.button1;
nandm.notesupdate.horizontalalignment = 'center';
nandm.notesupdate.string = 'Update';
nandm.notesupdate.callback = 'scorevideo(''notes_update'');';
nandm.marksloglabel.type = 'uicontrol';
nandm.marksloglabel.position = [.04 .55 .195 .025];
nandm.marksloglabel.style = 'text';
nandm.marksloglabel.backgroundcolor = CON.clr.frame2;
nandm.marksloglabel.horizontalalignment = 'center';
nandm.marksloglabel.fontweight = 'bold';
nandm.marksloglabel.string = 'MARKS LOG';
nandm.markslog.type = 'uicontrol';
nandm.markslog.position = [.04 .43 .195 .12];
nandm.markslog.style = 'listbox';
nandm.markslog.backgroundcolor = CON.clr.listbox;
nandm.markslog.fontname = 'courier';
nandm.markslog.fontsize = CON.fontsize.ax;
nandm.markslog.tooltipstring = 'COLUMNS:  frame | time(min:sec) | mark name';
nandm.marksframelabel.type = 'uicontrol';
nandm.marksframelabel.position = [.04 .40 .05 .02];
nandm.marksframelabel.style = 'text';
nandm.marksframelabel.backgroundcolor = CON.clr.frame2;
nandm.marksframelabel.fontsize = CON.fontsize.sm;
nandm.marksframelabel.string = 'Frame #';
nandm.marksframe.type = 'uicontrol';
nandm.marksframe.position = [.04 .369 .05 .03];
nandm.marksframe.style = 'edit';
nandm.marksframe.backgroundcolor = CON.clr.uitext;
nandm.marksframe.horizontalalignment = 'center';
nandm.marksnamelabel.type = 'uicontrol';
nandm.marksnamelabel.position = [.10 .40 .05 .02];
nandm.marksnamelabel.style = 'text';
nandm.marksnamelabel.backgroundcolor = CON.clr.frame2;
nandm.marksnamelabel.fontsize = CON.fontsize.sm;
nandm.marksnamelabel.string = 'Mark name';
nandm.marksname.type = 'uicontrol';
nandm.marksname.position = [.10 .369 .135 .03];
nandm.marksname.style = 'edit';
nandm.marksname.backgroundcolor = CON.clr.uitext;
nandm.marksadd.type = 'uicontrol';
nandm.marksadd.position = [.04 .33 .04 .03];
nandm.marksadd.style = 'pushbutton';
nandm.marksadd.backgroundcolor = CON.clr.button1;
nandm.marksadd.horizontalalignment = 'center';
nandm.marksadd.string = 'Add';
nandm.marksadd.callback = 'scorevideo(''marks_add'');';
nandm.marksdelete.type = 'uicontrol';
nandm.marksdelete.position = [.085 .33 .05 .03];
nandm.marksdelete.style = 'pushbutton';
nandm.marksdelete.backgroundcolor = CON.clr.button1;
nandm.marksdelete.foregroundcolor = CON.clr.button4;
nandm.marksdelete.horizontalalignment = 'center';
nandm.marksdelete.string = 'Delete';
nandm.marksdelete.callback = 'scorevideo(''marks_delete'');';
nandm.marksedit.type = 'uicontrol';
nandm.marksedit.position = [.14 .33 .04 .03];
nandm.marksedit.style = 'pushbutton';
nandm.marksedit.backgroundcolor = CON.clr.button1;
nandm.marksedit.horizontalalignment = 'center';
nandm.marksedit.string = 'Edit';
nandm.marksedit.callback = 'scorevideo(''marks_edit'');';
nandm.marksupdate.type = 'uicontrol';
nandm.marksupdate.position = [.185 .33 .05 .03];
nandm.marksupdate.style = 'pushbutton';
nandm.marksupdate.backgroundcolor = CON.clr.button1;
nandm.marksupdate.horizontalalignment = 'center';
nandm.marksupdate.string = 'Update';
nandm.marksupdate.callback = 'scorevideo(''marks_update'');';
nandm.markssetlabel.type = 'uicontrol';
nandm.markssetlabel.position = [.26 .52 .12 .03];
nandm.markssetlabel.style = 'text';
nandm.markssetlabel.backgroundcolor = CON.clr.frame2;
nandm.markssetlabel.fontweight = 'bold';
nandm.markssetlabel.string = 'Analysis window marks';
nandm.marksstartlabel.type = 'uicontrol';
nandm.marksstartlabel.position = [.26 .48 .03 .03];
nandm.marksstartlabel.style = 'text';
nandm.marksstartlabel.backgroundcolor = CON.clr.frame2;
nandm.marksstartlabel.string = 'Start';
nandm.marksstart.type = 'uicontrol';
nandm.marksstart.position = [.29 .48 .05 .03];
nandm.marksstart.style = 'text';
nandm.marksstart.backgroundcolor = CON.clr.uitext;
nandm.marksstart.horizontalalignment = 'center';
nandm.markssetstart.type = 'uicontrol';
nandm.markssetstart.position = [.35 .49 .03 .03];
nandm.markssetstart.style = 'pushbutton';
nandm.markssetstart.backgroundcolor = CON.clr.button1;
nandm.markssetstart.horizontalalignment = 'center';
nandm.markssetstart.string = 'Set';
nandm.markssetstart.callback = 'scorevideo(''marks_setstart'');';
nandm.marksalignlabel.type = 'uicontrol';
nandm.marksalignlabel.position = [.26 .44 .03 .03];
nandm.marksalignlabel.style = 'text';
nandm.marksalignlabel.backgroundcolor = CON.clr.frame2;
nandm.marksalignlabel.string = 'Align';
nandm.marksalign.type = 'uicontrol';
nandm.marksalign.position = [.29 .44 .05 .03];
nandm.marksalign.style = 'text';
nandm.marksalign.backgroundcolor = CON.clr.uitext;
nandm.marksalign.horizontalalignment = 'center';
nandm.markssetalign.type = 'uicontrol';
nandm.markssetalign.position = [.35 .45 .03 .03];
nandm.markssetalign.style = 'pushbutton';
nandm.markssetalign.backgroundcolor = CON.clr.button1;
nandm.markssetalign.horizontalalignment = 'center';
nandm.markssetalign.string = 'Set';
nandm.markssetalign.callback = 'scorevideo(''marks_setalign'');';
nandm.marksendlabel.type = 'uicontrol';
nandm.marksendlabel.position = [.26 .40 .03 .03];
nandm.marksendlabel.style = 'text';
nandm.marksendlabel.backgroundcolor = CON.clr.frame2;
nandm.marksendlabel.string = 'End';
nandm.marksend.type = 'uicontrol';
nandm.marksend.position = [.29 .40 .05 .03];
nandm.marksend.style = 'text';
nandm.marksend.backgroundcolor = CON.clr.uitext;
nandm.marksend.horizontalalignment = 'center';
nandm.markssetend.type = 'uicontrol';
nandm.markssetend.position = [.35 .41 .03 .03];
nandm.markssetend.style = 'pushbutton';
nandm.markssetend.backgroundcolor = CON.clr.button1;
nandm.markssetend.horizontalalignment = 'center';
nandm.markssetend.string = 'Set';
nandm.markssetend.callback = 'scorevideo(''marks_setend'');';
nandm.marksinclstartsbefore.type = 'uicontrol';
nandm.marksinclstartsbefore.position = [.26 .35 .015 .03];
nandm.marksinclstartsbefore.style = 'checkbox';
nandm.marksinclstartsbefore.backgroundcolor = CON.clr.uitext;
nandm.marksinclstartsbefore.callback = 'scorevideo(''marks_inclstartsbefore'');';
nandm.marksinclstartsbefore.value = 0;
nandm.marksinclstartsbeforelabel.type = 'uicontrol';
nandm.marksinclstartsbeforelabel.position = [.28 .33 .10 .05];
nandm.marksinclstartsbeforelabel.style = 'text';
nandm.marksinclstartsbeforelabel.backgroundcolor = CON.clr.uitext;
nandm.marksinclstartsbeforelabel.horizontalalignment = 'left';
nandm.marksinclstartsbeforelabel.string = 'Include starts before analysis window';
nandm.marksinclstopsafter.type = 'uicontrol';
nandm.marksinclstopsafter.position = [.26 .30 .015 .03];
nandm.marksinclstopsafter.style = 'checkbox';
nandm.marksinclstopsafter.backgroundcolor = CON.clr.uitext;
nandm.marksinclstopsafter.callback = 'scorevideo(''marks_inclstopsafter'');';
nandm.marksinclstopsafter.value = 1;
nandm.marksinclstopsafterlabel.type = 'uicontrol';
nandm.marksinclstopsafterlabel.position = [.28 .28 .10 .05];
nandm.marksinclstopsafterlabel.style = 'text';
nandm.marksinclstopsafterlabel.backgroundcolor = CON.clr.uitext;
nandm.marksinclstopsafterlabel.horizontalalignment = 'left';
nandm.marksinclstopsafterlabel.string = 'Include stops after analysis window';
uicp.nandm = nandm;
uicp = checkmodules('init',FFL,CON,uicp);
analy.title.type = 'uicontrol';
analy.title.position = [.03 .94 .36 .025];
analy.title.style = 'text';
analy.title.backgroundcolor = CON.clr.frame2;
analy.title.horizontalalignment = 'center';
analy.title.fontsize = CON.fontsize.lg;
analy.title.fontweight = 'bold';
analy.title.string = 'ANALYSIS';
analy.figureslabel.type = 'uicontrol';
analy.figureslabel.position = [.03 .89 .10 .03];
analy.figureslabel.style = 'text';
analy.figureslabel.backgroundcolor = CON.clr.frame2;
analy.figureslabel.fontweight = 'bold';
analy.figureslabel.string = 'FIGURES';
analy.plottable.type = 'uicontrol';
analy.plottable.position = [.04 .86 .09 .03];
analy.plottable.style = 'pushbutton';
analy.plottable.backgroundcolor = CON.clr.button1;
analy.plottable.horizontalalignment = 'center';
analy.plottable.string = 'Table';
analy.plottable.callback = 'scorevideo(''analy_plots'',''table'');';
analy.plotraster.type = 'uicontrol';
analy.plotraster.position = [.15 .86 .09 .03];
analy.plotraster.style = 'pushbutton';
analy.plotraster.backgroundcolor = CON.clr.button1;
analy.plotraster.horizontalalignment = 'center';
analy.plotraster.string = 'Raster';
analy.plotraster.callback = 'scorevideo(''analy_plots'',''raster'');';
analy.plotrasterandtable.type = 'uicontrol';
analy.plotrasterandtable.position = [.26 .86 .09 .03];
analy.plotrasterandtable.style = 'pushbutton';
analy.plotrasterandtable.backgroundcolor = CON.clr.button1;
analy.plotrasterandtable.horizontalalignment = 'center';
analy.plotrasterandtable.string = 'Raster and table';
analy.plotrasterandtable.callback = 'scorevideo(''analy_plots'',''rasterandtable'');';
analy.settingslabel.type = 'uicontrol';
analy.settingslabel.position = [.035 .805 .08 .022];
analy.settingslabel.style = 'text';
analy.settingslabel.backgroundcolor = CON.clr.frame2;
analy.settingslabel.string = 'Settings';
analy.fontsizelabel.type = 'uicontrol';
analy.fontsizelabel.position = [.04 .755 .06 .022];
analy.fontsizelabel.style = 'text';
analy.fontsizelabel.backgroundcolor = CON.clr.frame2;
analy.fontsizelabel.fontsize = CON.fontsize.sm;
analy.fontsizelabel.string = 'Font size';
analy.fontsize.type = 'uicontrol';
analy.fontsize.position = [.09 .75 .04 .035];               % width good for PC
analy.fontsize.style = 'popup';
analy.fontsize.backgroundcolor = CON.clr.uitext;
analy.fontsize.string = {'6';'9';'10'};
analy.fontsize.value = 2;
analy.npanelslabel.type = 'uicontrol';
analy.npanelslabel.position = [.04 .71 .06 .022];
analy.npanelslabel.style = 'text';
analy.npanelslabel.backgroundcolor = CON.clr.frame2;
analy.npanelslabel.fontsize = CON.fontsize.sm;
analy.npanelslabel.string = 'Panels per page';
analy.npanels.type = 'uicontrol';
analy.npanels.position = [.06 .68 .03 .03];
analy.npanels.style = 'edit';
analy.npanels.backgroundcolor = CON.clr.uitext;
analy.npanels.horizontalalignment = 'center';
analy.npanels.string = '4';
analy.npanels.userdata = 1;
analy.npanels.callback = 'scorevideo(''analy_updateparams'',''npanels'');';
analy.npageslabel.type = 'uicontrol';
analy.npageslabel.position = [.04 .65 .05 .022];
analy.npageslabel.style = 'text';
analy.npageslabel.backgroundcolor = CON.clr.frame2;
analy.npageslabel.fontsize = CON.fontsize.sm;
analy.npageslabel.string = 'Total pages';
analy.npages.type = 'uicontrol';
analy.npages.position = [.06 .62 .03 .03];
analy.npages.style = 'edit';
analy.npages.backgroundcolor = CON.clr.uitext;
analy.npages.horizontalalignment = 'center';
analy.npages.userdata = 3;
analy.npages.callback = 'scorevideo(''analy_updateparams'',''npages'');';
analy.nminslabel.type = 'uicontrol';
analy.nminslabel.position = [.04 .59 .05 .022];
analy.nminslabel.style = 'text';
analy.nminslabel.backgroundcolor = CON.clr.frame2;
analy.nminslabel.fontsize = CON.fontsize.sm;
analy.nminslabel.string = 'Min per panel';
analy.nmins.type = 'uicontrol';
analy.nmins.position = [.06 .56 .03 .03];
analy.nmins.style = 'edit';
analy.nmins.backgroundcolor = CON.clr.uitext;
analy.nmins.horizontalalignment = 'center';
analy.nmins.string = '15';
analy.nmins.userdata = 2;
analy.nmins.callback = 'scorevideo(''analy_updateparams'',''nmins'');';
analy.calcparams.type = 'uicontrol';
analy.calcparams.position = [.105 .595 .025 .03];
analy.calcparams.style = 'pushbutton';
analy.calcparams.backgroundcolor = CON.clr.button1;
analy.calcparams.horizontalalignment = 'center';
analy.calcparams.fontsize = CON.fontsize.sm;
analy.calcparams.string = 'calc';
analy.calcparams.callback = 'scorevideo(''analy_calcparams'');';
analy.axes_links.type = 'axes';
analy.axes_links.position = [.09 .535 .018 .20];
analy.axes_links.color = CON.clr.frame2;
analy.axes_links.xcolor = CON.clr.frame2;
analy.axes_links.ycolor = CON.clr.frame2;
analy.axes_links.xlim = [0 2];
analy.axes_links.ylim = [0 1];
analy.links1.type = 'plot';
analy.links1.xdata = [1 1 1];
analy.links1.ydata = [.2 .5 .8];
analy.links1.sdata = '.';
analy.links1.markersize = 20;
analy.links1.color = CON.clr.frame4;
analy.links2.type = 'plot';
analy.links2.xdata = [1 1.5];
analy.links2.ydata = [.2 .2];
analy.links2.sdata = '-';
analy.links2.color = CON.clr.frame4;
analy.links3.type = 'plot';
analy.links3.xdata = [1 1.5];
analy.links3.ydata = [.5 .5];
analy.links3.sdata = '-';
analy.links3.color = CON.clr.frame4;
analy.links4.type = 'plot';
analy.links4.xdata = [1 1.5];
analy.links4.ydata = [.8 .8];
analy.links4.sdata = '-';
analy.links4.color = CON.clr.frame4;
analy.links5.type = 'plot';
analy.links5.xdata = [1.5 1.5];
analy.links5.ydata = [.2 .8];
analy.links5.sdata = '-';
analy.links5.color = CON.clr.frame4;
analy.setpanelht.type = 'uicontrol';
analy.setpanelht.position = [.043 .51 .015 .03];
analy.setpanelht.style = 'checkbox';
analy.setpanelht.backgroundcolor = CON.clr.uitext;
analy.panelhtlabel.type = 'uicontrol';
analy.panelhtlabel.position = [.062 .51 .07 .022];
analy.panelhtlabel.style = 'text';
analy.panelhtlabel.backgroundcolor = CON.clr.frame2;
analy.panelhtlabel.fontsize = CON.fontsize.sm;
analy.panelhtlabel.string = 'Panel ht';
analy.panelht.type = 'uicontrol';
analy.panelht.position = [.075 .48 .04 .03];
analy.panelht.style = 'edit';
analy.panelht.backgroundcolor = CON.clr.uitext;
analy.panelht.horizontalalignment = 'center';
analy.panelht.tooltipstring = 'Proportion of y-axis, 0 to 1';
analy.inclsubjname.type = 'uicontrol';
analy.inclsubjname.position = [.043 .436 .015 .025];
analy.inclsubjname.style = 'checkbox';
analy.inclsubjname.backgroundcolor = CON.clr.uitext;
analy.inclsubjname.value = 1;
analy.inclsubjnamelabel.type = 'uicontrol';
analy.inclsubjnamelabel.position = [.062 .423 .075 .04];
analy.inclsubjnamelabel.style = 'text';
analy.inclsubjnamelabel.backgroundcolor = CON.clr.frame2;
analy.inclsubjnamelabel.fontsize = CON.fontsize.sm;
analy.inclsubjnamelabel.string = 'Include subject in raster axis labels';
analy.behavtoincllabel.type = 'uicontrol';
analy.behavtoincllabel.position = [.14 .805 .12 .022];
analy.behavtoincllabel.style = 'text';
analy.behavtoincllabel.backgroundcolor = CON.clr.frame2;
analy.behavtoincllabel.string = 'Behaviors to include';
analy.behaviorslabel.type = 'uicontrol';
analy.behaviorslabel.position = [.154 .78 .08 .022];
analy.behaviorslabel.style = 'text';
analy.behaviorslabel.backgroundcolor = CON.clr.frame2;
analy.behaviorslabel.fontsize = CON.fontsize.sm;
analy.behaviorslabel.string = 'Behaviors';
analy.orderlabel.type = 'uicontrol';
analy.orderlabel.position = [.235 .78 .035 .022];
analy.orderlabel.style = 'text';
analy.orderlabel.backgroundcolor = CON.clr.frame2;
analy.orderlabel.fontsize = CON.fontsize.sm;
analy.orderlabel.string = 'Order';
analy.colorlabel.type = 'uicontrol';
analy.colorlabel.position = [.27 .78 .09 .022];
analy.colorlabel.style = 'text';
analy.colorlabel.backgroundcolor = CON.clr.frame2;
analy.colorlabel.fontsize = CON.fontsize.sm;
analy.colorlabel.string = 'Color (RGB)';
analy.behaviorslist.type = 'uicontrol';
analy.behaviorslist.position = [.15 .50 .24 .28];
analy.behaviorslist.style = 'listbox';
analy.behaviorslist.backgroundcolor = CON.clr.listbox;
analy.behaviorslist.fontname = 'courier';
analy.behaviorslist.fontsize = CON.fontsize.ax;
analy.behaviorslist.callback = 'scorevideo(''analy_updatecolor'');';
analy.modorderlabel.type = 'uicontrol';
analy.modorderlabel.position = [.15 .472 .05 .018];
analy.modorderlabel.style = 'text';
analy.modorderlabel.backgroundcolor = CON.clr.frame2;
analy.modorderlabel.fontsize = CON.fontsize.sm;
analy.modorderlabel.string = 'Modify order';
analy.orderup.type = 'uicontrol';
analy.orderup.position = [.15 .435 .02 .03];
analy.orderup.style = 'pushbutton';
analy.orderup.backgroundcolor = CON.clr.button1;
analy.orderup.horizontalalignment = 'center';
analy.orderup.fontsize = CON.fontsize.sm;
analy.orderup.string = '^';
analy.orderup.callback = 'scorevideo(''analy_plotorder'',''^'');';
analy.orderdn.type = 'uicontrol';
analy.orderdn.position = [.175 .435 .02 .03];
analy.orderdn.style = 'pushbutton';
analy.orderdn.backgroundcolor = CON.clr.button1;
analy.orderdn.horizontalalignment = 'center';
analy.orderdn.fontsize = CON.fontsize.sm;
analy.orderdn.string = 'v';
analy.orderdn.callback = 'scorevideo(''analy_plotorder'',''v'');';
analy.orderadd.type = 'uicontrol';
analy.orderadd.position = [.20 .435 .02 .03];
analy.orderadd.style = 'pushbutton';
analy.orderadd.backgroundcolor = CON.clr.button1;
analy.orderadd.horizontalalignment = 'center';
analy.orderadd.fontsize = CON.fontsize.sm;
analy.orderadd.string = '+';
analy.orderadd.callback = 'scorevideo(''analy_plotorder'',''+'');';
analy.ordersub.type = 'uicontrol';
analy.ordersub.position = [.225 .435 .02 .03];
analy.ordersub.style = 'pushbutton';
analy.ordersub.backgroundcolor = CON.clr.button1;
analy.ordersub.horizontalalignment = 'center';
analy.ordersub.fontsize = CON.fontsize.sm;
analy.ordersub.string = '-';
analy.ordersub.callback = 'scorevideo(''analy_plotorder'',''-'');';
analy.colordisplaylabel.type = 'uicontrol';
analy.colordisplaylabel.position = [.30 .47 .058 .018];
analy.colordisplaylabel.style = 'text';
analy.colordisplaylabel.backgroundcolor = CON.clr.frame2;
analy.colordisplaylabel.fontsize = CON.fontsize.sm;
analy.colordisplaylabel.string = 'Selected color';
analy.colordisplay.type = 'uicontrol';
analy.colordisplay.position = [.36 .47 .028 .02];
analy.colordisplay.style = 'text';
analy.colordisplay.backgroundcolor = CON.clr.frame2;
analy.coloroption1.type = 'uicontrol';
analy.coloroption1.position = [.283 .439 .015 .026];
analy.coloroption1.style = 'pushbutton';
analy.coloroption1.backgroundcolor = CON.clr.plots(1,:);
analy.coloroption1.foregroundcolor = CON.clr.plots(1,:);
analy.coloroption1.horizontalalignment = 'center';
analy.coloroption1.string = '|||||';
analy.coloroption1.callback = ['scorevideo(''analy_coloroption'',[', ...
    num2str(CON.clr.plots(1,:)),']);'];
analy.coloroption2.type = 'uicontrol';
analy.coloroption2.position = [.301 .439 .015 .026];
analy.coloroption2.style = 'pushbutton';
analy.coloroption2.backgroundcolor = CON.clr.plots(2,:);
analy.coloroption2.foregroundcolor = CON.clr.plots(2,:);
analy.coloroption2.horizontalalignment = 'center';
analy.coloroption2.string = '|||||';
analy.coloroption2.callback = ['scorevideo(''analy_coloroption'',[', ...
    num2str(CON.clr.plots(2,:)),']);'];
analy.coloroption3.type = 'uicontrol';
analy.coloroption3.position = [.319 .439 .015 .026];
analy.coloroption3.style = 'pushbutton';
analy.coloroption3.backgroundcolor = CON.clr.plots(3,:);
analy.coloroption3.foregroundcolor = CON.clr.plots(3,:);
analy.coloroption3.horizontalalignment = 'center';
analy.coloroption3.string = '|||||';
analy.coloroption3.callback = ['scorevideo(''analy_coloroption'',[', ...
    num2str(CON.clr.plots(3,:)),']);'];
analy.coloroption4.type = 'uicontrol';
analy.coloroption4.position = [.337 .439 .015 .026];
analy.coloroption4.style = 'pushbutton';
analy.coloroption4.backgroundcolor = CON.clr.plots(4,:);
analy.coloroption4.foregroundcolor = CON.clr.plots(4,:);
analy.coloroption4.horizontalalignment = 'center';
analy.coloroption4.string = '|||||';
analy.coloroption4.callback = ['scorevideo(''analy_coloroption'',[', ...
    num2str(CON.clr.plots(4,:)),']);'];
analy.coloroption5.type = 'uicontrol';
analy.coloroption5.position = [.355 .439 .015 .026];
analy.coloroption5.style = 'pushbutton';
analy.coloroption5.backgroundcolor = CON.clr.plots(5,:);
analy.coloroption5.foregroundcolor = CON.clr.plots(5,:);
analy.coloroption5.horizontalalignment = 'center';
analy.coloroption5.string = '|||||';
analy.coloroption5.callback = ['scorevideo(''analy_coloroption'',[', ...
    num2str(CON.clr.plots(5,:)),']);'];
analy.coloroption6.type = 'uicontrol';
analy.coloroption6.position = [.283 .41 .015 .026];
analy.coloroption6.style = 'pushbutton';
analy.coloroption6.backgroundcolor = CON.clr.plots(6,:);
analy.coloroption6.foregroundcolor = CON.clr.plots(6,:);
analy.coloroption6.horizontalalignment = 'center';
analy.coloroption6.string = '|||||';
analy.coloroption6.callback = ['scorevideo(''analy_coloroption'',[', ...
    num2str(CON.clr.plots(6,:)),']);'];
analy.coloroption7.type = 'uicontrol';
analy.coloroption7.position = [.301 .41 .015 .026];
analy.coloroption7.style = 'pushbutton';
analy.coloroption7.backgroundcolor = CON.clr.plots(7,:);
analy.coloroption7.foregroundcolor = CON.clr.plots(7,:);
analy.coloroption7.horizontalalignment = 'center';
analy.coloroption7.string = '|||||';
analy.coloroption7.callback = ['scorevideo(''analy_coloroption'',[', ...
    num2str(CON.clr.plots(7,:)),']);'];
analy.coloroption8.type = 'uicontrol';
analy.coloroption8.position = [.319 .41 .015 .026];
analy.coloroption8.style = 'pushbutton';
analy.coloroption8.backgroundcolor = CON.clr.plots(8,:);
analy.coloroption8.foregroundcolor = CON.clr.plots(8,:);
analy.coloroption8.horizontalalignment = 'center';
analy.coloroption8.string = '|||||';
analy.coloroption8.callback = ['scorevideo(''analy_coloroption'',[', ...
    num2str(CON.clr.plots(8,:)),']);'];
analy.colorcustom.type = 'uicontrol';
analy.colorcustom.position = [.337 .409 .033 .026];
analy.colorcustom.style = 'pushbutton';
analy.colorcustom.backgroundcolor = CON.clr.button1;
analy.colorcustom.horizontalalignment = 'center';
analy.colorcustom.fontsize = CON.fontsize.sm;
analy.colorcustom.string = 'custom';
analy.colorcustom.callback = 'scorevideo(''analy_colorcustom'');';
analy.outputlabel.type = 'uicontrol';
analy.outputlabel.position = [.03 .35 .10 .03];
analy.outputlabel.style = 'text';
analy.outputlabel.backgroundcolor = CON.clr.frame2;
analy.outputlabel.fontweight = 'bold';
analy.outputlabel.string = 'OUTPUT FILES';
analy.tabletoxls.type = 'uicontrol';
analy.tabletoxls.position = [.04 .32 .09 .03];
analy.tabletoxls.style = 'pushbutton';
analy.tabletoxls.backgroundcolor = CON.clr.button1;
analy.tabletoxls.horizontalalignment = 'center';
analy.tabletoxls.string = 'Table to Excel';
analy.tabletoxls.callback = 'scorevideo(''analy_tabletoxls'');';
uicp.analy = analy;
uicp = checkmodules('checkuicp',FFL,uicp);

%=========================================================
function[varout] = checkmodules(opname,FIGM,varin1,varin2)
varout = [];
if (nargin < 3); varin1 = []; end
if (nargin < 4); varin2 = []; end
if (isfield(FIGM,'ispresent_posnmodule'))
    ispresent_posnmodule = FIGM.ispresent_posnmodule;
else
    ispresent_posnmodule = getstoreddata(FIGM.FFLh,'ispresent_posnmodule');
end
switch (opname)
    case ('init')
        % varin1 = CON; varin2 = uicp; varout = uicp;
        if (ispresent_posnmodule == 1)
            varout = posnmodule(opname,varin1,varin2);
        else
            varout = varin2;
        end
    case ('checkuicp')
        % varin1 = uicp; varout = uicp;
        if (ispresent_posnmodule == 1)
            varout = posnmodule(opname,varin1);
        else
            varout = varin1;
        end
    case ('updateposnlog')
        if (ispresent_posnmodule == 1)
            posnmodule(opname);
        end
    case ('clearposnlog')
        if (ispresent_posnmodule == 1)
            posnmodule(opname);
        end
    case ('plotposns')
        if (ispresent_posnmodule == 1)
            varout = posnmodule(opname,FIGM,varin1);
        else
            varout = FIGM;
        end
    case ('updateposns')
        if (ispresent_posnmodule == 1)
            varout = posnmodule(opname,FIGM,varin1);
        else
            varout = FIGM;
        end
    case ('getnsubj')
        if (ispresent_posnmodule == 1)
            varout = posnmodule(opname,varin1);
        else
            varin1.vnsubj = 2;
            varout = varin1;
        end
    case ('setnsubj')
        if (ispresent_posnmodule == 1)
            posnmodule(opname,varin1);
        end
    case ('setvtype')
        if (ispresent_posnmodule == 1)
            posnmodule(opname,varin1);
        end
    case ('dispnsubj')
        if (ispresent_posnmodule == 1)
            posnmodule(opname,varin1);
        end
    case ('clearnsubj')
        if (ispresent_posnmodule == 1)
            posnmodule(opname);
        end
end