#!/usr/bin/env slsh

% Copyright (C) 2005-2010 John E. Davis

% This file is part of the S-Lang Curl Module

% This script is free software; you can redistribute it and/or
% modify it under the terms of the GNU General Public License as
% published by the Free Software Foundation; either version 2 of the
% License, or (at your option) any later version.

% The script 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
% General Public License for more details.

% You should have received a copy of the GNU General Public License
% along with this library; if not, write to the Free Software
% Foundation, Inc., 59 Temple Place - Suite 330, Boston, MA 02111-1307,
% USA.

private variable Script_Version = "1.1.0";

require ("babelfish");
require ("cmdopt");

private variable My_Language = "English";

private define make_encode_table ()
{
   variable table = array_map (String_Type, &sprintf, ("%%%02X", [0:255]));
   variable ok = [['A':'Z'], ['a':'z'], ['0':'9'], '.', '-', '*', '_', '/', '~'];
   table[ok] = array_map (String_Type, &char, ok);
   table[' '] = "+";
   return table;
}
private variable Encode_Table = make_encode_table ();

private define encode (text)
{
   variable len = strbytelen (text);
   variable new_text = String_Type[len];
   variable i;
   _for i (0, len-1, 1)
     new_text[i] =  Encode_Table[text[i]];
   return strjoin (new_text, "");
}

private define usage ()
{
   variable pgm = path_basename (__argv[0]);
   () = fprintf (stderr, "%s version %S\n", pgm, Script_Version);
   () = fprintf (stderr, "Usage: %s [--to lang-out] lang-in [phrase|-]\n", pgm);
   exit (1);
}

define slsh_main ()
{
   variable lang_out = My_Language, lang_in = NULL;

   variable c = cmdopt_new ();
   c.add ("to", &lang_out; type="str");
   c.add ("h|help", &usage);
   c.add ("v|version", &usage);
   variable i = c.process (__argv, 1);

   if (i + 1 > __argc)
     usage ();

   lang_in = __argv[i]; i++;

   variable text = "-";
   if (i == __argc)
     {
	if (isatty (stdin))
	  usage ();
     }
   else text = strjoin (__argv[[i:]], " ");

   if (text == "-")
     {
	text = "";
	variable line;
	while (-1 != fgets (&line, stdin))
	  text = strcat (text, line);
     }
   message (babelfish (lang_in, lang_out, encode (text)));
}

