function  out = blockcom(filein,fileout,flag)

% BLOCKCOM Commenting and uncommenting a block in a file.
%	Used to comment and uncomment blocks of a program
%	to prevent them from being executed.
%	Blocks to be (un)commented are confined between lines
%	beginning with %{ and lines beginning with %}.
%
%	BLOCKCOM(FILEIN,FILEOUT,FLAG) takes file FILEIN as an input
%	and writes resulting text into a file FILEOUT.
%	FLAG ('on' or 'off') controls the action:
% 	'on' - to comment, 'off' - to uncomment.
%	When FLAG is not input BLOCKCOM toggles comment state.
%	BLOCKCOM(FILEIN,FLAG) writes results to the same file FILEIN.
%	OUT = BLOCKCOM(...) returns the file id numbers for
%	FILEIN and FILEOUT.

%  Kirill K. Pankratov,  kirill@plume.mit.edu
%  8/20/94, 10/3/94

 % Set relevant characters and numbers ........................
ch_cm = '%';
numb = inf;

 % Handle input ...............................................
on  = nan;
if nargin == 0
  fprintf('\n  Error: the file name is not specified. \n\n')
  return
end
if nargin==3, on = strcmp(flag,'on'); end
if nargin==2
  if strcmp(fileout,'on')|strcmp(fileout,'off')
    flag = fileout;
    fileout = filein;
  end
elseif nargin==1
  fileout = filein;
end

 % Read from the file FILE ....................................
[fidi,msg] = fopen(filein,'r');      % Open file to read
if nargout, out = fidi; end
if fidi==-1, disp(msg), return, end
s = fread(fidi,numb,'char');       % Read input file
fclose(fidi);                      % Close input file

s = [s(:)' '  '];
ls = length(s);

fnd_nl = find( s==10 | s==13 );   % Indices of new lines
n_nl = length(fnd_nl);
nn = find(s(fnd_nl+1)=='%');
nn1 = fnd_nl(nn)+2;
no = nn(s(nn1)=='{');
nc = nn(s(nn1)=='}');

a = zeros(1,n_nl);
a(no) = ones(size(no));
a(nc) = -ones(size(nc));
a = cumsum(a);
a(no) = zeros(size(no));
is_cm = all(s(fnd_nl(a)+1)=='%');  % If commented already
if isnan(on), on = ~is_cm; end
nn = fnd_nl(a)+1;
onn = ones(size(nn));

 % Now comment or uncomment
if on
  as = ones(size(s));
  as(nn) = 2*onn;
  as = cumsum(as);
  as1 = zeros(1,as(ls));
  as1(as) = abs(s);
  as1(find(~as1)) = '%'*onn;
  s = as1;
else
  nn = nn(s(nn)=='%');
  onn = ones(size(nn));
  as = ones(size(s));
  as(nn) = 0*onn;
  s = s(as);
end

 % Duplicate '%' characters
ls = length(s);
fnd = find(s==ch_cm);
s = [s '%'*ones(size(fnd))];
[a,ind] = sort([1:ls fnd]);
s = setstr(s(ind));
s = s(1:length(s)-2);

 % Write to the output file ...................................
[fido,msg] = fopen(fileout,'w');      % Open file to write
if fido==-1, disp(msg), return, end
fprintf(fido,s);
fclose(fido);

if nargout, out = [out; fido]; end    % Add to output
