module external Gblocks, Gblocks_relaxed, Aliscore, Noisy, trimAl_generic, trimAl_gappyout, trimAl_strict, trimAl_automated1, probmask, guidance, DummyFilter, NoFilter, RandFilter, MostGaps, PSAR, BMGE, guidanceFull;

tmpDir := GetTmpDir();

# This function is used to read the profile file generated by Aliscore and extract the postions' numbers we need. Here when the score is larger than 0, then we consider it's not a variable position.
ReadAliscoreProfile := proc(fn:string)
   WholeFile := ReadRawFile(fn);
   EntryTables := SearchDelim('\n', WholeFile);
   ResultList:=[];
   for i from 2 to length(EntryTables) do
       temp := SearchDelim('\t', EntryTables[i]);
       if parse(temp[2]) > 0 then
           ResultList := append(ResultList, parse(temp[1]));
       fi;
   od;
   return(ResultList);
end:

ReadProbmask := proc(fn:string,probmask_threshold:numeric)
    WholeFile := ReadRawFile(fn);
    EntryTables := SearchDelim('\n', WholeFile);
    ResultList := [];
    for i to length(EntryTables) do
        if parse(EntryTables[i]) > probmask_threshold then
	    ResultList := append(ResultList, i);
	fi;
    od;
    return(ResultList);
end:

ReadGuidance := proc(fn:string, threshold:numeric)
    WholeFile := ReadRawFile(fn);
    Entries := SearchDelim('\n', WholeFile);
    ResultList := [];
    for i from 2 to (length(Entries)-1) do
        value := sscanf(Entries[i], ' %f %f')[2];
        position := sscanf(Entries[i], ' %f %f')[1];
        if value >= threshold then
            ResultList := append(ResultList, position);
        fi;
    od;
    return(ResultList);
end:

ReplaceUnderlineWithHyphen := proc(AlignedSeqs:list(string))
#this function replace the gaps notations underlines to hyphens in aligned sequences in MSA
    NewAlignedSeqs := [];
    for each in AlignedSeqs do
        temp := ReplaceString('_','-',each);
        NewAlignedSeqs := append(NewAlignedSeqs, temp);
    od;
    return(NewAlignedSeqs); 
end:

RemoveUninformativeSites := proc(AlignedSeqs:list(string))
#this function remove the uninformative sites from the aligned sequences, including the columns with all same character or only one character while the others are gaps.
    NewAlignedSeqs1 := [];
    lengthOfAlignment := length(AlignedSeqs[1]);
    numberOfAlignment := length(AlignedSeqs);
    indices := [];
    #remove the column with one character and the others gaps.
    for j from 1 to lengthOfAlignment do
        indicator := true;
        numberOfGaps := 0;
        for i from 1 to numberOfAlignment do
            if AlignedSeqs[i][j] = '_' or AlignedSeqs[i][j] = '-' then
                numberOfGaps := numberOfGaps + 1;
            fi;
        od;
        if numberOfGaps = numberOfAlignment - 1 then
            indicator := false;
        fi;
        indices := append(indices, indicator);
    od;
    for i from 1 to numberOfAlignment do
        temp := '';
        for j from 1 to lengthOfAlignment do
            if indices[j] then
                temp := temp.AlignedSeqs[i][j];
            fi;
        od;
        NewAlignedSeqs1 := append(NewAlignedSeqs1, temp);
    od;
    return(NewAlignedSeqs1);
end:


ReadAlignmentsFromtrimAlFasta := proc(fn:string)
    WholeFile := ReadRawFile(fn);
    EntryTables := SearchDelim('\n',WholeFile);
    ResultList := [];
    temp := NULL;
    for i to length(EntryTables) do
        if EntryTables[i,1] = '>' then
            ResultList := append(ResultList, temp);
            temp := '';
        else
            temp := temp.EntryTables[i];
        fi;
    od;
    ResultList := append(ResultList, temp);
    return(ResultList);
end:

ReadPSAR := proc(fn:string, PSARThresh:numeric)
    WholeFile := ReadRawFile(fn);
    EntryTables := SearchDelim('\n', WholeFile);
    ResultList := [];
    for i from 2 to length(EntryTables) do
        temp := SearchDelim('\t', EntryTables[i]);
        if parse(temp[2]) > PSARThresh then
            ResultList := append(ResultList, parse(temp[1]));
        fi;
    od;
    return(ResultList);
end:

#------------Gblocks-------------------------------
Gblocks := proc(msaI ;   'seqtype'=((seqtype='AA'):{'AA','DNA','Codon'}),  #sequence type
                         'binary'=((binary=''):string),
                         'b1'=((b1=floor(length(msaI['AlignedSeqs'])/2)+2):posint),   #Minimum number of sequences for a conserved position
                         'b2'=((b2=floor(length(msaI['AlignedSeqs'])*0.85)+1):posint),  #Minimum number of sequences for a flank position
                         'b3'=((b3=8):posint),                                      #Maximum number of contiguous nonconserved positions
                         'b4'=((b4=10):posint),                                     #Minimum length of a block:
                         'b5'=((b5='n'):{'n','h','a'}))                             #Allowed gap positions

    msa := copy(msaI);
    MinSeqLen := 0;
    
    if seqtype = 'AA' then
        t := 'p';
    elif seqtype = 'DNA' then
        t := 'd';
    else t := 'c';
    fi;

    pid    := getpid();
    seqin  := tmpDir.'seqs.fa.'.pid;
    seqout := seqin.'-gb';
    
    selection := GetWrapperChoice('Filters/gblocks/Gblocks_0.91b/Gblocks','Gblocks',binary);
    if selection = BINARY_HARDCODED then 
        GblocksFn := binary;
    elif selection = BINARY_IN_PATH then
        GblocksFn := 'Gblocks';
    elif selection = BINARY_IN_WRAPPER_FOLDER then
        GblocksFn := GetWrapperDir().'Filters/gblocks/Gblocks_0.91b/Gblocks';
    else
        error('no such selection');
    fi;

    if b1 < length(msa[AlignedSeqs])/2+1 or b2 < b1 then
        error(sprintf('parameter out of range b1=%d b2=%d', b1, b2));
    fi;
    msa['AlignedSeqs'] := ReplaceUnderlineWithHyphen(msa['AlignedSeqs']);
    WriteFasta(msa['AlignedSeqs'], msa['labels'], seqin);
    sleep(1);
    cmd := sprintf('%s %s -t=%s -b1=%d -b2=%d -b3=%d -b4=%d -b5=%s',
                   GblocksFn, seqin, t, b1, b2, b3, b4, b5);
    cputime := time(all);
    res := TimedCallSystem(cmd);
    cputime := time(all) - cputime;
    if res[1] = -1 then
        error('could not run gblocks: '.res[2].'; code='.res[1]);
    fi;
    aSeqs := ReadFastaWithCheck(seqout, msa['labels']);
    DeleteFiles([seqin, seqout, seqout.'.htm']);
    if length(aSeqs[1]) <= MinSeqLen then
        error('gblocks produced MSA of length '.string(length(aSeqs[1])));
    fi;
    msa2 := MAlignment(msa['InputSeqs'], aSeqs, msa['labels'], 'Time'=cputime);
    return(msa2);
end:

Gblocks_relaxed := proc(msa ; 
                            'seqtype'=((seqtype_relaxed='AA'):{'AA','DNA','Codon'}))
    b1_relaxed := floor(length(msa['AlignedSeqs'])/2)+2;
    b2_relaxed := b1_relaxed; b3_relaxed := 10; b4_relaxed := 5; b5_relaxed := 'h';
    Gblocks(msa, seqtype=seqtype_relaxed, b1=b1_relaxed, b2=b2_relaxed, b3=b3_relaxed, b4=b4_relaxed, b5=b5_relaxed);
end:
#---------end of Gblocks--------------------------


#------------ALISCORE-----------------------------------
Aliscore := proc(msaI;   
            'WindowSize'=((WindowSize=6):posint), #set the windows size, larger than 4
            'TreatGapsAsUnknown'=((TreatGapsAsUnknown=false):boolean), # treat the gaps as ambiguous unknown chracter or as a 5th character
            'NumberOfPairs'=((NumberOfPairs=-1):posint),  # set the number of pairs used to check replications. if used without an argument, 4*N pairs are compared. If used with a argument, this number of randomly selected pairs is analysed.
            'NumberOfIterations'=((NumberOfIterations=-1):posint), #used to restrict iterating through the tree to a specific node level.
            'seqtype'=((seqtype='AA'):{'AA','DNA'}),  #set the type of data
            'binary'=((binary=''):string)
			)
    msa := copy(msaI);
    MinSeqLen := 0;
    pid     := getpid();
    seqin   := tmpDir.'seqs.fa.'.pid;
    if seqtype = 'AA' then
        seqout := seqin.'_Profile_random.txt';
    elif seqtype = 'DNA' then
        seqout := seqin.'_Profile-l_all.txt';
    else
        error('unsupported sequence type');
    fi;
    selection := GetWrapperChoice('Filters/Aliscore/Aliscore.02.pl','Aliscore.02.pl',binary);
    
    if selection = BINARY_HARDCODED then
        AliscoreFn := binary;
    elif selection = BINARY_IN_PATH then
        AliscoreFn := 'Aliscore.02.pl';
    elif selection = BINARY_IN_WRAPPER_FOLDER then
        AliscoreFn := GetWrapperDir().'Filters/Aliscore/Aliscore.02.pl';
    else 
        error('no such selection');
    fi;
    
    AliscoreModuleFn := GetWrapperDir().'Filters/Aliscore/Aliscore_module.pm';

    if WindowSize < 4 then
        error(sprintf('windows size is too small(smaller than 4), and Alisocre will start making substantial type I errors and call non-randomly similar sites randomly similar.'));
    fi;
    msa['AlignedSeqs'] := ReplaceUnderlineWithHyphen(msa['AlignedSeqs']); 
    WriteFasta(msa['AlignedSeqs'], msa['labels'], seqin);
    sleep(1);
    paramlist := [AliscoreModuleFn, '-i '.seqin, '-w '.WindowSize, If(TreatGapsAsUnknown=false, NULL, '-N'), If(NumberOfPairs=-1, NULL, '-r '.NumberOfPairs), If(NumberOfIterations=-1, NULL, '-l '.NumberOfIterations)];
    params := string(seq(string(i).' ', i = paramlist));
    cmd := sprintf('perl %s %s',AliscoreFn, params);
    
    cputime := time(all);
    res := TimedCallSystem(cmd);
    cputime := time(all) - cputime;

    if res[1] = -1 then
        error('could not run Aliscore: '.res[2].'; code= '.res[1]);
    fi;
    
    aPositions := ReadAliscoreProfile(seqout);
    if length(aPositions) <= MinSeqLen then
        error('Aliscore produced MSA of length '.string(length(aPositions)));
    fi;
    #-----to get the curated aligned sequences according to the returned postion from Alisocre-----
    aSeqs :=[];
    for each in msa['AlignedSeqs'] do
        temp := '';
        for i in aPositions do
        temp := temp.each[i];
        od;
        aSeqs := append(aSeqs, temp);
    od;
    if seqtype = 'AA' then
        DeleteFiles([seqin, seqout, seqin.'_List_random.txt']);
    elif seqtype = 'DNA' then
        DeleteFiles([seqin, seqout, seqin.'_List-l_all.txt']);
    else
        error('unsupported sequence type');
    fi;
    msa2 := MAlignment(msa['InputSeqs'], aSeqs, msa['labels'], 'Time'=cputime);
    return(msa2);
end:

#----------end of Aliscore----------------------------


#-------begin of Noisy-------------------------------
Noisy := proc(msaI; 'binary'=((binary=''):string),
                   'seqtype'=((seqtype = 'AA'):{'DNA','AA','RNA'}),         #sequence type
                   'cutoff'=((cutoff = 0.80):numeric),                      #Set the lower bound of the reliability score for an alignment column to float
                   'distance'=((distance = 'HAMMING'):{'HAMMING', 'GTR'}),  #distance measurement
		           'ordering'=((ordering = 'nnet'):{'nnet', 'qnet', 'rand[]', 'all'}),  #Set the method to calculate the cyclic order to one of the major methods
		           'nogap'=((nogap = false):boolean),                       #this parameter will add the gap symbols to the set of missing characters
		           'noconstant'=((noconstant = false):boolean))             #Suppress constant columns in the output MSA with this option
    msa := copy(msaI);
    MinSeqLen := 0;

    pid     := getpid();
    seqin   := tmpDir.'seqs.fa.'.pid.'.fas';
    seqout  := 'seqs.fa.'.pid.'_out.fas';
    
    selection := GetWrapperChoice('Filters/Noisy-1.5.11/noisy','noisy',binary);
    
    if selection = BINARY_HARDCODED then
        NoisyFn := binary;
    elif selection = BINARY_IN_PATH then
        NoisyFn := 'noisy';
    elif selection = BINARY_IN_WRAPPER_FOLDER then
        NoisyFn := GetWrapperDir().'Filters/Noisy-1.5.11/noisy';
    else
        error('no such selection');
    fi;


    if seqtype = 'DNA' then
        sq := 'D';
    fi;
    if seqtype = 'AA' then
        sq := 'P';
    fi;
    if seqtype = 'RNA' then
        sq := 'R';
    fi;
    msa['AlignedSeqs'] := ReplaceUnderlineWithHyphen(msa['AlignedSeqs']);
    WriteFasta(msa['AlignedSeqs'], msa['labels'], seqin);
    sleep(1);
    paramlist := [seqin, '--cutoff '.string(cutoff), '--distance '.distance, '--ordering '.ordering, '--seqtype '.sq, If(nogap = false, NULL, '--nogap'), If(noconstant = false, NULL, '--noconstant')];
    params := string(seq(string(i).' ', i = paramlist));
    cmd := sprintf('%s %s', NoisyFn, params);
    
    cputime := time(all);
    res := TimedCallSystem(cmd);
    cputime := time(all) - cputime;

    if res[1] = -1 then
        error('could not run Noisy: '.res[2].'; code='.res[1]);
    fi;
    CallSystem('mv *'.seqout.' '.seqout);
    aSeqs := ReadFastaWithCheck(seqout, msa['labels']);
    if length(aSeqs[1]) <= MinSeqLen then
        error('Noisy produced MSA of length '.string(length(aSeqs[1])));
    fi;
    DeleteFiles([seqin, seqout, '*seqs.fa.'.pid.'_sta.gr', '*seqs.fa.'.pid.'_typ.eps', '*seqs.fa.'.pid.'_idx.txt']);
    msa2 := MAlignment(msa['InputSeqs'], aSeqs, msa['labels'], 'Time'=cputime);
    return(msa2);
end:



#-----------------begin of trimAl-------------------
trimAl_generic := proc(msaI; 
                    'binary' = ((binary = ''):string),
                    'criterion' = ((criterion = 'notInvoked'):{'gappyout','strict', 'strictplus', 'automated1'}), # 3 automatically-selected thresholds methods or Automated trimming heuristic method
                    'seqtype' = ((seqtype = 'AA'):{'DNA','AA','RNA'}),
                    'GapThreshold' = ((GapThreshold = -1):numeric), #Gap Threshold range from 0 to 1.
                    'SimilarityThreshold' = ((SimilarityThreshold = -1):numeric),  # Similarity Score range from 0 to 1.
                    'ConservationThreshold' = ((ConservationThreshold = -1):numeric), #conservation threshold, minimum percentage of columns from the input alignment that should be part of the trimmed alignment. This threshold is defined between 0 and 100.
                    'ConsistencyScore' = ((ConsistencyScore = -1):numeric), #minimal values of the consistency score (range of values between 0 and 1).
                    'ResidueOverlap' = ((ResidueOverlap = -1):numeric),  #the minimum residue overlap score for each residue, range from 0 to 1.
                    'SequenceOverlap' = ((SequenceOverlap = -1):numeric) #the minimum percentage of the residues for each sequence that should pass the residue overlap threshold in order to maintain the sequence in the new alignment should be set. range from 0 to 100.
                    )
    msa := copy(msaI);

    MinSeqLen := 0;
    
    if GapThreshold <> -1 then
        if GapThreshold > 1 or GapThreshold < 0 then
            error('The parameter GapThreshold out of bound!');
        fi;
    fi;
    if SimilarityThreshold <> -1 then
        if SimilarityThreshold > 1 or SimilarityThreshold < 0 then
            error('The parameter SimilarityThreshold out of bound!');
        fi;
    fi;
    if ConservationThreshold <> -1 then
        if ConservationThreshold > 100 or ConservationThreshold < 0 then
            error('The parameter ConservationThreshold out of bound!');
        fi;
    fi;
    if ConsistencyScore <> -1 then
        if ConsistencyScore > 1 or ConsistencyScore < 0 then
            error('The parameter ConsistencyScore out of bound!');
        fi;
    fi;
    if ResidueOverlap <> -1 then
        if ResidueOverlap > 1 or ResidueOverlap < 0 then
            error('The parameter ResidueOverlap out of bound!');
        fi;
    fi;
    if SequenceOverlap <> -1 then
        if SequenceOverlap > 100 or SequenceOverlap < 0 then
            error('The parameter SequenceOverlap out of bound!');
        fi;
    fi;

    pid    := getpid();
    seqin  := tmpDir.'seqs.fa.'.pid;
    seqoutTemp := seqin.'.result.temp';
    seqout := seqin.'.result';
    
    selection := GetWrapperChoice('Filters/trimAl/source/trimal','trimal',binary);

    if selection = BINARY_HARDCODED then
        trimAlFn := binary;
    elif selection = BINARY_IN_PATH then
        trimAlFn := 'trimal';
    elif selection = BINARY_IN_WRAPPER_FOLDER then
        trimAlFn := GetWrapperDir().'Filters/trimAl/source/trimal';
    else
        error('no such selection');
    fi;
    msa['AlignedSeqs'] := ReplaceUnderlineWithHyphen(msa['AlignedSeqs']);
    WriteFasta(msa['AlignedSeqs'], msa['labels'], seqin);
    sleep(1);
    
    paramlist := ['-in '.seqin, '-out '.seqoutTemp, If(criterion = 'notInvoked', NULL, '-'.criterion), If(GapThreshold = -1, NULL, '-gt '.string(GapThreshold)), If(SimilarityThreshold = -1, NULL, '-st '.string(SimilarityThreshold)), If(ConservationThreshold = -1, NULL, '-cons '.string(ConservationThreshold)), If(ConsistencyScore = -1, NULL, '-ct '.string(ConsistencyScore)), If(ResidueOverlap = -1, NULL, '-resoverlap '.string(ResidueOverlap)), If(SequenceOverlap = -1, NULL, '-seqoverlap '.string(SequenceOverlap))];
    print(paramlist);
    params := string(seq(string(i).' ', i = paramlist ));
    cmd := sprintf('%s %s ', trimAlFn, params);
    
    cputime := time(all);
    res := TimedCallSystem(cmd);
    cputime := time(all) - cputime;

    if res[1] = -1 then
        error('could not run trimAl: '.res[2].'; code= '.res[1]);
    fi;
    #TempModify := ReadFasta(seqoutTemp);
    temp := ReadAlignmentsFromtrimAlFasta(seqoutTemp);
    WriteFasta(temp, msa['labels'], seqout);
    aSeqs := ReadFastaWithCheck(seqout, msa['labels']);
    if length(aSeqs[1]) <= MinSeqLen then
        error('trimAl produced MSA of length '.string(length(aSeqs[1])));
    fi;
    DeleteFiles([seqin, seqout, seqoutTemp]);
    msa2 := MAlignment(msa['InputSeqs'], aSeqs, msa['labels'], 'Time'=cputime);
    return(msa2);
end:

trimAl_gappyout := proc(msa; 'seqtype'=((seqtype_gappyout = 'AA':{'DNA','AA','RNA'})))
    criterion_gappyout := 'gappyout';
    trimAl_generic(msa, criterion = criterion_gappyout);
end:
trimAl_strict := proc(msa; 
                            'seqtype'=((seqtype_strict = 'AA'):{'DNA','AA','RNA'}))
    criterion_strict := 'strict';
    trimAl_generic(msa, criterion = criterion_strict);
end:
trimAl_automated1 := proc(msa;
                            'seqtype'=((seqtype_automated1 = 'AA'):{'DNA','AA','RNA'}))
    criterion_automated1 := 'automated1';
    trimAl_generic(msa, criterion = criterion_automated1);
end:
#--------------------------end of trimAl--------------------




#-------------------------begin of GUIDANCE--------------------
guidance := proc(seqs:list(string), labels:list(string); 
                    'msaProg'=((msaProg='MAFFT'):{'PRANK','MAFFT','CLUSTALW'}),
                    'seqtype'=((seqtype = 'AA'):{'AA','DNA','Codon'}), 
                    'threshold'=((threshold=0.93):numeric),
                    'program'=((program='GUIDANCE'):{'HoT','GUIDANCE'}),
                    'nBootstrap'=((nBootstrap=100):integer),
                    'seqCutoff'=((seqCutoff=0.6):numeric),
                    'colCutoff'=((colCutoff=0.93):numeric),
                    'binary'=((binary=''):string),
                    'mafftbinary'=((mafftbinary=''):string),
                    'prankbinary'=((prankbinary=''):string))
    MinSeqLen := 0;
    
    if seqtype = 'AA' then
        seqType := 'aa';
    elif seqtype = 'DNA' then
        seqType := 'nuc';
    else seqType := 'codon';
    fi;
    
    pid := getpid();
    tmpdir := tmpDir.'GUIDANCE.'.pid;
    TimedCallSystem('mkdir '.tmpdir);
    seqin := tmpdir.'/inputseqs';
    seqout := tmpdir.'/outputseqs';
    
    #if prankbinary = '' then
    #    prankbinary := If(ETHMachines[hostname()]['CpuBits']=32,
    #                        GetWrapperDir().'MSA/prank/prank.100802/prank.linneus55',
    #                        GetWrapperDir().'MSA/prank/prank.100802/prank');
    #fi;
    #if mafftbinary = '' then
    #    mafftbinary := If(ETHMachines[hostname()]['CpuBits']=32,
    #                    GetWrapperDir().'MSA/mafft-6.843-with-extensions_32/scripts/mafft',
    #                    GetWrapperDir().'MSA/mafft-6.843-with-extensions/scripts/mafft');
    #fi;
    mafftbinary := GetWrapperDir().'MSA/mafft-6.843-with-extensions/scripts/mafft';
    prankbinary := GetWrapperDir().'MSA/prank/prank.100802/prank';
    clustalwbinary := GetWrapperDir().'MSA/clustalw-2.0.10/src/clustalw2';
    selection := GetWrapperChoice('Filters/guidance.v1.1/www/Guidance/guidance.pl','GUIDANCE',binary);
    
    setenv('MAFFT_BINARIES', GetWrapperDir().'MSA/mafft-6.843-with-extensions/binaries');
    
    if selection = BINARY_HARDCODED then
        guidanceFn := binary;
    elif selection = BINARY_IN_PATH then
        guidanceFn := 'guidance.pl';
    elif selection = BINARY_IN_WRAPPER_FOLDER then
        guidanceFn := GetWrapperDir().'Filters/guidance.v1.1/www/Guidance/guidance.pl';
    else
       error('no such selection');
    fi;
    
    WriteFasta(seqs, labels, seqin);
    
    cmd := sprintf('perl %s --seqFile %s --msaProgram %s --seqType %s --outDir %s --program %s '.
                    '--bootstraps %d --outOrder as_input --seqCutoff %f --colCutoff %f --mafft %s --prank %s --clustalw %s',
                    guidanceFn, seqin, msaProg, seqType, seqout, program, nBootstrap, seqCutoff, colCutoff, mafftbinary, prankbinary, clustalwbinary);
    
    printf('%s\n',cmd);
    cputime := time(all);
    res := TimedCallSystem(cmd);
    cputime := time(all) - cputime;
    
    if res[1] = -1 then
        error('could not run guidance: '.res[2].'; code='.res[1]);
    fi;
   # begin to read the position 
    scoreFn := seqout.'/MSA.'.msaProg.'.Guidance_res_pair_col.scr';
    print(scoreFn);
    aPositions := ReadGuidance(scoreFn, threshold);
    if length(aPositions) <= MinSeqLen then
        error('guidance produced MSA of length '.string(length(aPositions)));
    fi;
    
    # begin to read the aligned fasta
    if msaProg = 'MAFFT' then
        alignedFn := seqout.'/MSA.'.msaProg.'.aln.With_Names';
    elif msaProg = 'PRANK' then
        alignedFn := seqout.'/MSA.'.msaProg.'.aln.Sorted.With_Names';
    elif msaProg = 'CLUSTALW' then
        alignedFn := seqout.'/MSA.'.msaProg.'.aln.Sorted.With_Names';
    fi;
    aligned := ReadFasta(alignedFn)[1];
    alignedLabels := ReadFasta(alignedFn)[2];
    aSeqs :=[];
    for each in aligned do
        temp := '';
        for i in aPositions do
            temp := temp.each[i];
        od;
        aSeqs := append(aSeqs, temp);
    od;
    #DeleteFiles([seqin, seqiout]);
    CallSystem('rm -rf '.tmpdir);
    msa := MAlignment(seqs, aSeqs, alignedLabels, 'Time'=cputime);
    return(msa);

end:
                    
guidanceFull := proc(seqs:list(string), labels:list(string); 
                    'msaProg'=((msaProg='MAFFT'):{'PRANK','MAFFT','CLUSTALW'}),
                    'seqtype'=((seqtype = 'AA'):{'AA','DNA','Codon'}), 
                    'threshold'=((threshold=0.93):numeric),
                    'program'=((program='GUIDANCE'):{'HoT','GUIDANCE'}),
                    'nBootstrap'=((nBootstrap=100):integer),
                    'seqCutoff'=((seqCutoff=0.6):numeric),
                    'colCutoff'=((colCutoff=0.93):numeric),
                    'binary'=((binary=''):string),
                    'mafftbinary'=((mafftbinary=''):string),
                    'prankbinary'=((prankbinary=''):string))
    MinSeqLen := 0;
    
    if seqtype = 'AA' then
        seqType := 'aa';
    elif seqtype = 'DNA' then
        seqType := 'nuc';
    else seqType := 'codon';
    fi;
    
    pid := getpid();
    tmpdir := tmpDir.'GUIDANCE.'.pid;
    TimedCallSystem('mkdir '.tmpdir);
    seqin := tmpdir.'/inputseqs';
    seqout := tmpdir.'/outputseqs';
    
    #if prankbinary = '' then
    #    prankbinary := If(ETHMachines[hostname()]['CpuBits']=32,
    #                        GetWrapperDir().'MSA/prank/prank.100802/prank.linneus55',
    #                        GetWrapperDir().'MSA/prank/prank.100802/prank');
    #fi;
    #if mafftbinary = '' then
    #    mafftbinary := If(ETHMachines[hostname()]['CpuBits']=32,
    #                    GetWrapperDir().'MSA/mafft-6.843-with-extensions_32/scripts/mafft',
    #                    GetWrapperDir().'MSA/mafft-6.843-with-extensions/scripts/mafft');
    #fi;
    mafftbinary := GetWrapperDir().'MSA/mafft-6.843-with-extensions/scripts/mafft';
    prankbinary := GetWrapperDir().'MSA/prank/prank.100802/prank';
    clustalwbinary := GetWrapperDir().'MSA/clustalw-2.0.10/src/clustalw2';
    selection := GetWrapperChoice('Filters/guidance.v1.1/www/Guidance/guidance.pl','GUIDANCE',binary);
    
    setenv('MAFFT_BINARIES', GetWrapperDir().'MSA/mafft-6.843-with-extensions/binaries');
    
    if selection = BINARY_HARDCODED then
        guidanceFn := binary;
    elif selection = BINARY_IN_PATH then
        guidanceFn := 'guidance.pl';
    elif selection = BINARY_IN_WRAPPER_FOLDER then
        guidanceFn := GetWrapperDir().'Filters/guidance.v1.1/www/Guidance/guidance.pl';
    else
       error('no such selection');
    fi;
    
    WriteFasta(seqs, labels, seqin);
    
    cmd := sprintf('perl %s --seqFile %s --msaProgram %s --seqType %s --outDir %s --program %s '.
                    '--bootstraps %d --outOrder as_input --seqCutoff %f --colCutoff %f --mafft %s --prank %s --clustalw %s',
                    guidanceFn, seqin, msaProg, seqType, seqout, program, nBootstrap, seqCutoff, colCutoff, mafftbinary, prankbinary, clustalwbinary);
    
    printf('%s\n',cmd);
    cputime := time(all);
    res := TimedCallSystem(cmd);
    cputime := time(all) - cputime;
    
    if res[1] = -1 then
        error('could not run guidance: '.res[2].'; code='.res[1]);
    fi;
   # begin to read the position 
    scoreFn := seqout.'/MSA.'.msaProg.'.Guidance_res_pair_col.scr';
    print(scoreFn);
    aPositions := ReadGuidance(scoreFn, threshold);
    if length(aPositions) <= MinSeqLen then
        error('guidance produced MSA of length '.string(length(aPositions)));
    fi;
    
    # begin to read the aligned fasta
    if msaProg = 'MAFFT' then
        alignedFn := seqout.'/MSA.'.msaProg.'.aln.With_Names';
    elif msaProg = 'PRANK' then
        alignedFn := seqout.'/MSA.'.msaProg.'.aln.Sorted.With_Names';
    elif msaProg = 'CLUSTALW' then
        alignedFn := seqout.'/MSA.'.msaProg.'.aln.Sorted.With_Names';
    fi;
    aligned := ReadFasta(alignedFn)[1];
    alignedLabels := ReadFasta(alignedFn)[2];
    aSeqs :=[];
    for each in aligned do
        temp := '';
        for i in aPositions do
            temp := temp.each[i];
        od;
        aSeqs := append(aSeqs, temp);
    od;
    #DeleteFiles([seqin, seqiout]);
    CallSystem('rm -rf '.tmpdir);
    msa := MAlignment(seqs, aSeqs, alignedLabels, 'Time'=cputime);
    msa2 := MAlignment(seqs, aligned, alignedLabels, 'Time'=cputime);
    ans := table();
    ans['msa'] := msa;
    ans['msa2'] := msa2;
    return(ans);

end:
 
#-------------------------end of GUIDANCE----------------------

#-------------------------begin of ZORRO(probmask)-------------
probmask := proc(msaI; 'binary'=((binary=''):string),
                      'SampleWay'=((SampleWay = 'nosample'):{'sample','nosample'}),  #Sampling pairs to calculate alignment reliabilty or No Sampling i.e. using every pair to calculate alignment reliabilty
                      'seqtype'=((seqtype = 'AA'):{'AA','DNA','RNA'}),   #sequence type
                      'probmask_threshold'=((probmask_threshold = 4 ):numeric),  # the threshold used to filter the columns, range from 0 to 10.
                      'noweighting'=((noweighting = false):boolean),
                      'Nsample'=((Nsample = -1):numeric),  #Tells ZORRO to sample #NUMBER pairs when sampling, automatically turns on -sample option [Samples 10*Nseq sequences By Default]
                      'IgnoreGaps'=((IgnoreGaps = false):boolean),  #Ignore pair-gaps in columns when calculating column confidences [Off By Default]
                      'treeprog'=((treeprog = 'notInvoked'):string), #Tells ZORRO to use PROGRAM instead of the default FastTree to create guide tree [FastTree By Default]
                      'guide'=((guide = 'notInvoked'):string)
)
    msa := copy(msaI);
    MinSeqLen := 0;

    pid    := getpid();
    seqin  := tmpDir.'seqs.fa.'.pid;
    seqout := seqin.'.mask';
    
    selection := GetWrapperChoice('Filters/probmask/src/zorro','zorro',binary);

    if selection = BINARY_HARDCODED then
        probmaskFn := binary;
    elif selection = BINARY_IN_PATH then
        probmaskFn := 'zorro';
    elif selection = BINARY_IN_WRAPPER_FOLDER then
        probmaskFn := GetWrapperDir().'Filters/probmask/src/zorro';
    else
       error('no such selection');
    fi;
    
    setenv('PATH',getenv('PATH').':'.GetWrapperDir().'Filters/probmask/src');
    msa['AlignedSeqs'] := ReplaceUnderlineWithHyphen(msa['AlignedSeqs']); 
    WriteFasta(msa['AlignedSeqs'], msa['labels'], seqin);
    sleep(1);
    
    paramlist := ['-'.SampleWay, If(noweighting, '-noweighting', NULL), If(Nsample = -1, NULL, '-Nsample '.string(Nsample)), If(IgnoreGaps, '-ignoregaps', NULL), If(treeprog = 'notInvoked', NULL, '-treeprog '.treeprog), If(guide = 'notInvoked', NULL, '-guide '.guide), seqin.' > '.seqout];
    params := string(seq(string(i).' ', i = paramlist));
    cmd := sprintf('%s %s', probmaskFn, params);
    
    cputime := time(all);
    res := TimedCallSystem(cmd);
    cputime := time(all) - cputime;

    if res[1] = -1 then
        error('could not run probmask: '.res[2].'; code='.res[1]);
    fi;
    aPositions := ReadProbmask(seqout, probmask_threshold);
    if length(aPositions) <= MinSeqLen then
        error('probmask produced MSA of length '.string(length(aPositions)));
    fi;
    #-----to get the curated aligned sequences according to the returned postion from probmask-----
    aSeqs :=[];
    for each in msa['AlignedSeqs'] do
        temp := '';
        for i in aPositions do
        temp := temp.each[i];
    od;
    aSeqs := append(aSeqs, temp);
    od;
    DeleteFiles([seqin, seqout, seqin.'.zorro.tre']);
    msa2 := MAlignment(msa['InputSeqs'], aSeqs, msa['labels'], 'Time'=cputime);
    return(msa2);
end:


#-------------------------------begin of Dummy Filter methods-----------------
DummyFilter := proc(msaI; (seqtype = 'AA'):{'AA','DNA','RNA'})
    msa := copy(msaI);
    msa['AlignedSeqs'] := ReplaceUnderlineWithHyphen(msa['AlignedSeqs']);
    msa['AlignedSeqs'] := RemoveUninformativeSites(msa['AlignedSeqs']);
    return(MAlignment(msa['InputSeqs'], msa['AlignedSeqs'], msa['labels'], 'Time'=0));
end:

NoFilter := proc(msaI; (seqtype = 'AA'):{'AA','DNA','RNA'})
    msa := copy(msaI);
    msa['AlignedSeqs'] := ReplaceUnderlineWithHyphen(msa['AlignedSeqs']);
    return(MAlignment(msa['InputSeqs'], msa['AlignedSeqs'], msa['labels'], 'Time'=0));
end:


#---------------------------RandFilter--------------------
# This wrapper will randomly filter X% 
RandFilter := proc(msaI, percentage:numeric)
    msa := copy(msaI);
    msa['AlignedSeqs'] := ReplaceUnderlineWithHyphen(msa['AlignedSeqs']);
    lengthOfAlignment := length(msa['AlignedSeqs',1]);
    numberOfAlignment := length(msa['AlignedSeqs']);
    randIndex := CreateRandPermutation(lengthOfAlignment);
    percentage2 := 1 - percentage / 100;
    randIndex := randIndex[1..floor(percentage2 * lengthOfAlignment)];
    randIndex := sort(randIndex);
    NewAlignedSeqs1 := [];
    for i from 1 to numberOfAlignment do
        temp := '';
        for j from 1 to length(randIndex) do
            temp := temp.msa['AlignedSeqs', i, randIndex[j]];
        od;
        NewAlignedSeqs1 := append(NewAlignedSeqs1, temp);
    od;
    return(MAlignment(msa['InputSeqs'], NewAlignedSeqs1, msa['labels'], 'Time'=0));
end:


#----------------------------Most Gaps------------------------
#This wrapper removes the x% sites with most gaps
MostGaps := proc(msaI, percentage:numeric)
    msa := copy(msaI);
    msa['AlignedSeqs'] := ReplaceUnderlineWithHyphen(msa['AlignedSeqs']);
    lengthOfAlignment := length(msa['AlignedSeqs',1]);
    numberOfAlignment := length(msa['AlignedSeqs']);
    percentage2 := 1 - percentage / 100;
    numberToKeep := floor(lengthOfAlignment * percentage2);
    indexToKeep := [];
    numberKept := 0;
    
    numberOfGapsOfSeqs := [];
    for i from 1 to lengthOfAlignment do
        numberOfGaps := 0;
        for j from 1 to numberOfAlignment do
            if msa['AlignedSeqs', j, i] = '-' then
                numberOfGaps := numberOfGaps + 1;
            fi;
        od;
        numberOfGapsOfSeqs := append(numberOfGapsOfSeqs, numberOfGaps);
    od;

    for j from 0 to numberOfAlignment do
        if numberKept >= numberToKeep then
            break;
        fi;
        for i from 1 to lengthOfAlignment do
            if numberOfGapsOfSeqs[i] = j then
                indexToKeep := append(indexToKeep, i);
                numberKept := numberKept + 1;
            fi;
            if numberKept >= numberToKeep then
                break;
            fi;
        od;
    od;
    indexToKeep := sort(indexToKeep);
    
    NewAlignedSeqs1 := [];
    for i from 1 to numberOfAlignment do
        temp := '';
        for j from 1 to length(indexToKeep) do
            temp := temp.msa['AlignedSeqs', i, indexToKeep[j]];
        od;
        NewAlignedSeqs1 := append(NewAlignedSeqs1, temp);
    od;
    return(MAlignment(msa['InputSeqs'], NewAlignedSeqs1, msa['labels'], 'Time'=0));
end:

PSAR := proc(msaI;  'seqtype'=((seqtype='DNA'):{'DNA'}),
                    'SampThresh'=((SampThresh=-1):numeric),
                    'binary'=((binary=''):string),
                    'paraFile'=((paraFile=''):string),
                    'PSARThresh'=((PSARThresh=0.7):numeric))
### PSAR only works on DNA sequences. A parameter file is required. By default, the parameter file is in the same directory of PSAR binary.
    msa := copy(msaI);
    MinSeqLen := 0;
    if seqtype <> 'DNA' then
        error('PSAR only works on DNA sequences!');
    fi;
    
    pid := getpid();
    seqin := tmpDir.'seqs.fa.'.pid;
    seqout := seqin.'out';
    
    selection := GetWrapperChoice('Filters/PSAR/psar', 'psar', binary);
    if selection = BINARY_HARDCODED then
        PSARFn := binary;
    elif selection = BINARY_IN_PATH then
        PSARFn := 'psar';
    elif selection = BINARY_IN_WRAPPER_FOLDER then
        PSARFn := GetWrapperDir().'Filters/PSAR/psar';
    else
        error('no such selection');
    fi;
    
    if SampThresh <> -1 then
        if SampThresh > 1 or SampThresh < 0 then
            error('Sampling threshold shoule be in range [0,1].');
        fi;
    fi;

    msa['AlignedSeqs'] := ReplaceUnderlineWithHyphen(msa['AlignedSeqs']);
    WriteFasta(msa['AlignedSeqs'], msa['labels'], seqin);
    sleep(1);
    
    if paraFile = '' then
        paraFile := GetWrapperDir().'Filters/PSAR/parameters.txt';
    fi;
    
    paramlist := [seqin, paraFile, seqout, If(SampThresh=-1, NULL, '-s '.string(SampThresh))];
    params := string(seq(string(i).' ', i = paramlist));
    cmd := sprintf('%s %s', PSARFn, params);
    
    cputime := time(all);
    res := TimedCallSystem(cmd);
    cputime := time(all) - cputime;
    if res[1] = -1 then
        error('could not run PSAR: '.res[2].'; code='.res[1]);
    fi;
    
    aPositions := ReadPSAR(seqout.'/PSAR_column.txt', PSARThresh);
    DeleteFiles([seqin]);
    CallSystem('rm -rf '.seqout);
    if length(aPositions) <= MinSeqLen then
        error('PSAR produced MSA of length '.string(length(aPositions)));
    fi;
    aSeqs :=[];
    for each in msa['AlignedSeqs'] do
        temp := '';
        for i in aPositions do
            temp := temp.each[i];
        od;
        aSeqs := append(aSeqs, temp);
    od;
    msa2 := MAlignment(msa['InputSeqs'], aSeqs, msa['labels'], 'Time'=cputime);
    return(msa2);
end:


#-------------------------- begin of BMGE ---------------------------------
BMGE := proc(msaI; 'binary'=((binary=''):string),
                   'seqtype'=((seqtype='AA'):{'AA', 'DNA', 'Codon'}),
                   'similarityMatrix'=((similarityMatrix='BLOSUM62'):string), 
                   ## for amino acid, the matrix can be 15 estimated BLOSUM matrices: BLOSUM30, BLOSUM35, BLOSUM40, BLOSUM45, BLOSUM50, BLOSUM55, BLOSUM60, BLOSUM62, BLOSUM65, BLOSUM70, BLOSUM75, BLOSUM80, BLOSUM85, BLOSUM90, BLOSUM95. The trimming is progressively more stringent as the BLOSUM index increases (e.g. BLOSUM95); reciprocally, the trimming is progressively more relaxed as the BLOSUM index is lower (e.g. BLOSUM30).
                   ## for DNA, the matrix can be all possible PAM matrices, from the most stringent (i.e. -m DNAPAM1) to highly relaxed ones (e.g. -m DNAPAM500).
                   ## for Codon, as BMGE performs a conversion into aa seqs, so only BLOSUM matrices can be used.
                   'windowSize'=((windowSize=3):integer), ## 3 is the default. It is not recommended to increase this size (which must be odd). However, when set to 1, no averaging operations will be performed by BMGE.
                   'cutoff'=((cutoff=0.5):numeric), ## BMGE selects characters associated with a score value below a fixed threshold. However, it is strongly recommended to use the option -m rather than the option -h to obtain biologically-relevant stringent or relaxed character trimming.
                   'gapCutoff'=((gapCutoff=0.2):numeric), ## By default, BMGE removes all characters with a gap frequency greater than 0.2.
                   'minBlockSize'=((minBlockSize=5):numeric), ## By default, BMGE only selects regions of size greater than or equal to 5 characters.
                   'stationaryTrimming'=((stationaryTrimming='NO'):{'NO', 'YES', 'FAST'}) ## By setting the option -s to YES (NO by default), BMGE performs another character trimming until the remaining characters are compositionally homogeneous, as assessed by Stuart’s (1955) test of marginal homogeneity between each pair of sequences. by setting the option -s to FAST, BMGE performs a faster stationary-based character trimming.
                   )
    msa := copy(msaI);
    MinSeqLen := 0;
    
    pid := getpid();
    seqin := tmpDir.'seqs.fa.'.pid;
    seqout := seqin.'BMGE.fa';
    
    selection := GetWrapperChoice('Filters/BMGE-1.1/BMGE.jar', 'BMGE.jar', binary);
    if selection = BINARY_HARDCODED then
        BMGEFn := binary;
    elif selection = BINARY_IN_PATH then
        BMGEFn := 'BMGE.jar';
    elif selection = BINARY_IN_WRAPPER_FOLDER then
        BMGEFn := GetWrapperDir().'Filters/BMGE-1.1/BMGE.jar';
    else
        error('no such selection');
    fi;

    WriteFasta(msa['AlignedSeqs'], msa['labels'], seqin);
    sleep(1);

    cmd := sprintf('java -Xmx1500M -jar %s -i %s -t %s -m %s -w %d -h %f -g %f -b %d -s %s -of %s', 
                   BMGEFn, seqin, seqtype, similarityMatrix, windowSize, cutoff, gapCutoff, minBlockSize, stationaryTrimming, seqout);
    ## when having the error "Exception in thread “main” java.lang.OutOfMemoryError: Java heap space", increase the maximum size of the memory allocation pool in MB with -Xmx
    printf('%s\n', cmd);
    cputime := time(all);
    res := TimedCallSystem(cmd);
    cputime := time(all) - cputime;

    if res[1] = -1 then
        error('could not run BMGE: '.res[2].'; code='.res[1]);
    fi;
    aSeqs := ReadFastaWithCheck(seqout, msa['labels']);
    DeleteFiles([seqin, seqout]);
    if length(aSeqs[1]) <= MinSeqLen then
        error('BMGE produced MSA of length '.string(length(aSeqs[1])));
    fi;
    msa2 := MAlignment(msa['InputSeqs'], aSeqs, msa['labels'], 'Time'=cputime);
    return(msa2);
end:

#--------------------------- end of BMGE ------------------------------------

end:
