function timeseries(varargin)
% FORMAT timeseries
% 
% Timeseries analysis - interactive graphical facility for exploring
% global and peristimulus intensity and % signal timecourse at 
% chosen points or regions in the brain.
% ----------------------------------------------------------------------
%
% -----------------------
% Initialize
% -----------------------

clear all;

imgfig = [];
pfig = [];
%intfig = [];

% ------------------------
% Default values
% ------------------------
WS = spm('WinScale');


% ------------------------
% Collect files
% ------------------------

%if nargin == 0
    %cfg = spm_get(1, '*SPMcfg.mat', 'Select cfg.mat file');
% else

if nargin == 0
    cfg = spm_get(1, '*SPM.mat', 'Select SPM.mat (SPM2) file');
else
    
    cfg = varargin{1};
end

if nargin < 2
    bg_img = spm_get(1,'.img', 'Choose background anatomical image:');
else
    bg_img = varargin{2};
end

load(cfg);
% load config gives us Sess, VY, xX

[Cond, Vf, RT] = kc_get_design('Load',cfg);
%nsess = length(Sess);
%nscans = length(VY);

nscans = length(SPM.xY.VY);
bg_vol = spm_vol(bg_img);
cache.v = cell(bg_vol.dim(1:3));
cache.r = [];

% ------------------------
% Compute global values
%--------------------------

g = Vf.G;

%g      = zeros(nscans,1);

%fprintf('%-4s: %3s','Calculating globals...',' ')
        
%for i  = 1:nscans
%	g(i) = spm_global(VY(i));
%end
%fprintf('%s%3s\n','...done')

g_z = abs(zscore(g));

fprintf('\nMapping default values... :');

vinv_data = inv(SPM.xY.VY(1).mat);  %matrix converting mm->voxels
def_pos = vinv_data(1:3,:)*[0; 0; 0; 1];
def_pos = round(def_pos);

def_int = [];
for i = 1:nscans
    def_int(i, 1) = spm_sample_vol(SPM.xY.VY(i), def_pos(1), def_pos(2), def_pos(3), 1);
end
cache.v{def_pos(1), def_pos(2), def_pos(3)} = def_int;
def_int_z = abs(zscore(def_int));

fprintf('   ...done\n');


            

% -------------------------
% Set up image and interactive figures
% -------------------------

imgfig = timeseries_image('init',bg_img);
defx_vox = round(str2num(get(findobj('Tag', 'postext_x_vox'), 'String')));
defy_vox = round(str2num(get(findobj('Tag', 'postext_y_vox'), 'String')));
defz_vox = round(str2num(get(findobj('Tag', 'postext_z_vox'), 'String')));
%def_int = [];
%for i = 1:nscans
%    def_int(i,1) = spm_sample_vol(VY(i), defx_vox, defy_vox, defz_vox, 1);
%end




%intfig = spm_input_ui('!GetWin');

% -----------------------
% Draw initial figure
% -----------------------


figure('Units', 'pixels', 'Position', [005 015 600 800].*WS, 'Tag', 'plotfig', ...
    'PaperPositionMode', 'auto', 'InvertHardcopy', 'off');
pfig = gcf;




%---------------------------------
% Intensity plot
%       - Checkboxes for global and z-score plots    
% --------------------------------
h = axes('Parent', pfig, 'Units', 'pixels', 'Position', [50 620 500 150].*WS, 'Tag', 'IntensityAxes', ...
    'UserData', VY);
%subplot(4,1,1);
%h = gca;
%set(h, 'Tag', 'Intensity Axes');
%set(h, 'XAxisLocation', 'top');

uicontrol(pfig, 'Style', 'frame', 'Position', [50 575 500 40].*WS, 'Tag', 'IntensityAxisControlFrame');
uicontrol(pfig, 'Style', 'checkbox', 'Position', [60 585 100 20].*WS, 'Max', 1, 'Min', 0, 'Value', 1, ...
    'String', 'Selection intensity', 'Tag', 'IntensityCheckBox', 'UserData', cache, ...
    'Callback', 'timeseries_plotcontrol(''intensitycheckpush'')');
uicontrol(pfig, 'Style', 'checkbox', 'Position', [170 585 100 20].*WS, 'Max', 1, 'Min', 0, 'Value', 0, ...
    'String', 'Global intensity', 'Tag', 'GlobalIntensityCheckBox', 'UserData', g, ...
    'Callback', 'timeseries_plotcontrol(''globalintensitycheckpush'')');
uicontrol(pfig, 'Style', 'checkbox', 'Position', [280 585 100 20].*WS, 'Max', 1, 'Min', 0, 'Value', 0, ...
    'String', 'Z-score', 'Tag', 'ZScoreCheckBox', ...
    'Callback', 'timeseries_plotcontrol(''zscorecheckpush'')');
uicontrol(pfig, 'Style', 'checkbox', 'Position', [390 585 100 20].*WS, 'Max', 1, 'Min', 0, 'Value', 0, ...
    'String', 'Global z-score', 'Tag', 'GlobalZScoreCheckBox', 'UserData', g_z, ...
    'Callback', 'timeseries_plotcontrol(''globalzscorecheckpush'')');

uicontrol(pfig, 'Style', 'frame', 'Position', [63 609 94 4].*WS, 'BackgroundColor', 'b', ...
    'Tag', 'IntensityLegend1');
uicontrol(pfig, 'Style', 'frame', 'Position', [173 609 94 4].*WS, 'BackgroundColor', 'm', ...
    'Tag', 'IntensityLegend2');
uicontrol(pfig, 'Style', 'frame', 'Position', [283 609 94 4].*WS, 'BackgroundColor', 'r', ...
    'Tag', 'IntensityLegend3');
uicontrol(pfig, 'Style', 'frame', 'Position', [393 609 94 4].*WS, 'BackgroundColor', 'k', ...
    'Tag', 'IntensityLegend4');


hold on
plot(def_int, 'b', 'Tag', 'IntensityPlot', 'Visible', 'on');
plot(g, 'm', 'Tag', 'GlobalIntensityPlot', 'Visible', 'off');
plot(def_int_z, 'r', 'Tag', 'ZScorePlot', 'Visible', 'off');
plot(g_z, 'k', 'Tag', 'GlobalZScorePlot', 'Visible', 'off');
set(h, 'XAxisLocation', 'top');
set(h, 'YGrid', 'on');
set(h, 'XGrid', 'on');

xlabel('scans');
ylabel('MR Intensity');


%---------------------------------
% Percent signal change plot
%       - Preprocessing checkboxes    
% --------------------------------
h = axes('Parent', pfig, 'Units', 'pixels', 'Position', [50 390 500 150].*WS, 'Tag', 'PercentAxes', ...
    'XAxisLocation', 'top', 'UserData', Vf.iS);
%subplot(4,1,2)
%h = gca;
%set(h, 'Tag', 'Percent Axes');
%set(h, 'XAxisLocation', 'top');


uicontrol(pfig, 'Style', 'frame', 'Position', [50 160 500 40].*WS, 'Tag', 'PercentControlFrame', ...
        'UserData', RT);
uicontrol(pfig, 'Style', 'text', 'Position', [60 170 70 20].*WS, 'String', 'Preprocessing: ');

uicontrol(pfig, 'Style', 'checkbox', 'Position', [140 170 70 20].*WS, 'Max', 1, 'Min', 0, 'Value', 1, ...
    'String', 'Detrend?', 'Tag', 'DetrendCheckBox', ...
    'Callback', 'timeseries_plotcontrol(''percentify'')');
uicontrol(pfig, 'Style', 'checkbox', 'Position', [220 170 50 20].*WS, 'Max', 1, 'Min', 0, 'Value', 1, ...
    'String', 'Trim?', 'Tag', 'TrimCheckBox', ...
    'Callback', 'timeseries_plotcontrol(''percentify'')');
uicontrol(pfig, 'Style', 'checkbox', 'Position', [280 170 90 20].*WS, 'Max', 1, 'Min', 0, 'Value', 0, ...
    'String', 'High-pass filter?', 'Tag', 'HPFilterCheckBox', ...
    'Callback', 'timeseries_plotcontrol(''highpasspush'')');
uicontrol(pfig, 'Style', 'edit', 'Position', [370 170 30 20].*WS, 'Max', 1, 'Min', 1, ...
    'Enable', 'off', 'String', num2str(xX.K{1}.HParam), 'Tag', 'HPFilterText', ...
    'Callback', 'timeseries_plotcontrol(''percentify'')');
uicontrol(pfig, 'Style', 'checkbox', 'Position', [410 170 90 20].*WS, 'Max', 1, 'Min', 0, 'Value', 0, ...
    'String', 'Low-pass filter?', 'Tag', 'LPFilterCheckBox', ...
    'Callback', 'timeseries_plotcontrol(''lowpasspush'')');
uicontrol(pfig, 'Style', 'edit', 'Position', [500 170 30 20].*WS, 'Max', 1, 'Min', 1, ...
    'Enable', 'off', 'String', num2str(xX.K{1}.LParam), 'Tag', 'LPFilterText', ...
    'Callback', 'timeseries_plotcontrol(''percentify'')');


timeseries_plotcontrol('percentify');

xlabel('scans');
ylabel('% Signal Change');



%---------------------------------
% Peristimulus plot
%       - Condition controls    
% --------------------------------
h = axes('Parent', pfig, 'Units', 'pixels', 'Position', [50 210 500 150].*WS, 'Tag', 'PeristimAxes', ...
    'XAxisLocation', 'top', 'UserData', Cond);
%subplot(4,1,3)
%h = gca;
%set(h, 'Tag', 'Peristim Axes');
%set(h, 'XAxisLocation', 'top');

cond_menu = vertcat({'<None>'}, Cond.name);  % man, I love that syntax.  That's pretty.
def_data = zeros(Cond(1).num_scans, 1);

uicontrol(pfig, 'Style', 'frame', 'Position', [50 115 500 40].*WS, 'Tag', 'PeristimControlFrame');
uicontrol(pfig, 'Style', 'text', 'Position', [60 125 70 20].*WS, 'String', 'Conditions: ');
uicontrol(pfig, 'Style', 'popupmenu', 'Position', [140 125 70 20].*WS, 'String', cond_menu, ...
    'Tag', 'ConditionPopup1', 'Callback', 'timeseries_plotcontrol(''popuppush'', 1)');
uicontrol(pfig, 'Style', 'popupmenu', 'Position', [220 125 70 20].*WS, 'String', cond_menu, ...
    'Tag', 'ConditionPopup2', 'Callback', 'timeseries_plotcontrol(''popuppush'', 2)');
uicontrol(pfig, 'Style', 'popupmenu', 'Position', [300 125 70 20].*WS, 'String', cond_menu, ...
    'Tag', 'ConditionPopup3', 'Callback', 'timeseries_plotcontrol(''popuppush'', 3)');
uicontrol(pfig, 'Style', 'popupmenu', 'Position', [380 125 70 20].*WS, 'String', cond_menu, ...
    'Tag', 'ConditionPopup4', 'Callback', 'timeseries_plotcontrol(''popuppush'', 4)');
uicontrol(pfig, 'Style', 'popupmenu', 'Position', [460 125 70 20].*WS, 'String', cond_menu, ...
    'Tag', 'ConditionPopup5', 'Callback', 'timeseries_plotcontrol(''popuppush'', 5)');

uicontrol(pfig, 'Style', 'frame', 'Position', [143 149 64 4].*WS, 'BackgroundColor', 'b', ...
    'Tag', 'ConditionLegend1');
uicontrol(pfig, 'Style', 'frame', 'Position', [223 149 64 4].*WS, 'BackgroundColor', 'm', ...
    'Tag', 'ConditionLegend2');
uicontrol(pfig, 'Style', 'frame', 'Position', [303 149 64 4].*WS, 'BackgroundColor', 'r', ...
    'Tag', 'ConditionLegend3');
uicontrol(pfig, 'Style', 'frame', 'Position', [383 149 64 4].*WS, 'BackgroundColor', 'k', ...
    'Tag', 'ConditionLegend4');
uicontrol(pfig, 'Style', 'frame', 'Position', [463 149 64 4].*WS, 'BackgroundColor', 'g', ...
    'Tag', 'ConditionLegend5');




hold on;
plot(def_data, 'b', 'Tag', 'ConditionPlot1', 'Visible', 'off');
plot(def_data, 'm', 'Tag', 'ConditionPlot2', 'Visible', 'off');
plot(def_data, 'r', 'Tag', 'ConditionPlot3', 'Visible', 'off');
plot(def_data, 'k', 'Tag', 'ConditionPlot4', 'Visible', 'off');
plot(def_data, 'g', 'Tag', 'ConditionPlot5', 'Visible', 'off');

set(h, 'XAxisLocation', 'top');
set(h, 'YGrid', 'on');
set(h, 'XGrid', 'on');
xlabel('poststimulus scans');
ylabel('% Signal Change');



%%%%%%%%%%%%%%%%%%%%%%%
% Set up frame containing output controls,etc.
%%%%%%%%%%%%%%%%%%%%%%%

savetime_menu = {'Intensity'; '% Signal'; 'Conditions'};
savefig_menu = {'JPEG'; 'TIFF'; 'EPS'; 'PNG'};

uicontrol(pfig, 'Style', 'frame', 'Position', [50 10 500 80].*WS, 'Tag', 'OutputControlFrame');
uicontrol(pfig, 'Style', 'text', 'Position', [60 60 120 20].*WS, 'String', 'Output Directory:');
uicontrol(pfig, 'Style', 'text', 'Position', [60 40 120 20].*WS, 'Tag', 'OutputDirText', ...
    'String', spm_str_manip(pwd, 'a25'), 'UserData', pwd);
uicontrol(pfig, 'Style', 'pushbutton', 'Position', [75 20 90 20].*WS, 'String', 'Change Directory', ...
    'Callback', 'timeseries_plotcontrol(''changedirpush'')');

uicontrol(pfig, 'Style', 'frame', 'Position', [200 15 170 70].*WS);
uicontrol(pfig, 'Style', 'text', 'Position', [205 62 90 20].*WS, 'String', 'Save Timecourse:');
uicontrol(pfig, 'Style', 'popupmenu', 'Position', [295 62 70 20].*WS, 'String', savetime_menu, ...
    'Tag', 'SaveTimePopup');
uicontrol(pfig, 'Style', 'text', 'Position', [205 40 50 20].*WS, 'String', 'Name:');
uicontrol(pfig, 'Style', 'edit', 'Position', [255 40 110 20].*WS, 'Tag', 'SaveTimeText');
uicontrol(pfig, 'Style', 'checkbox', 'Position', [205 18 40 20].*WS, 'Max', 1, 'Min', 0, 'Value', 1, ...
    'String', '.txt', 'Tag', 'SaveCheckText', 'Callback', 'timeseries_plotcontrol(''savecheckpush_text'')');
uicontrol(pfig, 'Style', 'checkbox', 'Position', [245 18 40 20].*WS, 'Max', 1, 'Min', 0, 'Value', 0, ...
    'String', '.mat', 'Tag', 'SaveCheckMat', 'Callback', 'timeseries_plotcontrol(''savecheckpush_mat'')');
uicontrol(pfig, 'Style', 'pushbutton', 'Position', [305 18 60 20].*WS, 'String', 'Save', ...
    'Callback', 'timeseries_plotcontrol(''savetimepush'')', 'FontWeight', 'bold');

uicontrol(pfig, 'Style', 'frame', 'Position', [375 15 170 70].*WS);
uicontrol(pfig, 'Style', 'text', 'Position', [380 62 90 20].*WS, 'String', 'Save Figure:');
uicontrol(pfig, 'Style', 'popupmenu', 'Position', [470 62 70 20].*WS, 'String', savefig_menu, ...
    'Tag', 'SaveFigPopup');
uicontrol(pfig, 'Style', 'text', 'Position', [380 40 50 20].*WS, 'String', 'Filename:');
uicontrol(pfig, 'Style', 'edit', 'Position', [430 40 110 20].*WS, 'Tag', 'SaveFigText');
uicontrol(pfig, 'Style', 'pushbutton', 'Position', [480 18 60 20].*WS, 'String', 'Save', ...
    'Callback', 'timeseries_plotcontrol(''savefigpush'')', 'FontWeight', 'bold');

uicontrol(pfig, 'Style', 'text', 'Position', [175 95 250 20].*WS, 'String', 'File saved!: ', ...
    'Tag', 'FileSavedText', 'Visible', 'off');
uicontrol(pfig, 'Style', 'text', 'Position', [175 95 250 20].*WS, 'String', 'Figure saved!: ', ...
    'Tag', 'FigSavedText', 'Visible', 'off');


