/*
# proc: transpose_binary_image - takes a binary image and transposes its
# proc:                          rows and columns of pixels.
*/

/* LINTLIBRARY */

/*
 * Stan Janet
 * 1/17/91
 *
 * Transpose a binary image p_in of dimensions w by h.
 * The result is placed in p_out, which should have
 * dimensions roundup(h,8) by w.
 *
 */

#include <stdio.h>
#include <values.h>
#include <sys/types.h>
#include <sys/param.h>

#define SUBR_STR	"transpose_binary_image"


transpose_binary_image(p_in,w,h,p_out)
u_char *p_in, *p_out;
u_int w, h;
{
int i, j, ii, jj;
u_int bw, bh, hpad, scanline, indx;
u_char **q, *b;
register u_char byte, m;
extern char *malloc();

if (p_in == (u_char *) NULL)
	fatalerr(SUBR_STR,"null input buffer pointer",(char *)NULL);
if (p_out == (u_char *) NULL)
	fatalerr(SUBR_STR,"null output buffer pointer",(char *)NULL);
if (w % BITSPERBYTE)
	fatalerr(SUBR_STR,"width not multiple of byte size",(char *)NULL);

if (w == 0)
	return;

q = (u_char **) malloc(w * sizeof(char *));
if (q == (u_char **) NULL)
	fatalerr(SUBR_STR,"malloc failed",(char *)NULL);

b = (u_char *) malloc(w);
if (b == (u_char *) NULL)
	fatalerr(SUBR_STR,"malloc failed",(char *)NULL);

bw = w / BITSPERBYTE;
hpad = roundup(h,BITSPERBYTE);
bh = hpad / BITSPERBYTE;

/*
(void) printf("w=%u h=%u hpad=%u     bw=%u bh=%u\n",w,h,hpad,bw,bh);
*/

for (i=0; i<w; i++)
	q[i] = p_out + i * bh;

memset((char *)p_out,NULL,(int)(w*bh));

scanline = 0;
for (j=0; j < bh; j++) {
	memset((char *)b,NULL,(int)w);
	for (jj=0; (jj < BITSPERBYTE) && (scanline < h); jj++) {
		scanline++;
		m = 0x1 << ((BITSPERBYTE - 1) - jj);
		indx = 0;
		for (i=0; i < bw; i++) {
			byte = *p_in++;
			/*
			(void) printf("byte=%.2x\n",byte);
			*/
			for (ii=0; ii < BITSPERBYTE; ii++) {
				if (byte & (0x1 << ((BITSPERBYTE - 1) - ii))) {
					b[indx] |= m;
					/*
					(void) printf("  b[%d]=%.2x\n",
							indx,b[indx]);
					*/
				}
				indx++;
			}
		}
	}
	for (i=0; i<w; i++)
		*q[i]++ = b[i];
}

free((char *)q);
free((char *)b);
}

