#!/usr/bin/perl
#
# Script de création des étiquettes (en PS) avec xfig/fig2dev

my $num     = 0;
my $id      = 0;
my $print   = 0;
my $rm      = 0;
my $hasfile = 0;
my $hasnum  = 0;
my $maxnum  = 8;
my $list    = "nameslist.txt";
my $labels  = "labels.fig";
my $file    = "";


sub create_labelfile {
    $id++;
    $figfile = "labels-$id.fig";
    $psfile  = "labels-$id.ps";
    $sedcmd  = "sed";
    print "\n>>> TAKEN NAMES : $figfile\n";
    for ($i = 1 ; $i <= $num ; $i++) {
        print " $name[$i]\n";
        $sedcmd = "$sedcmd -e 's/LABEL$i\./$name[$i]/g'";
    }
    system ("$sedcmd $labels > $figfile");
    system ("fig2dev -L ps $figfile $psfile");
    if ($print == 1) {
        system ("lpr $psfile");
    }
    if ($rm == 1) {
        unlink $figfile;
        unlink $psfile;
    }
}


foreach $arg (@ARGV) {
    if ($arg eq "-p") {
        $print = 1;
    } elsif ($arg eq "-rm") {
        $rm = 1;
    } elsif ($arg eq "-h") {
        print "makelabels v 0.0.3, Thomas Nemeth 2002\n";
        print "Usage : makelabels [-h] [-p] [-rm] [-f file] [-n num]\n";
        print " -h      : this help\n";
        print " -p      : print files\n";
        print " -rm     : delete generated files\n";
        print " -f file : use 'file' as source for names (default: $list)\n";
        print " -n num  : take 'num' names per page (default: 8)\n";
        print "makelabels uses '$labels' as xfig formatted label-file.\n";
        print "Each label should be named 'LABEL#.', with # a number from 1";
        print " to whatever you want (see option -n): don't forget the dot.";
        print " Of course, there should be as many labels in the xfig file";
        print " as declared to exist with '-n'.\n";
        exit;
    } elsif ($arg eq "-f") {
        $hasfile = 1;
    } elsif ($arg eq "-n") {
        $hasnum = 1;
    } else {
        if ($hasfile == 1) {
            $file = $arg;
            $hasfile = 0;
        } elsif ($hasnum == 1) {
            $maxnum = $arg;
            $hasnum = 0;
        } else {
            print "$arg : unknown argument !\n";
        }
    }
}

if ($file eq "") {
    $file = $list;
}

open (FILE, $file) or die "File $file does not exist : $!";
while (defined ($line = <FILE>) ) {
    $num++;
    $name[$num] = $line;
    chomp ($name[$num]);
    if ($num == $maxnum) {
        &create_labelfile();
        $num = 0;
    }
}
if ($num != 0) {
    &create_labelfile();
}
close (FIFO);
