%% Calculate Number of Lines of Code by Using Report Information Object
% This example shows how to calculate the number of lines in the source code and the generated code by using the report information object. For more information on the report information object, see Access Code Generation Report Information Programmatically.
%% Setup
% Add example files to path.

path = fullfile(matlabroot, 'examples', 'coder', 'main');
addpath(path);

%
%% The MATLAB Code
% In this example, you generate code for the MATLAB function dijkstra. This function calculates the lengths of the shortest paths from a node to every other node in a graph by using Dijkstra's algorithm.

type dijkstra

% Specify the adjacency matrix A for a graph and a node p where the traversal of the graph begins. Plot the graph. Call dijkstra to compute the shortest distance from p to every node in the graph and display these distances.

% Sample adjacency Matrix for graph with 5 nodes
A = [
        0 1 1 0 0; 
        1 0 0 1 1; 
        1 0 0 1 0; 
        0 1 1 0 1; 
        0 1 0 1 0
    ];

% Plot the graph to see how it looks like
G = graph(A, 'omitselfloops');
plot(G, 'EdgeLabel', G.Edges.Weight)
% Source node from where graph traversal begins
p = randi(size(A, 1));

% Calculate shortest distance from 'p' to every other node in graph G
D = dijkstra(A, p);

for i=1:numel(D)
    fprintf("Length of shortest path from %d to %d is %d. \n", p, i, D(i));
end

%
%% Export Information about Code Generation
% The report information object provides programmatic access to information about code generation. The properties of this object provide information about code generation settings, input files, generated files, and code generation error, warning, and information messages.
% To export the report information object to a variable in your base MATLAB workspace, include the -reportinfo option with the name of the variable while running the codegen command. In this example, you export the code generation report information to the variable info.

codegen -c dijkstra -args {A, p} -reportinfo info

%
%% Calculate Number of Lines of Code
% The loc function takes a report information object as input and returns two outputs that contain the number of lines in the source code and the generated code, respectively. This function excludes blank lines and the lines containing comments while computing the number of lines of code.

type loc

% Call loc with the report information object info as input. Display the number of lines of code in the source files and the generated files.

info = evalin('base', 'info');
[nLocIn, nLocOut] = loc(info);
fprintf('Lines of code in source MATLAB file(s): %d', nLocIn);
fprintf('Lines of code in generated file(s): %d', nLocOut);

%
%% Cleanup
% Remove example files from path.

rmpath(path);

% Copyright 2018 The MathWorks, Inc.
%