function MpdrRangeDopplerVideo(UDP, MODE, VIDEO, varargin)
% MpdrQuickLook(Filenane,Pathname) -- parse a data recording file for MPDR radar
%   filername -- filename of the file to parse;  if no file then UDP
%   network mode is assumed.

%UDP = false; 
Filename = '';
Pathname = '';
fprintf("NARGIN:%d\n",nargin);

% fixme -- 'analysis mode' button. 
choice = MODE;

azangles = [ ]
elangles = [ ]

% args: UDP MODE VIDEO
if( length(varargin)== 1)
    [fPath, fName, fExt] = fileparts(varargin{1});

    Filename = strcat(fName, fExt);
    Pathname = fPath;
    fprintf("filename: %s, pathname: %s\n",Filename,Pathname);
end

if( length(varargin) == 2 )

    Filename = varargin{1};
    Pathname = varargin{2};

    fprintf("filename: %s, pathname: %s\n",Filename,Pathname);
end

PlotPlot =  false; % switch for adding detection history graphs
PlotPrint = false; % switch for creation of csv file with detections are in

% fixme -- make a config struct:
% min/max range, doppler extents
% nci/not, sr/lr
% overlay context or title context
% create video, etc.
% Honestly should be possible to do sr/lr in the same plot

if(UDP)
    RealTimeVideo = false;
    videoFile = false;
    nci=false;                   %non-coherent integration
else
    RealTimeVideo = false;
    videoFile = VIDEO;
    nci=true;
    PlotPlot =  false;
    PlotPrint = false;
end

alpha = 1/16; % nci time constant (fraction between zero and one)

configFile = 'mpdr2PlusRadarConfig.yaml';
% radarFile = 'mpdr2RadarConfig.yaml';
% UDPradarFile = 'mpdr2RadarConfig_new.yaml';
myRadar = mpdrRadar(configFile);
if exist('Filename',"var")
    if exist('Pathname',"var")
%         myRadar.openDataRecordFile(Filename,Pathname);
        myCip=cipCube.factory(myRadar, UDP, Filename, Pathname);
    else
%         myRadar.openDataRecordFile(Filename);
        myCip=cipCube.factory(myRadar, UDP, Filename);
    end
else
    myCip=cipCube.factory(myRadar, UDP);
end
% myCip=cipCube.factory(myRadar, UDP, Filename, Pathname);
%fprintf("Processing data record file: \n(\'%s\',\'%s\')\n", myCip.myRadarIO.Filename, myCip.myRadarIO.Pathname);

%myTrack=gpsTrack();


%load the first CIP...
[cipMetaData,eof] = myCip.loadCip(4);

% if( ~UDP )
%   if(cipMetaData.wxMode == false )
%         dlgTitle    = 'Long Range / Short Range Selection';
%         dlgQuestion = 'Display LR or SR returns?';
%         choice = questdlg(dlgQuestion,dlgTitle,'LR','SR', 'LR');
%   end
% end
minRange = 0; 
%choice = 'SR';
%hds determine where channel data is coming from (radChan.sumxr is an enum)
if strcmp(choice,'LR')
    dispChan=uint32(radChan.sumLr);
    %     endRange=cipMetaData.cells.detEnd(dispChan);
    %hds process 8km
    maxRange = 8000;
    if( cipMetaData.wxMode == true)
        maxRange = 14000;
        minRange = 2000;
    end
    endRange=ceil(maxRange/cipMetaData.rangeCellSize_m(dispChan)+cipMetaData.cells.rangeZero(dispChan));
else
    dispChan=uint32(radChan.sumSr);
    % process only up to 2.2 km
    endRange=ceil(10000/cipMetaData.rangeCellSize_m(dispChan)+cipMetaData.cells.rangeZero(dispChan));
    %     endRange=cipMetaData.cells.detEnd(dispChan);
end
startRange=cipMetaData.cells.rangeZero(dispChan);
if (cipMetaData.wxMode)

    %scaling=[7 30];
    scaling=[-5 30];
else
    scaling=[8 50];
end
range=[startRange endRange];

%%  video processing...
if(videoFile)
    [~,vidFileName,~]=fileparts(cipMetaData.Filename);

   dispChanName = replace(radChan.getString(dispChan),' ','_');
    vidFileName= sprintf("%s_%s",vidFileName,dispChanName);
    
    % vidfile = VideoWriter(vidFileName,'MPEG-4');
    vidfile = VideoWriter(vidFileName,'Motion JPEG AVI');
    vidfile.open();
end

% plot detections over time to allow eyeball tracking observations...
if (PlotPlot)
    % PPI
    lPpi=figure;
    lPpiAxis=gca;
    set(lPpi,'position',[20 20 600 800]);
    set(lPpi,'Name',['Range Azimuth ' cipMetaData.Filename]);
    xlim(lPpiAxis,[-2 2]);
    ylim(lPpiAxis,[0 800]);
    hold(lPpiAxis,'on');

    % range time...
    lRTf=figure;
    lRTa=gca;
    set(lRTf,'Name',['Range Time ' cipMetaData.Filename]);
    % xlim(lRTa,[0 9000]);
    % ylim(lRTa,[0 2000]);
    hold(lRTa,'on');

    % doppler time...
    lDTf=figure;
    lDTa=gca;
    set(lDTf,'Name',['Doppler Time ' cipMetaData.Filename]);
    % xlim(lDTa,[0 9000]);
    ylim(lDTa,[0 160]);
    hold(lDTa,'on');

    % Az time...
    lATf=figure;
    lATa=gca;
    set(lATf,'Name',['Azimuth TIme ' cipMetaData.Filename]);
    % xlim(lATa,[0 9000]);
    ylim(lATa,[-2 2]);
    hold(lATa,'on');
end
% range doppler map (the video frame)
lFig=figure;

lAxis=gca;

%set(lFig,'Visible','off');
set(lFig,'position',[20 20 600 800]);
set(lFig,'Name',['Range Doppler Map ' cipMetaData.Filename]);

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

% load the next CIP...
deltaTime = 1/30; % default to 30 frames/second;
if nci
    deltaTime = 1/60; % don't skip any data... overlap if necessary
end
frameTime = 0.0;

if (PlotPrint)
    try
        csvfid = fopen('plots.csv','w');
        fprintf(csvfid,"cip,time_s,rangeCell,dopplerCell,Az_deg,snr_db\n");
    catch
        fprintf("can't open plots.csv file: do you  have it open in excel?");
    end
end

procSum = 0;
cipNum = 0; % 0 first time through loop, >0 thereafter
start=tic;
once = true;
while ~eof % && cipNum < (30*60)
    proc=tic;
    t1=tic;
    tic;
    myCip.correctDcBias();
    myCip.calibrate();
    myCip.compress();

    %% look at the cal once.

    if once
        once = false; 
        
        [checkdata,cipMetaData] = myCip.getCipCube();
        checkdata = abs(checkdata(dispChan,:,size(checkdata,3)/2));
        [pvals,plocs] =findpeaks(checkdata,"MinPeakHeight",1e5);
        
    end

    e1=toc(t1);t1=tic;
    myCip.dopplerFilter();
    e2=toc(t1);t1=tic;
    myCip.normalize();  
    e3=toc(t1);t1=tic;

    plots=myCip.threshold(dispChan);
    %     plots.range=[];
    %     plots.doppler=[];
    e4=toc(t1);t1=tic;
    procSum = procSum + toc(proc);

    if (PlotPlot)
        plot(lPpiAxis,plots.dAz_deg,(plots.range*cipMetaData.rangeCellSize_m(dispChan)),'+');
        xValues = ones(size(plots.range)).* cipNum;
        plot(lRTa,xValues,(plots.range*cipMetaData.rangeCellSize_m(dispChan)),'+');
        plot(lDTa,xValues,plots.doppler,'+');
        plot(lATa,xValues,plots.dAz_deg,'+');
    end

    elangles = [elangles round(cipMetaData.cipCenterElevation_d)];
    azangles = [azangles round(cipMetaData.cipCenterAzimuth_d)];
    if (PlotPrint)
        for ii=1:size(plots.range)
            fprintf(csvfid,"%d,%f,%d,%d,%f,%f\n",cipNum,frameTime,plots.range(ii),plots.doppler(ii),plots.dAz_deg(ii),plots.amp_db(ii));
        end
    end
    if nci && cipNum > 0
        [rawCipData,cipMetaData] = myCip.getMagSqCube();
        cipData = rawCipData.*alpha + cipData.*(1-alpha);
    else
        [cipData,cipMetaData] = myCip.getMagSqCube();
    end
    %     first = false;
    RTPlotInterval = 4;
    %    if ~nci || rem(cipNum,2)==0 % plot even cips when doing nci...
    if ((~UDP && (~nci || (rem(cipNum,2)==0))) || (UDP && rem(cipMetaData.cipNum, RTPlotInterval)==0)) % plot even cips when doing nci..., CIP cips when doing UDP real time video

        [time_s] = myRangeDopplerMap.plot(lAxis,cipData,cipMetaData,plots, RealTimeVideo);
        %     if (~cipMetaData.wxMode)
        %         [~,aRange_m,aRadialSpeed_mps]=myTrack.getNext( );
        %         hold(lAxis,'on');
        %         plot(lAxis,aRadialSpeed_mps,aRange_m,'md',...
        %             'MarkerSize',20,...
        %             'LineWidth',1.0);
        %     end
        %e5=toc(t1);
        if(videoFile)
            %  t1=tic;
            Frame=getframe(lFig);

            [img,~]=frame2im(Frame);

            vidfile.writeVideo(img);
            e6=toc(t1);
        else
            drawnow limitrate nocallbacks;
        end
    end

    % load the next CIP...
    if nci
        deltaTime = 1/60; % don't skip any data... overlap if necessary
    else
        deltaTime = 1/30; % default to 30 frames/second;

    end
    cipNum = cipNum +1;
    if RealTimeVideo                            %Are we doing this for non-UDP mode? No
        frameTime = cipMetaData.cipTime_s + deltaTime;
        [cipMetaData,eof] = myCip.loadCip(cipNum); %[],frameTime);
    else
        [cipMetaData,eof] = myCip.loadCip(cipNum); %#ok<UNRCH>
    end
    etot=toc;
    %     fprintf("%d Radar:%-6.2f Loop:%-6.2f pc:%-6.2f dop:%-6.2f norm:%-6.2f th:%-6.2f plot:%-6.2f vid:%-6.2f \n",...
    %         cipNum,time_s,etot,e1,e2,e3,e4,e5,e6);

end
endTime=toc(start);
avg = endTime/cipNum;
fprintf("Runtime %f Frame Average: %f ProcSum: %f ProcAvg %f\n",endTime, avg, procSum, procSum/cipNum);
if(videoFile)
    close(vidfile);
end
fclose('all');
azangles = abs(azangles);
azangles = mod(azangles+360,360);
azangles = azangles - (max(azangles)-min(azangles));
azangles = azangles-mean(azangles);
azangles = unique(azangles);
elangles = unique(elangles);
fmt=['\nel =' repmat(' %1.0f',1,numel(elangles))];
fprintf(fmt,elangles);
fmt=['\naz =' repmat(' %1.0f',1,numel(azangles))];

fprintf(fmt, azangles);
end
