%mGenerateBPListsFromPDB.m
%Generates all possible BP lists from a PDB file, by way of zGetNTData.
%function mGenerateBPListsFromPDB
warning off all

if ispc, sep='\'; else, sep='/';end

if ~exist('Audio','var'),Audio=0;end
if (~exist('pdbFILEpath','var'))||(exist('pdbFILEname','var')&&(~strcmp(class(pdbFILEname),'char')))
    if exist(['..',sep,'..',sep,'PDB_structures'],'dir')
        OrigDir=cd;
        ind= findstr(sep,OrigDir);  %Doesn't work on MAC
        pdbFILEpath=strcat(OrigDir(1:ind(length(ind)-1)),'PDB_structures',sep);
    elseif exist(['..',sep,'PDB_structures'],'dir')
        OrigDir=cd;
        ind= findstr(sep,OrigDir);  %Doesn't work on MAC
        pdbFILEpath=strcat(OrigDir(1:ind(length(ind))),'PDB_structures',sep);
    else pdbFILEpath=strcat(cd,sep);
    end
    %chdir ../PDB_structures/
elseif pdbFILEpath==0
    pdbFILEpath=strcat(cd,sep);
end

if ispc
    [pdbFILEname, pdbFILEpath] = uigetfile({...
    '*.pdb','*.pdb';...
    '*.pdbs','*.pdbs';...
    '*.*','*.* (all files)'},...
    'Pick a PDB file',pdbFILEpath);
else
    [pdbFILEname, pdbFILEpath] = uigetfile({...
    '*.pdb','*.pdb'},...
    'Pick a PDB file',pdbFILEpath);    
end


if strcmp(class(pdbFILEname),'char') %In case browser prompt was cancelled
    ind= findstr('.',pdbFILEname);
    pdbFILEname=pdbFILEname(1:ind-1); %remove .pdb or .pdbs, that's how zGetNTData likes it

    PDBOrganism = 'Haloarcula_marismortui'; %the default value

    %prompting for any change in the default values:
    prompt = {'Type the name of the organism represented by this PDB file exactly as it appears in your FASTA alignment (first unique combination of words is enough). NOTE: make sure this organism appears in your FASTA alignment with exactly the same sequence as your PDB file. Otherwise, manually adjust its FASTA sequence. (If you cancel now you can later type the organism name manually in the produced xls sheets)'};
    title = 'Determining the organism name represented by this PDB file';
    lines = 1;
    def = {PDBOrganism};%the default values set above
    % answer = inputdlg(prompt,title,lines,def);
    % assignin('base','PDBOrganism',answer{1});
    %     try
    PDBOrganism = inputdlg(prompt,title,lines,def); %This is needed not to contradict with the GUI
    PDBOrganism=str2mat(PDBOrganism); %this is to change it back from string to character
    if isempty(PDBOrganism)
        fprintf('%s\n','Naming reference organism cancelled by user. You should type the name manually in the produced xls sheets later');
        if Audio == 1
            try
            [Ys,Fs] = wavread(['..',filesep,'Audio',filesep,'cancel']);
            sound(Ys,Fs); %wavplay(Ys,Fs,'async')
            end
        end
    end
    pdbFILE={strcat(pdbFILEpath,pdbFILEname)};
    File = zGetNTData(pdbFILE,0);  %%%%%%%%%%%%%%%%%%%%%%%%%%THIS IS THE HEART%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%

    IncludeDecimalClasses = 1; %This variable switches between considering only
    %classes that are whole numbers, or all classes including decimal ones too


    PresentClasses =[];     %This loop is just to know what classes are present, to create xls files for only those
    for n = 1:length(File.Pair),                % File.Pair is taken from zGetNTData
        B1 = File.Pair(n).Base1Index;
        B2 = File.Pair(n).Base2Index;
        if (File.Pair(n).Class > 0) && (File.Pair(n).Class < 14)
            PresentClasses = [PresentClasses File.Pair(n).Class];
        end
    end

    %Now decide whether you want to use decimal classes or not:
    if IncludeDecimalClasses == 1
        PresentClasses = floor(PresentClasses); %This keeps the decimal classes, and merges them with the class before them
    end

    PresentClasses = mCollapseArray(PresentClasses); %removes repeted values

    if IncludeDecimalClasses ~= 1
        PresentClasses = mRemoveDecimals(PresentClasses); %This removes decimal classes
    end


    %%%%Writing xls lists of present families of basepairs in this PDB file%%%%
    %First Prepare to send them to default directory for xls position lists:

    OrigDir=cd;
    if ispc ==1 %ispc returns 1 if this is run on a PC (Windows)
        ind= findstr('\',OrigDir);  %Doesn't work on MAC
    else
        ind= findstr('/',OrigDir);  %Works on MAC
    end
    if ~exist(strcat(pdbFILEpath(1:ind(length(ind))),'NT_lists'),'dir')
        mkdir (pdbFILEpath(1:ind(length(ind))),'NT_lists')
        fprintf('%s\n','NT_lists directory created');
    end
    PositionPath=strcat(pdbFILEpath(1:ind(length(ind))),'NT_lists\');

    %%%%%%%%%%%%Writing all BPs in one file:
    if ~isempty(PresentClasses)
        xlsFilename = strcat(PositionPath,pdbFILEname,'_AllClasses.xls');
        if exist(xlsFilename,'file')
            delete(xlsFilename);
        end
        clear StringForExcel;
        StringForExcel(1,:)={'Organism','LB1','LB2','Interaction'};
        count=1;
        for n = 1:length(File.Pair),        %File.Pair is created after running zGetNTData
            [count StringForExcel]=mMakeStringForXLSwrite(count,PDBOrganism,File,n,IncludeDecimalClasses,StringForExcel);
        end
        xlswrite(xlsFilename, StringForExcel);
    else fprintf('%s\n','Warning: No RNA Baspairs were found in your pdb file')
    end

    %%%%%%%%%%%%Writing the the non-cWW families all in one file:
    xlsFilename = strcat(PositionPath,pdbFILEname,'_NOTcWW.xls');
    if exist(xlsFilename,'file')
        delete(xlsFilename);
    end
    clear StringForExcel;
    StringForExcel(1,:)={'Organism','LB1','LB2','Interaction'};
    count=1;
    for n = 1:length(File.Pair),        %File.Pair is created after running zGetNTData
        if floor(abs(File.Pair(n).Class))~=1
            [count StringForExcel]=mMakeStringForXLSwrite(count,PDBOrganism,File,n,IncludeDecimalClasses,StringForExcel);
        end
    end
    xlswrite(xlsFilename, StringForExcel);

    %%%%%%%%%%%%Writing the whatever BPs exist in each of the 13 Classes:
    for C=PresentClasses
        xlsFilename = strcat(PositionPath,pdbFILEname,'_Class',num2str(C),'(',mGetClassNameFromNumber(C),').xls');
        if exist(xlsFilename,'file')
            delete(xlsFilename);
        end
        clear StringForExcel;
        StringForExcel(1,:)={'Organism','LB1','LB2','Interaction'};
        count=1;
        for n = 1:length(File.Pair),        %File.Pair is created after running zGetNTData
            if floor(abs(File.Pair(n).Class))==C
                [count StringForExcel]=mMakeStringForXLSwrite(count,PDBOrganism,File,n,IncludeDecimalClasses,StringForExcel);
            end
        end
        xlswrite(xlsFilename, StringForExcel);
    end

    fprintf('%s\n','Excel lists of basepairs from your PDB file have been created in the NT_lists directory:');
    fprintf('%s\n',PositionPath);
    
    if exist('Audio','var')
        if Audio == 1
            try
            [Ys,Fs] = wavread(['..',filesep,'Audio',filesep,'done2']);
            sound(Ys,Fs); %wavplay(Ys,Fs,'async')
            end
        end
    end

else
    fprintf('%s\n','Loading PDB file cancelled by user');
    if Audio == 1
        try
        [Ys,Fs] = wavread(['..',filesep,'Audio',filesep,'cancel']);
        sound(Ys,Fs); %wavplay(Ys,Fs,'async')
        end
    end
end
