function freq = bigram_frequency ( filename )

%*****************************************************************************80
%
%% bigram_frequency() counts letter-pair frequencies in a file.
%
%  Discussion:
%
%    A sequnce of two letters is known as a "bigram".
%
%    Capital and lower case letters are merged.
%
%    Any nonalphabetic character is treated as a 27-th blank character.
%
%    The text is prepended and appended by a single blank.
%
%  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,27): counts the number of times character i
%    was immediately followed by character j.
%
  freq = zeros ( 27, 27 );

  input = fopen ( filename );

  if ( input < 0 ) 
    fprintf ( 1, '\n' );
    fprintf ( 1, 'bigram_frequency - Error!\n' );
    fprintf ( 1, '  Could not open the file "%s".\n', filename );
    error ( 'bigram_frequency - Error!' );
    return;
  end
%
%  Initial blank.
%
  c2 = 27; 
%
%  Read one character at a time.
%
  while ( true )

    c1 = c2;
    [ c2, count ] = fread ( input, 1 );
%
%  At end of text, append a final blank.
% 
    if ( count < 1 )
      c2 = 27;
    end
%
%  Preprocess characters: 
%    uppercase to lower case
%    nonalphabetic to blank.
%
    c2 = lower ( c2 ); 
    c2 = c2 + 1 - 'a'; 
    if ( c2 < 1 | 26 < c2 )
      c2 = 27;
    end
%
%  Increment the frequency.
%
    freq(c1,c2) = freq(c1,c2) + 1;
%
%  If end of file, we are done.
%
    if ( count < 1 )
      break;
    end

  end

  fclose ( input );

  return
end
