home *** CD-ROM | disk | FTP | other *** search
- /* libpbm.c - pbm utility library
- **
- ** Copyright (C) 1988 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"
-
- int
- pbm_getint( file )
- FILE *file;
- {
- char ch;
- int i;
-
- do
- {
- ch = pbm_getc( file );
- }
- while ( ch == ' ' || ch == '\t' || ch == '\n' );
-
- if ( ch < '0' || ch > '9' )
- {
- fprintf( stderr, "Junk in file where an integer should be!\n" );
- exit( 1 );
- }
-
- i = 0;
- do
- {
- i = i * 10 + ch - '0';
- ch = pbm_getc( file );
- }
- while ( ch >= '0' && ch <= '9' );
-
- return ( i );
- }
-
-
- bit
- pbm_getbit( file )
- FILE *file;
- {
- char ch;
-
- do
- {
- ch = pbm_getc( file );
- }
- while ( ch == ' ' || ch == '\t' || ch == '\n' );
-
- if ( ch != '0' && ch != '1' )
- {
- fprintf( stderr, "Junk in file where bits should be!\n" );
- exit( 1 );
- }
-
- return ( ( ch == '1' ) ? 1 : 0 );
- }
-
- char
- pbm_getc( file )
- FILE *file;
- {
- int ich;
- char ch;
-
- ich = getc( file );
- if ( ich == NULL )
- {
- fprintf( stderr, "Premature EOF.\n" );
- exit( 1 );
- }
- ch = (char) ich;
-
- if ( ch == '#' )
- {
- do
- {
- ich = getc( file );
- if ( ich == NULL )
- {
- fprintf( stderr, "Premature EOF.\n" );
- exit( 1 );
- }
- ch = (char) ich;
- }
- while ( ch != '\n' );
- }
-
- return ( ch );
- }
-
- bit **
- pbm_allocarray( cols, rows )
- int cols, rows;
- {
- bit **bits;
- int i;
-
- bits = (bit **) malloc( rows * sizeof( bit *) );
- for ( i = 0; i < rows; i++ )
- {
- bits[i] = (bit *) malloc( cols * sizeof( bit ) );
- }
-
- return ( bits );
- }
-
-
- bit **pbm_readpbm( file, colsP, rowsP )
- FILE *file;
- int *colsP, *rowsP;
- {
- bit **bits;
- int row, col;
-
- *colsP = pbm_getint( file );
- *rowsP = pbm_getint( file );
-
- bits = pbm_allocarray( *colsP, *rowsP );
-
- for ( row = 0; row < *rowsP; row++ )
- for ( col = 0; col < *colsP; col++ )
- bits[row][col] = pbm_getbit( file );
-
- return ( bits );
- }
-
- pbm_writepbm( file, bits, cols, rows )
- FILE *file;
- bit **bits;
- int cols, rows;
- {
- int row, col, linecount;
-
- fprintf( file, "%d %d\n", cols, rows );
-
- for ( row = 0; row < rows; row++ )
- {
- linecount = 0;
- for ( col = 0; col < cols; col++ )
- {
- if ( linecount >= 70 )
- {
- putc( '\n', file );
- linecount = 0;
- }
- putc( bits[row][col] ? '1' : '0', file );
- linecount++;
- }
- putc( '\n', file );
- }
- }
-