/*
 * Copyright (C) 2005 Universitat d'Alacant / Universidad de Alicante
 *
 * This program 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.
 *
 * This program 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 program; if not, write to the Free Software
 * Foundation, Inc., 59 Temple Place - Suite 330, Boston, MA
 * 02111-1307, USA.
 */

#include <string>
#include <iostream>
#include <cstdio>
#include <list>

using namespace std;

int trans[] = {0xc9, 0x71, 0xc9, 0x70, 0xc7, 0xc9,
               0xc6, 0xc9, 0xc4, 0xc9, 0xca, 0x6c, 
               0xc9, 0x75, 0x6f, 0x64, 0x62, 0xc9,
               0x73, 0xca, 0x6e, 0xca, 0xca, 0x78,
               0xca, 0x7a};

wint_t trans2[] = {0x90,  0x0, 0x94,  0x0, 0x9d, 0x9f,
                   0x83, 0xa5, 0xb1, 0xbe, 0x9e,  0x0,
                   0xaf,  0x0,  0x0,  0x0,  0x0, 0xb9,
                    0x0, 0x87,  0x0, 0x8c, 0x8d,  0x0,
                   0x8e,  0x0};

wstring 
readFullBlock(FILE *input, wchar_t const delim1, wchar_t const delim2)
{
  wstring result = L"";
  result += delim1;
  wchar_t c = delim1;

  while(!feof(input) && c != delim2)
  {
    c = static_cast<wchar_t>(fgetwc(input));
    result += c;
    if(c != L'\\')
    {
      continue;
    }
    else
    {
      //result += L'\\';
      c = static_cast<wchar_t>(fgetwc(input));
      result += c;
    }
  }   

  if(c != delim2)
  {
    cerr << "Error!" << endl;
    exit(1);
  }

  return result;
}

int
main (int argc, char** argv)
{
  wstring buf = L"";
  list<wstring> blankbuf;

  while(!feof(stdin))
  {
    wint_t c = fgetwc(stdin);

    if(c >= 65 && c <= 90)
    {
      if(trans2[(c-65)] != 0)
      {
        buf += (wchar_t) trans2[(c-65)];
      }
      buf += (wchar_t) trans[(c-65)];
    }
    else if(c >= 97 && c <= 122)
    {
      if(trans2[(c-97)] != 0)
      {
        buf += (wchar_t) trans2[(c-97)];
      }
      buf += (wchar_t) trans[(c-97)];
    }
    else if(c == (wint_t) ' ')
    {
      buf += L' ';
      blankbuf.push_back(L" ");
    }
    else if(c == (wint_t) '\\')
    {
      c = fgetwc(stdin);
      buf += c;
      buf += L'\\';
    }
    else if(c == (wint_t) '[')
    {
      buf += L' ';
      blankbuf.push_back(readFullBlock(stdin, L'[', L']'));
    }
    else
    {
      buf += c;
    } 
  }

  for(int i=buf.length(); i >= 0; i--)
  {
    if(buf[i] != L' ')
    {
      fputwc((wchar_t) buf[i], stdout);
    }
    else
    {
      wstring tmpblank = blankbuf.front();
      fputws(tmpblank.c_str(), stdout);
      blankbuf.pop_front();
    }
  }
  return 0;
}

