function [mxgain,delta,tryr] = wcrggen1cop(m,L,U,Mcheck)
% Maximize UPPER-LOOP closure with a repeated real scalar (1 time) between
% bounds L and U.  Gets critical points (of absolute value) using
% 2x2 matrix M, and then evaluates NORM on F_U(Mcheck,delta) if
% Mcheck is provided.

% Copyright 2003-2004 The MathWorks, Inc.

if isreal(m(1,1)) && m(1,1)~=0 && (1/m(1,1) >= L) && (1/m(1,1) <= U)
   mxgain = Inf;
   delta = 1/m(1,1);
   tryr=[delta];
   return
end   

% lft = (a+b*delta)/(1+d*delta)
a = m(2,2);
b = m(2,1)*m(1,2)-m(1,1)*m(2,2);
c = 1;
d = -m(1,1);

% Find critical points / endpoints
asq = a'*a;
bsq = b'*b;
csq = 1; %csq = c'*c;
dsq = d'*d;
cd = real(d); %cd = real(c'*d);
ab = real(a'*b);

c1 = bsq*cd-dsq*ab;
%c2 = bsq*csq-asq*dsq;
%c3 = csq*ab-asq*cd;
c2 = bsq-asq*dsq;
c3 = ab-asq*cd;
if c1==0
    if c2~=0
       pts = -c3/c2;
       if pts>=L & pts<=U
            tryr = [L pts U];
       else
            tryr = [L U];
       end
    else
        if c3==0
            tryr = L;
        else
            tryr = [L U];
        end
    end 
else
	disc = c2^2-4*c1*c3;
	if disc < 0
       tryr = [L U];
	else
       pts = [-c2+sqrt(disc)  -c2-sqrt(disc)]/2/c1;
       idx = find(pts<=U & pts>=L);
       tryr = [L pts(idx) U];
	end
end
   
% evaluate ||lft||^2
tryr_sq = tryr.^2;
numvals = bsq*tryr_sq+2*ab*tryr+asq;
denvals = dsq*tryr_sq+2*cd*tryr+csq;
vals = numvals./denvals;

[mxgain,idx] = max(vals);
mxgain = sqrt(mxgain);
delta = tryr(idx);
