/*
 * Levenstein.js
 * Javascript implementation of Levenshtein distance.
 * It is only a port of the Java code of Michael Gilleland and Merriam Park Software
 * You can find the original version on http://www.merriampark.com/ld.htm
 * Copyright (c) 2000-2001 Alexis Grandemange
 * Mail: alexis.grandemange@pagebox.net
 * This program is free software; you can redistribute it and/or
 * modify it under the terms of the GNU Lesser General Public
 * License as published by the Free Software Foundation; version
 * 2.1 of the License.
 * This library is distributed in the hope that it will be useful,
 * but WITHOUT ANY WARRANTY; without even the implied warranty of
 * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
 * GNU Lesser General Public License for more details.
 * A copy of the GNU Lesser General Public License lesser.txt should be
 * included in the distribution.
 */
//****************************
// Get minimum of three values
//****************************
function Minimum (a, b, c) {
  var mi = a;
  if (b < mi)
    mi = b;
  if (c < mi)
    mi = c;
  return mi;
}
//*****************************
// Compute Levenshtein distance
// Parameters:
// Strings to compare
//*****************************
function Levenshtein (s, t) {
  var d;	// matrix
  var n;	// length of s
  var m;	// length of t
  var i;	// iterates through s
  var j;	// iterates through t
  var s_i;	// ith character of s
  var t_j;	// jth character of t
  var cost;	// cost
  // Step 1
  n = s.length;
  m = t.length;
  if (n == 0)
    return m;
  if (m == 0)
    return n;
  // d = new var[n+1][m+1];
  d = new Array(n+1);
  for (var k = 0; k <= n+1; ++k)
    d[k] = new Array(m+1);
  // Step 2
  for (i = 0; i <= n; i++)
    d[i][0] = i;
  for (j = 0; j <= m; j++)
    d[0][j] = j;
  // Step 3
  for (i = 1; i <= n; i++) {
    s_i = s.charAt (i - 1);
    // Step 4
    for (j = 1; j <= m; j++) {
      t_j = t.charAt (j - 1);
      // Step 5
      if (s_i == t_j)
        cost = 0;
      else
        cost = 1;
      // Step 6
      d[i][j] = Minimum (d[i-1][j]+1, d[i][j-1]+1, d[i-1][j-1] + cost);
    }
  }
  // Step 7
  return d[n][m];
}
// To test Levenshtein in WSH
var argsNamed = WScript.Arguments.Named;
var str1;
var str2;
if (argsNamed.Exists("str1")) 
  str1 = argsNamed.Item("str1");
else {
  WScript.Echo("Usage: levenshtein.js /str1:string /str2:string");
  exit;
}
if (argsNamed.Exists("str2")) 
  str2 = argsNamed.Item("str2");
else {
  WScript.Echo("Usage: levenshtein.js /str1:string /str2:string");
  exit;
}
WScript.Echo("Distance between " + str1 + " and " + str2 + " = " + Levenshtein(str1, str2));

