clear;
fname = input('Name of topo quad? ','s')

im = imread(sprintf('/morgan/topo/tif/%s.tif',fname),'tif');
imout = double(rot90(im)); 
[ny,nx] = size(imout);

tie0 = input('Do you warp map with affine transformation? (1=yes, 0=no)  ');
if( tie0 == 1)
	imtmp = imout;
	imout = affineTransf( imtmp);
end

clf; imagesc(imout);
tie = input('Do you want to clean up map boundaries? (1=yes, 0=no)  ');
if( tie == 1)
	disp('First pick left boundary.  Pick only two interior points,'); 
	disp('first at the bottom, then at the top.  This defines a ');
	disp('straight line.  Everything to the left of the line will be');
	disp('marked as `bad`.');
	title('Pick left map boundary');
	xlabel('x: easting'); ylabel('y: northing'); 
	[xl,yl] = ginput(2);
	ml = (xl(1)-xl(2))/(yl(1)-yl(2));
	bl = xl(1)-ml*yl(1);
	ll = ml*[1:ny] + bl;
	for il = 1:ny
		rpt = ceil(ll(il));
		if( rpt > 1)
			for ir = rpt:-1:1
				clear vals;
				it = max(1,il-1);  ib = min(ny,il+1);
				vals = imout(it:ib,ir+2:ir+5);
				imout(il,ir) = median(median(vals));
			end
		end
	end
	disp('Here is your result');

	clf; imagesc(imout);
	title('Left bad zone muted - Now pick right boundary');
	xlabel('x: easting'); ylabel('y: northing'); 
	disp('Now pick right boundary in the same fashion. '); 
	[xr,yr] = ginput(2);
	mr = (xr(1)-xr(2))/(yr(1)-yr(2));
	br = xr(1)-mr*yr(1);
	lr = mr*[1:ny] + br;
	for ir = 1:ny
		lpt = min(nx,floor(lr(ir)));
		if( lpt < nx)
			for il = lpt:nx
				clear vals;
				it = max(1,ir-1);  ib = min(ny,ir+1);
				vals = imout(it:ib,il-5:il-2);
				imout(ir,il) = median(median(vals));
			end
		end
	end
	disp('Here is your result');
	imagesc(imout);
	title('Right bad zone muted');
	xlabel('x: easting'); ylabel('y: northing'); 
end

tie = input('Do you want to quick clean top edge? (1=yes, 0=no)  ');
if( tie == 1)
	imout(2,:)    = (imout(3,:) + imout(4,:))/2;	
	imout(1,:)    = (imout(2,:) + imout(3,:))/2;	
	imout(ny-1,:) = (imout(ny-2,:) + imout(ny-3,:))/2;	
	imout(ny,:)   = (imout(ny-1,:) + imout(ny-2,:))/2;	
end

clf
imagesc(imout);

imwrite(uint8(rot90(imout,-1)),sprintf('/morgan/topo/tif/%s.tif',fname),'tif');

diarystr = sprintf('%s/%s.info',fname,fname);
delete(diarystr);
diary(diarystr)
	disp([nx;ny]);
diary off
