function [mmap,pmap] = phase_fit(fnames,C,image_thresh,fft_thresh,fname_out,exclude,create_tmap,window_data);
%function [mmap,pmap] = phase_fit(fnames,C,image_thresh,fft_thresh,fname_out,exclude,create_tmap,window_data);
% for visual field sign mapping, both eccentricity and polar angle phase mapping.
%
% input:
%  fnames	: files to be analysed
%  C 		: number of stimulus cycles (normally 10)
%  image_thresh	: typically 128, above which data will be analysed
%  fft_thresh 	: fraction of the average power in fft noise-bins (40-60) (.e.g. 2), 
%		  above which data will be analysed.
%  fname_out	: output base name (_fft_phase.mnc and _fft_magnitude.mnc will be added)
%  exclude 	: blanks at start to be ignored. (usually [1:8])
%  create_tmap  : create tmap (spearman) as well (default=[], no)
%
% output:
%  Phase file 	: phase of Fourier component C+1 (after detrending - nochange in phases).
%		  	no phase unwrapping
%  Mag file	: magnitude file of component C+1 (abs(F(C+1))/mean(F(tf/2-tf/6:tf/2));
%  		  	i.e. assumes that bins tf/2-tf/6:tf/2 are just noise,
%			 tf=timeframes, usually 120 -> bins 40:60 will be used.

% ---------------------------------
% Copyright (c) 2003 Serge Dumoulin and Rick Hoge
% This program is free software; you can redistribute it and/or
% modify it under the terms of the GNU General Public License version 2
% as published by the Free Software Foundation.
% ---------------------------------


tic
if nargin < 8,
  window_data=0;
end;
if nargin < 7,
   create_tmap=[];
end;
if nargin < 6
  exclude = [];
end
if nargin < 5
 fname_out = [];
end
if nargin < 4
 fft_thresh = [];
end
if nargin < 3
 image_thresh = [];
end
if nargin < 2.
   help phase_fit_gen2;
   return;
end;

if isempty(fft_thresh)
  fft_thresh = 0;
end
if (~isempty(create_tmap) & create_tmap==0);
   create_tmap = [];
end;


do_plot=0; % for debugging
uplimit=50; % set magnitude in case of division by zero

% open the minc file
nfiles = size(fnames,1);
handles = zeros(1,nfiles);

for ix=1:nfiles
  handles(ix) = openimage(fnames(ix,:));
end

frames=getimageinfo(handles(1),'NumFrames');
sizes=getimageinfo(handles(1),'ImageSize');
FrameTimes=getimageinfo(handles(1),'FrameTimes');
ImageHeight=sizes(1);
ImageWidth=sizes(2);
len = sizes(1).*sizes(2);
size_ = sizes(1);
ns=getimageinfo(handles(1),'NumSlices');

if ~isempty(fname_out)
  fname_m = [ fname_out '_fft_magnitude.mnc'];
  new_handle_m = newimage(fname_m,[0 ns],fnames(1,:));
  fname_p = [ fname_out '_fft_phase.mnc'];
  new_handle_p = newimage(fname_p,[0 ns],fnames(1,:));
  if ~isempty(create_tmap), 
     fname_t = [ fname_out '_dspear_tmap.mnc'];
     new_handle_t = newimage(fname_t,[0 ns],fnames(1,:));
  end;
end;

% set up vector of points to keep, given exclusions:

allpts = 1:frames;
allpts(exclude) = zeros(1,length(exclude));
keep = allpts( find( allpts ) );

% adjust # of frames:

frames2 = frames - length(exclude);


% perform FFTs, slice by slice, row by row:
% write results to MINC file

% create vectors for activation map:
if ~isempty(create_tmap), 
   tmap = zeros(len,ns); 
end;
mmap = zeros(len,ns);
pmap = NaN.*ones(len,ns);

fprintf('[%s]: Processing:',mfilename);drawnow;
for slice=1:ns,
   for row=1:ImageHeight,
      rowindex=(1+(row-1)*ImageWidth):((row-1)*ImageWidth)+ImageWidth;
      data = [];
      for ix = 1:nfiles
         data = [ data.' ;...
                  getimages(handles(ix),slice,keep,data,row,1).'].';
      end
      
      if isempty(image_thresh),
         above = 1:length(data(:,1));
      else,
         above = find(data(:,1) > image_thresh);
      end;
      
      rowindex=rowindex(above);
      v=data(above,:);

      % subtract mean from intensity vector + detrend
      v=detrend(v')';

      %if window_data,
      %   v=v.*hanw';
      %end; % if window_data
      vft = fft(v')';
    
      % make list of other frequencies, excluding DC and C
      %other_frequencies = 2:frames2/2;
      %other_frequencies = other_frequencies(...
      %		  find(rem(other_frequencies+C-1,2.*C)));
      %
      %negatives=fliplr(vft(round(frames2/2)+1:length(vft)));
      % Mag = (abs(vft(C+1))+abs(negatives(C)))./...
      % sum([abs(vft(other_frequencies)) ...
      %	      abs(negatives(other_frequencies-1))]);

      meannoisebins=mean(abs(vft(:,round((frames2/2)-frames2/6):floor(frames2/2))'))';
      auto_thresh=meannoisebins*fft_thresh;

      Mag=abs(vft(:,C+1)); 
      Phase = angle(vft(:,C+1));
     
      zindex=find(meannoisebins==0);
      Mag(zindex)=uplimit;
      meannoisebins(zindex)=1;%protect for divisions by 0
      mmap(rowindex,slice)=Mag./meannoisebins;
      
      abovemagtheshold=find(Mag >= auto_thresh);
      pmap(rowindex(abovemagtheshold),slice)=Phase(abovemagtheshold);
            
      if ~isempty(create_tmap),
         tmptmap=zeros(size(Mag));
         %vft2=vft;
         %vft2(:,[1:C C+2:length(vft)])=0;
         %nonzero=find(vft2(:,C+1)~=0);
         nonzero=find(Mag~=0);
         
         range=(ones(size(vft(nonzero,:),1),1)*(0:frames2-1)) ./(frames2/C)*2*pi;
         shift=angle(vft(nonzero,C+1)) * ones(1,frames2);
         ss=round((cos(range-shift).*.5)+0.5);

         
         %ss=real(ifft(vft2(nonzero,:)'))';
         %ss=round((ss-min(ss')'*ones(1,size(ss,2))) ./ ...
         %         (max(ss')'*ones(1,size(ss,2))-min(ss')'*ones(1,size(ss,2))));
         tmptmap(nonzero)= spear( v(nonzero,:), ss );
         tmap(rowindex,slice)=tmptmap;
      end;
  end % of row loop

  % take care of sub-threshold values:
  junk=find(isnan(pmap(:,slice)));
  pmap(junk,slice)=-3.5 * ones(length(junk), 1);

  % write maps to file, if requested
 
  if ~isempty(fname_out)
     putimages(new_handle_m,mmap(:,slice),slice);
     putimages(new_handle_p,pmap(:,slice),slice);
     if ~isempty(create_tmap),
        putimages(new_handle_t,tmap(:,slice),slice);
     end;
  end;
  fprintf('.');
end;

for ix=1:nfiles
  closeimage(handles(ix));
end
closeimage(new_handle_m);
closeimage(new_handle_p);
if ~isempty(create_tmap),
   closeimage(new_handle_t);
end;
fprintf('Done[%d minutes].\n',round(toc./60));






