#include "copyright.h"

/* $XConsortium: XAllCells.c,v 11.18 89/12/09 19:14:31 rws Exp $ */
/* Copyright    Massachusetts Institute of Technology    1986	*/

/* -- 'Shared X' Version -- */

#define NEED_REPLIES

#include "Xlibint.h"
#include "XmuXlibint.h"

Status XAllocColorCells(calling_dpy, cmap, contig, masks, nplanes, pixels, ncolors)
register Display *calling_dpy;
Colormap cmap;
Bool contig;
unsigned int ncolors; /* CARD16 */
unsigned int nplanes; /* CARD16 */
unsigned long *masks; /* LISTofCARD32 */ /* RETURN */
unsigned long *pixels; /* LISTofCARD32 */ /* RETURN */
{

    Status status;
    xAllocColorCellsReply rep;
    register xAllocColorCellsReq *req;
    register Display *dpy ;

    register int                i ;
             unsigned long     *new_pixels = NULL ,
                               *new_masks = NULL ;
    if( nplanes )
	if( ( new_masks = ( unsigned long * ) 
	      Xmalloc( nplanes * sizeof( long ) ) ) == NULL )
	{
	    errno = ENOMEM ;  
	    ( * _XIOErrorFunction )( calling_dpy ) ;
	}
    if( ncolors )
	if( ( new_pixels = ( unsigned long * ) 
	      Xmalloc( ncolors * sizeof( long ) ) ) == NULL ) 
	{
	    errno = ENOMEM ;
	    ( * _XIOErrorFunction )( calling_dpy ) ;
	}

    /* -- flush default dpy to keep buffers aligned -- */
    XmuXFlushDefault( calling_dpy ) ;
    
    status = True ;
    for( i = 0 ; 
	 ( dpy = XmuXGetDisplay( calling_dpy , i ) ) != NULL && status ; i++ )
    {
	LockDisplay(dpy);
	GetReq(AllocColorCells, req);

	if( i != 0 )
	    req->cmap = XmuXMapID( dpy , cmap , FromClient ) ;
	else
	    req->cmap = cmap ;

	req->colors = ncolors;
	req->planes = nplanes;
	req->contiguous = contig;

	status = _XReply(dpy, (xReply *)&rep, 0, xFalse);

	if (status) 
	{
	    if( i == 0 )
	    {
		_XRead32 (dpy, (long *) pixels, 4L * (long) (rep.nPixels));
		_XRead32 (dpy, (long *) masks, 4L * (long) (rep.nMasks));

	    if( XmuXStoreResources( dpy ) )
		XmuXUpdateColormapInfo( dpy , cmap , pixels , ncolors ,
				        masks , nplanes , False , True ) ;
	    }
	    else
	    { 
                _XRead32 (dpy, (long *) new_pixels, 4L * (long) (rep.nPixels));
                _XRead32 (dpy, (long *) new_masks, 4L * (long) (rep.nMasks));
		
		XmuXInsertPrivateCells( dpy , req->cmap ,
				        pixels , new_pixels , ncolors ,
				        masks , new_masks , nplanes , True ) ;
	    }
	}
	UnlockDisplay(dpy);
	SyncHandle();
    }
    if( ncolors )
	Xfree( ( char * ) new_pixels ) ;
    if( nplanes )
	Xfree( ( char * ) new_masks ) ;
    return(status);
}
