function demoOnVideo (hW, frameLimit)
%DEMOONVIDEO: Run pretrained network on video

if nargin < 2
    frameLimit = 1000000;
end

writeToFile = false;

videoFile = 'caltech_cordova1.avi'; %This file ships with ADST


if ~isfile(videoFile)
  	url = append('https://www.mathworks.com/supportfiles/gpucoder/media/', videoFile);
   	websave('caltech_cordova1.avi', url);
end

ss = getLaneDetectionData();

sensor = caltechMonoCamera();

%Initialize video readers and writers
vR = VideoReader(videoFile);
vPlayer = vision.DeployableVideoPlayer();

if writeToFile
    [~, name, ext] = fileparts(videoFile);
    outFileName = [name '_out' ext];
    vW = VideoWriter(outFileName);
    vW.FrameRate = vR.FrameRate;
    open(vW);
end

isOpen = true;

frameCount = 0;
while frameCount < frameLimit && isOpen && hasFrame(vR)
    testImg = readFrame(vR);
    inputImg = imresize(testImg, [227 227]);

%     profile off
    outputs = hW.predict(inputImg, 'Profile', 'on');

    laneim = showNetworkOutputs(testImg, outputs, ss.laneCoeffMeans, ss.laneCoeffsStds, sensor);
    step(vPlayer, laneim);
    frameCount = frameCount + 1;
    if writeToFile
        writeVideo(vW, laneim);
    end
    isOpen = vPlayer.isOpen();
end

if writeToFile
    close(vW);
end

release(vPlayer);
delete(vR);

end

function laneim = showNetworkOutputs(img, lanecoeffsNetworkOutput, laneCoeffMeans, laneCoeffStds, sensor)
%SHOWNETWORKOUTPUTS

%Recover original coeffs by reversing the normalization steps
params = lanecoeffsNetworkOutput .* laneCoeffStds + laneCoeffMeans;

%Visualize with ADST
isRightLaneFound = abs(params(6)) > 0.5; %c should be more than 0.5 for it to be a right lane
isLeftLaneFound =  abs(params(3)) > 0.5;

if isRightLaneFound
    rtBoundary = parabolicLaneBoundary(params(4:6));
else
    rtBoundary = parabolicLaneBoundary.empty(1, 0);
end

if isLeftLaneFound
    ltBoundary = parabolicLaneBoundary(params(1:3));
else
    ltBoundary = parabolicLaneBoundary.empty(1, 0);
end

laneboundaries = [ltBoundary, rtBoundary];

%Visualize lane boundaries of the ego vehicle
vehicleXPoints = 3:30; %meters, ahead of the sensor
laneim = insertLaneBoundary(img,laneboundaries,sensor, vehicleXPoints, 'Color', 'green');

end

