#! PERL
# maptoxbm Version 1.0pl0 - Convert an Xpilot map to an xbm image.
# Copyright (C) 1994 Michael Lazarou, INSSOMNIAK.
#
#    This program is free software; you can redistribute it and/or modify
#    it under the terms of the GNU General Public License as published by
#    the Free Software Foundation; either version 2 of the License, or
#    (at your option) any later version.
#
#    This program is distributed in the hope that it will be useful,
#    but WITHOUT ANY WARRANTY; without even the implied warranty of
#    MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
#    GNU General Public License for more details.
#
#    You should have received a copy of the GNU General Public License
#    along with this program; if not, write to the Free Software
#    Foundation, Inc., 675 Mass Ave, Cambridge, MA 02139, USA.
#
# Requirements:
#   perl.
#   pbmplus utilities.

if ($#ARGV > 0) {
   die "$0: Usage $0 [<Xsize>] < <map> > <xpm>\n";
} 
if ($#ARGV == 0) {
  $newXsize = $ARGV[0];
  $#ARGV = -1;
} else {
  $newXsize = 0;
}

# Temporary file definitions.
$TMPFILE = "/tmp/MAP.$$";
$TMPFILE2 = "/tmp/MAP2.$$";

# Main Program
  open (TMP, ">$TMPFILE") || die "$0: $TMPFILE. $!\n";

  while(<>) {
    (/map[W|w]idth\s*:\s*(\d+)\s/) && ($mapWidth = $1);
    (/map[H|h]eight\s*:\s*(\d+)\s/) && ($mapHeight = $1);

    if(/mapData:\s*\\multiline:\s*(\S+)/) {
      $EndOfMapdata = $1;
      while(<>) {
        last if (/$EndOfMapdata/o);
        s/ /1/g;
        tr/1/0/c;
        chop;
        print TMP $_, "\n";
      }
      close TMP;
    }
  }

  if (!$newXsize) {
    $newXsize = $mapWidth;
  }
  $ratio = $newXsize/$mapWidth;

  open (TMPFILE) || die "$0: $TMPFILE. $!\n";
  open (PBM, "| pnmscale $ratio > $TMPFILE2 2> /dev/null") || die "$0: pnmscale. $!\n";

  print PBM "P1\n";
  print PBM "$mapWidth $mapHeight\n";

  while (<TMPFILE>) {
    print PBM $_;
  }

  close TMPFILE;
  close PBM;

  system("pgmtopbm < $TMPFILE2 | pbmtoxbm");
  if ($? >> 8) {
    unlink $TMPFILE;
    unlink $TMPFILE2;
    die "$0: System Exec Error\n";
  }

  unlink $TMPFILE;
  unlink $TMPFILE2;
