#include<iostream>


struct Cellule {
  const char *id;
  int value;
  struct Cellule *next;
};




struct Cellule *createList(const char *const * t){
  if (t==NULL)
    throw "Invalid parameter";

  struct Cellule *l=NULL;
  for(int i=0;t[i]!=NULL;i++){
    struct Cellule *tmp=new struct Cellule;
    tmp->id=t[i];
    tmp->value=i;
    tmp->next=l;
    l=tmp;
  }
  return l;
}


void cleanList(struct Cellule *&l){
  while(l!=NULL){
    struct Cellule *tmp=l;
    l=l->next;
    delete tmp;
  }
}


struct Cellule &findList(struct Cellule &l,const char *word){
  struct Cellule *p=&l;
  while(p!=NULL){
    if (strcmp(p->id,word)==0)
      return *p;
    p=p->next;
  }
  throw "Word not found";
}

const struct Cellule &findList(const struct Cellule &l,const char *word){
  const struct Cellule *p=&l;
  while(p!=NULL){
    if (strcmp(p->id,word)==0)
      return *p;
    p=p->next;
  }
  throw "Word not found";
}


struct Cellule *concatList(const struct Cellule *l,const struct Cellule *m){
  struct Cellule *reversedList=NULL;
  while(l!=NULL){
    struct Cellule *tmp=new struct Cellule;
    tmp->id=l->id;
    tmp->value = l->value;
    tmp->next=reversedList;
    reversedList=tmp;
  }
  while(m!=NULL){
    struct Cellule *tmp=new struct Cellule;
    tmp->id=m->id;
    tmp->value = m->value;
    tmp->next=reversedList;
    reversedList=tmp;
  }
  struct Cellule *list=0;
  while(reversedList!=NULL){
    struct Cellule *tmp=reversedList;
    reversedList=reversedList->next;
    tmp->next=list;
    list=tmp;
  }
  return list;
}


std::ostream &operator<<(std::ostream &os,const struct Cellule *l){
  while(l!=NULL){
    os<<l->id<<"/"<<l->value<<std::endl;
    l=l->next;
  }
  return os;
}


int main(int argc, const char *const *argv,const char *const *arge){

  try{
  
    struct Cellule *arguments=createList(argv);
    struct Cellule *environment=createList(arge);
    
    char buffer[100];
    std::cout<<"*** Prog. Arguments ***"<<std::endl;
    std::cout<<arguments;
    std::cout<<"*** Environment Variables ***"<<std::endl;
    std::cout<<environment;
    
    std::cin>>buffer;

    std::cout<<"Looking for in prog. arg.:"<<buffer<<std::endl;

    struct Cellule &result=findList(*arguments,buffer);

    std::cout<<"Word \""<<buffer<<"\" found at position "<<result.value<<std::endl;
    
  }
  catch (const char *e){
    std::cerr<<"Exception: "<<e<<std::endl;
  }
  catch(...){
    std::cerr<<"Unknown Exception"<<std::endl;
  }
  return 0;
}
