function mimagesc(varargin)
% MIMAGESC Vector graphics replacement for the imagesc function
%
% Usage
%     mimagesc(X) 
%     mimagesc(X, 'Argument', value, ...)
%
% Input:
%     X            : Array (grey scale image) to be plotted (matrix)
%
% Optional arguments
%     EdgeColor    : Color of cell edges (default none)

% Parse options
GridInput = false;
if nargin>=3 && isvector(varargin{1}) && isvector(varargin{2})
    GridInput = true;
    XGrid = varargin{1};
    YGrid = varargin{2};
    % Convert pixel centers to grid
    XGrid = 1.5*XGrid(1)-0.5*XGrid(2)+[0 cumsum(gradient(XGrid))];
    YGrid = 1.5*YGrid(1)-0.5*YGrid(2)+[0 cumsum(gradient(YGrid))];
    
    X = varargin{3};
    opts = mgetopt(varargin(4:end));
else
    X = varargin{1};    
    opts = mgetopt(varargin(2:end));
end
    
EdgeColor = mgetopt(opts, 'EdgeColor', 'none');

% Create grid of pixels 
M = size(X,2)+1;
N = size(X,1)+1;
if ~GridInput
    XGrid = 0:(M-1);
    YGrid = 0:(N-1);
end
[xg, yg] = meshgrid(XGrid, YGrid);

% Vertices
v = [xg(:) yg(:)];

% Faces
f = [1:(N*(M-1)-1); 2:(N*(M-1)); (N+2):(N*M); (N+1):(N*M-1)]';
f(N:N:end,:) = [];

% Face colors
col = X(:);

% Remove nan-colored faces
f(isnan(col),:) = [];
col(isnan(col)) = [];

% Plot image
h = patch('Faces',f,'Vertices',v,'FaceVertexCData',col,'FaceColor','flat');
set(h, 'EdgeColor', EdgeColor);
   