function parm = gmix_deflate(parm,min_weight_1,min_weight_all, debug)
%function parm = gmix_deflate(parm,min_weight_1,min_weight_all, debug)
%
% This function removes ALL modes whose weight is < min_weight_all
% and at most ONE mode whose weight is < min_weight_1.
%
% NOTE: This function removes modes ONE-AT-A-TIME, and recomputes
%  mode weights after each removal, so a mode whose initial weight
%  is less than the threshold may not be removed after another mode
%  with an even smaller weight is removed first.

%
% NAVAL UNDERSEA WARFARE CENTER
% class-specific@npt.nuwc.navy.mil
% http://www.npt.nuwc.navy.mil/csf
% Paul M. Baggenstoss
% 401-832-8240
% Do not disseminate.
%



%  Dr. Paul M. Baggenstoss
%  Naval Undersea Warfare Center
%  Newport, RI
%  p.m.baggenstoss@ieee.org
%  Date              Reason
%  ------------      --------------
%  Mar 28, 1997      Initial release
%  Feb 4, 1999       Fixed bug
%  Feb 14, 1999      Added: if(nmode==1), return; end;
%  Oct 3, 2001       converted to MATLAB5
%  Jul 23, 2004:     added debug flag


wts=[parm.modes.weight]';
means=[parm.modes.mean];
nmode = length(wts);
if(nmode==1), return; end;
if(nargin < 4), debug=0; end;

ndefl=0;
% --- deflate weakest mode ---
flag = 1;
while(flag==1),
    [ymn,imn] = min(wts);
    if (ymn < min_weight_all || ((ymn < min_weight_1) && (ndefl < 1))) 
		if(ymn >= min_weight_all), ndefl=ndefl+1; end;
        flag = 1;
        if(debug), 
            fprintf('DEFLATE: Deflating mode %g, weight=%g, nmode=%d\n', ...
            imn,ymn,nmode-1);
         end;
        ii = 1;
        for i=1:nmode,
            if i ~= imn,
                parm.modes(ii)= parm.modes(i);
                ii = ii + 1;
            end;
        end;
        %wts = wts / (1-ymn);
        nmode = nmode-1;
        parm.modes=parm.modes(1:nmode);
        wts=[parm.modes.weight]';
        wts = wts/sum(wts);
    else
        flag = 0;
    end
end

wts = [parm.modes.weight]';
wts = wts / sum(wts);
for i=1:length(wts), parm.modes(i).weight=wts(i); end;
