/* logic.js - part of the dna-rna-amino package
 * Licensed under the MIT license found in the file LICENSE
 * If the text of the license is not included, refer to this
 * website for the terms of the license:
 *   http://www.opensource.org/licenses/mit-license.php
 */
var baseDNA = "ACGT";
var baseRNA = "UGCA";
var DNA_to_RNA = new Object();
var RNA_to_DNA = new Object();

for (var i = 0; i < 4; i++) {
  DNA_to_RNA[baseDNA.charAt(i)] = baseRNA.charAt(i);
  RNA_to_DNA[baseRNA.charAt(i)] = baseDNA.charAt(i);
}

function _converter (table) {
  return function (s) {
    var result = "";
    for (var i = 0; i < s.length; i++) {
      if (i % 3 == 0)
	result += " ";
      result += table[s.charAt(i)];
    }
    return result;
  };
}
var convertDNA_to_RNA = _converter(DNA_to_RNA);
var convertRNA_to_DNA = _converter(RNA_to_DNA);

function verifySequence (s, baseSequence) {
  var result = "";
  for (var i = 0; i < s.length - (s.length % 3);i++)
    if (baseSequence.indexOf(s.charAt(i)) >= 0)
      result += s.charAt(i);
  return result;
}

function _cleanup_sequence (s, baseSequence) {
  //console.log("cleaning up: /%s/", s);
  return s.toUpperCase().replace(new RegExp("[^" + baseSequence + "]", "g"), "");
}

function isSequenceCorrectLength (s) {
  //console.log("checking: /%s/", s);
  return s.length % 3 == 0;
}

function transcribeDNA (DNAsequence) {
  return convertDNA_to_RNA(verifySequence(DNAsequence, baseDNA));
}

function reverseTranscribe(RNAsequence){
  return convertRNA_to_DNA(verifySequence(RNAsequence, baseRNA));
}

function aminoTranslateLoop (head, tail) {
  //console.log("The length of head: %d", head.length);
  //console.log("The length of tail: %d", tail.length);
  if (tail.length == 0)
    return [aminoKeys[head]];
  return [aminoKeys[head]].concat(aminoTranslateLoop(tail.substring(0, 3),
						     tail.substring(3)));
}

function aminoTranslate (RNAsequence) {
  if (RNAsequence.length == 0)
    return "";
  var rnaString = verifySequence(RNAsequence, baseRNA);
  return aminoTranslateLoop(rnaString.substring(0, 3),
			    rnaString.substring(3));
}

function aminoTotal (aminosList, memberVar) {
  // Calculates the sum of the memberVars of all the elements in
  // the aminosList.
  var total = 0.0;
  for (var i = 0; i < aminosList.length; i++) {
    total += aminosList[i][memberVar];
  }
  return total;
}