function [LOGM]=FACSTC_PlotHist(filenames, gates, col, Bins, varargin)
%%
%%%
% SUMMARY:
% This function takes a filename of a .fcs file OR the data from the .fcs
% file (see below), and uses the gate information (gates) to plot a
% histogram of the logarithm of the data in column col of the .fcs file
% using the bins Bins.
%
% INPUTS:
%   filenameORdata: This is either the name of a .fcs file to open, or the actual fcs FACS data 
%   (ie fcsdat from the call to  [fcsdat, fcshdr] = fca_readfcs(filename))
%   
%   gates: Gate information from FindGate (indices of points that should be
%   included in the analysis)
%
%   col: Column from the .fcs file that we want the histogram of (for our
%   FACS machine the first two columns are the forward and side scatter,
%   the last column is the Time information (when even was detected) and
%   the inner columns are the fluorescence data.  Order depends on how the
%   run was set-up
%
%   Bins: bins to use when making the histogram of the logarithm of the
%   data
%
%   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:
%   LOGM: Each row corresponds to the # of counts (for the bins defined by
%   Bins) for each file (if filenameORdata is such that we are going to
%   analyze multiple files)
%   
%    
% 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 3, 2012




%%
LOGM=[];
Names={};

%%
if ~iscell(filenames)
    files=dir(filenames);
else
    files=struct('name',[]);    
    for i=1:length(filenames)
        files(i).name=filenames{i};
    end
end 

%% 
%Calculate the appropriate log_10 of the fluorescence data, take a
%histogram with bins Bins, and store the counts in LOGM (each row
%corresponds to a different file)

for i=1:length(files)
  [fcsdat, fcshdr] = fca_readfcs(files(i).name);
  logx=log(fcsdat(gates{i},col));
  logx=real(logx);
  f=find(logx==-Inf);
  logx(f)=-1000;
  x=linspace(0,10,100);
  [n,x]=hist(logx,Bins);
  LOGM=[LOGM; n];
  Names{i}=files(i).name;
    
end
close all;

%%
%%Plot the histograms
h=figure; hold;
for j=1:length(gates)
    plot(Bins, LOGM(j,:),'LineWidth',2,'Color',[rand(1) rand(1)  rand(1)]);
end
legend(Names); xlabel('ln(Fluorescence)','FontSize',14); ylabel('Counts','FontSize',14)

%%
%Save figure
if size(varargin)>0
    saveas(h,varargin{1},'fig')
    saveas(h,varargin{1},'png')
end