function freq = unigram_frequency ( filename )

%*****************************************************************************80
%
%% unigram_frequency() counts letter frequencies in a file.
%
%  Discussion:
%
%    An instance of a single letter is known as a "unigram".
%
%    Capital and lower case letters are merged.
%
%    Any nonalphabetic character is treated as a 27-th blank character.
%
%  Licensing:
%
%    This code is distributed under the MIT license.
%
%  Modified:
%
%    29 August 2021
%
%  Author:
%
%    John Burkardt
%
%  Input:
%
%    string FILENAME, the name of the input file.
%
%  Output:
%
%    integer FREQ(27): counts the number of occurrences of character i.
%
  freq = zeros ( 27, 1 );

  input = fopen ( filename );

  if ( input < 0 ) 
    fprintf ( 1, '\n' );
    fprintf ( 1, 'unigram_frequency(): Fatal error!\n' );
    fprintf ( 1, '  Could not open the file "%s".\n', filename );
    error ( 'unigram_frequency(): Fatal error!' );
    return;
  end
%
%  Read one character at a time.
%
  while ( true )

    [ c, count ] = fread ( input, 1 );
%
%  Exit loop if no more characters.
% 
    if ( count < 1 )
      break;
    end
%
%  Preprocess characters: 
%    uppercase to lower case
%    nonalphabetic to blank.
%
    c = lower ( c ); 
    c = c + 1 - 'a'; 
    if ( c < 1 || 26 < c )
      c = 27;
    end
%
%  Increment the frequency.
%
    freq(c) = freq(c) + 1;

  end

  fclose ( input );

  return
end
