/* Multq.c */
/* Multiplying two quaternions, given the 8 integer coefficients in the
     1, i, j, k order */
#include <stdio.h>
void MULT(int*,int*,int*);
void PRNT(int*);

void main(void)
{
int I,P[5],Q[5],PROD[5];
char CH;

  puts("The PRODUCT of two quaternions each with integer coefficients");
  puts("if a term is missing, then use zero (0) as coefficient\n");
LP:
  puts("First quaternion:");
  puts("Input 4 integer coefficients, separated by spaces. Then press Enter");
  for (I=0; I<4; I++) scanf("%d",&P[I]);

  puts("Second quaternion:");
  puts("Input 4 integer coefficients, separated by spaces. Then press Enter");
  for (I=0; I<4; I++) scanf("%d",&Q[I]);
  getchar();  /* dummy pause */

  printf("\n\nThe product of quaternions p = "); PRNT(P);
  printf("  and q = "); PRNT(Q);
  printf("\n  in that order =  ");
  MULT(P,Q,PROD); PRNT(PROD);

  printf("\n\nThe product of quaternions q = "); PRNT(Q);
  printf("  and p = "); PRNT(P);
  printf("\n  in that order =  ");
  MULT(Q,P,PROD);  PRNT(PROD);


  printf("\n\nmore?  "); CH = (char)getchar();
  if (CH=='Y' || CH=='y') goto LP;
}

/***********************/

void MULT(int* P1,int* P2,int* P3)
 /* receive two pairs of quadruples of real numbers pointed to by P1,P2;
    return a quadruple pointed to by P3, the quaternion product of the two
    the first two quadruples */
{
 int a1,b1,c1,d1,a2,b2,c2,d2,a,b,c,d;

 a1=*P1; P1++;  b1=*P1; P1++;  c1=*P1; P1++;  d1=*P1;
 a2=*P2; P2++;  b2=*P2; P2++;  c2=*P2; P2++;  d2=*P2;

 a = a1*a2 - b1*b2 - c1*c2 - d1*d2;
 b = b1*a2 + a1*b2 - d1*c2 + c1*d2;
 c = c1*a2 + d1*b2 + a1*c2 - b1*d2;
 d = d1*a2 - c1*b2 + b1*c2 + a1*d2;


 *P3=a; P3++;  *P3=b; P3++;  *P3=c; P3++;  *P3=d;
 return;
}

/***************/

void PRNT(int* P)    /* receive 4 coefficients of a quaternion in order */
{
 int I,MARK=0;  char UNIT[] = " ijk";

 for (I=0; I<4; I++) if (P[I])
  {
   if (P[I]==1) {if (MARK) printf("+"); printf(" %c ",UNIT[I]);} else
   if (P[I]==-1) printf("- %c ",UNIT[I]); else
   if (P[I]>1)  {if (MARK) printf("+"); printf(" %d%c ",P[I],UNIT[I]);}    else
   if (P[I]<1)  printf("- %d%c ",-P[I],UNIT[I]);
   MARK++;
  }
 return;
}

