function make(mexFile, varargin)

%MAKE   Compile and link a C MEX-file and copy the help-comments to an M-file.
%
%   MAKE(mexFile) searches for $Make: *** $ in the MEX-file mexFile.mex.cpp and
%   compiles and links this file by evaluation of ***.  It also extracts the
%   help-comments from the header of this file to save it to mexFile.m.
%
%   Example MEX-file header:
%
%   /*NCHAOS   Calculate the number of elements of the polynomial chaos.
%    *
%    *   Q = NCHAOS(M,P) returns the number of M-dimensional polynomials up to
%    *   order P.
%    *
%    *   M    Dimension of the polynomials.
%    *   P    Order of the polynomials.
%    *   Q    Number of polynomials.
%
%    * Mattias Schevenels
%    * July 2004
%    */
%
%   /* $Make: mex -O -output nchaos nchaos.mex.c nchaos.c $ */

% Mattias Schevenels
% July 2004

if nargin == 0 || isempty(mexFile)
    files1 = dir('*.mex.c');
    files2 = dir('*.mex.cpp');
    files = [
        files1
        files2
        ];
    files = {files.name};
    for k = 1:length(files)
        make(files{k}, varargin{:});
        disp(files{k});
    end
else
    [p,n,~] = fileparts(mexFile);
    [~, n, ~] = fileparts(n);
    mFile = fullfile(p, [n '.m']);
    if ~exist(mexFile,'file')
        error(['MEX-file ' mexFile ' not found.']);
    end
    mexFid = fopen(mexFile);
    mFid = fopen(mFile,'w');
    help = 0;
    while true
        line = fgetl(mexFid);
        if ~ischar(line)
            break;
        end;

        expr = '/\*\s*\$Make:(?<command>.*)\$\s*\*/';
        result = regexp(line, expr, 'names');
        if ~isempty(result)
            command = result.command;
            eval(sprintf('%s ', command, varargin{:}));
            break;
        end
        
        line = strtrim(line);
        if strcmp(line(1:min(2,end)),'/*') && (help == 0)
            help = 1;
        end
        if strcmp(line(1:min(2,end)),'*/')
            help = 2;
        end
        if help == 1
            if strcmp(line(1:min(2,end)),'/*')
                line = line(2:end);
            end
            if line(1:min(1,end))=='*'
                line(1) = '%';
            end
            fprintf(mFid,'%s\n',line);
        end
    end
    fclose(mexFid);
    fclose(mFid);
end
