function acqResultsAll = acquisitionDriver( pathName, fileName, ...
                                            fidIn, settings )

%==============================================================================%
%                                                                              %
%   acqResultsAll = acquisitionDriver( pathName, fileName, fidIn, settings )   %
%                                                                              %
%   Main acquisition driver                                                    %
%   David S. De Lorenzo                                                        %
%   28 January 2008                                                            %
%                                                                              %
%==============================================================================%
%                       GPS Software Receiver in Matlab                        %
%     Copyright (c) 2003-2017 David S. De Lorenzo / 2018-2023 Trimble Inc.     %
%==============================================================================%

%=== Initialize the acquisition results structure for final storage ============
acqResultsAll = repmat(struct('acqResults', []), ...
                       1, length(settings.acq.prnSearchVec));

%=== Acquisition - loop over each satellite in the search vector ===============
for ii = 1:length(settings.acq.prnSearchVec)
    
    %--- Assign satellite for this trip through the acquisition loop -----------
    %    For each satellite, the function advances through the stored
    %    data in the input file (possibly several times), and then
    %    rewinds and repeats for the next satellite.
    prn = settings.acq.prnSearchVec(ii);
    
    %--- Assign Doppler frequency estimate -------------------------------------
    %    This is the center of the Doppler frequency search band.
    dopplerEstimate = settings.acq.dopplerEstimateVec(ii);
    
    %--- Start time and message ------------------------------------------------
    startTime = datetime('now');
    fprintf('\n=== PRN %d ===\n', prn);
    fprintf('   Blk #     cppr       cppm     code-phase    doppler freq\n');
    
    %=== Acquisition over (possibly) several time offsets ======================
    %    Several offsets within each navigation data bit are
    %    searched; this allows multi-millisecond coherent
    %    integration while ensuring that navigation data bit
    %    reversals do not bleed energy from the accumulators.
    for jj = 1:length(settings.acq.coherentBlockStartMs)
        
        %--- Time offset for this iteration ------------------------------------
        msToSkip = settings.msToSkip + settings.acq.coherentBlockStartMs(jj);
        
        %--- Seek forward to the specified file position pointer location ------
        placeFilePositionPointer(fidIn, msToSkip, ...
                                 settings.extraSamplesToSkip, settings);
        
        %--- Initialize the millisecond counter, increments once per data read -
        %    msCount is used to calculate the time vector 'timePts' from which
        %    the replica chip sequence 'replicaCodeSequence' is determined.
        %    Also, the code-phase of the correlation peak is used in the logic
        %    of the satellite detection algorithm, so it's desirable that all
        %    acquisition trials (in which each call to this function represents
        %    one such trial) have a common code-phase basis.  Therefore, setting
        %    msCount to the number of milliseconds separating this acquisition
        %    trial from the first acquisition trial is the proper approach.
        msCount = settings.acq.coherentBlockStartMs(jj);
        
        %=== Run acquisition engine ============================================
        [acqResults,resultsNoncoherent] = ...
            acquisitionIntegrationEngine(fidIn, prn, dopplerEstimate, ...
                                         msCount, settings);
        
        %--- Echo acquisition results to screen --------------------------------
        fprintf('    %2d.   %7.2f    %7.2f      %7.1f        %7.1f\n', ...
                jj, acqResults.cppr, acqResults.cppm, ...
                acqResults.codePhase, acqResults.dopplerFreq);
        
        %--- Save results ------------------------------------------------------
        %    If this is the first time through the loop,
        %    then ititialize the output structure.
        if (jj == 1)
            acqResultsAll(ii).acqResults     = acqResults;
        else
            acqResultsAll(ii).acqResults(jj) = acqResults;
        end
        
        %=== Plotting --> 3D doppler frequency vs. code-phase search ===========
        if (strcmp(settings.acq.plotSwitch, '3D') ...
         && (length(acqResults.dopplerFreqVector) > 1))
            acquisitionPlot3D(jj, prn, acqResults.dopplerFreqVector, ...
                              resultsNoncoherent, settings.chipsPer1ms);
            
            %--- Save 3D plot to JPEG ------------------------------------------
            if (settings.acq.plotToJPEG == true)
                print('-djpeg', sprintf('-f%d', 700+prn), ...
                      fullfile(pathName, ...
                               [fileName '__acq_' ...
                                sprintf('PRN%02d_3D_%d', prn, jj)]));
            end
            
        end % plot & save figure
        
    end % loop over time offset
    
    %--- Stop time and message -------------------------------------------------
    finishTime = datetime('now');
    fprintf('  Elapsed time = %6.1f sec\n', seconds(finishTime - startTime));
    
    %=== Plotting --> 2D code-phase multi-plots ================================
    if (strcmp(settings.acq.plotSwitch, '2D') ...
     || strcmp(settings.acq.plotSwitch, '3D'))
        acquisitionPlot2D(acqResultsAll(ii).acqResults, settings.chipsPer1ms);
    end
    
end % loop over satellite number

return
%===============================================================================