function measure_mm2pix
%This script will allow the user to prepare the "mm_pix.txt" file required 
%for the CobbleCam script.  The script will display all JPG images in a selected folder,
%then prompts the user to click on two points (on the tape) which are 100mm
%away from each other.  Once the user clicks on the photo there will be a
%short pause before the measuring tool becomes active.  Once the user is
%done clicking on the two points, the ENTER button must be pushed to
%continue.

%This version is written to be platform independent (will work with both
%"/" and "\" paths.

%                                       Joshua Logan, jlogan@usgs.gov
%                                       6/25/08

%Use the following var to set the amount of time (seconds) between first clicking on
%the photo and the pixel measuring tool becoming active
pausetime=1.5;

%Determine platform, adjust path dividers.
if ismac 
    slashdir = '/';
elseif ispc
    slashdir = '\';
end

%Get folder where photos to be measured reside.
phtdir = uigetdir();

%Get folder where output file will go.
[outfilename, outpathname] = uiputfile( ...
    {'*.txt', 'text files'}, ...
    'Save mm_pix.txt',[phtdir slashdir 'mm_pix.txt']);
outname=[outpathname outfilename];

%Get list of all photos using rdir (make sure that files are greater than
%100kb to filter out thumbnail files)
dirlist=dir(fullfile(phtdir,'*.JPG'));
notthumbsidx=find([dirlist.bytes]>100000);
phtlist=dirlist(notthumbsidx);

for i = 1:length(phtlist)
    rgb=imread([phtdir slashdir phtlist(i).name]);
    %turn off warnings
    warning off all
    himg=imshow(rgb);
    %turn on warnings
    warning on all
    %Turn on zoom tool (one less click)
    zoom on
    disp('------------------------------------------------------------------');
    disp(['Displaying image: ' phtlist(i).name]);
    disp([num2str(i) ' of ' num2str(length(phtlist))]);
    disp('Zoom in to measuring tape...');
    k=waitforbuttonpress;
    pause(pausetime);
    disp('Click on two points, 100 mm apart, then hit ENTER on the keyboard');
    [xi,yi,P]=impixel;
    disp('Calculating ....');
    [pixlength]=dist(xi(1),yi(1),xi(2),yi(2));
    mmperpix(i)=100/pixlength;
end

fid=fopen(outname,'w');
fprintf(fid,'%f\n',mmperpix);
fclose(fid);

close
disp('------------------------------------------------------------------');
disp(num2str(mmperpix'));
disp('------------------------------------------------------------------');
disp(['File written to: ' outname]); 

return



%--------------------------------------------------------------------------
function [d]=dist(x1,y1,x2,y2);
%DISTANCE calculates the distance between two coordinate pairs
%
%   USAGE:[distance]=distance(x1,y1,x2,y2)
%
d=sqrt(((x2-x1).*(x2-x1))+((y2-y1).*(y2-y1)));

%--------------------------------------------------------------------------





