function ConvertFasta2Phylip( FastaDir,PhylipDir,RemoveStopCodon,SelectedSeq )
% example:
% FastaDir = '/home/lowie/Software/Mega5/HIVData/ExtendedHIVFull_NaiveNT_SubtypeB.fasta';
% PhylipDir = '/home/lowie/Software/Mega5/HIVData/ExtendedHIVFull_NaiveNT_SubtypeB.phy';

% if RemoveStopCodon ==1, remove the stop codon; otherwise, keep them.
% written by Guangdi Li (lowieli@gmail.com)

[ OrigSeq,~,TitleID ] = ExtractSequenceOut( FastaDir );
fid = fopen(PhylipDir,'w');

[ Row,Col ] = size( OrigSeq );
if nargin == 2
   RemoveStopCodon = 0;
   SelectedSeq = 1:Row;
elseif nargin == 3
   SelectedSeq = 1:Row;
end
fprintf(fid,'  %d   %d\n',length(SelectedSeq),Col);

RowSet = cell( 1,length( SelectedSeq ) );

if RemoveStopCodon
   StopCodonSet ={ 'TAA' 'TAG' 'TGA'};   
   parfor p = 1:length( SelectedSeq )
       Line = OrigSeq( SelectedSeq(p),:);
       for n = 1:3
           Loc1 = findstr( Line,StopCodonSet{n} );
           for q = 1:length(Loc1)
               if mod( Loc1(q),3 ) == 1
                 Line(Loc1(q):Loc1(q)+2) = '---';
               end
           end
       end
       Last = find(Line~='-',1,'last');
       if mod(Last,3)~= 0 % if the sequence cannot be aligned with 3*3
           Line = Line( 1:Last-mod(Last,3) );
       end
       RowSet{ p } = Line;
   end
else
   parfor p = 1:length( SelectedSeq )
       RowSet{ p } = OrigSeq( SelectedSeq(p),:);
   end
end

LineNum = 10000000%45;
for p = 1:length( SelectedSeq )
    fprintf( fid,'%s\n',TitleID{ SelectedSeq(p) } );
    Line = RowSet{p};
    Len = length(Line);
    while Len > 0
      if Len >= LineNum
         fprintf( fid,'%s\n',Line(1:LineNum) );
         Line = Line(LineNum+1:Len);
         Len = Len -LineNum;
      else
         fprintf( fid,'%s\n',Line );
         Len = 0;
      end
    end
end

end
