/* pbmtocmuwm.c - read a portable bitmap and produce a CMU window manager bitmap
**
** Copyright (C) 1989 by Jef Poskanzer.
**
** Permission to use, copy, modify, and distribute this software and its
** documentation for any purpose and without fee is hereby granted, provided
** that the above copyright notice appear in all copies and that both that
** copyright notice and this permission notice appear in supporting
** documentation.  This software is provided "as is" without express or
** implied warranty.
*/

#include <stdio.h>
#include "pbm.h"
#include "cmuwm.h"

main( argc, argv )
int argc;
char *argv[];
    {
    FILE *ifd;
    register bit *bitrow, *bP;
    int rows, cols, format, padright, row, col;

    pm_progname = argv[0];

    if ( argc > 2 )
	pm_usage( "[pbmfile]" );

    if ( argc == 2 )
	ifd = pm_openr( argv[1] );
    else
	ifd = stdin;

    pbm_readpbminit( ifd, &cols, &rows, &format );
    bitrow = pbm_allocrow( cols );
    
    /* Round cols up to the nearest multiple of 8. */
    padright = ( ( cols + 7 ) / 8 ) * 8 - cols;

    putinit( rows, cols );
    for ( row = 0; row < rows; row++ )
	{
	pbm_readpbmrow( ifd, bitrow, cols, format );
        for ( col = 0, bP = bitrow; col < cols; col++, bP++ )
	    putbit( *bP );
	for ( col = 0; col < padright; col++ )
	    putbit( 0 );
        }

    pm_close( ifd );

    putrest( );

    exit( 0 );
    }


unsigned char item;
int bitsperitem, bitshift;

putinit( rows, cols )
int rows, cols;
    {
    put_big_long( stdout, CMUWM_MAGIC );
    put_big_long( stdout, cols );
    put_big_long( stdout, rows );
    put_big_short( stdout, 1 );

    item = 0;
    bitsperitem = 0;
    bitshift = 7;
    }

putbit( b )
bit b;
    {
    if ( bitsperitem == 8 )
	putitem( );
    if ( b == PBM_WHITE )
	item += 1 << bitshift;
    bitsperitem++;
    bitshift--;
    }

putrest( )
    {
    if ( bitsperitem > 0 )
	putitem( );
    }

putitem( )
    {
    put_byte( stdout, item );
    item = 0;
    bitsperitem = 0;
    bitshift = 7;
    }


put_byte( f, b )
FILE *f;
unsigned char b;
    {
    if ( putc( b, f ) == EOF )
	{
	perror( "put_byte" );
	exit( 1 );
	}
    }

put_big_short( f, s )
FILE *f;
short s;
    {
    put_byte( f, s >> 8 );
    put_byte( f, s & 0xff );
    }

put_big_long( f, l )
FILE *f;
long l;
    {
    put_byte( f, l >> 24 );
    put_byte( f, ( l >> 16 ) & 0xff );
    put_byte( f, ( l >> 8 ) & 0xff );
    put_byte( f, l & 0xff );
    }
