%function [bnds,rowd,sens,rowp,rowg,sm] = munochk(matin,blk,opt)
function [sm] = munochk(matin,blk,opt)

% Copyright 2003-2004 The MathWorks, Inc.

% This must be in ROBUST/ROBUST, so that the PRIVATE routines can
% be accessed.
% calls: reindex, rubind, rub(deebal, rublow, newga, lamb, newub, dang, dand, geestep)

if nargin==2 || isempty(opt)
   opt = '';
end

% Map old options into new options
bigC = find(opt=='C'); opt(bigC) = 'a';
lowerr = find(opt=='r'); opt(lowerr) = 'i';
bigR = find(opt=='R'); opt(bigR) = 'm';
% Strip off 'c' and 'w'
lowerc = find(opt=='c'); opt(lowerc) = [];
lowerw = find(opt=='w'); opt(lowerw) = [];
ostruc.displaywarnings = any(opt=='d');
ostruc.fastupper = any(opt=='f');
ostruc.bestupper = any(opt=='a');
ostruc.bestuppernoscaling = any(opt=='n');
ostruc.initialize = any(opt=='i');
ostruc.multiplelower = any(opt=='m');
if ostruc.multiplelower
    ostruc.multiplelowertimes = goptvl(opt,'m',1,1);
end
ostruc.silent = any(opt=='s');
ostruc.decreaselower = any(opt=='x');
ostruc.increaselower = any(opt=='t');
ostruc.gui = any(opt=='g');
ostruc.backup = any(opt=='b');

% Using original (ie., 1989) tolerances
% numits = [30; 200];      contol = 1.001;
numits = [10; 50];      contol = 1.01;
if ostruc.decreaselower, numits(2)  = 50;             end


[nblk,dum] = size(blk);

[Or,Oc,Ur,Uc,K,I,J] = reindex(blk);
[Kc,Kr,Ic,Ir,Jc,Jr,Fc,Fr,kc,kr,ic,ir,jc,jr,fc,fr,sc,sr,csc,csr,...
 csF,nK,nI,nJ,nF,nc,nr,kcK,icI,jcJ,jrJ,fcF] = rubind(K,I,J);
LFr = logical(Fr); LFc = logical(Fc);
LJr = logical(Jr); LJc = logical(Jc);
ps = [];
dmask = fcF'*fcF;
ds = [];
wd = sum(sum(dmask)) + nJ;
Ldmask = logical(dmask);

rowdmat = [];
wg = sum(K);

szm = size(matin);
sm = zeros(szm);
npts = prod(szm(3:end));
for i=1:npts
	M = matin(Oc,Or,i);
	[bnds,prt,dc,dri,dcb,drib,dcd,drid,g,y,b] = ...
     rub(M,K,I,J,ostruc,numits,contol,Kc,Kr,Ic,Ir,Jc,Jr,Fc,Fr,kc,kr,ic,ir,...
     jc,jr,fc,fr,sc,sr,csc,csr,csF,nK,nI,nJ,nF,nc,nr,kcK,icI,...
     jcJ,jrJ,fcF);
	if sum(Fc)
       df = dcd(LFc,LFc); rowdmat = df(Ldmask);
	end
	if sum(Jc)
       ds = max(jcJ'.*(diag(dcd(LJc,LJc))*ones(1,nJ)));
	end
	rowdmat = [rowdmat(:); ds(:)].';
	wdf = sum(sum(dmask));
	LKc = logical(Kc); LKr = logical(Kr);
	LFc = logical(Fc); LFr = logical(Fr);
	LJc = logical(Jc); LJr = logical(Jr);
	Ldmask = logical(dmask);
	
	dl = zeros(csc(4),csc(4));
	dr = zeros(csr(4),csr(4));
	df = zeros(csc(3),csc(3));
	if sum(Fc),
       df(Ldmask) = rowdmat(1,1:wdf);
       dl(LFc,LFc) = df;
       dr(LFr,LFr) = df;
	end
	if sum(Jc)
       dl(LJc,LJc) = diag(diag(jcJ'*diag(rowdmat(1,wdf+1:wd))*jcJ));
       dr(LJr,LJr) = diag(diag(jrJ'*diag(rowdmat(1,wdf+1:wd))*jrJ));
	end
	dl = dl(Uc,Uc);
	dr = dr(Ur,Ur);
	sm(:,:,i) = dl*(matin(:,:,i)/dr);
end

