#!/usr/bin/perl

$prog = &basename($0);
&help unless ($#ARGV == 1);

($config, $paper) = @ARGV;

&default_paper($paper);

sub default_paper {
	@config = &readconfig;

	$found=0;
	for ($[ .. $#config) {
		$paper_section = $_, $found=1, last if ($config[$_] =~ /^@/);
	}

	$paper_section = $#config unless $paper_section;

	$found=0;
	for ($paper_section .. $#config) {
		$paper_start = $_, $found=1, last if ($config[$_] =~ /^@ $paper /);
	}

	&error ("papertype $paper not found in file $config") unless $found;

	$found=0;
	for ($paper_start+1 .. $#config) {
		$next_paper = $_, $found=1, last if ($config[$_] =~ /^@ /);
	}
	$next_paper = $#config+1 unless $found;

	@new_config= (	@config[ $[ .. $paper_section-1 ],
			@config[ $paper_start .. $next_paper-1],
			@config[ $paper_section .. $paper_start-1],
			@config[ $next_paper .. $#config ]);
	close CONFIG;
	rename ($config, "$config.orig") || &error("can't mv '$config' to '$config.orig'. $!.");
	open(CONFIG, ">$config") || &error("can't open '$config'. $!.");
	print(CONFIG  @new_config) || &error("can't write to '$config'. $!.");
	close(CONFIG) || &error("can't close '$config'. $!.");
	&shutdown;
}

sub basename {
        local ($name) = @_;
        local (@liste) = split("/", $name);

        return (pop(@liste));
}

sub shutdown {
	close CONFIG;
	exit 0;
}

sub error {
	print STDERR "$prog: @_\n";
	close CONFIG;
	exit 1;
}

sub readconfig {
	local (@ary);
	open(CONFIG, $config) || &error("can't open '$config'. $!.");
	@ary = <CONFIG>;
	close CONFIG;
	return(@ary);
}

sub help {
	print  <<EOF;

Usage: $prog config_file default_paper

This will make default_paper the default papertype for dvips,
by reordering the papersize definitions in config_file.

For details see dvips(1).

EOF
	exit 1;
}
