%ver 1.3 sa dva nivoa varijabli


h_1 = WndCreat ([], "RIM Weighting", [NaN,NaN,357,400], 2);

CtrCreat (h_1, 510, [11,11,81,13], "Margin variables:");
h_2 = CtrCreat (h_1, 320, [11,24,132,143], marvar);
CtrCreat (h_1, 510, [210,11,131,13], "RIM variables - Priority high");
h_3 = CtrCreat (h_1, 320, [207,24,132,60], "");
CtrCreat (h_1, 510, [210,94,131,13], "RIM variables - Priority low");
h_4 = CtrCreat (h_1, 320, [207,107,132,62], "");

CtrCreat (h_1, 510, [11,182,131,13], "Other variables");
h_5 = CtrCreat (h_1, 320, [11,195,132,169], vars);
CtrCreat (h_1, 510, [210,180,131,13], "Split variable");
h_6 = CtrCreat (h_1, 310, [207,195,132,20], "");
CtrCreat (h_1, 510, [210,215,131,13], "Start weight");
h_7 = CtrCreat (h_1, 310, [207,228,132,18], wgh_name);

CtrCreat (h_1, 510, [174,265,90,13], "Minimum trim value");
h_8 = CtrCreat (h_1, 410, [272,265,68,20], "0.3");
CtrCreat (h_1, 510, [174,289,90,13], "Maximum trim value");
h_9 = CtrCreat (h_1, 410, [272,288,68,20], "3.0");
CtrCreat (h_1, 510, [174,312,90,13], "Size after RIM");
h_10 = CtrCreat (h_1, 410, [272,310,68,20], "5395376");

h_11 = CtrCreat (h_1, 150, [156, 47,38,21], "", "");
h_12 = CtrCreat (h_1, 150, [156,122,38,21], "", "");
h_13 = CtrCreat (h_1, 150, [156,195,38,18], "", "");
h_14 = CtrCreat (h_1, 150, [156,228,38,20], "", "");

CtrConect(h_11,h_2,h_3);
CtrConect(h_12,h_2,h_4);
CtrConect(h_13,h_5,h_6);
CtrConect(h_14,h_5,h_7);

CtrCreat (h_1, 110, [174,341,75,23], "OK","rim_m2;if dalje;WndClose(h_1);rim_m3;end;");
CtrCreat (h_1, 110, [266,341,75,23], "Cancel","WndClose(h_1);");




global macro rim_m2
	dalje=1;
	marvarf1 = CtrGet(h_3);
	marvarf2 = CtrGet(h_4);
	splitvar = CtrGet(h_6);
	startw   = CtrGet(h_7);
	splitvar_s = splitvar;

	if (~size(marvarf1,1))
		dalje=0;
		MsgBox(h_1,"You must supply weighting variables in");
	end
	
	a=CtrGet(h_8);
	if strlen(a)
		trimin = str2num(a);
	else
		trimin = 0.4;
	end
	
	a=CtrGet(h_9);
	if strlen(a)
		trimax = str2num(a);
	else
		trimax = 3;
	end
	
	a=CtrGet(h_10);
	if strlen(a)
		expan = str2num(a);
	else
		expan = 0;
	end
end




global macro rim_m3
	%izbaciti i one margine koje nisu selektovane u marvarf
	c=zeros(brdim,1);
	for i=1:brdim
		if size(marvarf2,1)
			c(i)=sum(~strcmp(marvarf1,marvar(i))) + sum(~strcmp(marvarf2,marvar(i)));
		else
			c(i)=sum(~strcmp(marvarf1,marvar(i)));
		end
	end
	c=find(~c);
	if c~=[]
		marvar(c)=[];
		if ~min(size(marvar))
			error("U fajlu nema ni jedna varijabla sa imenom margina")
		end
		k=1:brdim;
		k(c)=[];
		brdim=max(size(k));
		%smanjenje originalnih mar nizova iz fajla, na one koje su izabrani
		for j=1:brdim
			mar#(j)=mar#(k(j));
		end
	end
	type12=zeros(brdim,1)+1;
	for i=1:brdim
		type12(i)=type12(i)+sum(~strcmp(marvarf1,marvar(i))); % ako je 1 ide u prvom krugu ako je dvojka ide u drugom
	end
	%uraditi split varijablu
	if size(splitvar,1)
		splitvar=Data(:,splitvar);
		[splitval j]=freq(splitvar);		
	else
		splitvar=ones(ncase,1);
		splitval=1;
	end
	
	%pamti u mari originlne margine
	for i=1:brdim
		sorta(mar#i);
		mari#i=mar#i;
	end
	
	ponder_f = ones(ncase,1);
	
	for spl=1:size(splitval,1)
		splcase=find(splitvar==splitval(spl));
		if size(splitvar_s,1)
			print("\n============================================================================")
			printf("Vrednost na %s : %d\n\n", splitvar_s, splitval(spl));
		end
		Z=Data(splcase,marvar);
		if Z==[]
			error("Nema ni jedan validini listwise record")
		end
		
		
		if size(marvarf2,1)
			krug = 1; %ima i varijabli sa niskim prioritetom
		else
			krug = 2;
		end
		
		if size(startw,1)
			PonderStart = Data(splcase,startw);
		else
			PonderStart = ones(size(splcase));
		end		
		
		for i=1:brdim
			[v n]=freq(Z(:,i),PonderStart);
			org#i=n;
			n=size(v,1);
			if v(n)==NaN
			   	v(n)=[];
			   	org#i(n)=[];
				n=n-1;
			end
			org#i=org#i/sum(org#i);
		end
		%ovo isto brisati
		
		while (krug<3)
			pd=zeros(size(Z));
			%vraca originalne margine
			for i=1:brdim
				mar#i=mari#i;
			end
			
			for i=1:brdim
				mari=mar#i;
				[v n]=freq(Z(:,i),PonderStart);
				n=size(v,1);
				if v(n)==NaN
				   	v(n)=[];
					n=n-1;
				end
				m=size(mari,1);
				
				c=zeros(m,1);
				for j=1:m
					c(j)=sum(v==mari(j,1));
				end
				c=find(~c);
				if c~=[]
					mari(c,:)=[];
				end
				if (size(mari,1)~=size(v,1))
					error(sprintf("U varijabli %s ima kod koji ne postoji u margini", marvar(i)));
				end
				mar#i=mari;
				mar#i(:,2)=mar#i(:,2)/sum(mar#i(:,2));
				dum#i=dummy(Z(:,i));
				wd#i=ones(size(mar#i,1),1);
				pd(:,i)=dum#i*wd#i;
			end
			
			p=find(~pd);
			if p~=[]
				pd(p)=1;
			end
	
			n=size(Z,1);
			iter=0;
			rez=[];
			ind=-1;
			hi = zeros(brdim,1);
			%slucaj=ceil(rand(500)*10);
			repeat
				iter=iter+1;
				rms=0;
				ponder=(PonderStart.*rprod(pd))';
				for i=1:brdim
					if type12(i)==krug
						sum#i=(ponder*dum#i)';
						rsum#i=sum#i/sum(sum#i);
						m=mar#i(:,2);
						hi(i)=sum((rsum#i-m).^2./m)/size(m,1);
					end
				end
				a=find(hi==max(hi));
				a=a(1);
				%a=slucaj(iter);
				wd#a=mar#a(:,2)./rsum#a;
				pd(:,a)=pd(:,a).*dum#a*wd#a;
				if p~=[]
					pd(p)=1;
				end
				%rms=rms+sum((mar#a(:,2)-rsum#a).^2)*n*n;
				aa=[a hi(a)*1000];
				print([iter aa],marvar(a),[])
				
				%print(hi')
				if rez~=[]
					rr=sum(abs(rez-aa)')<0.00001;
					if any(rr)
						k=find(rr);
						k=max(k);
						rr=rez(k:size(rez,1),1);
						ind=find(rr==min(rr))-1;
						ind=min(ind);
					end
				end
				rez=[rez;aa];
				if (ind>0)
					ind=ind-1;
				end
				%ovo brisati
				%if iter>200
				%	ind=0;
				%else
				%	ind=1;
				%end
			until (ind==0);
			%rsum#i je proporcija ponderisanih podataka pre trimovanja
			
			%izracunavanje frekvenci pre trimovanja
			ponder=(PonderStart.*rprod(pd))';
			for i=1:brdim
				sum#i=(ponder*dum#i)';
				rsum#i=sum#i/sum(sum#i);
			end
			%TRIMOVANJE
			c=find(ponder>trimax);
			trimn1=size(c,1);
			if trimn1
				ponder(c)=trimax;
			end
			c=find(ponder<trimin);
			trimn2=size(c,1);
			if trimn2
				ponder(c)=trimin;
			end
			print("")
			printf("Triming cut out %d less then %f and %d more then %f\n", trimn2, trimin, trimn1, trimax);
			print("")
			if expan==0
				ponder=ponder*(max(size(ponder))/sum(ponder));
			else
				ponder=ponder*(expan/sum(ponder));
			end
			%sum#i je proporcija ponderisanih podataka nakon trimovanja
			for i=1:brdim
				sum#i=(ponder*dum#i)';
				sum#i=sum#i/sum(sum#i);
			end
			
			%ispis statistike
			if krug == 2
				for i=1:brdim
					print("")
					mari = mar#i(:,2)*100;
					mary = mar#i(:,1);
					printf("%s : %5.2f\n",marvar(i),sum((mari - sum#i*100).^2./mari)/size(mari,1)*100);
					print("  Kod    Target     Orig    O/T   NonTrimed    RIM     Epsilon     Delta")
					for j=1:size(mary,1)
						printf("%5d %9.2f %8.2f  %5d %9.2f %9.2f %9.2f %10.2f\n",mary(j),mari(j),org#i(j)*100,org#i(j)*100/mari(j)*100,rsum#i(j)*100,sum#i(j)*100,(mari(j) - sum#i(j)*100),(abs(mari(j) - sum#i(j)*100)./mari(j))*100) 
					end
				end
			end
			if min(find(rez(:,2)==min(rez(:,2))))==1
				print("   Bolje je nekoristiti ponder~")
				ponder=ones(size(ponder));
			end
			ponder_f(splcase)=ponder;
			PonderStart = ponder';
			krug = krug+1;
		end
	end
	
	krug = 1;
	while (vdef(RIM_W_#krug))
		krug = krug + 1;
	end
	ssv = "RIM_W_" + num2str("%d",krug);
	DataAddVar(ssv);
	Data(:,ssv) = ponder_f;
	
	
	l = "HI: ";
	if max(size(marvarf1))
		marvarf1 = lcase(marvarf1);
		for i=1:max(size(marvarf1))
			l = l + marvarf1(i) + " ";
		end
	end
	if max(size(marvarf2))
		marvarf2 = lcase(marvarf2);
		l = l + "  LO: ";
		for i=1:max(size(marvarf2))
			l = l + marvarf2(i) + " ";
		end
	end
	l = l + " TRIM("+sprintf("%0.1f - %0.1f)", trimin, trimax);
	if size(startw,1)
		l = l + " FROM: " + lcase(startw);
	end
	SetVarLabel(ssv,l);
	DataSave();
	printf("\nVariable %s created into the data file\n", ssv);
	
	clear
end

function y = dummy(x)
	if size(x,2)==1
	    [a,b]=freq(x);
	    c=max(size(a));
	    if a(c)==NaN
	    	a(c)=[];
	  		c=c-1;
	  	end
		y = zeros(size(x,1),c);
		for i=1:c
			y(:,i) = (x==a(i));
		end
	elseif size(x,1)==1
	    [a,b]=freq(x);
	    c=max(size(a));
	    if a(c)==NaN
	    	a(c)=[];
	  		c=c-1;
	  	end
		y = zeros(c,size(x,2));
		for i=1:c
			y(i,:) = (x==a(i));
		end
	else
		error("Argument funkcije 'dummy' mora biti vektor")
	end
end



