%mMatchSeqLengths_PresetLength.m
%This program simply takes an existing Fasta sequence alignment and adds gaps to its end to make = to the preset length

clear
if ~isdeployed,clc,end;

PresetLength = 147;

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

% chdir ../AlignmentAnalysis/
mGetFasta
% chdir ../FASTA_alignments/

[FN FL]=size(Sequences);

if PresetLength-FL>0

    OutFilename      = strcat(pathname,FastaFilename,'_GapsAdded.fasta'); %pathname is created in 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:length(Sequences(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:PresetLength-length(Sequences(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
else fprintf('%s\n','The preset sequence length in the program is less or equal to the original sequence length, nothing was done')
end
