function D = getdistances(coeff,bin_img)
% GETDISTANCES Distances between top points and nearest baseline point
% 
% D = GETDISTANCES(COEFF,TOPS_IMG) where COEFF is a vector containing
% the coefficients, [c b] or [c b a], of the baseline of the binarized
% text contained. In the case when DEG=2, the baseline coefficients,
% COEFF, are from the quadratic model y = ax^2 + bx + c. When DEG=1,
% the coefficients COEFF are from a linear model y=b*x+c. The
% coefficient's coordinates are with respect to the image coordinate
% system.

% Copyright (c) 2012
% Jerod Weinman
% jerod@acm.org

% $Id: getdistances.m 595 2014-10-24 18:15:54Z weinman $
 
% Jerod Weinman, Zach Butler, Dugan Knoll, Alexander Turner, Yirong Jing
% jerod@acm.org
% Copyright 2011, 2012, 2013, 2014
 
%    This file is part of PIONEER WordNorm.
%
%    PIONEER WordNorm is free software: you can redistribute it and/or modify
%    it under the terms of the GNU General Public License as published by
%    the Free Software Foundation, either version 3 of the License, or
%    (at your option) any later version.
%
%    PIONEER WordNorm is distributed in the hope that it will be useful,
%    but WITHOUT ANY WARRANTY; without even the implied warranty of
%    MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
%    GNU General Public License for more details.
%
%    You should have received a copy of the GNU General Public License
%    along with PIONEER WordNorm.  If not, see <http://www.gnu.org/licenses/>.

  if (length(coeff)==2) % If deg==1 (linear)
    coeff(3) = 0; % Extend coefficients for compatibility
  end
  
  % Translate quadratic to better condition root-finding for
  % distances

  [rows,cols] = find(bin_img);
  rowshift = mean(rows);
  colshift = mean(cols);
  rows = rows - rowshift;
  cols = cols - colshift;
  
  coeff_tr = translatequadratic(coeff,[-rowshift -colshift]);

D = arrayfun( @(x,y) norm([x y]-closestquadraticpoint(coeff_tr,[x y])), ...
              cols, rows);
