function [stXtmesh_pat, stXtpat_sym, stXusym, stXtmesh, stXtmesh_ref, stXidx_X50, stXsymi_X50] = ...
    TIfilter(myconn, emesh, stage, orientation)

% Filter clearly unstained & ubiquitous ones
fprintf('Querying DB for images\n');
allStageX_idx = gmesh(myconn, emesh, '%', orientation, stage, 0);
fprintf('-> Found %d images\n', length(allStageX_idx));
X = emesh.stain(:,allStageX_idx)';
X = X - repmat(mean(X,2), 1, size(X,2));
Xnorm = sqrt(sum(X.^2,2));
stXidx_X50 = allStageX_idx(Xnorm>50);

% Query db and assign symbols
fprintf('Querying gene symbols\n');
for i=1:size(stXidx_X50,1), 
    stXtsym = pg_query(myconn,0, my_insitus('symbol'),emesh.files{stXidx_X50(i)}); 
    stXsym_X50{i} = stXtsym{1}; 
    fprintf('%d=%s\n', i, stXsym_X50{i}); 
end
stXusym = unique(stXsym_X50);
stXsymi_X50 = zeros(length(stXidx_X50),1);
for i=1:size(stXusym,2), 
    stXsymi_X50(strmatch(stXusym{i}, stXsym_X50)) = i; 
end

% Temporal filtering & sorting
fprintf('Temporal filtering and sorting\n');
j=1; stXtmesh=[]; stXtmesh_ref=[];
for i=1:max(stXsymi_X50),
    [tmesh_ref, tmesh, tmesh_sl] = temporal_meshsort(emesh, stXidx_X50(stXsymi_X50 == i)', 0);
    stXtmesh = [stXtmesh, tmesh];
    tmesh_max= length(tmesh_sl);
    stXtmesh_ref = [stXtmesh_ref; repmat(i, [tmesh_max,1]), tmesh_sl'];
    if size(stXtmesh, 2) ~= size(stXtmesh_ref, 1),
        fprintf('Size mismatch at %d: %d vs %d\n', i, size(stXtmesh, 2), size(stXtmesh_ref, 1));
        break;
    end
end
fprintf('-> Filtered to %d\n', length(stXtmesh_ref));

% Find the clearly patterned ones
fprintf('Filtering for clearly patterned ones\n');
stXtkmesh = zeros(311, size(stXtmesh, 2));
for i=1:size(stXtmesh, 2),
    fprintf('%d\n', i);
    stXtkmesh(:,i) =  meshdiscretize_emrf(emesh, stXtmesh(:,i), 'verbose', 0, 'single_mesh', 'kmeans');
end
%
stXtpat = zeros(size(stXtmesh, 2), 1);
for i=1:size(stXtmesh, 2),
    stXtpat(i) = abs(median(stXtmesh(stXtkmesh(:,i) == 1, i)) - median(stXtmesh(stXtkmesh(:,i) == 0.5, i))) > 30;
end
stXtmesh_pat = stXtmesh(:, stXtpat==1);
stXtpat_sym = stXtmesh_ref(stXtpat==1,1);
fprintf('-> filtered %d patterns\n', length(stXtpat_sym));
