%
%--------------------------------------------------------------------------
% function [center_row, center_col]=FT_guess_center_LG(data_in,threshold, mode, verbose)
%
% A function for Matlab that tries to guess the center of an LG mode shape
% in a given 2D array
% 
% data_in:   2D data grid of an LG image
% threshold: threshold for boxing method
% mode: if mode==1 the box method is used, mode==2 uses center of math
% verbose: if verbose=1 the function plots and prints additional infor for debugging
%
% center_row: row index of center
% center_col: col index of center
%
% Andreas Freise  12.08.2009
%--------------------------------------------------------------------------
%

% Description: Guesses the center of an LG mode shape in a given 2D array
% Keywords: guess, center, centre, LG, mode, shape, 2D

function [center_row, center_col]=FT_guess_center_LG(data_in,threshold, mode, verbose)
  
  baseid='FT_guess_center_LG';

  if (mode~=1 && mode~=2)
    msgid=[baseid,':checkinarg'];
    result='mode must be 1 or 2';
    error(msgid,result);
  end
  
  % the following is a good idea but in practise does not work well
  %data_in=FT_remove_piston_data(data_in);

  % Method two: boxing the data
  [rows,cols]=size(data_in);
  
  [data_box,boffset]=FT_box_data(data_in,threshold);
  [rows2,cols2]=size(data_box);
  crow1=rows2/2.0 + boffset(1);
  ccol1=cols2/2.0 + boffset(2);
  
  % Method two: finding center of mass
  [cguess]=FT_center_of_mass(data_box);
  crow2=cguess(1) + boffset(1);
  ccol2=cguess(2) + boffset(2);

  
  if (verbose>=2)
    figure
    hold on;
    surf(data_in,'EdgeColor','None');
    view(2)
    [lineY,lineX]=meshgrid(linspace(1,rows,rows),boffset(2));
    line(lineX,lineY)
    [lineY,lineX]=meshgrid(linspace(1,rows,rows),boffset(2)+cols2);
    line(lineX,lineY)
    [lineY,lineX]=meshgrid(boffset(1),linspace(1,cols,cols));
    line(lineX,lineY)
    [lineY,lineX]=meshgrid(boffset(1)+rows2,linspace(1,cols,cols));
    line(lineX,lineY)
    p1=plot(ccol1,crow1,'rx','Linewidth',4,'Erasemode','none');
    p2=plot(ccol2,crow2,'gx','Linewidth',4,'Erasemode','none');
    legend([p1,p2],'box method','center of mass method');
    axis square;
    axis tight;
    hold off;
    title('LG center guess');
    text(cols*0.5,rows*-0.1,datestr(now));
  end
  
  if (mode==1)
    center_row=crow1;  
    center_col=ccol1;
  else
    center_row=crow2;  
    center_col=ccol2;
  end    