function dopOSCCIcrash(err,dc,functionName,varargin)
% dopOSCCI Mark II: dopOSCCIcrash ~ 12-8-2010 (last edit)
%
% catches the dopOSCCI crash, saves the relevant variables, and rethrows
% the error
% note: this isn't necessarily the 'dop' structure, e.g., could be tx
% structure from getTXfileList
%

fprintf('\n%s\n',['!!! Caught dopOSCCI crash in ',functionName,'!!!']);
tmpSave=1;
if isfield(dc,'saveCrash');
    tmpSave=dc.saveCrash;
end
if tmpSave
    dc.translation='dopOSSCI caught variables';
    dc.err=err; % save the error into the structure as well
%     if isfield(dc,'structAbbreviation') % rename the structure to previous name
%         fprintf('%s\n',['Assigning caught stucture to',dc.stuctAbbreviation]);
%         assignin('caller',eval('dc.structAbbreviation'),dc);
%         clear dc
%     end
    if ~isempty(varargin) % assume it's an input variable
        dc.inputs=varargin{1};
    end
    % close any open files:
    fclose all;
    
    % get the location of the dopOSCCI function - should be on matlab path
    dfl=which('dopOSCCI'); % dopOSCCI file location
    dl=fileparts(dfl); % dopOSCCI location
    
    % play sound to alert user
    dopOSCCIalert('Caught');
    
    % set save path on same level as dopOSCCI but different directory
    cl=[dl,'Data\dopOSCCIcrash\'];
    % check that the directory exists
    if ~exist(cl,'dir')
        fprintf('\n\t%s\n','Making directory');
        mkdir(cl);
    end
    % make file name
    cf=['dopCrash',datestr(now,30)]; % crash file
    cfl=[cl,cf];
    tn=0; % tmp number for file renaming
    while exist([cfl,'.mat'],'file') % add number to make it original
        fprintf('\t%s\n','File exists, creating unique name...');
        tn=tn+1;
        cf=['dopCrash',datestr(now,30),'_',num2str(tn)]; % crash file
        cfl=[cl,cf];
    end
        fprintf('\t%s\n\n\t%s\n\t%s\n\n\n\t%s\n\t\t%s\n',...
            'Saving caught variables to:',...
            ['Dir: ',cl],['File: ',cf],...
            'Access by typing:',['load(''',cfl,''')']);
    
    % save the mat file
    save(cfl);
else
    fprintf('\n%s\n\t%s\n\n','Not saving caught variables - ',...
        'dop.saveCrash turned off');
end
% clear the variables
clear dc dfl dl cl cf cfl tmpSave tn functionName
% rethrow the error
rethrow(err);




