#!/usr/bin/perl

use warnings;
use strict;

if (@ARGV == 0) {
    print <<'EOF';
Pouzitie: ./psmangle.pl vstup.ps > vystup.ps

Skript sluzi na odstranenie problemu s duplexnou tlacou landscape dokumentu,
kedy niektore tlaciarne pocinajuc druhou stranou tlacia obsah dokumentu otocene
o 90 stupnov oproti papierovemu mediu.

Autor: Tomas Szaniszlo, unix@fi.muni.cz, 2013
EOF
    exit 0;
}

my $landscape_correction = 0;
my $page = 0;
my ($llx, $lly, $urx, $ury);

while (my $line = <>) {
    print $line;

    if ($line =~ m/^%%Page: .*\s+(\d+)$/) {
        $page = $1;

        # opravujem boundingbox media, v ktorom bude renderovany vystup
        print "%%PageBoundingBox: 0 0 $ury $urx\n" if $landscape_correction && $page > 1;

    } elsif ($line =~ m/^%%PageOrientation: Portrait$/) {
        # upravujem CTM, aby bola poloha renderovaneho vystupu na mediu korektna
        print "0.0 $urx.0 translate -90 rotate\n" if $landscape_correction && $page > 1;

    } elsif ($line =~ m/^%%BoundingBox: (\d+) (\d+) (\d+) (\d+)$/) {
        ($llx, $lly, $urx, $ury) = ($1, $2, $3, $4);

        # ma dokument bounding box zacinajuci v (0,0) a vyzerat byt orientovany landscape?
        if ($llx == 0 && $lly == 0 && $urx > $ury) {
            print STDERR "Dokument je Landscape, budem aplikovat korekciu\n";
            $landscape_correction = 1;
        }
    }
}
