%{
#include <stdio.h>
typedef struct diff {char *a; char *b;} DIFF;
char  *temp,*temp1;
 strcatt5(char *x, char *y, char *z, char *w, char *v,char *r)
{ strcat(r,x);
  strcat(r,y);
  strcat(r,z);
  strcat(r,w);
  strcat(r,v);
}
 strcatt7(char *x, char *y, char *z, char *w, char *v,char *p, char *q,char *r)
{ 
 strcatt5(x,y,z,w,v,r);
 strcat(r,p);
  strcat(r,q);
}
yydebug=1;
char *plus="+";
char *star="*";
char *lp="(";
char *rp=")";
char *minus="-";
char *blank=" ";
char *carat="^";
int y;
#define YYSTYPE DIFF
%}
%left '=' ';'
%left '+' '-'
%left '*' '/' '<'
%left '^'
%token INTEGER
%%
 strt:    lines  
        ;
 lines:
        |  lines line 
        ;

line:  expr ';' { printf("%s\n",$1.a);}
            ;
expr: INTEGER   { $$.a=(char *)malloc(100);$$.b=(char *)malloc(10);$$.a="0";
                  strcpy($$.b,$1.a);}
    | 'x'       { $$.a=(char *)malloc(10);$$.b=(char *)malloc(10);$$.a="1";
                  $$.b="x";}
    | '(' expr ')' {  $$.a=(char *)malloc(200);$$.b=(char *)malloc(200);
                  strcpy($$.a,$2.a); strcpy($$.b,$2.b);}

    | expr '+' expr  { $$.a=(char *)malloc(200);$$.b=(char *)malloc(200);
                  strcatt5(lp,$1.a,plus,$3.a,rp,$$.a);
                  strcatt5(lp, $1.b,plus,$3.b,rp,$$.b);}
    | expr '-' expr  { $$.a=(char *)malloc(200);$$.b=(char *)malloc(200);
                  strcatt5(lp,$1.a,minus,$3.a,rp,$$.a);
                  strcatt5(lp, $1.b,minus,$3.b,rp,$$.b);}
    |   expr '*' expr  { $$.a=(char *)malloc(300);$$.b=(char *)malloc(200);
                  temp=(char *) malloc(300); temp1=(char *) malloc(300);
                  strcatt5(lp,$1.a,star,$3.b,rp,temp); 
                  strcatt5(lp,$1.b,star,$3.a,rp,temp1);
                  strcatt5(lp,temp,plus,temp1,rp,$$.a);
                  strcatt5( lp,$1.b,star,$3.b,rp,$$.b);}
   | expr '^' INTEGER { y =atoi($3.a); printf("%d\n",y);
                        $$.a=(char *)malloc(300);$$.b=(char *)malloc(200);
                        if (y==0) {printf("error\n");$$.a="0";
                        $$.b="0";} else { y=y-1; 
                         temp=(char *) malloc(200);
                         temp1=(char *) malloc(200);
                         sprintf(temp,"%d",y); 
                         strcatt7($3.a,star,lp,$1.b,rp,carat,temp,temp1);
                         strcatt5(lp,$1.a,rp,star,temp1,$$.a);
                         strcatt5($1.b,carat,$3.a,blank,blank,$$.b);}
                   
                       }
    ;
%%
#include "lex.yy.c"
main()
{  
   yyparse();
 }
