function fringestruct=CalcFringes(fighandle)
% FRINGESTRUCT=CalcFringes(FIGHANDLE)
%
% This function accepts the handle FIGHANDLE to the main GUI and returns a structure
% FRINGESTRUCT with fields:
%         FRINGESTRUCT.prinval    : principal values (2 x (number of nodes)) 
%                                   = average principal stress values (1st and 2nd) at each node
%         FRINGESTRUCT.prindir    : principal direction at each node (2 x (number of nodes)) 
%         FRINGESTRUCT.prindif    : maximum in-plane shear at each node (1 x (number of nodes)) 
%         FRINGESTRUCT.frinvec    : fringe value at each node (1 x (number of nodes)) 
%         FRINGESTRUCT.frinsha    : indicates color of node for shading fringe pattern (1 x (number of nodes))
% 
% The field sigeps in the main GUI data structure must already exist (i.e. the solver 
% and the function CalcStrainStress must have successfully run) before this function will work. 

% get handles struct
handles=guidata(fighandle);

% initialize variables
numels=handles.mesh.size(1);
numnp=handles.mesh.size(2);
nnpe=handles.mesh.size(3);
gsig=handles.sigeps.sig;
np=handles.mesh.connect;

hits = zeros(1,numnp);
gsignp = zeros(3,numnp);
gprinval = zeros(2,numnp);
gprindir = zeros(2,numnp);
gprindif = zeros(1,numnp);
fringe_vect = zeros(1,numnp);
fringe_shade = zeros(1,numnp);
dark_values = zeros(1,numnp);

myfringe=inputdlg('How many fringes do you want? (2-50)','# of Fringes',1,{'6'});
numfringe=str2num(myfringe{1});
if numfringe<2 |numfringe>50
    errordlg('Number of fringes out of range. Using default value (6).')
    numfringe=6;
end
% average stress components at np's
for  i=1:numels
    for j = 1:nnpe
        j1 = np(i,j);
        hits(j1) = hits(j1)+1;
        gsignp(:,j1) = gsignp(:,j1) + gsig(i,:)';
    end
end

for i = 1:numnp
    gsignp(:,i) = gsignp(:,i)/hits(i);
end

% find eigen values / vectors
for i = 1:numnp
    sigmat(1,1) = gsignp(1,i);
    sigmat(1,2) = gsignp(3,i);
    sigmat(2,1) = sigmat(1,2);
    sigmat(2,2) = gsignp(2,i);

    [prindir,prinval] = eig(sigmat);
    gprinval(1,i) = prinval(1,1);
    gprinval(2,i) = prinval(2,2);
    gprindir(1,i) = prindir(1,1);
    gprindir(2,i) = prindir(1,2);
    gprindif(i) =   gprinval(2,i)-gprinval(1,i); % max in-plane shear
end

% make fringes
high_shear = max(gprindif);
low_shear = min(gprindif);
shear_span = high_shear-low_shear;

if(high_shear == 0.0)
    set(handles.error_text,'String',' No fringes ');
end

if(shear_span < 0.02*high_shear)
    numfringe = 1.0;
    shear_span = high_shear;
end

fringe_vect = (numfringe/shear_span)*(gprindif - low_shear*ones(1,numnp));
dark_values = fix(fringe_vect);
fringe_shade = sin((fringe_vect - dark_values)*pi);

% make output structure
fringestruct = struct('prinval',gprinval,...
    'prindir',gprindir,...
    'prindif',gprindif,...
    'frinvec',fringe_vect,...
    'frinsha',fringe_shade);

