#include "vektor.h"
#include "printer.h"
#include "parser.h"
#include "gfanapplication.h"

typedef list<string> StringList;

class SubstituteApplication : public GFanApplication
{
public:
  const char *helpText()
  {
    return "This program substitutes the variable names of a text string. The input is a list of the variable names in the original string. The new variable names will be a, b, c... After the list of variables the text string is read from the input. Everything matching one of the variable names is substituted. The new string is written to the output. When typing data into this program the user should end the typing with Ctrl-D. It is not possible to do the substitution the other way around with the current code.\n"
      "Example:\n"
      "Input:\n"
      "(x[1],x[2])(x[0]-2x[2])\n"
      "Output:\n"
      "(x[0]-2b)\n";
  }
  SubstituteApplication()
  {
    registerOptions();
  }
  char *name()
  {
    return "_substitute";
  }
  string charToString(char c)
  {
    char S[2];S[0]=c;S[1]=0;
    return string(S);
  }
  int matches(StringList const &l, string const &s)
  {
    int i=0;
    for(StringList::const_iterator I=l.begin();I!=l.end();I++)
      {
	if(*I==s)return i;
	i++;
      }
    return -1;
  }
  int main()
  {
    StringList l;
    FileParser P(Stdin);
    
    int c=P.nextNonBlank();

    assert(P.isLeftBrackets(c));
    do
      {
	string s;
	c=P.nextNonBlank();
	while(c!=')' && c!=',' && c!=0)
	  {
	    s+=charToString(c);
	    c=P.nextNonBlank();
	  }
	l.push_back(s);
      }
    while(c==',');

    int I=0;
    for(StringList::const_iterator i=l.begin();i!=l.end();i++)
      {
	AsciiPrinter(Stderr).printVariable(I++);
	fprintf(Stderr," %s\n",i->c_str());
      }

    string d;
    c=P.nextNonBlank();
    while(c)
      {
	d+=charToString(c);
	c=P.parseChar();
      }

    for(int t=0;t<d.size();t++)
      {
	StringList::const_iterator m=l.end();
	int mi=-1;
	int matchLength=1;
	int i=0;
	for(StringList::const_iterator I=l.begin();I!=l.end();I++)
	  {
	    bool match=true;
	    for(int k=0;k!=I->size();k++)
	      if((*I)[k]!=d[t+k])
		{
		  match=false;
		  break;
		}
	    if(match && I->size()>=matchLength){
	      m=I;
	      mi=i;
	      matchLength=m->size();
	    }
	    i++;
	  }
	if(m!=l.end())
	  {
	    AsciiPrinter(Stdout).printVariable(mi);
	    t+=matchLength-1;
	  }
	else
	  fprintf(Stdout,"%c",d[t]);
      }

    return 0;
  }
};

static SubstituteApplication theApplication;
