/* ppmmargin - add a margin to a portable anymap
 *
 * Copyright (C) 1994 by Ingo Wilken (Ingo.Wilken@informatik.uni-oldenburg.de)
 * Based on the ppmmargin sh-Script 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.
 */
parse source junk junk progname junk

address command
signal on error
signal on break_c
signal on break_d
signal on ioerr
signal on halt
ID = pragma('Id')

call open(err, "CONSOLE:", 'W')
if ~result then exit 20

if ~show('L', 'rexxsupport.library') then do
    if ~addlib('rexxsupport.library', 0, -30, 0) then exit 20
    end
if ~showlist('A', 'PBMTMP') then 'assign PBMTMP: T:'

tmp1 = 'PBMTMP:pnmm1.'ID
tmp2 = 'PBMTMP:pnmm2.'ID
tmp3 = 'PBMTMP:pnmm3.'ID
tmp4 = 'PBMTMP:pnmm4.'ID
call rm tmp1 tmp2 tmp3 tmp4

color = '-gofigure'

parse arg tail
do forever
    parse var tail first tail
    select
        when abbrev('-white', first, 2) then do
            color = '-white'
            end
        when abbrev('-black', first, 2) then do
            color = '-black'
            end
        when abbrev('-color', first, 2) then do
            parse var tail color tail
            end
        when abbrev(first, '-', 1) then call usage
        otherwise leave
    end /* select */
end

size = first
if ~datatype(size, 'W') then call usage
if size < 1 then call usage

/* Capture input file in a tmp file, in case it's a pipe */
'pnmcat -tb' tail '>' tmp1

/* Construct space files */
select
    when color = '-gofigure' then do
        'pnmcut 0 0 1 1' tmp1 '>' tmp3
        'pnmtile' size '1' tmp3 '>' tmp2
        call rm tmp3
        end
    when color = '-white' | color = '-black' then do
        'pbmmake' color size '1 >' tmp2
        end
    otherwise do
        'ppmmake' color size '1 >' tmp2
        end
end /* select */
'pnmflip -rotate90' tmp2 '>' tmp3

/* Cat things together */
'pnmcat -lr' tmp2 tmp1 tmp2 '>' tmp4
'pnmcat -tb' tmp3 tmp4 tmp3

/* All done */
call rm tmp1 tmp2 tmp3 tmp4
exit 0

usage:
    call writeln err, 'usage:' progname '[-white|-black|-color <colorspec>] <size> [pnmfile]'
    exit 10

rm: procedure
    arg name
    signal off error    /* ignore WARN */
    'delete' name 'quiet force >NIL:'
    signal on error
    return

error:
break_c:
break_d:
ioerr:
halt:
    call writeln err, progname ': break/error at line' SIGL 'code' RC
    call rm tmp1 tmp2 tmp3 tmp4
    exit 10

