function numFilesWritten = par2prt(NameExp,TR,Con,Color,framesPerBlock);
% par2prt:
% 	converts .par file(fsfast format) to .prt file(BrainVoyager format)
%
% 	Usage: numFilesWritten = par2prt(NameOfExperiment,[TR],[Con],[Color],[framesPerBlock]);
%
% 	Entering 'all' as the name of experiment will cause all files
% 	in the current directory ending in .par to be converted.
% 	
%   TR: specify TR (default is 1)
%
%   'Con' is a cell-of-strings, in which the names of each condition
%   are specified in order of the number value specified
% 	starting with lowest-valued condition (usually 0, null)
%
%   'Color': cell-of-1X3 arrays containing RGB values for colors
%   for each condition to be used in BV
%
%   framesPerBlock: optional input for block designs where every block
%   is the same length in TRs; this is equivalent to doing a client
%   file -> prt conversion. Default = 1: treat each TR separately
%
% Leave any parameter empty (...,[],...) to use the default value.
%
% 8/02 by SK; 
% 08/24/02 (ras): Modified assignment of conditions so that 
% the first condition in Con is mapped to the lowest value used 
% in the .par file, the next condition is mapped to the next lowest
% value, etc.
% 11/08/02 (ras): Modified to better work with block design, with
% 'framesPerBlock' parameter added.

if ~exist('NameExp','var') | isempty(NameExp)
	NameExp = input('Name of the Experiment?','s');
end

%%%%%%% PARAMETERS %%%%%%%%%%%%%%
%% Define your contrast and color here
%% specify condition names in 'Con', in 
%% order of the number value specified
%% starting with lowest-valued condition (usually 0, null)
% define colors (RGB triplets) for different conditions for
% use in BrainVoyager:
if ~exist('Con','var') | isempty(Con)
	Con = {'Null/Fixation','Condition1','Condition2','Condition3','Condition4'...
            ,'Condition5','Condition6','Condition7','Condition8','Condition9'...
            ,'Condition10','Condition11','Condition12'}; 
end

if ~exist('Color','var')| isempty(Color)
    Color = {[195 195 195],[255 0 0],[0 0 255],[0 255 0],[160 0 0], [0 0 160]...
            ,[0 160 0],[80 0 0],[0 0 80],[0 80 0],[0 255 255],[0 160 160], [0 80 80]};
end
if ~exist('TR','var') | isempty(TR)
    TR = 1;
end
if ~exist('framesPerBlock','var')
    framesPerBlock = 1;
end
%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%	

numFilesWritten = 0;
if strcmp(NameExp,'all')==1
	%% convert all par-files in current directory
	fileList = filterdir('.par');
	for file = 1:length(fileList)
		periods = findstr(fileList(file).name,'.');
		currFile = fileList(file).name(1:periods(1)-1);
		% ignore first entry in directory ('..', or parent directory)
		if length(currFile)>=1
			par2prt(currFile,TR,Con,Color,framesPerBlock);
		end
	end
	numFilesWritten = file;
	fprintf('Wrote %i .prt files successfully. \n',numFilesWritten);
else

	NamePar = [NameExp,'.par'];
	NamePrt = [NameExp,'.prt'];
	
	%% Open files to read and write
	fid_par = fopen(NamePar,'r');
	fid_prt = fopen(NamePrt,'w');
	if (fid_par==-1) 
		error('ERROR: Couldn''t find specified .par file.')
	end
	
	%% Read par files info
	%M = load('fid_par', 'ascii'); % somehow 'load' only works for .mat in Macs
	%Time = M(:,1);
	%ConNum = M(:,2);
	
	ConOrder = [];
	TimeOrder = [];
    FrameOrder = [];
	while ~feof(fid_par),
		line = fgetl(fid_par);
	    if isempty(line), break, end
		if ~isstr(line), break, end
		[Time, ConNum] = strtok(line);
		TimeOrder = [TimeOrder str2num(Time)];
        FrameOrder = [FrameOrder floor(str2num(Time)/TR)];
		ConOrder = [ConOrder str2num(ConNum)];
	end
    % correct for block size
    FrameOrder = [FrameOrder(1:framesPerBlock:end) FrameOrder(end)];
    ConOrder = [ConOrder(1:framesPerBlock:end) ConOrder(end)];
    
    valsInParFile = unique(ConOrder);    
	fclose(fid_par);
	
	% Fill in the header
	fprintf(fid_prt, '\nFileVersion:\t\t2\n');
	fprintf(fid_prt, '\nResolutionOfTime:\tVolumes\n');
	fprintf(fid_prt, '\nExperiment:\t\t\t%s\n',NameExp);
	fprintf(fid_prt, '\nBackgroundColor:\t0 0 0\n');
	fprintf(fid_prt, 'TextColor:\t\t\t255 255 255\n');
	fprintf(fid_prt, '\nTimeCourseColor:\t255 255 255\n');
	fprintf(fid_prt, 'TimeCourseThick:\t3\n');
	fprintf(fid_prt, 'ReferenceFuncColor:\t0 0 80\n');
	fprintf(fid_prt, 'ReferenceFuncThick:\t3\n');
	fprintf(fid_prt, '\nNrOfconditions: \t%d\n',length(valsInParFile));
	
	% Start writing the real condition orders		
    valsInParFile = unique(ConOrder);
	for i = 1:length(valsInParFile)
		% map each specified condition in Con 
		% to one of the values used in the .par file,
		% in increasing order (i.e., start with first 
		% condition = 0 if 0 is used, 1 if 0 isn't used, etc.)
		currVal = valsInParFile(i);
		temp = find(ConOrder == currVal);
        
        % ignore trial onset if it was assigned
        % at the last line of the .prt file (end of run):
        if temp(end)==length(FrameOrder)
            temp = temp(1:end-1);
		end
		fprintf(fid_prt, '\n%s \n',Con{i});
		fprintf(fid_prt, '%d \n',length(temp));
		
		for j = 1:length(temp),			
            startFrame = FrameOrder(temp(j));
            endFrame = FrameOrder(temp(j)+1) - 1;
  			fprintf(fid_prt, '\t %d %d \n',startFrame,endFrame);
        end
		fprintf(fid_prt, 'Color: %d %d %d\n',Color{i});
	end
	fclose('all');
	numFilesWritten = 1;
end

return

