/* cmuwmtopbm.c - read a CMU window manager bitmap and produce a portable 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, depth, padright, row, col;
    bit getbit();

    pm_progname = argv[0];

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

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

    getinit( ifd, &cols, &rows, &depth, &padright );
    if ( depth != 1 )
	pm_error(
	    "CMU window manager file has depth of %d, must be 1",
	    depth, 0,0,0,0 );

    pbm_writepbminit( stdout, cols, rows );
    bitrow = pbm_allocrow( cols );

    for ( row = 0; row < rows; row++ )
	{
	/* Get data. */
        for ( col = 0, bP = bitrow; col < cols; col++, bP++ )
	    *bP = getbit( ifd );
	/* Discard line padding */
        for ( col = 0; col < padright; col ++ )
	    (void) getbit( ifd );
	pbm_writepbmrow( stdout, bitrow, cols );
	}

    pm_close( ifd );

    exit( 0 );
    }


unsigned char item;
int bitsperitem, bitshift;

getinit( file, colsP, rowsP, depthP, padrightP )
FILE *file;
int *colsP, *rowsP, *depthP, *padrightP;
    {
    long magic;
    long get_big_long();
    short get_big_short();

    magic = get_big_long( file );
    if ( magic != CMUWM_MAGIC )
	pm_error( "bad magic number in CMU window manager file", 0,0,0,0,0 );
    *colsP = get_big_long( file );
    *rowsP = get_big_long( file );
    *depthP = get_big_short( file );
    *padrightP = ( ( *colsP + 7 ) / 8 ) * 8 - *colsP;

    bitsperitem = 0;
    }

bit
getbit( file )
FILE *file;
    {
    bit b;
    unsigned char get_byte();

    if ( bitsperitem == 0 )
	{
	item = get_byte( file );
	bitsperitem = 8;
	bitshift = 7;
	}
    b = ( ( item >> bitshift) & 1 ) ? PBM_WHITE : PBM_BLACK;
    bitsperitem--;
    bitshift--;
    return b;
    }

unsigned char
get_byte( f )
FILE *f;
    {
    int i;

    i = getc( f );
    if ( i == EOF )
	pm_error( "premature EOF", 0,0,0,0,0 );

    return (unsigned char) i;
    }

short
get_big_short( f )
FILE *f;
    {
    short s;

    s = get_byte( f ) << 8;
    s |= get_byte( f );

    return s;
    }

long
get_big_long( f )
FILE *f;
    {
    long l;

    l = get_byte( f ) << 24;
    l |= get_byte( f ) << 16;
    l |= get_byte( f ) << 8;
    l |= get_byte( f );

    return l;
    }
