Index: trunk/src/civ_uvmat.m
===================================================================
--- trunk/src/civ_uvmat.m	(revision 273)
+++ trunk/src/civ_uvmat.m	(revision 309)
@@ -1,4 +1,36 @@
-% To develop....
-function [Data,errormsg]= civ_uvmat(Param,ncfile)
+%'civ_matlab': Matlab version of the PIV programs CivX
+% --- call the sub-functions:
+%   civ: PIV function itself
+%   fix: removes false vectors after detection by various criteria
+%   patch: make interpolation-smoothing 
+%------------------------------------------------------------------------
+% function [Data,errormsg,result_conv]= civ_uvmat(Param,ncfile)
+%
+%OUTPUT
+% Data=structure containing the PIV results and information on the processing parameters
+% errormsg=error message char string, default=''
+% resul_conv: image inter-correlation function for the last grid point (used for tests)
+%
+%INPUT:
+% Param: input images and processing parameters
+% ncfile: name of a netcdf file to be created for the result (extension .nc)
+%
+%AAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAA
+%  Copyright  2011, LEGI / CNRS-UJF-INPG, joel.sommeria@legi.grenoble-inp.fr.
+%AAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAA
+%     This is part of the toolbox UVMAT.
+% 
+%     UVMAT 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 2 of the License, or
+%     (at your option) any later version.
+% 
+%     UVMAT 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 (open UVMAT/COPYING.txt) for more details.
+%AAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAA
+
+function [Data,errormsg,result_conv]= civ_uvmat(Param,ncfile)
 errormsg='';
 Data.ListGlobalAttribute={'Conventions','Program','CivStage'};
@@ -20,37 +52,36 @@
     image1=imread(par_civ1.filename_ima_a);
     image2=imread(par_civ1.filename_ima_b);
-    stepx=str2num(par_civ1.dx);
-    stepy=str2num(par_civ1.dy);
-    ibx2=ceil(str2num(par_civ1.ibx)/2);
-    iby2=ceil(str2num(par_civ1.iby)/2);
-    isx2=ceil(str2num(par_civ1.isx)/2);
-    isy2=ceil(str2num(par_civ1.isy)/2);
-    shiftx=str2num(par_civ1.shiftx);
-    shifty=str2num(par_civ1.shifty);
+    ibx2=ceil(par_civ1.Bx/2);
+    iby2=ceil(par_civ1.By/2);
+    isx2=ceil(par_civ1.Searchx/2);
+    isy2=ceil(par_civ1.Searchy/2);
+    shiftx=par_civ1.Shiftx;
+    shifty=par_civ1.Shifty;
     miniy=max(1+isy2+shifty,1+iby2);
     minix=max(1+isx2-shiftx,1+ibx2);
     maxiy=min(size(image1,1)-isy2+shifty,size(image1,1)-iby2);
     maxix=min(size(image1,2)-isx2-shiftx,size(image1,2)-ibx2);
-    [GridX,GridY]=meshgrid(minix:stepx:maxix,miniy:stepy:maxiy);
-    PointCoord(:,1)=reshape(GridX,[],1);
-    PointCoord(:,2)=reshape(GridY,[],1);
-    if isfield(par_civ1,'maskname') && ~isempty(par_civ1.maskname) && ~isequal(par_civ1.maskname,'noFile use default')
-        maskname=par_civ1.maskname;
+    if ~isfield(par_civ1,'PointCoord')    
+        [GridX,GridY]=meshgrid(minix:par_civ1.Dx:maxix,miniy:par_civ1.Dy:maxiy);
+        par_civ1.PointCoord(:,1)=reshape(GridX,[],1);
+        par_civ1.PointCoord(:,2)=reshape(GridY,[],1);
+    end
+    if par_civ1.CheckMask && isfield(par_civ1,'MaskName') && ~isempty(par_civ1.MaskName) 
+        maskname=par_civ1.MaskName;
         mask=imread(maskname);
     end
     % caluclate velocity data (y and v in indices, reverse to y component)
-    [xtable ytable utable vtable ctable F] = pivlab (image1,image2,ibx2,iby2,isx2,isy2,shiftx,-shifty,PointCoord,str2num(par_civ1.rho), mask);
+    [xtable ytable utable vtable ctable F result_conv errormsg] = civ (image1,image2,ibx2,iby2,isx2,isy2,shiftx,-shifty,par_civ1.PointCoord,par_civ1.Rho, mask);
     list_param=(fieldnames(par_civ1))';
     list_remove={'pxcmx','pxcmy','npx','npy','gridflag','maskflag','term_a','term_b','T0'};
-    index=zeros(size(list_param));
-    for ilist=1:length(list_remove)
-        index=strcmp(list_remove{ilist},list_param);
-        if ~isempty(find(index,1))
-            list_param(index)=[];
-        end
-    end
+    index_remove=zeros(size(list_param));
+    for name=list_remove %loop on the list of names
+        index_remove=index_remove +strcmp(name{1},list_param);%index of the current name = name{1} 
+    end
+    list_param(find(index_remove,1))=[];
+    Civ1_param=list_param;%initialisation
     for ilist=1:length(list_param)
         Civ1_param{ilist}=['Civ1_' list_param{ilist}];
-        eval(['Data.Civ1_' list_param{ilist} '=Param.Civ1.' list_param{ilist} ';'])
+        Data.(['Civ1_' list_param{ilist}])=par_civ1.(list_param{ilist});
     end
     if isfield(Data,'Civ1_gridname') && strcmp(Data.Civ1_gridname(1:6),'noFile')
@@ -96,4 +127,80 @@
 
 %% Fix1
+%                 if Param.CheckCiv1==1
+%                     Param.Civ1=Param.Civ1;
+%                 end
+%                 if Param.CheckFix1==1
+%                     Param.Fix1=Param.Fix1;
+%                     fix1.WarnFlags=[];
+%                     if get(handles.CheckFmin2,'Value')
+%                         fix1.WarnFlags=[fix1.WarnFlags -2];
+%                     end
+%                     if get(handles.CheckF3,'Value')
+%                         fix1.WarnFlags=[fix1.WarnFlags 3];
+%                     end
+%                     fix1.LowerBoundCorr=thresh_vecC1;
+%                     if get(handles.num_MinVel,'Value')
+%                         fix1.UppperBoundVel=thresh_vel1;
+%                     else
+%                         fix1.LowerBoundVel=thresh_vel1;
+%                     end
+%                     if get(handles.CheckMask,'Value')
+%                         fix1.MaskName=maskname;
+%                     end
+%                     Param.Fix1=fix1;
+%                 end
+%                 if Param.CheckPatch1==1
+%                     if strcmp(compare,'stereo PIV')
+%                         filebase_A=filecell.filebase;
+%                         [pp,ff]=fileparts(filebase_A);
+%                         filebase_B=fullfile(pp,get(handles.RootName_1,'String'));
+%                         %TO CHECK: filecell.nc.civ1{ifile,j},filecell.ncA.civ1{ifile,j} have been switched according to Matias Duran
+%                         RUN_STLIN(filecell.nc.civ1{ifile,j},filecell.ncA.civ1{ifile,j},'civ1',filecell.st{ifile,j},...
+%                             str2num(nx_patch1),str2num(ny_patch1),str2num(thresh_patch1),[filebase_A '.xml'],[filebase_B '.xml'])
+%                     else
+%                         Param.Patch1.Rho=rho_patch1;
+%                         Param.Patch1.Threshold=thresh_patch1;
+%                         Param.Patch1.SubDomain=subdomain_patch1;
+%                     end
+%                 end
+%                 if Param.CheckCiv2==1
+%                     Param.Civ2=Param.Civ2;
+%                 end
+%                 if Param.CheckFix2==1
+%                     fix2.WarnFlags=[];
+%                     if get(handles.CheckFmin2,'Value')
+%                         fix2.WarnFlags=[fix2.WarnFlags -2];
+%                     end
+%                     if get(handles.CheckF4,'Value')
+%                         fix2.WarnFlags=[fix2.WarnFlags 4];
+%                     end
+%                     if get(handles.CheckF3,'Value')
+%                         fix2.WarnFlags=[fix2.WarnFlags 3];
+%                     end
+%                     fix2.LowerBoundCorr=thresh_vec2C;
+%                     if get(handles.num_MinVel,'Value')
+%                         fix2.UppperBoundVel=thresh_vel2;
+%                     else
+%                         fix2.LowerBoundVel=thresh_vel2;
+%                     end
+%                     if get(handles.CheckMask,'Value')
+%                         fix2.MaskName=maskname;
+%                     end
+%                     Param.Fix2=fix2;
+%                 end
+%                 if Param.CheckPatch2==1
+%                     if strcmp(compare,'stereo PIV')
+%                         filebase_A=filecell.filebase;
+%                         [pp,ff]=fileparts(filebase_A);
+%                         filebase_B=fullfile(pp,get(handles.RootName_1,'String'));
+%                         RUN_STLIN(filecell.ncA.civ2{ifile,j},filecell.nc.civ2{ifile,j},'civ2',filecell.st{ifile,j},...
+%                             str2num(nx_patch2),str2num(ny_patch2),str2num(thresh_patch2),[filebase_A '.xml'],[filebase_B '.xml'])
+%                     else
+%                         Param.Patch2.Rho=rho_patch2;
+%                         Param.Patch2.Threshold=thresh_patch2;
+%                         Param.Patch2.SubDomain=subdomain_patch2;
+%                     end
+%                 end
+
 if isfield (Param,'Fix1')
     ListFixParam=fieldnames(Param.Fix1);
@@ -117,5 +224,5 @@
             Data.VarDimName=[Data.VarDimName {'nb_vectors'}];
         end
-        Data.vec_FixFlag=fix_uvmat(Param.Fix1,Data.vec_F,Data.vec_C,Data.vec_U,Data.vec_V,Data.vec_X,Data.vec_Y);
+        Data.vec_FixFlag=fix(Param.Fix1,Data.vec_F,Data.vec_C,Data.vec_U,Data.vec_V,Data.vec_X,Data.vec_Y);
     else
         Data.ListVarName=[Data.ListVarName {'Civ1_FF'}];
@@ -123,5 +230,5 @@
         nbvar=length(Data.ListVarName);
         Data.VarAttribute{nbvar}.Role='errorflag';    
-        Data.Civ1_FF=fix_uvmat(Param.Fix1,Data.Civ1_F,Data.Civ1_C,Data.Civ1_U,Data.Civ1_V);
+        Data.Civ1_FF=fix(Param.Fix1,Data.Civ1_F,Data.Civ1_C,Data.Civ1_U,Data.Civ1_V);
         Data.CivStage=2;    
     end
@@ -148,5 +255,5 @@
     end
     [Data.Civ1_X_SubRange,Data.Civ1_Y_SubRange,Data.Civ1_NbSites,FFres,Ures, Vres,Data.Civ1_X_tps,Data.Civ1_Y_tps,Data.Civ1_U_tps,Data.Civ1_V_tps]=...
-                            patch_uvmat(Data.Civ1_X(ind_good)',Data.Civ1_Y(ind_good)',Data.Civ1_U(ind_good)',Data.Civ1_V(ind_good)',Data.Patch1_Rho,Data.Patch1_Threshold,Data.Patch1_SubDomain); 
+                            patch(Data.Civ1_X(ind_good)',Data.Civ1_Y(ind_good)',Data.Civ1_U(ind_good)',Data.Civ1_V(ind_good)',Data.Patch1_Rho,Data.Patch1_Threshold,Data.Patch1_SubDomain); 
       Data.Civ1_U_Diff(ind_good)=Data.Civ1_U(ind_good)-Ures;
       Data.Civ1_V_Diff(ind_good)=Data.Civ1_V(ind_good)-Vres;
@@ -164,6 +271,6 @@
             image2=imread(par_civ2.filename_ima_b);%read second image if not already done for civ1 
     end
-    stepx=str2double(par_civ2.dx);
-    stepy=str2double(par_civ2.dy);
+%     stepx=str2double(par_civ2.dx);
+%     stepy=str2double(par_civ2.dy);
     ibx2=ceil(str2double(par_civ2.ibx)/2);
     iby2=ceil(str2double(par_civ2.iby)/2);
@@ -182,5 +289,5 @@
         end
             [Data.Civ1_X_SubRange,Data.Civ1_Y_SubRange,Data.Civ1_NbSites,FFres,Ures, Vres,Data.Civ1_X_tps,Data.Civ1_Y_tps,Data.Civ1_U_tps,Data.Civ1_V_tps]=...
-                                patch_uvmat(Data.Civ1_X(ind_good)',Data.Civ1_Y(ind_good)',Data.Civ1_U(ind_good)',Data.Civ1_V(ind_good)',Data.Patch1_Rho,Data.Patch1_Threshold,Data.Patch1_SubDomain);
+                                patch(Data.Civ1_X(ind_good)',Data.Civ1_Y(ind_good)',Data.Civ1_U(ind_good)',Data.Civ1_V(ind_good)',Data.Patch1_Rho,Data.Patch1_Threshold,Data.Patch1_SubDomain);
         end 
 %     shiftx=str2num(par_civ1.shiftx);
@@ -192,5 +299,5 @@
     maxiy=min(size(image1,1)-isy2+shifty,size(image1,1)-iby2);
     maxix=min(size(image1,2)-isx2-shiftx,size(image1,2)-ibx2);
-    [GridX,GridY]=meshgrid(minix:stepx:maxix,miniy:stepy:maxiy);
+    [GridX,GridY]=meshgrid(minix:par_civ2.Dx:maxix,miniy:par_civ2.Dy:maxiy);
     PointCoord(:,1)=reshape(GridX,[],1);
     PointCoord(:,2)=reshape(GridY,[],1);
@@ -199,5 +306,5 @@
     end
     % caluclate velocity data (y and v in indices, reverse to y component)
-    [xtable ytable utable vtable ctable F] = pivlab (image1,image2,ibx2,iby2,isx2,isy2,shiftx,-shifty,PointCoord,str2num(par_civ1.rho),mask);
+    [xtable ytable utable vtable ctable F] = civ (image1,image2,ibx2,iby2,isx2,isy2,shiftx,-shifty,PointCoord,str2num(par_civ1.rho),mask);
     list_param=(fieldnames(par_civ1))';
     list_remove={'pxcmx','pxcmy','npx','npy','gridflag','maskflag','term_a','term_b','T0'};
@@ -254,5 +361,5 @@
             Data.VarDimName=[Data.VarDimName {'nb_vectors2'}];
         end
-        Data.vec_FixFlag=fix_uvmat(Param.Fix2,Data.vec2_F,Data.vec2_C,Data.vec2_U,Data.vec2_V,Data.vec2_X,Data.vec2_Y);
+        Data.vec_FixFlag=fix(Param.Fix2,Data.vec2_F,Data.vec2_C,Data.vec2_U,Data.vec2_V,Data.vec2_X,Data.vec2_Y);
     else
         Data.ListVarName=[Data.ListVarName {'Civ2_FF'}];
@@ -260,5 +367,5 @@
         nbvar=length(Data.ListVarName);
         Data.VarAttribute{nbvar}.Role='errorflag';    
-        Data.Civ2_FF=fix_uvmat(Param.Fix2,Data.Civ2_F,Data.Civ2_C,Data.Civ2_U,Data.Civ2_V);
+        Data.Civ2_FF=fix(Param.Fix2,Data.Civ2_F,Data.Civ2_C,Data.Civ2_U,Data.Civ2_V);
         Data.CivStage=5;    
     end
@@ -286,5 +393,5 @@
     end
     [Data.Civ2_X_SubRange,Data.Civ2_Y_SubRange,Data.Civ2_NbSites,FFres,Ures, Vres,Data.Civ2_X_tps,Data.Civ2_Y_tps,Data.Civ2_U_tps,Data.Civ2_V_tps]=...
-                            patch_uvmat(Data.Civ2_X(ind_good)',Data.Civ2_Y(ind_good)',Data.Civ2_U(ind_good)',Data.Civ2_V(ind_good)',Data.Patch2_Rho,Data.Patch2_Threshold,Data.Patch2_SubDomain); 
+                            patch(Data.Civ2_X(ind_good)',Data.Civ2_Y(ind_good)',Data.Civ2_U(ind_good)',Data.Civ2_V(ind_good)',Data.Patch2_Rho,Data.Patch2_Threshold,Data.Patch2_SubDomain); 
       Data.Civ2_U_Diff(ind_good)=Data.Civ2_U(ind_good)-Ures;
       Data.Civ2_V_Diff(ind_good)=Data.Civ2_V(ind_good)-Vres;
@@ -293,9 +400,7 @@
 end   
 
-%% write result
-% 'TESTcalc'
-% [DataOut,errormsg]=calc_field('velocity',Data)
+%% write result in a netcdf file if requested
 if exist('ncfile','var')
-errormsg=struct2nc(ncfile,Data);
+    errormsg=struct2nc(ncfile,Data);
 end
 
@@ -323,18 +428,27 @@
 %fieldref: 'civ1','filter1'...feld used in fileref
 
-function FF=fix_uvmat(Param,F,C,U,V,X,Y)
+function FF=fix(Param,F,C,U,V,X,Y)
 FF=zeros(size(F));%default
+Param
 
 %criterium on warn flags
-if isfield (Param,'WarnFlags')
-    for iflag=1:numel(Param.WarnFlags)
-        FF=(FF==1| F==Param.WarnFlags(iflag));
-    end
-end
-
+FlagName={'CheckFmin2','CheckF2','CheckF3','CheckF4'};
+FlagVal=[-2 2 3 4];
+for iflag=1:numel(FlagVal)
+    if Param.(CheckFlag(iflag))
+        FF=(FF==1| F==FlagVal(iflag));
+% if isfield (Param,'WarnFlags')
+%     for iflag=1:numel(Param.WarnFlags)
+%         FF=(FF==1| F==Param.WarnFlags(iflag));
+%     end
+% end
+    end
+end
 %criterium on correlation values
-if isfield (Param,'LowerBoundCorr')
-    FF=FF==1 | C<Param.LowerBoundCorr;
-end
+if isfield (Param,'MinCorr')
+    FF=FF==1 | C<Param.MinCorr;
+end
+return
+
 
 if isfield (Param,'LowerBoundVel')&& ~isequal(Param.LowerBoundVel,0)
@@ -427,5 +541,5 @@
 %------------------------------------------------------------------------
 % patch function
-function [SubRangx,SubRangy,nbpoints,FF,U_smooth,V_smooth,X_tps,Y_tps,U_tps,V_tps] =patch_uvmat(X,Y,U,V,Rho,Threshold,SubDomain)
+function [SubRangx,SubRangy,nbpoints,FF,U_smooth,V_smooth,X_tps,Y_tps,U_tps,V_tps] =patch(X,Y,U,V,Rho,Threshold,SubDomain)
 %subdomain decomposition
 warning off
@@ -542,4 +656,202 @@
 
 
-
-
+% 'civ': function piv.m adapted from PIVlab http://pivlab.blogspot.com/
+%--------------------------------------------------------------------------
+% function [xtable ytable utable vtable typevector] = civ (image1,image2,ibx,iby step, subpixfinder, mask, roi)
+%
+% OUTPUT:
+% xtable: set of x coordinates
+% ytable: set of y coordiantes
+% utable: set of u displacements (along x)
+% vtable: set of v displacements (along y)
+% ctable: max image correlation for each vector
+% typevector: set of flags, =1 for good, =0 for NaN vectors
+%
+%INPUT:
+% image1:first image (matrix)
+% image2: second image (matrix)
+% ibx2,iby2: half size of the correlation box along x and y, in px (size=(2*iby2+1,2*ibx2+1)
+% isx2,isy2: half size of the search box along x and y, in px (size=(2*isy2+1,2*isx2+1)
+% shiftx, shifty: shift of the search box (in pixel index, yshift reversed)
+% step: mesh of the measurement points (in px)
+% subpixfinder=1 or 2 controls the curve fitting of the image correlation
+% mask: =[] for no mask
+% roi: 4 element vector defining a region of interest: x position, y position, width, height, (in image indices), for the whole image, roi=[];
+function [xtable ytable utable vtable ctable F result_conv errormsg] = civ (image1,image2,ibx2,iby2,isx2,isy2,shiftx,shifty, GridIndices, subpixfinder,mask)
+%this funtion performs the DCC PIV analysis. Recent window-deformation
+%methods perform better and will maybe be implemented in the future.
+nbvec=size(GridIndices,1);
+xtable=zeros(nbvec,1);
+ytable=xtable;
+utable=xtable;
+vtable=xtable;
+ctable=xtable;
+F=xtable;
+result_conv=[];
+errormsg='';
+%warning off %MATLAB:log:logOfZero
+[npy_ima npx_ima]=size(image1);
+if ~isequal(size(image2),[npy_ima npx_ima])
+    errormsg='image pair with unequal size';
+    return
+end
+
+%% mask
+testmask=0;
+image1=double(image1);
+image2=double(image2);
+if exist('mask','var') && ~isempty(mask)
+   testmask=1;
+   if ~isequal(size(mask),[npy_ima npx_ima])
+        errormsg='mask must be an image with the same size as the images';
+        return
+   end
+    % Convention for mask
+    % mask >200 : velocity calculated
+    %  200 >=mask>150;velocity not calculated, interpolation allowed (bad spots)
+    % 150>=mask >100: velocity not calculated, nor interpolated
+    %  100>=mask> 20: velocity not calculated, impermeable (no flux through mask boundaries)
+    %  20>=mask: velocity=0
+    test_noflux=(mask<100) ;
+    test_undefined=(mask<200 & mask>=100 );
+    image1(test_undefined)=min(min(image1));% put image to zero in the undefined  area
+    image2(test_undefined)=min(min(image2));% put image to zero in the undefined  area
+end
+
+%% calculate correlations: MAINLOOP on velocity vectors
+corrmax=0;
+sum_square=1;% default
+for ivec=1:nbvec 
+    iref=GridIndices(ivec,1);
+    jref=GridIndices(ivec,2);
+    testmask_ij=0;
+    test0=0;
+    if testmask
+        if mask(jref,iref)<=20
+           vector=[0 0];
+           test0=1;
+        else
+            mask_crop1=mask(jref-iby2:jref+iby2,iref-ibx2:iref+ibx2);
+            mask_crop2=mask(jref+shifty-isy2:jref+shifty+isy2,iref+shiftx-isx2:iref+shiftx+isx2);
+            if ~isempty(find(mask_crop1<=200 & mask_crop1>100,1)) || ~isempty(find(mask_crop2<=200 & mask_crop2>100,1));
+                testmask_ij=1;
+            end
+        end
+    end
+    if ~test0    
+        image1_crop=image1(jref-iby2:jref+iby2,iref-ibx2:iref+ibx2);%extract a subimage (correlation box) from images 1  
+        image2_crop=image2(jref+shifty-isy2:jref+shifty+isy2,iref+shiftx-isx2:iref+shiftx+isx2);%extract a larger subimage (search box) from image 2
+        image1_crop=image1_crop-mean(mean(image1_crop));%substract the mean
+        image2_crop=image2_crop-mean(mean(image2_crop));
+        %reference: Oliver Pust, PIV: Direct Cross-Correlation
+        result_conv= conv2(image2_crop,flipdim(flipdim(image1_crop,2),1),'valid');
+        corrmax= max(max(result_conv));
+        result_conv=(result_conv/corrmax)*255; %normalize, peak=always 255
+        %Find the correlation max, at 255
+        [y,x] = find(result_conv==255,1);
+        if ~isempty(y) && ~isempty(x)
+            try
+                if subpixfinder==1
+                    [vector,F(ivec)] = SUBPIXGAUSS (result_conv,x,y);
+                elseif subpixfinder==2
+                    [vector,F(ivec)] = SUBPIX2DGAUSS (result_conv,x,y);
+                end
+                sum_square=sum(sum(image1_crop.*image1_crop));
+                ctable(ivec)=corrmax/sum_square;% correlation value
+%                 if vector(1)>shiftx+isx2-ibx2+subpixfinder || vector(2)>shifty+isy2-iby2+subpixfinder
+%                     F(ivec)=-2;%vector reaches the border of the search zone
+%                 end
+            catch ME
+                vector=[0 0]; %if something goes wrong with cross correlation.....
+                F(ivec)=3;
+            end
+        else
+            vector=[0 0]; %if something goes wrong with cross correlation.....
+            F(ivec)=3;
+        end
+        if testmask_ij
+            F(ivec)=3;
+        end
+    end
+    
+    %Create the vector matrix x, y, u, v
+    xtable(ivec)=iref+vector(1)/2;% convec flow (velocity taken at the point middle from imgae1 and 2)
+    ytable(ivec)=jref+vector(2)/2;
+    utable(ivec)=vector(1)+shiftx;
+    vtable(ivec)=vector(2)+shifty;
+end
+result_conv=result_conv*corrmax/(255*sum_square);% keep the last correlation matrix for output
+
+
+function [vector,F] = SUBPIXGAUSS (result_conv,x,y)
+vector=[0 0]; %default
+F=0;
+[npy,npx]=size(result_conv);
+
+% if (x <= (size(result_conv,1)-1)) && (y <= (size(result_conv,1)-1)) && (x >= 1) && (y >= 1)
+    %the following 8 lines are copyright (c) 1998, Uri Shavit, Roi Gurka, Alex Liberzon, Technion  Israel Institute of Technology
+    %http://urapiv.wordpress.com
+    peaky = y;
+    if y <= npy-1 && y >= 1
+        f0 = log(result_conv(y,x));
+        f1 = real(log(result_conv(y-1,x)));
+        f2 = real(log(result_conv(y+1,x)));
+        peaky = peaky+ (f1-f2)/(2*f1-4*f0+2*f2);
+    else
+        F=-2; % warning flag for vector truncated by the limited search box
+    end
+    peakx=x;
+    if x <= npx-1 && x >= 1
+        f0 = log(result_conv(y,x));
+        f1 = real(log(result_conv(y,x-1)));
+        f2 = real(log(result_conv(y,x+1)));
+        peakx = peakx+ (f1-f2)/(2*f1-4*f0+2*f2);
+    else
+        F=-2; % warning flag for vector truncated by the limited search box
+    end
+    vector=[peakx-floor(npx/2)-1 peaky-floor(npy/2)-1];
+% else
+%     vector=[NaN NaN];
+% end
+
+function [vector,F] = SUBPIX2DGAUSS (result_conv,x,y)
+vector=[0 0]; %default
+F=-2;
+peaky=y;
+peakx=x;
+[npy,npx]=size(result_conv);
+if (x <= npx-1) && (y <= npy-1) && (x >= 1) && (y >= 1)
+    F=0;
+    for i=-1:1
+        for j=-1:1
+            %following 15 lines based on
+            %H. Nobach Æ M. Honkanen (2005)
+            %Two-dimensional Gaussian regression for sub-pixel displacement
+            %estimation in particle image velocimetry or particle position
+            %estimation in particle tracking velocimetry
+            %Experiments in Fluids (2005) 38: 511515
+            c10(j+2,i+2)=i*log(result_conv(y+j, x+i));
+            c01(j+2,i+2)=j*log(result_conv(y+j, x+i));
+            c11(j+2,i+2)=i*j*log(result_conv(y+j, x+i));
+            c20(j+2,i+2)=(3*i^2-2)*log(result_conv(y+j, x+i));
+            c02(j+2,i+2)=(3*j^2-2)*log(result_conv(y+j, x+i));
+            %c00(j+2,i+2)=(5-3*i^2-3*j^2)*log(result_conv_norm(maxY+j, maxX+i));
+        end
+    end
+    c10=(1/6)*sum(sum(c10));
+    c01=(1/6)*sum(sum(c01));
+    c11=(1/4)*sum(sum(c11));
+    c20=(1/6)*sum(sum(c20));
+    c02=(1/6)*sum(sum(c02)); 
+    deltax=(c11*c01-2*c10*c02)/(4*c20*c02-c11^2);
+    deltay=(c11*c10-2*c01*c20)/(4*c20*c02-c11^2);
+    if abs(deltax)<1
+        peakx=x+deltax;
+    end
+    if abs(deltay)<1
+        peaky=y+deltay;
+    end
+end
+vector=[peakx-floor(npx/2)-1 peaky-floor(npy/2)-1];
+
+
