#!/usr/bin/perl -w
#
# cdlabelgen - a program for making cd jewel box covers and traycards
#
# Copyright (C) 1998, 1999 B. W. Fitzpatrick <fitz@red-bean.com>
#
# Author: B. W. Fitzpatrick <fitz@red-bean.com>
# Maintainer: B. W. Fitzpatrick <fitz@red-bean.com>
# Created: October, 1998
# Keywords: postscript, labels
#
# $Id: cdlabelgen,v 1.35 1999/03/24 23:20:30 bwf Exp $
#
# 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, 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, you can either send email to this
# program's maintainer or write to: The Free Software Foundation,
# Inc.; 59 Temple Place, Suite 330; Boston, MA 02111-1307, USA.

use Getopt::Std;
use strict;

# Prepare to slurp up the file
my $template = 'template.ps';
my $directory;

# Modify this if you want to store your template somewhere else
# Perhaps we can make this part of a conf file in the future?
my @where_is_the_template = ('/usr/share/cdlabelgen/',
									  '/usr/local/share/cdlabelgen/',
									  '/usr/local/lib/cdlabelgen/',
									  '/etc/cdlabelgen/',
									  './postscript/');

my $found_template = '';
foreach $directory (@where_is_the_template) {
	if (-e ("$directory$template")) {
		$template = "$directory$template";
		$found_template = 1;
		last;
	}
}
unless ($found_template) {	&error("Postscript template file not found") }

my $tmpsep = $/;
undef $/;
my %flag;
my @items;
my $eps_cover_file;
my $eps_tray_card_file;
my $eps_cover_bounds;
my $eps_tray_card_bounds;
my $eps_cover_scale;
my $eps_tray_card_scale;
my $date;
my	$print_to_file;
my $default_bounds = "\n/bound1x 10 def\n/bound1y 10 def\n/bound2x 10 def\n/bound2y 10 def\n/scaleratio 1 def\n";
######################################################################
# Argument processing
getopts('c:s:f:i:d:S:T:e:E:o:Dh', \%flag);    

if($flag{h}) {
	&show_help();
}

# Do we have enough flags to go on?
&show_help unless $flag{c} && $flag{'s'};

# Category/title
my $category = &scrub($flag{c});

# Subcategory/subtitle
my $subcategory = &scrub($flag{'s'});

# Items | directories | songs
if($flag{f}) {
   my $infile = $flag{'f'};
   open(INFILE, "$infile") || die &error("Cannot open $infile");
   @items = map {"($_)"} split(/\n/, &scrub(<INFILE>));
   close(INFILE);
}
elsif ($flag{i}){
	my $clean_items = &scrub($flag{i});
   @items = map {"($_)"} (split (/%/, $clean_items));
}
else {
	@items = ('( )','( )'); # Need to at least have an empty array.
}

# Date stuff
if ($flag{d}) {
	$date = &scrub($flag{d});
}
else {
	$date = &get_date();
}
if ($flag{D}) {
	$date = '';
}
# cover espfile scaling
if ($flag{S}) {
	unless (($flag{S} =~ /^\d+(\.\d+)?$/) || ($flag{S} =~ /^\.\d+$/)) {
		die "$0: -S Cover scale ratio must be a number\n\n";
}
	$eps_cover_scale = $flag{S};
}
else { # Else, no scaling
	$eps_cover_scale = 1;
}
# traycard espfile scaling
if ($flag{T}) {
	unless (($flag{T} =~ /^\d+(\.\d+)?$/) || ($flag{T} =~ /^\.\d+$/)) {
		die "$0: -T: Traycard scale ratio must be a number\n\n";
}
	$eps_tray_card_scale = $flag{T};
}
else { # Else, no scaling
	$eps_tray_card_scale = 1;
}
# cover epsfile
if ($flag{e}) {
	open (EPS, "$flag{e}") or die &error("Cannot open $flag{e}");
	$eps_cover_file = <EPS>;
	close(EPS);
	$eps_cover_bounds = &get_bounding_box($flag{e}, $eps_cover_scale);
}
else {
	$eps_cover_bounds = $default_bounds;
	$eps_cover_file = '';
}
# traycard epsfile
if ($flag{E}) {
	open (EPS, "$flag{E}") or die &error("Cannot open $flag{E}");
	$eps_tray_card_file = <EPS>;
	close(EPS);
	$eps_tray_card_bounds = &get_bounding_box($flag{E}, $eps_tray_card_scale);
}
else {
	$eps_tray_card_bounds = $default_bounds;
	$eps_tray_card_file = '';
}
# output file
if ($flag{o}) {
	open (OUT, ">$flag{o}") or die &error("Cannot open $flag{o} for writing");
	$print_to_file = 1;
}

######################################################################
# Grab the template

open (TEMPLATE, "$template") or die &error("Cannot open $template");
my $psout = <TEMPLATE>;

$psout =~ s/TOKEN_BAN_STRING/$category/;
$psout =~ s/TOKEN_BAN_STRING/$category/;
$psout =~ s/TOKEN_SUBBAN_STRING/$subcategory/g;
$psout =~ s/TOKEN_DATE/$date/g;
$psout =~ s/TOKEN_ITEMS/@items/g;
$psout =~ s/TOKEN_EPS_BOUNDS/$eps_cover_bounds/g;
$psout =~ s/TOKEN_COVER_EPS/$eps_cover_file/g;
$psout =~ s/TOKEN_TRAY_CARD_BOUNDS/$eps_tray_card_bounds/g;
$psout =~ s/TOKEN_TRAY_CARD_EPS/$eps_tray_card_file/g;

if ($print_to_file) { print OUT $psout; }
else { print $psout; }
##################################################################################
# Subroutines

sub get_date {
   my ($sec,$min,$hour,$mday,$mon,$year,$wday,$yday,$isdst) = localtime(time);
   $mon++;
   if ($mon  < 10) { $mon = "0$mon"; }
   if ($mday < 10) { $mday = "0$mday"; }
	$year += 1900; 
	return "$year-$mon-$mday";     # ISO 8601:1988 

}   

sub show_help {
	print <<EOT;
usage: $0 -c <category> -s <subcategory> [-i <item1%item2%etc> -f<itemsfile> 
       -e <cover_epsfile> -S <cover_eps_scaleratio> -E <tray_epsfile> 
       s -T <tray_eps_scaleratio> -d <date> -D -o outputfile -h]
EOT
exit 255;
}

sub scrub {
	my $string = shift @_;
	$string =~ s?\(?\\050?g;
	$string =~ s?\)?\\051?g;
	return $string;
}


sub error {
	my $err = shift @_;
	warn "$0: $err: $!\n\n";
	&show_help;
}

sub get_bounding_box {
	my $file = shift @_;
	my $eps_scale = shift @_;
	my $bounds;
	my $got_bounding_box = 0;
	$/ = $tmpsep;
	open (EPS, "$file") or die &error("Cannot open epsfile $file");
	while (<EPS>) {
		chomp;
		if (s/\%\%BoundingBox: //) {
			my ($llx, $lly, $urx, $ury) = split (/ /, $_);
			$bounds ="\n/bound1x $llx def\n/bound1y $lly def\n/bound2x $urx def\n/bound2y $ury def\n/scaleratio $eps_scale def\n";
			$got_bounding_box = 1;
			last;
		}
	}
	unless ($got_bounding_box) {
		die "$0: Cannot get BoundingBox from $file. Are you sure it's an EPS file?\n";
	}
undef $/;
	return $bounds;
}

##################################################################################
# Documentation

=head1 NAME

cdlabelgen - generates frontcards and traycards for CDs

=head1 SYNOPSIS

   cdlabelgen -c <category> -s <subcategory> [-i <item1%item2%etc> -f<itemsfile> 
-e <cover_epsfile> -S <cover_eps_scaleratio> -E <tray_epsfile> 
s -T <tray_eps_scaleratio> -d <date> -D -o outputfile -h]

=head1 VERSION

=over

=item Version 1.1.3

=back

=head1 DESCRIPTION

cdlabelgen's purpose in life is twofold:

=over

=item * To be run automatically and swiftly from a shell script and
automatically generate a frontcard and a traycard for a cd--usually
data archive cd's. The traycard (which goes behind the CD itself) is
U-shaped and the ends of the CD case bear the label of what the CD is.

=item * To have a minimum of dependencies--cdlabelgen only requires perl.

=back

cdlabelgen was designed to simplify the process of generating labels
for CD's. It originated as a program to allow auto generation of
frontcards and traycards for CD's burned via an automated mechanism
(specifically for archiving data), but has now become popular for
labelling CD compilations of mp3's, and copies of CDs. Note that
cdlabelgen does not actually print anything--it just spits out
postscript, which you can then do with as you please.

The latest version of cdlabelmaker as well as this document can be
found at http://www.red-bean.com/~bwf/software/cdlabelgen/. Please
make certain that you are using the latest version before submitting
any bug reports or patches.

cdlabelgen requires Perl Version 5.003 or greater. Ghostscript is not
required, but B<is> recommended so that you can test out your labels
without wasting paper.

=head1 SWITCHES

=over

=item B<-c category>

Set the category (title) for the CD

=item B<-s subcategory>

Set the subcategory (subtitle) for the CD

=item B<-i items>

'items' should be a '%' separated list of items to print on the
traycard of the CD.  Note that if the items list is more than 192
items long, cdlabelgen will truncate it. cdlabelgen automatically
flows the items into 2, 3, or 4 columns and scales the fontsize
accordingly. Excessively wide items will be scaled down (into
illegibility sometimes--I plan on working on that in a future release)
to fit horizontally. You can insert blank lines by inserting 2 percent
signs in a row into the items list.

=item B<-f filename>

Get item names from file named filename. Each item should be on its
own line separated by carriage returns. Note that if the items list is
more than 192 items long, cdlabelgen will truncate it. cdlabelgen
automatically flows the items into 2, 3, or 4 columns and scales the
fontsize accordingly. Excessively wide items will be scaled down (into
illegibility sometimes--I plan on working on that in a future release)
to fit horizontally. You can insert blank lines by placing blank lines
between items in this file

=item B<-d date>

Set the date to be used as 'date' if not set or not overridden with
the B<-D> flag, today's date will be used (default is today's
date). Use this option if you don't like cdlabelgen's default format of
YYCC-MM-YY, for example.

=item B<-D> 

Do not print B<any> date (overrides B<-d> as well)

=item B<-e cover_epsfile>

Filename of eps file to print on cover. Note that cdlabelgen requires
that the eps file contain a proper '%%BoundingBox LLx LLy URx URy'
declaration according to the PostScript Document Structuring
Conventions. cdlabelgen uses this line to determine the dimensions of
the eps graphic so that it can position it appropriately on the cover.

=item B<-S cover_eps_scaleratio>

The ratio by which you want to scale the epsfile that appears on the
cover. If you omit this flag, cdlabelgen assumes a scaleratio of
1. This flag allows you to squeeze larger graphics into the cover or
expand smaller graphics to fill the cover. Scaleratio must be a number
(int or float).

=item B<-E tray_epsfile>

Filename of eps file to print on traycard. Note that cdlabelgen requires
that the eps file contain a proper '%%BoundingBox LLx LLy URx URy'
declaration according to the PostScript Document Structuring
Conventions. cdlabelgen uses this line to determine the dimensions of
the eps graphic so that it can position it appropriately on the cover.

=item B<-S tray_eps_scaleratio>

The ratio by which you want to scale the epsfile that appears on the
traycard. If you omit this flag, cdlabelgen assumes a scaleratio of
1. This flag allows you to squeeze larger graphics into the traycard or
expand smaller graphics to fill the traycard. Scaleratio must be a number
(int or float).

=item B<-o outputfile>

If the B<-o> flag is used, cdlabelgen prints to outputfile instead of STDOUT. 

=item B<-h>

print out the usage message

=back

=head1 EXAMPLES

	./cdlabelgen -c "My Filesystem" -s "/usr/local/foo" -e postscript/recycle.epsi > foo.ps

	./cdlabelgen -c "title of cd" -s "subtitle" -i "Item 1%and Item 2%a third item here perhaps" -e postscript/recycle.epsi > bar.ps

	./cdlabelgen -c "Fitz" -s "home directory" -o qux.ps

=head1 AUTHOR

B. W. Fitzpatrick E<lt>F<fitz@red-bean.com>E<gt>

=head1 THANKS

	- Karl Fogel, for general encouragement and that free software vibe
	- Adam Di Carlo, for bug testing, help and making the .deb
	- Greg Gallagher, for bug testing, coding, and tons of suggestions
	- Goran Larsson, for feedback and date fixes

=head1 ERRATA

Perhaps one of the most important features that I wanted in a
CD labelling program was the ability to print Title/Subtitle, and date
information on the endcaps of the CD jewel box to allow me to keep
archive disks in a standard CD rack and find a particular one without
yanking them all out and shuffling through them like a deck of cards.

cdlabelgen was inspired by the need for not only a simple cd labelling
program (there are many available), but by the need for a free
labelling program which could be integrated easily with scheduled CD
archiving routines. I did find a program called cdlabel
http://londo.ncl.ac.uk/~npac/cdlabel/, but that one is designed to work
with CDDB.

I searched the net for a suitable program, but found none, so taking
cues from programs that I found that perform similar tasks (like tape
labellers and DAT labellers), I embarked on this venture. Notable
inspiration came from the incredible audio-tape.ps by Jamie Zawinski
(which is indeed, as Jamie notes, completely out of control). Other
ideas were drawn from casslabel.c, and cdlabel.cc (noted above).

People have already pointed out to me that cdlabelgen could be
extended to perform other functions:

=over

=item * Print out the actual label that goes on the disk (I suppose it
is kinda funny that it is named cdB<label>gen and doesn't really
generate any label per se).

=item * Integrate with cdindex (I had intended to integrate with the
CDDB, but the owners of the CDDB are currently providing their
information under a rather restrictive license--considering that it
was mostly entered by people scattered across the internet). As of
this publication of cdlabelgen, you can get more info about cdindex
from http://www.freeamp.org/cdlabelgen/.

=back

If you are interesting in doing or contributing to the above features
(or any other features for that matter!), please contact me at the
above address. Please report bugs and submit any patches to the above
address as well--all help is appreciated.

=head1 BUGS

=over

=item * Excessively wide (> 30 chars) traycard items are shrunk into
illegibility.

=back

=head1 TODO

In order of importance.

=over

=item * Add cdindex support

=back

=head1 LAST MODIFIED

$Id: cdlabelgen,v 1.35 1999/03/24 23:20:30 bwf Exp $


=cut




