function [wMat, eegData, cMat, tInfo] = eegFwdModelCondOutWgtOnly(outMat, Elc, ev, outLier)
%
% A routine for forward encoding/decoding model analysis
%
% outMat: output of prepareEEGfwdModel.m function
% Elc: electrodes indices
% 
% 03/01/2017 Joonyeol Lee
% joonyeol@skku.edu
%
% 06/09/2018 Revisit the eegFwdModel leave one condition outMat
% reedit the file based on the eegFwdModel_ver1.m function
%
% 07/11/2018 Joonyeol Lee
% Extract weight only for one condition out fitting
%
% 10/24/2018 Joonyeol Lee
% Select trials based on ev and outlier criterion
%

rng('shuffle', 'twister');

timeTick = outMat.eegTimeTick;
tDur = length(timeTick);
NoT = length(outMat.rIdx);
eegTmp = outMat.binEEG;
cTmp = outMat.fwdModel;
stimTmp = outMat.stim;
modesTmp = outMat.behavior;
beSpdTmp = outMat.behavSpd;
beDirTmp = outMat.behavDir;
fitQualTmp = outMat.fitQual;

accSpdTmp = outMat.accelSpd;
accDirTmp = outMat.accelDir;

randIdx = transpose(randperm(NoT));

eegData = eegTmp(:, :, randIdx);
cMat = cTmp(:, randIdx);
stimInfo = stimTmp(randIdx,:);
modes = modesTmp(randIdx,:);
beSpd = beSpdTmp(randIdx,:);
beDir = beDirTmp(randIdx,:);
accSpd = accSpdTmp(randIdx,:);
accDir = accDirTmp(randIdx,:);
fitQual = fitQualTmp(randIdx);

oIdx = find(fitQual < ev);

eegData(:, :, oIdx) = [];
cMat(:, oIdx) = [];
stimInfo(oIdx,:) = [];
modes(oIdx,:) = [];
beSpd(oIdx,:) = [];
beDir(oIdx,:) = [];
accSpd(oIdx,:) = [];
accDir(oIdx,:) = [];
fitQual(oIdx) = [];

dirCond = sort(unique(stimInfo(:,3)));
numCond = length(dirCond);
wMat = cell(tDur, numCond);

for c = 1:numCond
	currCondDir = dirCond(c);
	select = find(stimInfo(:,3) == currCondDir);
		
	if exist('outLier') & outLier == 1
		cr = 2.576;

		tMode = modes(select, 3);
		dMode = modes(select, 2);
		sMode = modes(select, 1);
		
		oLiers = find(tMode > mean(tMode)+cr*std(tMode) | tMode < mean(tMode)-cr*std(tMode) | dMode > mean(dMode)+cr*std(dMode) | dMode < mean(dMode)-cr*std(dMode) | sMode > mean(sMode)+cr*std(sMode) | sMode < mean(sMode)-cr*std(sMode));
		
		eegData(:, :, select(oLiers)) = [];
		cMat(:, select(oLiers)) = [];
		stimInfo(select(oLiers),:) = [];
		modes(select(oLiers),:) = [];
		beSpd(select(oLiers),:) = [];
		beDir(select(oLiers),:) = [];
		accSpd(select(oLiers),:) = [];
		accDir(select(oLiers),:) = [];
		fitQual(select(oLiers)) = [];
	end
	
end

for dCond = 1:numCond
	select = find(stimInfo(:,3) == dirCond(dCond));
	trData = eegData;
	trData(:,:,select) = [];

	trC = cMat;
	trC(:,select) = [];

	for i = 1:tDur
		trainData = squeeze(trData(Elc, i, :));
		tmpCov = trC*transpose(trC);
		CCinv = pinv(tmpCov);
		B1 = trainData;
		W = B1*transpose(trC)*CCinv;
		wMat{i, dCond} = W;
	end
end

tInfo.stimInfo = stimInfo;
tInfo.timeTick = timeTick;
tInfo.cond = dirCond;