function [Q rect] = m4sync()
d = imread('face.png');
d = double(rgb2gray(d));
d = d/max(d(:));
d = abs(1-d); d = flipud(d);
d = resizem(d,0.7);
d = d(1:end-1,:);
d = padarray(d, [170 130]);

ang = 0;
t = 1:150;
sg = 1; dsg = 0.23;
for ii = 1:length(t);
    dn = phasespacetrans(d,[1.5 -1; 0 1/1.5],ang);
    f1 = figure(1); set(f1, 'Color', [1 1 1]);
    imagesc(dn); colormap(gray); truesize;
    axis xy; caxis([-1 0.6]); colormap(graywhitered(256));
    %title(sprintf('t = %g, sg = %.2f', t(ii),sg));
    hold on;
    plot(1:size(dn,2), sum(dn,1)*1.3,'k','LineWidth', 2);
    plot([1 size(dn,2)], [0 0], 'k'); axis off;
    hold off;
    drawnow;
    
    rect = get(f1, 'Position');
    rect(1:2) = [1 1];
    rect = [50 50 rect(3)-100 rect(4)-60];
    Q(:,ii) = getframe(f1, rect);

    ang = t(ii)*5;
    if sg > 18 && dsg > 0
        dsg = -dsg;
    end
    sg = sg + dsg;
    if sg < 1
        sg = 1;
    end
    t(ii)
    h = fspecial('gaussian', (2*ceil(sg)+1)*[1 1], sg);
    d = imfilter(d,h);

end

end

function out = phasespacetrans(in, m, ang)

in = imrotate(in,ang,'bilinear','crop');

f = @(x,unused) [m(1,1)*x(:,1)+m(1,2)*x(:,2), m(2,1)*x(:,1)+m(2,2)*x(:,2)];
% maketform arguments
ndims_in = 2;
ndims_out = 2;
forward_mapping = [];
inverse_mapping = f;
tdata = [];
tform = maketform('custom', ndims_in, ndims_out, ...
    forward_mapping, inverse_mapping, tdata);
out = imtransform(in, tform, 'UData', [-1 1], 'VData', [-1 1], ...
    'XData', [-1 1], 'YData', [-1 1]);

end