function [state,options,optchanged] = gaStateFcn(options,state,flag)
% Saves and restarts GA optimization where it left off in the event of a
% crash.

optchanged = false;

persistent restartedInit
persistent actGeneration

switch flag
    case 'init'
        if exist('gaIterSave.mat', 'file') == 2
            load gaIterSave;
            optchanged = true; 
            disp(['Generation ' num2str(state.Generation) ' loaded.']);
%             actGeneration = state.Generation;
%             restartedInit = true;
%             state.Generation = 1;
%         else
%             restartedInit = false;
        end
    
    case 'iter'
        % needed to deal with poorly implemented StepSize persistent
        % variable in the mutationadaptfeasible function.
%         if restartedInit == true
%             restartedInit = false;
%             state.Generation = actGeneration + 1;
%         end
        save gaIterSave;
        disp(['Generation ' num2str(state.Generation) ' saved.']);        

    case 'done'
        save gaIterSave;

end

