function pj = ghostscript( pj )
%GHOSTSCRIPT Method to convert a PostScript file into a different format.
%   Ghostscript is a third-party application supplied with MATLAB. See the file
%   ghoscript/gs.rights in the MATLAB installation area for more information on
%   Ghostscript itself.
%
%   The PRINT command takes as in input argument a device driver. Some of
%   those arguments specify a temporary PostScript file should be created and
%   then translated by Ghostscript into a different format. The resulting file
%   is sent to an output device or left in a file named in the PRINT command.
%
%   These devices use Ghostscript and are supported on all platforms:
%      -dlaserjet - HP LaserJet
%      -dljetplus - HP LaserJet+
%      -dljet2p   - HP LaserJet IIP
%      -dljet3    - HP LaserJet III
%      -ddeskjet  - HP DeskJet and DeskJet Plus
%      -ddjet500  - HP Deskjet 500
%      -dcdjmono  - HP DeskJet 500C printing black only
%      -dpaintjet - HP PaintJet color printer
%      -dpjxl     - HP PaintJet XL color printer
%      -dpjetxl   - HP PaintJet XL color printer
%      -dbj10e    - Canon BubbleJet BJ10e
%      -dbj200    - Canon BubbleJet BJ200
%      -dbjc600   - Canon Color BubbleJet BJC-600 and BJC-4000
%      -dln03     - DEC LN03 printer
%      -depson    - Epson-compatible dot matrix printers (9- or 24-pin)
%      -depsonc   - Epson LQ-2550 and Fujitsu 3400/2400/1200
%      -deps9high - Epson-compatible 9-pin, interleaved lines 
%                      (triple resolution)
%      -dibmpro   - IBM 9-pin Proprinter
%
%   These devices use Ghostscript and are supported on UNIX platforms only:
%      -dcdjcolor - HP DeskJet 500C with 24 bit/pixel color and high-
%                      quality color (Floyd-Steinberg) dithering
%      -dcdj500   - HP DeskJet 500C
%      -dcdj550   - HP Deskjet 550C
%      -dpjxl300  - HP PaintJet XL300 color printer
%      -ddnj650c  - HP DesignJet 650C
%
%   The following formats will always result in a file being left on disk
%   because they are image formats. If no name is given to the PRINT command
%   a default name will be used and echoed to the command line.
%      -dbmp256   - 8-bit (256-color) .BMP file format
%      -dbmp16m   - 24-bit .BMP file format
%      -dpcxmono  - Monochrome PCX file format
%      -dpcx16    - Older color PCX file format (EGA/VGA, 16-color)
%      -dpcx256   - Newer color PCX file format (256-color)
%      -dpcx24b   - 24-bit color PCX file format, 3 8-bit planes
%      -dpbm      - Portable Bitmap (plain format)
%      -dpbmraw   - Portable Bitmap (raw format)
%      -dpgm      - Portable Graymap (plain format)
%      -dpgmraw   - Portable Graymap (raw format)
%      -dppm      - Portable Pixmap (plain format)
%      -dppmraw   - Portable Pixmap (raw format)
%
%   Copyright (c) 1984-98 by The MathWorks, Inc.
%   $Revision: 1.9 $  $Date: 1998/10/09 21:45:40 $

error( nargchk(1,1,nargin) )

if ~isa(pj,'printjob')
    error('Requires PrintJob object')
end

rsp_file = [tempname '.rsp'];
rsp_fid = fopen (rsp_file, 'w');
if (rsp_fid < 0)
    error('Unable to create response file')
end

if isvms
    ghostDir = fullfile( matlabroot, 'sys', 'ghostscript.dir' );
else
    ghostDir = fullfile( matlabroot, 'sys', 'ghostscript' );
end
if ~exist(ghostDir)
    error( ['Can not find the directory for Ghostscript in ' matlabroot] )
end

fprintf(rsp_fid, '-dNOPAUSE -q \n');
fprintf(rsp_fid, '-I%s\n', fullfile( ghostDir, 'ps_files', ''));
fprintf(rsp_fid, '-I%s\n', fullfile( ghostDir, 'fonts', ''));
fprintf(rsp_fid, '-sDEVICE=%s\n', pj.GhostDriver);

%If saving as a picture, not a printer format, crop the image.
if pj.GhostImage
    fprintf(rsp_fid, '-g%.fx%.f\n', pj.GhostExtent(1), pj.GhostExtent(2) );

else    
    %If not the default of letter/Ansi A, set the name Ghostscript wants
    %First object is 'master' object. What do do if the others are not the same?
    gsName = getget( pj.Handles{1}(1), 'papertype' );
    if ~( strcmp(gsName,'usletter') | strcmp(gsName,'A') )
        switch gsName
        case 'uslegal',  gsName = 'legal';
        case 'a4letter', gsName = 'a4';
        case 'tabloid',  gsName = '11x17';
        case 'arch-A',   gsName = 'archA';
        case 'arch-B',   gsName = 'archB';
        case 'arch-C',   gsName = 'archC';
        case 'arch-D',   gsName = 'archD';
        case 'arch-E',   gsName = 'archE';
        case 'B',        gsName = '11x17';
        case 'C',        gsName = 'archC'; %following ANSI sizes not supported
        case 'D',        gsName = 'archD';
        case 'E',        gsName = 'archE';
        otherwise
            % PaperType is already the correct name.
            gsName = lower( gsName );
        end
        fprintf( rsp_fid, '-sPAPERSIZE=%s\n', gsName );
    end
end

%If using GS to produce a TIFF image for an EPS preview.
if pj.PostScriptPreview == pj.TiffPreview 
    fprintf( rsp_fid, '-r72x72\n' );
end

fprintf(rsp_fid, '-sOutputFile=%s\n', pj.GhostName );
fclose(rsp_fid);

if strcmp( computer, 'PCWIN' )
    if (exist(fullfile(ghostDir,'bin','nt','gs.exe')))
        gsPath = fullfile(ghostDir,'bin','nt','');
    elseif (exist(fullfile(ghostDir,'bin','gs','gs.exe')))
        gsPath = fullfile(ghostDir,'bin','');
    else
        error( 'Can not find GhostScript executable.' )
    end
    
    [s, r] = dos( pj, [ 'echo quit | ' gsPath '\gs @' rsp_file ' ' pj.FileName ] );
    
elseif isvms
    vms_file = [tempname '.com'];
    vms_fid = fopen (vms_file, 'w');
    if (vms_fid < 0)
        error('Unable to create command file')
    else
        fprintf(vms_fid, '$ define sys$output/user nl:\n');
        fprintf(vms_fid, '$ define sys$input/user nl:\n');
        fprintf(vms_fid, 'gs @%s %s', rsp_file, pj.FileName);
    end
    fclose(vms_fid);
    [s,r] = vms( [ '@' vms_file ] );
    delete(vms_file);
    
else    
    [s, r] = unix( [ fullfile(ghostDir,'bin',getenv('ARCH'),'gs') ...
              ' @' rsp_file ' ' pj.FileName ' < /dev/null > /dev/null' ] );
end

if pj.DebugMode
    disp( ['PRINT debugging: GHOSTSCRIPT converting PS file = ''' pj.FileName '''.'] )
    disp( ['PRINT debugging: GHOSTSCRIPT response file = ''' rsp_file ''':'] )
    eval( ['type ' rsp_file] )
else
    delete(rsp_file)
    delete(pj.FileName)
    
    %For consistency with non-GS device output, file handling code uses FileName
    pj.FileName = pj.GhostName;
end

if ~s & ~isempty(r) & ~strcmp(r,'GS>')
    error( sprintf('Problem converting PostScript. GhostScript returned error:\n%s', r) )
elseif s
    error( sprintf('Problem calling GhostScript. System returned error:\n%s', r) )
end

%Ghostscript doesn't return an error if couldn't create file
%because of write protection. See if file was created.
fid = fopen( pj.GhostName, 'r');
if ( fid == -1 )
    error([ 'Ghostscript could not create ''' pj.GhostName '''.' ])
else
    fclose( fid );
end
