#!/usr/bin/perl
#
# Converts a DOS EPS file (usually with (TIFF-FX?) bitmap preview) to
# a proper EPS file. It is crude but effective, I hope ;)
#
# Author: Boi Sletterink
# Initial version: 3/6/2002.
#
# This program can be distributed under the GNU General Public License:
# http://www.gnu.org/copyleft/gpl.html


$CHUNKSIZE= 65535;


if ($#ARGV>=0)
{
  print STDERR <<END_OF_TEXT
doseps2eps extracts the PostScript part from a DOS style Encapsulated
PostScript file. Usually, this should be the kind of EPS that you can use
for eg. LaTeX.

doseps2eps does not take any parameters, you'll need to feed it through
stdin and the output comes from stdout. It might be necessary to filter the
resulting EPS file with dos2unix or mac2unix.
END_OF_TEXT
;
  exit 1;
}

$res= sysread(STDIN, $magic, 4);

die "Error reading stdin.\n" if !defined($res);
die "unexpected end of file.\n" if $res < 4;

die "this is not a DOS EPS file.\n" if unpack("V", $magic) != 0xc6d3d0c5;

$res = sysread(STDIN, $header, 26);
die "Error reading stdin.\n" if !defined($res);
die "unexpected end of file.\n" if $res < 26;

($psstart, $pssize, $mfstart, $mfsize, $tiffstart, $tiffsize, $checksum) =
  unpack("V6 S", $header);

#printf STDERR "psstart %08x, pssize %08x\n", $psstart, $pssize;

$bytesleft= $psstart - 30;
while ($bytesleft > 0)
{
  $chunk= ($bytesleft < $CHUNKSIZE)? $bytesleft : $CHUNKSIZE;
  $res= sysread(STDIN, $tmpbuffer, $chunk);
  die "Error reading stdin.\n" if !defined($res);
  die "unexpected end of file.\n" if $res < $chunk;
  $bytesleft -= $chunk;
}

$bytesleft= $pssize;
while ($bytesleft > 0)
{
  $chunk= ($bytesleft < $CHUNKSIZE)? $bytesleft : $CHUNKSIZE;
  $res= sysread(STDIN, $tmpbuffer, $chunk);
  die "Error reading stdin.\n" if !defined($res);
  die "unexpected end of file.\n" if $res < $chunk;
  $tmpbuffer=~ tr/\r/\n/;
  $res= syswrite(STDOUT, $tmpbuffer, $chunk);
  die "Error writing stdout.\n" if !defined($res);
  die "unexpected end of file.\n" if $res < $chunk;
  $bytesleft -= $chunk;
}

while (defined($res) && $res!=0)
{
  $res= sysread(STDIN, $tmpbuffer, $CHUNKSIZE);
}

exit 0;
