/* libpgm2.c - pgm utility library part 2 ** ** 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 "pgm.h" #include "libpgm.h" void pgm_writepgminit( FILE* file, int cols, int rows, gray maxval, int forceplain ) { #ifdef PGM_BIGGRAYS if ( maxval <= 65535 && ! forceplain ) #else /* PGM_BIGGRAYS */ if ( maxval <= 255 && ! forceplain ) #endif /* PGM_BIGGRAYS */ fprintf( file, "%c%c\n%d %d\n%d\n", PGM_MAGIC1, RPGM_MAGIC2, cols, rows, maxval ); else fprintf( file, "%c%c\n%d %d\n%d\n", PGM_MAGIC1, PGM_MAGIC2, cols, rows, maxval ); } static void putus( unsigned short n, FILE* file ) { if ( n >= 10 ) putus( n / 10, file ); (void) putc( n % 10 + '0', file ); } static void pgm_writepgmrowraw( FILE* file, gray* grayrow, int cols, gray maxval ) { #if defined(DEBUG) || defined(PGM_BIGGRAYS) int col; gray* gP; #endif #ifdef DEBUG for ( col = 0, gP = grayrow; col < cols; ++col, ++gP ) if ( *gP > maxval ) pm_error( "value out of bounds (%u > %u)", *gP, maxval ); #endif /*DEBUG*/ #ifdef PGM_BIGGRAYS if ( maxval > 255 ) { for ( col = 0, gP = grayrow; col < cols; ++col, ++gP ) if ( pm_writelittleshort( file, *gP ) < 0 ) pm_error( "write error" ); } else if ( fwrite( grayrow, 1, cols, file ) != cols ) pm_error( "write error" ); #else /* PGM_BIGGRAYS */ if ( fwrite( grayrow, 1, cols, file ) != cols ) pm_error( "write error" ); #endif /* PGM_BIGGRAYS */ } static void pgm_writepgmrowplain( FILE* file, gray* grayrow, int cols, gray maxval ) { int col, charcount; gray* gP; charcount = 0; for ( col = 0, gP = grayrow; col < cols; ++col, ++gP ) { if ( charcount >= 65 ) { (void) putc( '\n', file ); charcount = 0; } else if ( charcount > 0 ) { (void) putc( ' ', file ); ++charcount; } #ifdef DEBUG if ( *gP > maxval ) pm_error( "value out of bounds (%u > %u)", *gP, maxval ); #endif /*DEBUG*/ putus( (unsigned long) *gP, file ); charcount += 3; } if ( charcount > 0 ) (void) putc( '\n', file ); } void pgm_writepgmrow( FILE* file, gray* grayrow, int cols, gray maxval, int forceplain ) { #ifdef PGM_BIGGRAYS if ( maxval <= 65535 && ! forceplain ) #else /* PGM_BIGGRAYS */ if ( maxval <= 255 && ! forceplain ) #endif /* PGM_BIGGRAYS */ pgm_writepgmrowraw( file, grayrow, cols, maxval ); else pgm_writepgmrowplain( file, grayrow, cols, maxval ); } void pgm_writepgm( FILE* file, gray** grays, int cols, int rows, gray maxval, int forceplain ) { int row; pgm_writepgminit( file, cols, rows, maxval, forceplain ); for ( row = 0; row < rows; ++row ) pgm_writepgmrow( file, grays[row], cols, maxval, forceplain ); }