#include 	<math.h>
#include	<memory.h>
#include 	<string.h>
/****Copyright (c) 1997,1998,1999-2002 All rights reserved
 ****A. V. Gerbessiotis and C. J. Siniolakis
 ****Permission to use, copy, modify, and distribute this software,
 ****and to incorporate it, in whole or in part, into 
 ****other software,is hereby granted without fee, provided that
 ****  (1) the above copyright notice and this permission 
 ****      notice appear in all copies of the source code, and 
 ****      the above copyright notice appear in clearly visible 
 ****      form on all supporting documentation and distribution 
 ****      media, and
 ****     (2) any redistribution of the software, in original
 ****         or modified form, be without fee and subject to
 ****         these same conditions.
 ****   No guarantee, whatsoever, is offered that the code works as
 ****   advertised or is absent of any, even damaging,
 ****   side-effects. Use this code at your own personal risk.
 ****/

void	mergerg(char *src1, char *src2, int m, int k, 
              int size, int (*compare)())
{
	char *temp;
	register int i,j,l;


  if (((m <= 0)  && (k <= 0)) || (size <= 0)) return ;

  temp = (char *) malloc((m+k)*size);
#ifdef SANITY_CHECK
	if (temp == NULL)
	{
               	printf("merge: malloc ERROR\n");
                return;	
	}
#endif

  i = j = l = 0 ;
  while ((i < m) && (j < k))
    {
      if (compare(&src1[i*size], &src2[j*size]) < 0)
        {
          memcpy(&temp[l*size], &src1[i*size], size) ;
          ++i ; ++l ;
        }
      else
        {
          memcpy(&temp[l*size], &src2[j*size], size) ;
          ++j ; ++l ;
        }
    }

  if (i < m) memcpy(&temp[l*size], &src1[i*size], (m - i) * size) ;
  if (j < k) memcpy(&temp[l*size], &src2[j*size], (k - j) * size) ;

  memcpy(src1, temp, m * size) ;
  memcpy(src2, &temp[m*size], k * size) ;

  free((void *)temp);
}




void	merger2g(char *src1,char *src2,int m,int k,int size,int (*compare)())
{
 char *temp,*tmp,*first1,*last1,*first2,*last2;
 register int i,j,l;

  if (((m <= 0)  && (k <= 0)) || (size <= 0)) return ;

  tmp = (char *) malloc((m+k)*size);
  if (temp == NULL) {
     printf("merge: malloc ERROR\n"); return;	
  }

  first1=src1;first2=src2;
  last1 =&src1[(m-1)*size];
  last2 =&src2[(k-1)*size];
  temp=tmp;

    for (; first1 != last1 && first2 != last2; temp+=size)
        if (compare(first2,first1)<0) {
	   memcpy(temp,first2,size);
 	   first2+=size;
        } 
	else {
	   memcpy(temp,first1,size);
 	   first1+=size;
	}
/*
    for (; first1 != last1 ; temp+=size,first1+=size) 
         memcpy(temp,first1,size);
    for (; first2 != last2 ; temp+=size,first2+=size) 
         memcpy(temp,first2,size);
*/
    if ( first1 != last1) 
         memcpy(temp,first1,(last1-first1));
    if ( first2 != last2) 
         memcpy(temp,first2,(last2-first2));

  memcpy(src1,tmp,m*size) ;
  memcpy(src2,&tmp[m*size],k*size) ;

  free((void *)tmp);
}
