function outputNAME = nic_Tmap2pmap(imageIN,imageOUT,direction)
% Transform from t map or f map to p map.
%
% Usage: outputNAME = nic_Tmap2pmap(imageIN,imageOUT)
% 
% Input:
% 1. imageIN   - full file path and name for the t-test or F-test image to transform 
%                 [path\*.img or .nii]
% 2. imageOUT  - full file path and name for transformed p map, [path\*.img or .nii]
% 3. direction - (1 or -1) if the imageIN is a t-test file, which direction,
%                positive or negative, do you want to do contrast? 1 is
%                default.
% 
% NOTE: The transformed P value is the single side probability of T
%       distribution, that means, for each  voxel, Pvalue = P{ t > t0 },
%       where t0 is the t value in the specific voxel, positive or negative.
%       if direction ==1, 
%          transformed P = Pvalue = P{ t > t0 },
%       Otherwise ( direction == -1 ):
%          transformed P = P{ t < t0 } = P{ t > |t0| } = P{ t > -t0 } 
% 
% Output:
% 1. outputNAME - full file path and name of the resampled image for output
%                 [path\*.img]
%_______________________________________________________________________
% Copyright (C) 2007 Neuroimage Computing Group, State Key Laboratory of
% Cognitive Neuroscience and Learning
% 
% Yujin Zhang, zyjinjin@gmail.com
% @(#)nic_Tmap2pmap.m  ver 1.0, 07/11/30
% @(#)nic_Tmap2pmap.m  ver 1.1, 07/12/09

if ~exist('direction','var')
    direction = 1;
end

[stat,V] = nic_ReadNiftiImage(imageIN);
stat = stat*direction;

%  read degrees of freedom value (df)
TF = 'T';
T_start = strfind(V.descrip,'SPM{T_[')+length('SPM{T_[');
if isempty(T_start)
    T_start = strfind(V.descrip,'SPM{F_[')+length('SPM{F_['); 
    TF='F'; 
end
if isempty(T_start)
    TF=[]; df=[];
else
    T_end = strfind(V.descrip,']}')-1;
    df = str2num(V.descrip(T_start:T_end));    
end

pos = find(~isnan(stat));%  pos: the positions where the elements of stat are not NaN. 

pvalue = 1-tcdf(stat(pos), df);% Pvalue = P{ t > t0 }

% write out p map
stat(:) = 0;
stat(pos) = pvalue(pos);

V.descrip = 'SPM{P_[]}';
[flag] = nic_WriteNiftiImage(stat,V,imageOUT);
outputNAME = imageOUT;
return