clear;
disp('splice.m: Splice two 7.5 minute sections together - up and down.')
disp('          Type the quad names when prompted.')
fname1 = input('Name of N topo quad? ','s')
fname2 = input('Name of S topo quad? ','s')

im1 = imread(sprintf('/morgan/topo/tif/%s.tif',fname1),'tif');
im2 = imread(sprintf('/morgan/topo/tif/%s.tif',fname2),'tif');

loadstr = sprintf('/home/kana/morgan/topo/elev/%s.elev',fname1); 
elev = dlmread(loadstr,' '); 
x1coord = elev(2,:);   y1coord = elev(1,:);
min1 = elev(3,1);  max1 = elev(3,2);

loadstr = sprintf('/home/kana/morgan/topo/elev/%s.elev',fname2); 
elev = dlmread(loadstr,' '); 
x2coord = elev(2,:);   y2coord = elev(1,:);
min2 = elev(3,1);  max2 = elev(3,2);

minelev = min(min1,min2);  maxelev = max(max1,max2);

imout1 = double(rot90(im1));  [nx1,ny1] = size(imout1);
imout2 = double(rot90(im2));  [nx2,ny2] = size(imout2);

% Normalize, scale by (min-max)
imout1 = (imout1/255)*(max1-min1) + min1;
imout2 = (imout2/255)*(max2-min2) + min2;

clf;
subplot(2,1,1); imagesc(imout1)
subplot(2,1,2); imagesc(imout2)

%disp('Hit any key to continue'); pause

nx = nx1+nx2;  ny = max(ny1,ny2);

imout = zeros(nx,ny);
imout(1:nx1,    1:ny1) = imout1;
imout(nx1+1:nx, 1:ny2) = imout2;

isub = input('Subsample by factor of: ');
imout = imout(1:isub:nx,1:isub:ny);

% clip spurious value to min or max.
[ii,jj] = find(imout<minelev);
if( ~isempty(ii) )  
	imout(ii,jj) = minelev;
end

[ii,jj] = find(imout>maxelev);
if( ~isempty(ii) )  
	imout(ii,jj) = maxelev;
end

clf;
imagesc(imout)
colorbar
xlabel('x: easting'); ylabel('y: northing'); 
title('Your result');

imout = 255*( (imout-minelev)/(maxelev-minelev) );

imout = rot90(imout,-1);

fname = input('Desired output name: ','s')
imwrite(uint8(imout),sprintf('/morgan/topo/tif/%s.tif',fname),'tif');

%imout = reshape(imout, nx*ny,1);
%eval( sprintf('save /morgan/topo/mfiles/%s.m imout -ascii',fname) );

elevfilestr = sprintf('/home/kana/morgan/topo/elev/%s.elev',fname); 
delete(elevfilestr);

x10 = 0.5*(x1coord(3)+x1coord(4));  x11 = 0.5*(x1coord(1)+x1coord(1));
y10 = 0.5*(y1coord(1)+y1coord(3));  y11 = 0.5*(y1coord(2)+y1coord(4));
x20 = 0.5*(x2coord(3)+x2coord(4));  x21 = 0.5*(x2coord(1)+x2coord(1));
y20 = 0.5*(y2coord(1)+y2coord(3));  y21 = 0.5*(y2coord(2)+y2coord(4));

x0 = x20;            x1 = x11;
y0 = 0.5*(y10+y20);  y1 = 0.5*(y11+y21);

ystr = sprintf('%d %d %d %d',y0,y1,y0,y1);
xstr = sprintf('%d %d %d %d',x1,x1,x0,x0);
elevstr = sprintf('%d %d',minelev,maxelev);
diary(elevfilestr)
	disp(ystr);
	disp(xstr);
	disp(elevstr);
diary off

diarystr = sprintf('mosaic/%s.info',fname);
delete(diarystr);
blah = size(imout);
diary(diarystr)
	disp([blah(1);blah(2)]);
diary off

