function cf(nr,nc)

if nargin < 2
   nr = 6;
   nc = 7;
end

names{1} = input('Enter first player''s name: ', 's');
names{2} = input('Enter second player''s name: ', 's');

again = true;
startPlayer = 2;

while again
   board = zeros(nr,nc);
   startPlayer = 3-startPlayer;
   player = startPlayer;
   win = 0;
   displayCF(board)
   fprintf('%s, your move! (0: reset, 1 to %d: col to add, -1 to -%d: col to drop) ', ...
        names{player}, nc, nc)
   play = input('');
   while play ~= 0 && ~win
      if play < 0
          [board, statusGood] = dropOne(board, -play, player);
      else
          [board, statusGood] = addOne(board, play, player);
      end
      if statusGood
          displayCF(board)
          player = 3-player;
          win = checkWin(board);
      else
          fprintf('%s, invalid play.  Try again. \n', names{player})
      end
      if ~win
          fprintf('%s, your move! (0: reset, 1 to %d: col to add, -1 to -%d: col to drop) ', ...
                 names{player}, nc, nc)
          play = input('');
      else
          if win < 3
              fprintf('Congrats, %s wins!\n', names{win})
          else
              fprintf('Tie game!\n')
          end
      end
   end
   again = input('Another round? (no - 0, yes - 1) ');
end

end % end of main function

function displayCF(board)
   disp('diplaying board')
   [nr,nc] = size(board);
   board(board==0) = ' ';
   board(board==1) = 'X';
   board(board==2) = 'O';
   fprintf('\n')
   fprintf(' %1d ', 1:nc)
   fprintf('\n')
   for ii = nr:-1:1
       fprintf('|%c|', board(ii,:))
       fprintf('\n')
   end
   fprintf('\n')
end

function [board, status] = dropOne(board, play, marker)
   disp('dropping one')
   [nr,nc] = size(board);
   status = false;
   if play <= nc
      if board(1, play) == marker
         board(1:nr-1, play) = board(2:nr, play);
         board(nr, play) = 0;
         status = true;
      end
   end
end

function [board, status] = addOne(board, play, marker)
   disp('adding one')
   [nr,nc] = size(board);
   status = false;
   if play <= nc && board(nr, play) == 0
      r = find(board(:,play) == 0, 1);
      board(r, play) = marker;
      status = true;
   end 
end

function win = checkWin(board)
   disp('checking win')
   win = 0;
end
 
