module external CreateNucleotideMatrices, NucToNInt, NIntToNuc, NucleotideMutate;

# create rate matrix for mechanistic models
CreateNucleotideMatrices := proc(model: string, baseFreqs:list(nonnegative), 
                               params:list(numeric))
    global NM, NMS, NF, DNALogPAM1, AF, DM, DMS, logPAM1:

# Backup AF, logPAM1, DM and DMS
    if assigned(DM) then DMbak := DM fi;
    if assigned(DMS) then DMSbak :=DMS fi;
    if assigned(AF) then AFbak := AF fi;
    if assigned(logPAM1) then logPAM1bak := logPAM1 fi;

    fR := baseFreqs[1] + baseFreqs[3]:
    fY := baseFreqs[2] + baseFreqs[4]:
    if model = 'GTR' then
        if length(params) <> 6 then 
            error('number of parameters does not match (should be 6).'):
        fi:
        a := params[1]: b := params[2]: c := params[3]: 
        d := params[4]: e := params[5]: f := params[6]:
        Q := [[0, d*baseFreqs[2], f*baseFreqs[3], b*baseFreqs[4]],
              [d*baseFreqs[1], 0, e*baseFreqs[3], a*baseFreqs[4]],
              [f*baseFreqs[1], e*baseFreqs[2], 0, c*baseFreqs[4]],
              [b*baseFreqs[1], a*baseFreqs[2], c*baseFreqs[3], 0]]:
    else
        if model = 'HKY' then
            if length(params) <> 2 then 
                error('number of parameters does not match (should be 2).'): 
            fi:
            alpha1 := alpha2 := params[1]:
            beta := params[2]:
        elif model = 'F84' then
            if length(params) <> 2 then 
                error('number of parameters does not match (should be 2).'): 
            fi:
            alpha1 := (1+params[1]/fY)*params[2]:
            alpha2 := (1+params[1]/fR)*params[2]:
            beta := params[2]:
        elif model = 'TN93' then
            if length(params) <> 3 then 
                error('number of parameters does not match (should be 3).'): 
            fi:
            alpha1 := params[1]:
            alpha2 := params[2]:
            beta := params[3]:
        else
            error('Unknown Model!'):
        fi:
        Q := [[0, beta*baseFreqs[2], alpha2*baseFreqs[3], beta*baseFreqs[4]],
              [beta*baseFreqs[1], 0, beta*baseFreqs[3], alpha1*baseFreqs[4]],
              [alpha2*baseFreqs[1], beta*baseFreqs[2], 0, beta*baseFreqs[4]],
              [beta*baseFreqs[1], alpha1*baseFreqs[2], beta*baseFreqs[3], 0]]:
    fi:
    
    freqmat := CreateArray(1..4, 1..4, 0):
    for i to 4 do
        freqmat[i,i] := baseFreqs[i]:
    od:
    
    qsum := sum(sum(freqmat*Q)):
    Q := Q/qsum:
    
    for i to 4 do
        Q[i,i] := -sum(Q[i]):
    od:
    
    CreateDayMatrices(transpose(Q), baseFreqs, type='Nucleotide', NucleotideMapping):

    NM := DM;
    NMS := DMS;
    NF := AF;
    DNALogPAM1 := logPAM1;

# Reinstall the original Dayhoff matrices
    if assigned(DMbak) then DM := DMbak fi;
    if assigned(DMSbak) then DMS := DMSbak fi;
    if assigned(AFbak) then AF := AFbak fi;
    if assigned(logPAM1bak) then logPAM1 := logPAM1bak fi;
    NULL;    
end:

NucToNInt := proc(n:string)
    nint := 0:
    if n='T' then
        nint := 4:
    elif n='C' then
        nint := 2:
    elif n='A' then
        nint := 1:
    elif n='G' then
        nint := 3:
    else
        error('unknown nucleotide!'):
    fi:
    nint;
end:

NIntToNuc := proc(n:posint)
    nstr := 'X':
    if n = 4 then
        nstr := 'T':
    elif n = 2 then
        nstr := 'C':
    elif n = 1 then
        nstr := 'A':
    elif n = 3 then
        nstr := 'G':
    else
        error('unknown nucleotide!'):
    fi:
    nstr;
end:

# mutate
NucleotideMutate:=proc(seq1:string,time:{positive, list(positive)}; 
                       (lnM1=Q):matrix, classes:array(posint), 
                       (neutral=true):boolean)
    if not assigned(lnM1) then
        error('Q is not assigned.')
    fi;
    if type(time, list) and assigned(classes) then
        return(NucleotideMutateGamma(seq1, time, lnM1, classes, neutral)):
    elif type(time, list) or assigned(classes) then
        error('for gamma model NucleotideMutate requires a list of distances '.
              'and an array with the class assignment for each site'):
    fi:
    MP:=exp(time*lnM1);
    for i from 2 to length(MP) do
    MP[i]:=MP[i]+MP[i-1];
    od;
    MP:=transpose(MP);
    len:=length(seq1);
    #seq2:='';
    seq2 := CreateString(len,'X'):
    if neutral then
        for i to len do
            n0:=NucToNInt(seq1[i]);
            n:=RandomNucleotide(MP[n0]):
            seq2[i] := n;
        od;
    else
        for i to len by 3 do
            c := CreateString(3,'X'):
            do
                n0 := NucToNInt(seq1[i]):
                c[1] := RandomNucleotide(MP[n0]):
                n0 := NucToNInt(seq1[i+1]):
                c[2] := RandomNucleotide(MP[n0]):
                n0 := NucToNInt(seq1[i+2]):
                c[3] := RandomNucleotide(MP[n0]):
                if CodonToInt(c) <> 22 then break fi:
            od:
            seq2[i] := c[1]:
            seq2[i+1] := c[2]:
            seq2[i+2] := c[3]:
        od:
    fi:
    seq2;
end:

NucleotideMutateGamma:=proc(seq1:string,time:list(positive), lnM1:matrix, 
                            classes:array(posint); (neutral=true):boolean)
    option internal;
    # prepare matrices for the different gamma classes
    MP := CreateArray(1..length(time),0):
    for i to length(MP) do
        MP[i]:=exp(time[i]*lnM1);
    od:
    
    for j to length(MP) do
        for i from 2 to length(MP[j]) do
        MP[j,i]:=MP[j,i]+MP[j,i-1];
        od;
        MP[j]:=transpose(MP[j]);
    od:

    # now mutate
    len:=length(seq1);
#    seq2:='';
    seq2 := CreateString(len,'X'):
    if neutral then
        for i to len do
            n0:=NucToNInt(seq1[i]);
            n:=RandomNucleotide(MP[classes[i], n0]):
            seq2[i] := n;
        od;
    else
        for i to len by 3 do
            c := CreateString(3,'X'):
            do
                n0 := NucToNInt(seq1[i]):
                c[1] := RandomNucleotide(MP[classes[(i+2)/3], n0]):
                n0 := NucToNInt(seq1[i+1]):
                c[2] := RandomNucleotide(MP[classes[(i+2)/3], n0]):
                n0 := NucToNInt(seq1[i+2]):
                c[3] := RandomNucleotide(MP[classes[(i+2)/3], n0]):
                if CodonToInt(c) <> 22 then break fi:
            od:
            seq2[i] := c[1]:
            seq2[i+1] := c[2]:
            seq2[i+2] := c[3]:
        od:    
    fi:
    seq2;
end:

####################################################################
# Map chars that represent nucleotides to integer numbers          #
# (used for the generic dynamic programming).			           #
####################################################################
NucleotideMappingString :='ACGT':
NucleotideMapping := proc(chr:string) option internal;
#define 64 characters for the codons plus 1 for 'unknown'
return(CaseSearchString(chr,NucleotideMappingString)+1);
end:


#######################################################
# Return a random nucleotide. The input is the vector #
# with cumulated nucleotide probabilities. (f[i]      #
# gives the probability of a nucleotide being on of   #
# nucleotide 1 to i.)                                 #
#######################################################
RandomNucleotide:=proc(CumFreq:array(numeric)) option internal;
    do
        ind:=SearchOrderedArray(Rand(),CumFreq) + 1;
        if ind<=4 then
          	c:=NIntToNuc(ind);
          	break;
          fi;
    od:
    c;
end:

end: # module