function [t, anim] = twoImSFM2STL(im1, im2, show_figures)

%If no arguments are received, try to get input from an attached webcam
if nargin == 0
    show_figures = 1;
    vid = videoinput('winvideo');
    input('press enter to open video window', 's');
    preview(vid);
    input('press enter to take a picture', 's');
    im1 = getsnapshot(vid);
    input('press enter to take another picture', 's');
    im2 = getsnapshot(vid);
    
    close all;
    
    notRGB = ~(vid.ReturnedColorSpace == 'rgb');
    
    if notRGB == 1
        %currently assumes camera feed is in YUY2 format if it's not RGB
        im1 = YUY2toRGB(im1);
        im2 = YUY2toRGB(im2);
    end
end

im1g = rgb2gray(im1);
im2g = rgb2gray(im2);

imwrite(im1g, 'im1tmp.pgm', 'pgm');
imwrite(im2g, 'im2tmp.pgm', 'pgm');

im1_str = 'im1tmp.pgm';
im2_str = 'im2tmp.pgm';

% calculate feature correspondences
[match im1 im2] = sift_match(im1_str, im2_str);

%Show unrefined point correspondences
im3 = appendimages(im1,im2);
figure(1);
clf;
colormap('gray');
imagesc(im3);
hold on;
cols1 = size(im1,2);
for i = 1: size(match,1)
    line([match(i,1) match(i,3)+cols1],[match(i,2) match(i,4)], 'Color', 'c');
end
hold off;
num = sum(match > 0);
fprintf('Found %d matches.\n', num);


minSize = 16;

%if enough feature points have been found, try to calculate outliers using
%MAPSAC from Philip Torr's SaM toolkit
if size(match,1) > minSize
    
    
    f_optim_parameters = [500, 6.0];
    [~,~, ~,inlier_index] = torr_estimateF(match, 256, f_optim_parameters, 'mapsac');
    
    inlier_matches = match(inlier_index,:);
    
    %Show the new, refined matches
    figure(2);
    clf;
    colormap('gray');
    imagesc(im3);
    hold on;
    cols1 = size(im1,2);
    for i = 1: size(inlier_matches,1)
        line([inlier_matches(i,1) inlier_matches(i,3)+cols1],...
            [inlier_matches(i,2) inlier_matches(i,4)], 'Color', 'c');
    end
    hold off;
    
else
    disp('Your images had too few correspondences to mapsac. trying sfm anyway (may not work)');
    inlier_matches = match;
end

%Package the correspondences as separate frames for the SfM toolbox
W(1,:,1) = inlier_matches(:,1)';
W(2,:,1) = inlier_matches(:,3)';
W(1,:,2) = inlier_matches(:,2)';
W(2,:,2) = inlier_matches(:,4)';

%Compute the 3D point positions and camera locations using Vincent Rabaud's
%SfM toolkit.
anim = computeSMFromW(false, W);
figure(3);
playAnim(anim);

%Mesh the surface using MyCrust Robust
figure(4);
[t] = surfFromS(anim.S);

%Export the STL file
STL_Export(anim.S', t, 'output.stl', 'solid');
