function [output] = readScaledValues(firstSampleIndex, numSamples, lastSampleIndex, channel_handle)
%Funtion to read in samples for one channel of type scaled
%   Blockwise reading with blocks of 1e6
%   firstSampleIndex        index of first sample for this reading
%   numSamples              number of samples of this sweep
%   output                  total sweep with timestamp

    block = 1e6;
    numBlocks = max(1, uint64(ceil(double(numSamples)/double(block))));
    numValidSamples = uint64(0);
    nextSample = uint64(0);
    offset = 1;
    time = zeros(1);
    data_temp = zeros(1);

    firstSample = firstSampleIndex;

    for blockIdx = 0:numBlocks - 1

        blockData = zeros(block,1);
        blockTS = zeros(block,1);

        [DMDReader_ErrorCode, ~, blockData, blockTS, numValidSamples, nextSample] = calllib('dmdlib', 'DMDReader_GetSamplesAndTS_ScaledValue_Seconds', ...
            channel_handle, firstSample, block, blockData, blockTS, numValidSamples, nextSample);
        if (DMDReader_ErrorCode ~= 0)
           close(f)
           error(['Error: ', num2str(DMDReader_ErrorCode), ' DMDReader_GetSamplesAndTS_ScaledValue_Seconds'])
        end
        [~,sys] = memory;
        if (sys.PhysicalMemory.Available < sys.PhysicalMemory.Total * 0.2)
           close(f)
           error('Error: Not enough RAM available.')
        end
        if numValidSamples > 0
            time(offset:numValidSamples + offset - 1) = blockTS(1:numValidSamples);
            data_temp(offset:numValidSamples + offset - 1) = blockData(1:numValidSamples);
            offset = offset + numValidSamples;
        end
        
        firstSample = nextSample;

        if nextSample > lastSampleIndex
            break
        end

    end % for blockIdx
    

    output.time = time';
    output.data = data_temp';
  

end

