function a = pnm_write(t, name, a1, a2, a3)
#
# PNM_WRITE( t, name, a1 [, a2, a3] ) - write a pnm file
#
#   t:      indicates typ of file
#           {"pbm-ascii", "pbm-raw", "pgm-ascii", "pgm-raw",
#           "ppm-ascii", "ppm-raw"}
#   name:   file name
#   a1:     gray scale image for pbm and pgm, read image for ppm
#   a2,a3:  green and blue images for ppm
#

    [file, msg] = fopen( name, "w" );
    if ( file == -1 )
        error( msg );
    endif
    
    [nr, nc] = size(a1);
    
    # determine pbm, pgm, or ppm
    switch( t(1:3) )
    case ( "pbm" )
        error( "pbm not implemented" );
    case ( "pgm" )
        if ( nargin != 3 )
            usage( "pnm_write( typ, name, a1 [, a2, a3] )" );
        endif
        if ( index(t, "ascii") == 5 )
            % fprintf( file, "P2\n%d %d %d\n", nc, nr, max(max(a1)) );
            fprintf( file, "P2\n%d %d %d\n", nc, nr, 255 );
            fprintf( file, "%d %d %d %d %d %d %d %d\n", round(a1') );
        elseif ( index(t, "raw") == 5 )
            % fprintf( file, "P5\n%d %d %d\n", nc, nr, max(max(a1)) );
            fprintf( file, "P5\n%d %d %d\n", nc, nr, 255 );
            fwrite( file, a1', "uchar" );
        else
            error( "not ascii or raw" );
        endif
    case ( "ppm" )
        if ( nargin != 5 )
            usage( "pnm_write( typ, name, a1 [, a2, a3] )" );
        endif
        if ( index(t, "ascii") == 5 )
            error( "ppm-ascii not implemented" );
        elseif ( index(t, "raw") == 5 )
            fprintf( file, "P6\n%d %d %d\n", nc, nr, max(max([a1, a2, a3])) );
            rgb = zeros(3*nc, nr);
            rgb(1:3:3*nc,:) = a1';
            rgb(2:3:3*nc,:) = a2';
            rgb(3:3:3*nc,:) = a3';
            fwrite( file, rgb, "uchar" );
        else
            error( "not ascii or raw" );
        endif
    otherwise
        error( "illegal pnm type" );
    endswitch

    fclose(file);

endfunction
