function MpdrRangeDopplerVideo_Wx(Filename,Pathname,lr_or_sr,numCipsPerNcip)
% parse a data recording file for MPDR radar and process the data

% RealTimeVideo=true;
RealTimeVideo=false;
UDP = false;
radarFile = 'mpdr2PlusRadarConfig.yaml';
% radarFile = 'mpdr2RadarConfig.yaml';
UDPradarFile = 'mpdr2RadarConfig_new.yaml';
% myRadar = mpdrRadar();
if(~UDP )
    myRadar = mpdrRadarFileFread(radarFile);
    if exist('Filename',"var")
        if exist('Pathname',"var")
            myRadar.openDataRecordFile(Filename,Pathname);
        else
            myRadar.openDataRecordFile(Filename);
        end
    else
        myRadar.openDataRecordFile();
    end
else
    myRadar = mpdrRadarUDP(UDPradarFile);
    %read data from UDP, set up UDP
    fprintf("ML: Open UDP port\n");
    myRadar.openUDP();
end


% Set flag to process long range or short range waveform data
if ~exist('lr_or_sr',"var")
    dlgTitle    = 'Long Range / Short Range Selection';
    dlgQuestion = 'Display LR or SR returns?';
    lr_or_sr = questdlg(dlgQuestion,dlgTitle,'LR','SR', 'LR');
end

% Set number of coherent integrations to be averaged for each non-coherent integration
if ~exist('numCipsPerNcip',"var")
    numCipsPerNcip = 87;
end

% Specify maximum number of coherent integration periods to process (inf to
% process all of them)
% maxCips = numCipsPerNcip*2;
maxCips = inf; %numCipsPerNcip*2000;

% Initialize CIP object
myCip=cipCube.factory(myRadar);

% Load the first CIP and read CIP data and meta-data
%[cipMetaData,eof] = myCip.loadCip(870); % set starting CIP if desired
%[cipMetaData,eof] = myCip.loadCip([],13.86432); % check starting time if desired
[cipMetaData,eof] = myCip.loadCip();
% [cipData,cipMetaData] = myCip.getCipCube();

fileTimeSec = cipMetaData.priTime_s*cipMetaData.fileSizePris;
numPulsesPerCip = cipMetaData.numPris;
numCips = cipMetaData.fileSizeCips;
numNcips = floor(numCips/numCipsPerNcip);
ncipTimeSec = cipMetaData.priTime_s*cipMetaData.numPris*numCipsPerNcip;
fps = 30; % MP4 video frames per second
%framesPerNcip = floor(ncipTimeSec*fps)
framesPerNcip_realtime = floor(ncipTimeSec*fps);
framesPerNcip_user = 2*fps; % alternative delay between Ncip updates during MP4 video playback
framesPerNcip = framesPerNcip_realtime;
fprintf('File contents: %1.1f sec, %1d cips (%1d pulses per cip), %1d ncips (%1d cips per ncip)\n',fileTimeSec,numCips,numPulsesPerCip,numNcips,numCipsPerNcip);
pause(3)

%% Determine whether to process long range or short range waveform and select range cells
if strcmp(lr_or_sr,'LR')
    dispChan=uint32(radChan.sumLr);
    %endRange=cipMetaData.cells.detEnd(dispChan);
    % process only up to 10.0 km
    endRange=ceil(10000/cipMetaData.rangeCellSize_m(dispChan)+cipMetaData.cells.rangeZero(dispChan));
else
    dispChan=uint32(radChan.sumSr);
    % process only up to 2.2 km
    %endRange=ceil(2200/cipMetaData.rangeCellSize_m(dispChan)+cipMetaData.cells.rangeZero(dispChan));
    % process only up to 3.0 km
    %endRange=ceil(3000/cipMetaData.rangeCellSize_m(dispChan)+cipMetaData.cells.rangeZero(dispChan));
    % process only up to 8.0 km
    endRange=ceil(10000/cipMetaData.rangeCellSize_m(dispChan)+cipMetaData.cells.rangeZero(dispChan));
end
startRange=cipMetaData.cells.rangeZero(dispChan);
range=[startRange endRange];

if (cipMetaData.wxMode)
    if strcmp(lr_or_sr,'LR')
        scaling=[-5 15]; % long range
    else
        %scaling=[-5 5]; % short range
        scaling=[-5 15]; % short range
    end
else
    scaling=[8 50];
end

%%  video processing...
[~,vidFileName,~]=fileparts(cipMetaData.Filename);
vidFileName= sprintf("%s_%s_NCI_%s.mp4",vidFileName,radChan.getString(dispChan),int2str(numCipsPerNcip));
vidfile = VideoWriter(vidFileName,'MPEG-4');
vidfile.open();

lFig=figure;
lAxis=gca;
set(lFig,'Units','normalized','Position',[0.6 0.02 0.35 0.8]);
set(lFig,'Name',['Range Doppler Map ' cipMetaData.Filename]);

myRangeDopplerMap=rangeDopplerMap(lFig,dispChan,cipMetaData,scaling,range);

cipNum = 0;
nBurst = 0;
nNcips = 0;

start=tic;
t1 = tic;
while ~eof && cipNum < maxCips
    %fprintf('Processing cip %6d\n',cipNum);

    % Perform DC bias correction	
    myCip.correctDcBias();
	
    % Perform calibration
    myCip.calibrate();
	
    % Perform pulse compression
    myCip.compress();
    e1=toc(t1);t1=tic;
	
    % Perform Doppler filtering
    myCip.dopplerFilter();
    e2=toc(t1);t1=tic;
	
    % Perform background normalization (use average power in noise only range and Doppler region)
    myCip.normalize();
    e3=toc(t1);t1=tic;
	
	% Threshold processing (not used for Wx, keep for UAS compatibility, *fix this*)
    plots=myCip.threshold(dispChan);
    e4=toc(t1);t1=tic;
    %[cipData,cipMetaData] = myCip.getMagSqCube();
    
    %% Non-coherent processing
    %[avgPsd,nBurst] = myCip.magSquaredSum(nBurst);
    [cipData,nBurst] = myCip.magSquaredSum_alt(nBurst);
    %cipData = cipData / 2000; % 2000 is to normalize to ~ 0 dB noise level
    
    if (nBurst == numCipsPerNcip)
        %fprintf('Processing ncip %6d\n',nNcips);
        nNcips = nNcips + 1;
        nBurst = 0;
        fprintf('NCIP = %3d of %3d\n',nNcips,numNcips)
        
        title(lAxis,sprintf("Elapsed Time = %5.1f sec, NCIP (%d CIPs) = %3d of %3d",nNcips*ncipTimeSec,numCipsPerNcip,nNcips,numNcips))
        [time_s] = myRangeDopplerMap.plot(lAxis,cipData,cipMetaData,plots,RealTimeVideo);
        %fprintf('Updating MATLAB figure\n');
        
        e5=toc(t1);t1=tic;
        Frame=getframe(lFig);
        
        [img,~]=frame2im(Frame);
        %fprintf('Converting to image\n');
        
        for ii = 1:framesPerNcip
            vidfile.writeVideo(img);
            %pause(0.2)
            %fprintf('Writing frame to video file\n');
        end
        e6=toc(t1);
    end
    % End of non-coherent processing
    
    % load the next CIP...
    if RealTimeVideo
        frameTime=1/30*(cipNum+1);%#ok<UNRCH>
        [~,eof] = myCip.loadCip([],frameTime); %#ok<UNRCH>
    else
        [~,eof] = myCip.loadCip(); %#ok<UNRCH>
    end
    etot=toc;

    cipNum = cipNum +1;
end
endTime=toc(start);
avg = endTime/cipNum;
fprintf("Runtime %f Frame Average: %f\n",endTime, avg);
close(vidfile);
end
