function commentcpptoc(directory)
%COMMENTCPPTOC Change CPP // comments to C /* */ style
%   COMMENTCPPTOC(DIRECTORY) replaces all C++ style comments to C comments
%   in each file wifht .C extension within the directory DIRECTORY and its
%   subdirectories.
%   COMMENTCPPTOC works in the current directory.

% Copyright (c) 2010-2014 Peter Fiala

if nargin < 1
    directory = pwd;
end

fprintf(1, 'Processing directory %s\n', directory);

% list and process .C files
d1 = dir(fullfile(directory, '*.c'));
d2 = dir(fullfile(directory, '*.h'));
d = [d1;d2];
d = {d.name};
for i = 1 : length(d)
    hu(fullfile(directory, d{i}));
end

% list subdirectories
d = dir(directory);
d = d(cell2mat({d.isdir}));
d = {d.name};
for i = 1 : length(d)
    if strcmp(d{i}, '.') || strcmp(d{i}, '..') || strcmp(d{i}, '.git')
        continue
    end
    commentcpptoc(fullfile(directory, d{i}));
end

end

function hu(filename)
[di, na, ext] = fileparts(filename);

fprintf(1, 'formatting %s...', fullfile(di, na));

% read file into cell array
f = fopen(filename, 'rt');
s = textscan(f, '%s', 'delimiter', '\n', 'whitespace', '');
fclose(f);
s = regexprep(s{1}, '//(.*)', '/*$1 */');
% write file into temporary file
f = fopen('temp', 'wt');
for iLine = 1 : length(s)
    fprintf(f, '%s\n', s{iLine});
end
fclose(f);

% read back from temporary file into string
f = fopen('temp', 'rt');
s = fscanf(f, '%c', Inf);
fclose(f);

% rewrite original m file
f = fopen(fullfile(di, sprintf('%s%s', na, ext)), 'wt');
% f = fopen(sprintf('../%s.m', na), 'wt');
fprintf(f, '%c', s);
fclose(f);

delete('temp');

fprintf(1, 'ready\n');
end