#!/usr/bin/perl
# - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - #
#NAME
#  xbm2png - Convert XBM icon files to PNG files.
#
#SYNOPSIS
#  xbm2png [file]..
#
#SOURCE
# Based on non-working example at:
#   http://www.lemoda.net/images/poskanzer-example/index.html 2013-08-04
# This version takes input file names on the command line.
#
#DESCRIPTION
# The original program didn't work at all, and didn't make sense. It may have
# been damaged during conversion to HTML. The description made reference to a
# problem with anytopnm, but the code didn't use anytopnm.  A bit of  digging
# for  other  documentation  turned up the problem with anytopnm: It uses the
# file(1) command to determine a file's type, and for XBM  files,  file  says
# it's ascii C source, i.e., plain text.  The result converts that plain text
# to an image of the text, rather than to the bitmapped icon  image  that  it
# describes.
#
# This program seems to correctly "persuade" anytopnm, by feeding  the  input
# files  to xbmtopgm, which correctly converts XBM files to PNM.  This is fed
# to anytopnm, which produces a valid .pnm file containing the desired image.
# We can then feed this to pnmtopng to generate the PNG file.
#
# Or the conversion commands can be combined into a 3-program pipeline.
#
#BUGS
# This program leaves behind the intermediate  .pnm  files.   This  has  been
# useful for debugging, and also for conversion to other formats. But perhaps
# these files should be deleted.
#
#AUTHOR
#  John Chambers <jc@trillian.mit.edu>
# - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - #

use warnings;
#use strict;
my($cmd,$file,@files);
my($base, $suff);
my $P = $0;
$P =~ s'^.*/'';
my $V = $ENV{"V_$P"} || 2;

#if (opendir(DIR,'.')) {
#	@files = readdir(DIR);
#	closedir (DIR);
#} else {
#	die "$P: Can't readdir('.')\n";
#}
#my @xbmfiles = grep /.xbm$/, @files;
#print "@xbmfiles\n";
foreach $file (@ARGV) {
	print "$0: $file ...\n" if $V>2;
	if (($base,$suff) = ($file =~ /^(.*)\.(\w+)$/)) {
		print "$0: base='$base' suff='$suff'\n" if $V>2;
#		$outfile = "$base.png";
		print "$base:\n" if $V>1;
		$cmd = "xbmtopbm $base.xbm |anytopnm >$base.pnm";
		print "$P: cmd=\"$cmd\"\n" if $V>2;
		system($cmd);
		$cmd = "pnmtopng $base.pnm >$base.png";
		print "$P: cmd=\"$cmd\"\n" if $V>2;
		system($cmd);
		system('ls -ltr ' . $base . '.*');
	} else {
		print "$P: Bad file name '$file'\n" if $V>0;
	}
	sleep $V if $V>2;
}

