

uniform sampler2D lo;
uniform sampler2D hi;
uniform float mult;
uniform float xres, yres;
uniform float steps;

void main() {
	float mult2 = mult*steps;
	float randomi1 = sin(sin(sin(sin(gl_TexCoord[0].x*xres)*50+gl_TexCoord[0].y*yres)*50+gl_TexCoord[0].x*xres*1.2342342)*50+gl_TexCoord[0].y*yres*1.8123242)*.01;
	float randomi2 = sin(sin(sin(sin(gl_TexCoord[0].x*xres)*51+gl_TexCoord[0].y*yres)*49+gl_TexCoord[0].x*xres*1.345323342)*50+gl_TexCoord[0].y*yres*1.6123242)*.01;
	float randomi3 = sin(sin(sin(sin(gl_TexCoord[0].x*xres)*52+gl_TexCoord[0].y*yres)*47+gl_TexCoord[0].x*xres*1.7562342)*50+gl_TexCoord[0].y*yres*1.7123242)*.01;

	float sum = round(texture2D(lo, gl_TexCoord[0].xy)*mult2*4);
	vec2 hixy = round(gl_TexCoord[0].xy*vec2(xres,yres)*.5)*2;
	vec2 flop = gl_TexCoord[0].xy*vec2(xres,yres)-hixy;
	float a = texture2D(hi, (hixy+vec2(0,0))/vec2(xres,yres)).r*mult2;
	float b = texture2D(hi, (hixy+vec2(1,0))/vec2(xres,yres)).r*mult2+randomi1;
	float c = texture2D(hi, (hixy+vec2(0,1))/vec2(xres,yres)).r*mult2+randomi2;
	float d = texture2D(hi, (hixy+vec2(1,1))/vec2(xres,yres)).r*mult2+randomi3;

	float ra = round(a); a -= ra;
	float rb = round(b); b -= rb;
	float rc = round(c); c -= rc;
	float rd = round(d); d -= rd;

	float err = ra+rb+rc+rd-sum;
	if (err>.5) {
		if (a<b && a<c && a<d) ra-=1.,a+=1.; else
		if (b<a && b<c && b<d) rb-=1.,b+=1.; else
		if (c<a && c<b && c<d) rc-=1.,c+=1.; else
			rd-=1.,d+=1.;
		err -= 1.;
	}
	if (err>.5) {
		if (a<b && a<c && a<d) ra-=1.,a+=1.; else
		if (b<a && b<c && b<d) rb-=1.,b+=1.; else
		if (c<a && c<b && c<d) rc-=1.,c+=1.; else
			rd-=1.,d+=1.;
		err -= 1.;
	}
	if (err<-.5) {
		if (a>b && a>c && a>d) ra+=1.,a-=1.; else
		if (b>a && b>c && b>d) rb+=1.,b-=1.; else
		if (c>a && c>b && c>d) rc+=1.,c-=1.; else
			rd+=1.,d-=1.;
		err += 1.;
	}
	if (err<-.5) {
		if (a>b && a>c && a>d) ra+=1.,a-=1.; else
		if (b>a && b>c && b>d) rb+=1.,b-=1.; else
		if (c>a && c>b && c>d) rc+=1.,c-=1.; else
			rd+=1.,d-=1.;
		err += 1.;
	}
	gl_FragColor = (flop.x<0 ? (flop.y<0 ? ra : rc) : (flop.y<0 ? rb : rd))/mult2;
	//gl_FragColor = (rd)/mult2;
	//gl_FragColor = (a+b+c+d)/mult;
}

