function [Gates,FNames]=FindGate(filenameORdata, varargin)
% function [Gates,FNames]=FindGate(filenameORdata, varargin)
% SUMMARY:
%
% This function takes a filename (or part of name) of a .fcs file (or several files) OR the data from the .fcs
% file (see below), lets the user select a gate from a plot of the
% side-scatter vs the forward scatter and returns the indices of the data
% points in the fcs data that are within this gate.
%
% INPUTS:
%   filenameORdata: This is either the name of a single .fcs file to open, a
%   string that when used with dir will return several .fcs files (ie
%   '*177*'), or the actual fcs FACS data (ie fcsdat from the call to
%   [fcsdat, fcshdr] = fca_readfcs(filename))
%  
%   varargin:
%   varargin{1}: 0 if output is to be suppressed (default), 1 if output
%   (ie, plot of the gate and the stuff in the gate) IS to be plotted
%   varargin{2}: name for the title of the plot when data is sent in rather
%   than a filename
%   
%
% OUTPUTS:
%   Gate: A cell array, each entry is the indices of the points that fall within the user-defined
%   polygon for a given .fcs file.  In later functions, in order to just use these points you
%   would do the following: (Say you just wanted the GFP data for these points, and GFP is
%   the third column of fcsdat from the call [fcsdat, fcshdr] = fca_readfcs(filename))
%   use fcsdat(Gates{i},3) where you want the gates for the ith file.
%
%   FNames: A cell array with the names of the files that the gates belong
%   to (for data, assume user gave the appropriate filename), so Gates{i}
%   is the gate information for .fcs file FNames{i}
%   
%    
% REQUIRES:
%   fca_readfcs
%
% REFERENCES:
% Mathworks documentation on inpolygon:
%    http://www.mathworks.com/help/techdoc/ref/inpolygon.html
%
%    Written by Megan McClean, Ph.D.
%               Lewis-Sigler Institute for Integrative Genomics
%               Princeton University
%               120 Carl Icahn
%               Princeton, NJ 08544
%               mmcclean@princeton.edu
%
%    Last revised on February 22, 2012





%%
numarg=length(varargin);
Gates={};

%%
%Read in the data from the .fcs file using fca_readfcs or get the list of
%files represented by the substring filenameORdata
if ischar(filenameORdata)
    files=dir(filenameORdata);
    %If the user entered a filename, open that file and use it as the data
    for j=1:length(files)
        [fcsdat, fcshdr] = fca_readfcs(files(j).name);
        figure; hold;
        plot(fcsdat(:,1), fcsdat(:,2), '.')
        xlabel('FSC-A'); ylabel('SSA-A'); title(fcshdr.filename);


        %Get user input for the vertices of polygon surrounding the region of
        %interest
        [x,y]=ginput();

        %set up the polygon surrounding the points you want:
        x=[x; x(1)];
        y=[y; y(1)];
        InGate=inpolygon(fcsdat(:,1), fcsdat(:,2), x,y);
        Gates{j}=InGate;


        %display what points are in the polygon
        if numarg>0
            if varargin{1}==1
                plot(fcsdat(InGate,1), fcsdat(InGate,2),'ro')
                legend('All Points', 'Points within user-defined gate');
                pause; close all;
            else
                close all;
            end
        else
            close all;
        end
        FNames{j}=files(j).name;
    end
else
    %If the user just sent in a variable, then use the data in that
    %variable
    fcsdat=filenameORdata;
    numarg=length(varargin);
    if numarg<2
        fcshdr.filename='Unlabelled Data--Need to Edit Title';
    else
        fcshdr.filename=varargin(2);
    end
      FNames{1}=fcshdr.filename;
    %We are going to assume that the data in fcsdat is formatted so that forward scatter
    %(FSC-A) is the first column and side scatter (SSA-A) is in the second
    %column

    figure; hold;
    plot(fcsdat(:,1), fcsdat(:,2), '.')
    xlabel('FSC-A'); ylabel('SSA-A'); title(fcshdr.filename);


    %Get user input for the vertices of polygon surrounding the region of
    %interest
    [x,y]=ginput();


    %set up the polygon surrounding the points you want:
    x=[x; x(1)];
    y=[y; y(1)];
    InGate=inpolygon(fcsdat(:,1), fcsdat(:,2), x,y);
    Gates{1}=InGate;


    %display what points are in the polygon
    if numarg>0
        if varargin{1}==1
            plot(fcsdat(InGate,1), fcsdat(InGate,2),'ro');
            pause;
            legend('All Points', 'Points within user-defined gate');
            close all;
        else
            close all;
        end
    else
        close all;
    end
  
end
close all;


