%function [dleft,drighti,sm,sens] = ...
%   ap_up_bd(mat,nblk,blk,blkp,repp,rnblk,rblk,rblkp,opt)
%
%	Approximate upper bound for mu.  Not to be called by user.

function [dleft,drighti,sm,sens] = ...
   ap_up_bd(mat,nblk,blk,blkp,repp,rnblk,rblk,rblkp,opt)

 [nr nc] = size(mat);
 tol = 0.00001; % DO WE NEED THIS????
 maxit = 10;
 minpercd = 0.01;

 if length(repp) == 0	% no repeated blocks ?
   if nblk==1
	d = 1;
    else
	for i=1:nblk
	 for j=1:nblk
	  sm(i,j) = norm(mat(blkp(i,2):blkp(i+1,2)-1,blkp(j,1):blkp(j+1,1)-1));
    	 end %for j
   	end %for i
   	d = sblkbal(sm,opt);
   end %if nblk==1
   [rdleft,rdrighti] = mkd(d,blk,nblk,blkp);
   drighti = diag(rdrighti);
   dleft = diag(rdleft);
   sm = dleft*mat*drighti;
 else
   sm = mat;
   oldfnorm = norm(sm,'fro');
   dleft = eye(nr);
   drighti = eye(nc);
   ii = 0;
   percd = 1;
   while ii < maxit & percd > minpercd
     ii = ii+1;
     [rmat,dl,dri] = frotmat(sm,nblk,blk,blkp,repp,dleft,drighti);
     cm = zeros(rnblk,rnblk);
     for i=1:rnblk
       for j=1:rnblk
           cm(i,j)=...
           norm(rmat(rblkp(i,2):rblkp(i+1,2)-1,rblkp(j,1):rblkp(j+1,1)-1));
       end %for j
     end %for i
     d = sblkbal(cm,opt);
     [ndl ndri] = mkd(d,rblk,rnblk,rblkp);
     dleft = diag(ndl)*dl;
     drighti = dri*diag(ndri);
     sm = diag(ndl)*rmat*diag(ndri);
     fnorm = norm(sm,'fro');
     percd = abs((oldfnorm - fnorm)/fnorm);
     oldfnorm = fnorm;
   end % while
 end % if length(repp) == 0
 sens = zeros(1,nblk);
 for i=1:nblk
   row = [sm(blkp(i,2):blkp(i+1,2)-1,1:blkp(i,1)-1) ...
          sm(blkp(i,2):blkp(i+1,2)-1,blkp(i+1,1):nc)];
   col = [sm(1:blkp(i,2)-1,blkp(i,1):blkp(i+1,1)-1) ; ...
          sm(blkp(i+1,2):nr,blkp(i,1):blkp(i+1,1)-1)];
   sens(i) = norm(row) + norm(col);
 end
%
% Copyright MUSYN INC 1991,  All Rights Reserved
