Post Scriptum language

// Example 14

glo = dict( 1 );       // Create a dictionary for global variables

procedure DrawSlice( thelabel, startangle, endangle, grayshade ) 
{
        newpath();
        moveto(0, 0);
        arc( 0, 0, glo.radius, startangle, endangle );
        closepath();
        setmiterlimit( 1.415 );

        gsave();
        setgray( grayshade );
        fill();
        grestore();

        stroke();

        gsave();
        rotate( (startangle + endangle)/2 );
        translate( glo.radius, 0 );
        newpath();
        moveto( 0, 0 );
        lineto( 0.8 * glo.labelps, 0 );
        stroke();
        translate( glo.labelps, 0 );
        tr = [ transform( 0, 0 ) ];
        grestore();
        tr = [ itransform( tr[0], tr[1] ) ];
        x = tr[0];
        y = tr[1];
        moveto( x, y );
        if ( x < 0 ) {
                sw = [ stringwidth( thelabel ) ];
                rmoveto( -sw[0], 0 );
        }
        if ( y < 0 )
                rmoveto( 0, -glo.labelps );

        show( thelabel );
}

procedure findgray( n, i ) 
{
        if ( mod(i, 2) == 0 )
                return (i/2 + round( n/2 ))/n;
        else
                return ((i+1)/2)/n;
}

procedure DrawPieChart( title, titleps, labelps, PieArray,
                xcenter, ycenter, radius )
{
        glo.radius = radius;
        glo.labelps = labelps;

        gsave();
        translate( xcenter, ycenter );
        setfont( scalefont( findfont('Helvetica'), titleps ));
        sw = [ stringwidth(title) ];
        moveto( -sw[0]/2, -radius-3*titleps );
        show( title );

        setfont( scalefont( findfont('Helvetica'), labelps ));
        numslices = length( PieArray );
        slicecnt = 0;
        curangle = 0;

        for ( slicearray in PieArray ) {
                label = slicearray[ 0 ];
                percent = slicearray[ 1 ];
                perangle = 360*percent;
                slicecnt += 1;
                DrawSlice( label, curangle, curangle+perangle, 
                                findgray( numslices, slicecnt ) );
                curangle += perangle;
        }

        grestore();
}

DrawPieChart( "January Pie Sales", 24, 12,   
                [ ["Blueberry", .12 ],
                ["Cherry", .30 ],
                ["Apple", .26 ],
                ["Boston Cream", .16 ],
                ["Other", .04 ],
                ["Vanilla Cream", .12 ]
                ], 306, 396, 140 );

showpage();