function anaStruct = prepareConstGrowth(iBatch, measure)
% integrate analytical results in batches

%% load some data
pbeDef = obtainData('constGrowth_common');
load('./database/constGrowthIntegrals_0.matx', '-mat');
timeVector = pbeDef.timeSpan;
nTime = length(timeVector);

%% number of batches and estimated time
nBatch = 1;
timeOnce = integral.(measure).time;
timeTotalMinutes = timeOnce * (nTime-1) / 60
timeBatchMinutes = timeTotalMinutes / nBatch

%% load / save data
thisFileName = ['./data/anaConstGrowth_' measure '.matx'];
if ~exist(thisFileName, 'file')
    % time stamp will be used for filtering, later
    anaStruct.time = nan(1, nTime);
    anaStruct.value = nan(1, nTime);
    anaStruct.absError = nan(1, nTime);
    anaStruct.relError = nan(1, nTime);
    anaStruct.evalTime = nan(1, nTime);
    
    save(thisFileName, '-mat', 'anaStruct')
else
    load(thisFileName, '-mat');
end

%% run batch
for iTime = iBatch:nBatch:nTime
    disp(' ');disp(' ');disp(' ');
    disp(['--- RUNNING iTIME = ' num2str(iTime) ' of ' num2str(nTime) ' ---'])
    anaStruct = addTime(anaStruct, pbeDef, iTime, measure);
end
save(thisFileName, '-mat', 'anaStruct')

end


function anaStruct = addTime(anaStruct, pbeDef, iTime, measure)

% add timestamp // skip if already present
if isnan(anaStruct.time(iTime))
    thisTime = pbeDef.timeSpan(iTime);
    anaStruct.time(iTime) = thisTime;
elseif iTime~=1
    return
end


if iTime == 1
    %% collect data from prior integrations
    load('./database/constGrowthIntegrals_0.matx', '-mat');
    % assign results
    anaStruct.value(iTime) = integral.volume.value;
    anaStruct.relError(iTime) = integral.volume.relError;
    anaStruct.absError(iTime) = integral.volume.error;
    anaStruct.evalTime(iTime) = integral.volume.time;
    anaStruct.prob(iTime) = integral.volume.prob;
    
else
    % region of interest
    intMin = pbeDef.integrateMin + thisTime*pbeDef.growthConstant;
    intMax = pbeDef.integrateMax + thisTime*pbeDef.growthConstant;
    
    %% total volume
    % setup handle
    thisHandle = @(h)(pbeDef.analyticSolution(h, thisTime) .* ...
    computeMeasureDec(pbeDef.dec, 'hC', h, measure, 1e-16, [], -1));
        
    % integrate
    thisResult = integrateCuba(thisHandle, intMin, intMax, ...
        pbeDef.vegasOptions{:})
    
    % assign results
    anaStruct.value(iTime) = thisResult.value;
    anaStruct.relError(iTime) = thisResult.relError;
    anaStruct.absError(iTime) = thisResult.error;
    anaStruct.evalTime(iTime) = thisResult.time;
    anaStruct.prob(iTime) = thisResult.prob;
end
end