%mMatchSeqLengths.m
%This program simply takes an existing Fasta sequence alignment and 
%makes all its sequences equal in length by adding gaps (-) to the ends of the short ones

%clear  %clear by hand if you need to.
%clear FastaOrganismNames
%clear Sequences
%clc;


if ~exist('Audio'),Audio=0;end

% OrigDire=cd; %(OrigDire and not OrigDir because mGetFasta will interfere with this variable otherwise)
% chdir ..
mGetFasta
%chdir ../FASTA_alignments/
% cd(OrigDire)

fprintf('%s\n','please wait ...');
for s = 1:length(FastaOrganismNames)
    re1 = max(regexpi(Sequences(s,:), '[A-Z]')); %regexpi is case insensitive regular expression
    re2 = max(regexpi(Sequences(s,:), '[-]'));
    MaxSeqLen(s) = max([re1,re2]); %we're looking for the last letter or -
end

ind= findstr('.',FastaFilename);
OutFilename      = strcat(FastaPath,FastaFilename(1:ind-1),'_GapsAdded.fasta'); %FastaPath is created in mFastaFixerGUI or mGetFasta. It points to the original Fasta file to be fixed.
PrintArray = [];
fidOUT = fopen(OutFilename,'w+');
if fidOUT == -1      %Error check loop
    ErrorOUT = ['The file: ',OutFilename,' could not be written to. It may be open. Please close it and try again'];
else PrintArray = [PrintArray fidOUT];

    for P=1:length(PrintArray)
        for s = 1:length(FastaOrganismNames)
            clear BreakLine
            fprintf(PrintArray(P),'%s%s\n','>',FastaOrganismNames{s});
            for x=1:MaxSeqLen(s)
                if exist('BreakLine','var'),fprintf(PrintArray(P),'\n');end %From previous loop
                fprintf(PrintArray(P),'%s',Sequences(s,x));
                if (x/50)==fix(x/50),BreakLine=1;else clear BreakLine, end %Will create a LineBreak marker for the next loop, don't insert a linebreak immediately because maybe the sequence already ended!
            end
            for i=1:length(Sequences(s,:))-MaxSeqLen(s)
                fprintf(PrintArray(P),'%s','-');
            end
            fprintf(PrintArray(P),'\n');
        end
    end
    fclose(fidOUT);
end


if fidOUT == -1      %Error check loop
    ErrorOUT
    if Audio==1
        try
            [Ys,Fs] = wavread(['..',filesep,'Audio',filesep,'ohno']);
            sound(Ys,Fs); %wavplay(Ys,Fs,'async')
        end
    end
else
    fprintf('%s%s%s\n','The required number of gaps were added and the sequence alignment ',OutFilename,' was created');
    if Audio==1
        try
            [Ys,Fs] = wavread(['..',filesep,'Audio',filesep,'done1']);
            sound(Ys,Fs); %wavplay(Ys,Fs,'async')
        end
    end
end
