#!/usr/bin/perl

use strict;

use lib '/sw/lib/perl5';
use lib '/fink/lib/perl5';
#use lib '/Users/ranger/cvs/fink/perlmod';

use Clone qw(clone);
use File::Basename;
use File::Find;
use File::Path;
use Cwd 'abs_path';
use Fink;
use Fink::PkgVersion;
use Fink::Services qw(&read_properties_var &pkglist2lol &lol2pkglist);
use Data::Dumper;

Fink->import;

my $path = abs_path(dirname($0));
my $do_pangocairo = 0;

if (grep(/^-p$/, @ARGV)) {
	$do_pangocairo = 1;
}

my @files = @ARGV;
my %files;

my $translate = [
	'.*-pm.info$',
	'akode',
	'amanith-py',
	'apt',
	'blitz',
	'boson',
	'cairo',
	'clucene',
	'dbus\\.',
	'dbus-qt3',
	'distcc',
	'doxygen1.3',
	'dpkg',
	'ecj',
	'ekg',
	'enblend',
	'fam',
	'ffmpeg',
	'fontconfig2',
	'fung-calc',
	'gconfmm',
	'gemrb',
	'glew',
	'glib2',
	'glibmm',
	'glut',
	'gnomoradio',
	'gst.*0.10.*',
	'gst-plugins',
	'gstreamer',
	'gtk\\+2',
	'gtkmm',
	'guichan',
	'hdrie',
	'icecream',
	'imlib',
	'kde',
	'kgpg',
	'libagg',
	'libcapsi',
	'libmal',
	'libmath',
	'libmusicbrainz4',
	'libpg',
	'libpgeasy',
	'libpostproc',
	'libpq',
	'libpqpp',
	'libpqxx',
	'libsmoke',
	'libtheora',
	'libtunepimp',
	'libwpd',
	'libxft',
	'libxine1',
	'libxml\\\+\\\+',
	'libxml2-rb',
	'mediatomb',
	'mesa',
	'mesalib',
	'mplayer',
	'net-snmp',
	'openexr',
	'pango',
	'pbzip2',
	'perlmods',
	'piklab',
	'poppler',
	'popt',
	'postgis',
	'postgres',
	'pth2',
	'qca',
	'qt-rb',
	'qt3',
	'qt4',
	'readline-java',
	'rpm',
	'screensaver',
	'soprano',
	'sqlite3',
	'strigi',
	'swig',
	'/taglib',
	'wv2',
	'xfree86\\.',
	'xorg\\.',
];

my $package_lookup = {
	'10.4' => {
		'^autoconf2.5'                => 'autoconf',
#		'^libgettext3-dev'            => 'gettext-dev',
#		'^libgettext3-shlibs'         => 'gettext',
		'^gal199$'                    => 'gal2.4.0',
		'^gal199-shlibs$'             => 'gal2.4.0-shlibs',
		'^gal199-dev$'                => 'gal2.4.0-dev',
		'^gettext-dev$'               => 'libgettext3-dev',
		'^gettext$'                   => 'libgettext3-shlibs',
		'^libicu31-dev$'              => undef,
		'^gcc3.1$'                    => undef,
		'^gcc3.3$'                    => undef,
		'^gtkhtml3(.8.15)?$'          => 'gtkhtml3.14',
		'^gtkhtml3(.8.15)?-shlibs$'   => 'gtkhtml3.14-shlibs',
		'^gtkhtml3(.8.15)?-dev$'      => 'gtkhtml3.14-dev',
		'^imagemagick(-nox)-dev?$'    => 'imagemagick10-dev',
		'^imagemagick(-nox)-shlibs?$' => 'imagemagick10-shlibs',
		'^libcroco1'                  => 'libcroco3',
		'^libcroco1-bin'              => 'libcroco3-bin',
		'^libcroco1-shlibs'           => 'libcroco3-shlibs',
		'^libgda-dev$'                => 'libgda3-dev',
		'^libgda-shlibs$'             => 'libgda3-shlibs',
		'^libgnomedb-dev$'            => 'libgnomedb3-dev',
		'^libgnomedb-shlibs$'         => 'libgnomedb3-shlibs',
		'^libgnomeprint2.2$'          => 'libgnomeprint2.2-shlibs',
#		'^mjpegtools2-dev$'           => 'mjpegtools1.8-dev',
#		'^mjpetools2-shlibs$'         => 'mjpegtools1.8-shlibs',
		'^pango1-xft2-shlibs$'        => 'pango1-xft2-ft219-shlibs',
		'^pango1-xft2-dev$'           => 'pango1-xft2-ft219-dev',
		'^pango1-xft2$'               => 'pango1-xft2-ft219',
		'^swig-shlibs$'               => undef,
		'^vte-dev$'                   => 'vte9-dev',
		'^vte-shlibs$'                => 'vte9-shlibs',
	},
};

my $version_lookup = {
	'10.4' => {
		'^abiword$'                                 => [ '2.2.7',        '1003' ],
		'^advancemame$'                             => [ '0.84.0',       '1020' ],
		'^apache2.*$'                               => [ '2.0.55',       '1010' ],
		'^atk1(-dev|-shlibs)$'                      => [ '1.20.0',       '1' ],
		'^libapache2-mod-(actions|auth-anon|auth-dbm|auth-digest|bucketeer|cgid|expires|headers|info|isapi|mime-magic|proxy|proxy-connect|proxy-ftp|proxy-http|rewrite|speling|ssl|suexec|unique-id|usertrack|vhost-alias)$'                              => [ '2.0.55',       '1010' ],
		'^apr(-ssl)?(-common|-shlibs)?$'            => [ '0.9.7',        '1011' ],
		'^apt(-dev|-shlibs)?$'                      => [ '0.5.4',        '1052' ],
		'^aqbanking$'                               => [ '1.0.4',        '1beta.1000' ],
		'^aqhbci(-.*)?$'                            => [ '1.0.2',        '1beta.1000' ],
		'^aquaterm(-dev|-shlibs)?$'                 => [ '1.0.0',        '1002' ],
		'^aspell(-dev|-shlibs)?$'                   => [ '0.50.5',       '1002' ],
		'^atk1(-shlibs)?$'                          => [ '1.20.0',       '1'    ],
		'^audiofile(-dev|-shlibs)?$'                => [ '0.2.6',        '11'   ],
		'^autotrace(-bin|-shlibs)?$'                => [ '0.31.1',       '1014' ],
		'^boo$'                                     => [ '0.7.9',        '1'    ],
		'^boost1.32-py..(-shlibs)?$'                => [ '1.32.0',       '1002' ],
		'^boost1.32.python(-shlibs)?$'              => [ '1.32.0',       '1011' ],
		'^cairo(-shlibs)$'                          => [ '1.4',          '1001' ],
		'^ccp4(-.*)?$'                              => [ '5.99.5',       '1001' ],
		'^cdrdao$'                                  => [ '1.2.0',        '1010' ],
		'^cocoa-sharp$'                             => [ '0.9.1',        '1022' ],
		'^dasher(-.*)?$'                            => [ '3.2.18',       '1001' ],
		'^dbus(-shlibs|-dev)?$'                     => [ '1.0',          '1'    ],
		'^dbus(-qt3|-qt4)(-shlibs|-dev)?$'          => [ '0.70',         '1001' ],
		'^desktop-file-utils$'                      => [ '0.14',         '1'    ],
		'^dialog$'                                  => [ '0.9b-20020814', '1024' ],
		'^db3(-bin|-doc|-shlibs)?$'                 => [ '3.3.11',       '1027' ],
		'^db4(-bin|-doc|-shlibs)?$'                 => [ '4.0.14',       '1026' ],
		'^db41(-ssl)?(-bin|-doc|-shlibs)?$'         => [ '4.1.25',       '1023' ],
		'^db42(-ssl)?(-bin|-doc|-java|-shlibs)?$'   => [ '4.2.52',       '1017' ],
		'^db43(-ssl)?(-bin|-doc|-java|-shlibs)?$'   => [ '4.3.29',       '1001' ],
		'^db44(-aes)?(-bin|-doc|-java|-shlibs)?$'   => [ '4.4.16',       '1001' ],
		'^dods$'                                    => [ '3.4.5',        '1005' ],
		'^dpkg$'                                    => [ '1.10.21',      '1217' ],
		'^ecj$'                                     => [ '3.1.2',        '1021' ],
		'^firefox(-dev|-shlibs)?$'                  => [ '1.0.7',        '1007' ],
		'^flac(-nox)?(-.*)?$'                       => [ '1.1.1',        '1011' ],
		'^fltk-x11(-shlibs)?$'                      => [ '1.1.6',        '11.1' ],
		'^fontconfig2(-dev|-shlibs)?$'              => [ '2.4.1',        '1'    ],
		'^freetype219(-dev|-shlibs)?$'              => [ '2.3.5',        '1'    ],
		'^gal21(-shlibs)?$'                         => [ '0.22',         '1014' ],
		'^gc(-shlibs)?$'                            => [ '6.4',          '1001' ],
		'^gconf2(-dev|-shlibs)?$'                   => [ '2.20.0',       '1'    ],
		'^gconfmm2(-shlibs)?$'                      => [ '2.0.2',        '1022' ],
		'^gconfmm2.6(-dev|-shlibs)?$'               => [ '2.10.0',       '1002' ],
		'^gdal(-ssl)?(-dev|-doc|-grass|-shlibs)?$'  => [ '1.2.6',        '1005' ],
		'^gecko-sharp$'                             => [ '2.0',          '1039' ],
		'^gecko-sharp1$'                            => [ '0.6',          '1027' ],
		'^gimp(-default|-dev|-shlibs)?$'            => [ '1.2.5',        '1003' ],
		'^glib2(-dev|-shlibs)?$'                    => [ '2.14.0',       '1'    ],
		'^glibmm2.4(-dev|-shlibs)?$'                => [ '2.12.3',       '1001' ],
		'^glut(-shlibs)?$'                          => [ '3.7',          '1025' ],
		'^gnome-keyring(-dev|-shlibs)?$'            => [ '2.20.0',       '1'    ],
		'^gnome-panel(-dev|-shlibs)?$'              => [ '2.20.0',       '1'    ],
		'^gnome-sharp2$'                            => [ '2.16.0',       '1'    ],
		'^gnome-vfs2-unified(-dev|-shlibs)?$'       => [ '1:2.20.0',     '1'    ],
		'^gnuplot$'                                 => [ '4.0.0',        '1003' ],
		'^grads$'                                   => [ '1.9',          '1004' ],
		'^gtkmm2(-dev|-shlibs)?$'                   => [ '2.2.12',       '1002' ],
		'^gtkmm2.4(-dev|-shlibs)?$'                 => [ '2.10.6',       '1001' ],
		'^gtk.2(-dev|-shlibs)?$'                    => [ '2.12.0',       '1'    ],
		'^gtk-sharp$'                               => [ '1.0.10',       '1029' ],
		'^gtk-sharp(2|-monodoc)$'                   => [ '2.10.2',       '1'    ],
		'^gtksourceview-sharp$'                     => [ '2.0',          '1029' ],
		'^gtksourceview(-dev|-shlibs)?$'            => [ '1.8.5',        '1',   ],
		'^guile16(-dev|-libs|-shlibs)?$'            => [ '1.6.7',        '1010' ],
		'^gwenhywfar(-shlibs)?$'                    => [ '1.7.2',        '1002' ],
		'^hdf5(-bin|-shlibs)?$'                     => [ '1.6.5',        '1002' ],
		'^id3lib4(-dev|-doc|-shlibs)?$'             => [ '3.8.3',        '1014' ],
		'^ikvm$'                                    => [ '0.30.0.0',     '1'    ],
		'^imagemagick(-nox)?(-dev|-shlibs)?$'       => [ '6.1.8',        '1002' ],
		'^intltool'                                 => [ '0.36.0',       '1'    ],
		'^kaptain$'                                 => [ '0.72',         '1012' ],
		'^ktoblzcheck$'                             => [ '1.2',          '1003' ],
		'^ladspa(-dev)?$'                           => [ '1.12',         '1012' ],
		'^lammpi(-dev|-examples|-shlibs)?$'         => [ '7.0.6',        '1011' ],
		'^libart2(-dev|-shlibs)?$'                  => [ '2.3.19',       '1'    ],
		'^libbonobo(ui)?2(-dev|-shlibs)?$'          => [ '2.20.0',       '1'    ],
		'^libcapsinetwork(-dev)?$'                  => [ '0.3.0',        '1001' ],
		'^libcroco3(-bin|-shlibs)?$'                => [ '0.6.1',        '1002' ],
		'^libdap3(-shlibs)?$'                       => [ '3.5.2',        '1001' ],
		'^libemf(-shlibs|-bin)?$'                   => [ '1.0.2',        '1011' ],
		'^libgda(3-dev|3-shlibs)?$'                 => [ '1.2.4',        '1'    ],
		'^libgdiplus$'                              => [ '1.2.5',        '1'    ],
		'^libgeos2(-.*)?$'                          => [ '2.1.4',        '1001' ],
		'^libglade2(-dev|-shlibs)?$'                => [ '2.6.0',        '1'    ],
		'^libgnomedb(3-dev|3-shlibs)?$'             => [ '1.2.2',        '1'    ],
		'^libgnome(ui)?2(-dev|-shlibs)?$'           => [ '2.20.0',       '1'    ],
		'^libgnomecanvas2(-dev|-shlibs)?$'          => [ '2.20.0',       '1'    ],
		'^libgnomeprint(ui)?2.2(-dev|-shlibs)?$'    => [ '2.18.1',       '1'    ],
		'^libhttpd-persistent$'                     => [ '1.3',          '1010' ],
		'^libidl2(-shlibs)?$'                       => [ '0.8.9',        '1'    ],
		'^libmath..(-dev)?$'                        => [ '0.0.4',        '1001' ],
		'^libmp4v21(-dev|-shlibs)?$'                => [ '2.0.0',        '1013' ],
		'^libmusicbrainz4(-shlibs)?$'               => [ '2.1.1',        '1001' ],
		'^libnc-dap3(-shlibs)?$'                    => [ '3.5.2',        '1001' ],
		'^(libncurses5(-shlibs)?|ncurses)$'         => [ '5.4-20041023', '1006' ],
		'^libncursesw5(-shlibs)?$'                  => [ '5.4-20041023', '1001' ],
		'^libofx1(-shlibs)?$'                       => [ '0.7.0',        '1002' ],
		'^libogdi3(-bin|-shlibs)?$'                 => [ '3.1.5',        '1002' ],
		'^libpng3(-shlibs)?$'                       => [ '1.2.8',        '1'    ],
		'^librep(-dev|-shlibs)?$'                   => [ '0.16.2',       '1011' ],
		'^librsvg2(-bin|-gtk|-shlibs)?$'            => [ '2.18.2',       '1'    ],
		'^librsync(-bin|-shlibs)?$'                 => [ '0.9.7',        '1001' ],
		'^libsablot(-dev|-shlibs)?$'                => [ '0.98',         '1024' ],
		'^libsidplay(-shlibs)?$'                    => [ '1.36.59',      '1001' ],
		'^libsigc..12(-shlibs)?$'                   => [ '1.2.5',        '1002' ],
		'^libsigc..2(-shlibs)?$'                    => [ '2.0.11',       '1003' ],
		'^libtunepimp2(-shlibs)?$'                  => [ '0.3.0',        '1001' ],
		'^libusb(-shlibs)?$'                        => [ '0.1.8',        '1015' ],
		'^libwpd-0.8(-shlibs)?$'                    => [ '0.8.2',        '1001' ],
		'^libwpd1(-shlibs)?$'                       => [ '0.7.2',        '1011' ],
		'^libxml2(-shlibs)?$'                       => [ '2.6.27',       '1'    ],
		'^libxml..2(-shlibs)?$'                     => [ '2.10.0',       '1001' ],
		'^matplotlib-py..$'                         => [ '0.86.1',       '1002' ],
		'^mjpegtools2?(-dev|-shlibs)?$'             => [ '1.6.2',        '1003' ],
		'^mono(-dev|-shlibs)$',                     => [ '1.2.5',        '1021' ],
		'^mono-tools$',                             => [ '1.2.4',        '1'    ],
		'^monodevelop$'                             => [ '0.15',         '1'    ],
		'^monodoc$'                                 => [ '1.2',          '1021' ],
		'^mozilla(-.*)?$'                           => [ '1.7.5',        '1102' ],
		'^mysql(-dev|-shlibs)?$'                    => [ '3.23.58',      '1023' ],
		'^mysql12(-dev|-shlibs)?$'                  => [ '4.0.22',       '1012' ],
		'^mysql14(-dev|-shlibs)?$'                  => [ '4.1.10',       '1002' ],
		'^mysql15(-dev|-shlibs)?$'                  => [ '5.0.16',       '1001' ],
		'^nant$'                                    => [ '0.85',         '1038' ],
		'^ncurses-(dev|shlibs)$'                    => [ '5.3-20031018', '1501' ],
		'^netcdf(-bin|-shlibs)?$'                   => [ '3.6.0',        '1002' ],
		'^openexr(-dev)?$'                          => [ '1.2.2',        '31'   ],
		'^openhbci(-shlibs)?$'                      => [ '0.9.13',       '1012' ],
		'^openjade$'                                => [ '1.3.2',        '1028' ],
		'^orbit2(-dev|-shlibs)?$'                   => [ '2.14.9',       '1'    ],
		'^pango1-xft2-ft219(-shlibs|-dev)?$'        => [ '1.18.2',       '1'    ],
		'^pango1-xft2(-shlibs|-dev)?$'              => [ '1.10.0',       '1001' ],
		'^pdcurses(-shlibs)?$'                      => [ '2.6',          '1013' ],
		'^pdflib(-shlibs)?$'                        => [ '5.0.3',        '1002' ],
		'^pdflib-py..$'                             => [ '5.0.3',        '1001' ],
		'^pilot-link9(-bin|-py.+|-shlibs)?$'        => [ '0.11.8',       '1035' ],
		'^pkgconfig$'                               => [ '0.21',         '1'    ],
		'^postgresql-perl.*$'                       => [ '8.1.2',        '1022' ],
		'^postgresql-tcl.*$'                        => [ '8.1.2',        '1021' ],
		'^postgresql80(-.*)?$'                      => [ '8.0.6',        '1026' ],
		'^pstoedit(-bin|-shlibs)?$'                 => [ '3.40',         '1002' ],
		'^pygtk-py23$'                              => [ '0.6.9',        '1016' ],
		'^python23(-shlibs|-socket)?$'              => [ '1:2.3.5',      '1124' ],
		'^python23-nox(-shlibs|-socket)?$'          => [ '1:2.3.4',      '1104' ],
		'^python23-socket-ssl$'                     => [ '1:2.3.5',      '1101' ],
		'^python24(-shlibs|-socket)?$'              => [ '1:2.4.2',      '1004' ],
		'^python24-socket-ssl$'                     => [ '2.4.2',        '1101' ],
		'^qca(-shlibs)?$'                           => [ '1.0',          '1023' ],
		'^qcad$'                                    => [ '2.0.1.3-1',    '1002' ],
		'^qt3(-.+)?$'                               => [ '3.3.8',        '1021' ],
		'^qt3mac(-mysql|-postgresql)?$'             => [ '3.3.5',        '1001' ],
		'^r-base$'                                  => [ '2.1.1',        '1001' ],
		'^readline(-shlibs)?$'                      => [ '4.3',          '1028' ],
		'^readline5(-shlibs)?$'                     => [ '5.0',          '1004' ],
		'^rep-gtk$'                                 => [ '0.18',         '1013' ],
		'^reportlab-.*$'                            => [ '1.20',         '1011' ],
		'^sane-backends(-dev|-shlibs)?$'            => [ '1.0.15',       '1004' ],
		'^sdl(-shlibs)?$'                           => [ '1.2.9',        '1001' ],
		'^sdl-mixer(-shlibs)?$'                     => [ '1.2.6',        '1012' ],
		'^smpeg(-shlibs)?$'                         => [ '0.4.4',        '1025' ],
		'^svn(-.*)?$'                               => [ '1.2.3',        '1012' ],
		'^swig(-shlibs)?$'                          => [ '1.3.31',       '1'    ],
		'^taglib(-shlibs)?$'                        => [ '1.4',          '1001' ],
		'^unixodbc2(-.*)?$'                         => [ '2.2.11',       '1010' ],
		'^vte(9-dev|9-shlibs)?$'                    => [ '0.16.9',       '1'    ],
		'^w3m(-ssl)?$'                              => [ '0.5.1',        '1003' ],
		'^wv2(-shlibs)?$'                           => [ '0.2.2',        '1001' ],
		'^wxmac(-shlibs)?$'                         => [ '2.6.1',        '1001' ],
		'^xmlto$'                                   => [ '0.0.18',       '1005' ],
		'^xpdf$'                                    => [ '3.01',         '1002' ],
		'^yelp-viewer(-firefox|-mozilla)$'          => [ '2.12.2',       '1001' ],
		'^zope$'                                    => [ '2.6.3',        '1102' ],
		'^macosx$'                                  => [ '10.4.3',       '1'    ],
	},
	'all' => {
		'^arts(-dev|-shlibs)?$'                     => [ undef,          '+'    ],
		'^autoconf$'                                => [ '2.60',         '1'    ],
		'^fink$'                                    => [ '0.26.0',       '1'    ],
		'^glib2(-dev|-shlibs)?$'                    => [ '2.14.0',       '1'    ],
		'^gnokii2(-dev|-shlibs)?$'                  => [ '0.6.12',       '1'    ],
		'^gst.*$'                                   => [ undef,          '+'    ],
#		'^gtk.2(-dev|-shlibs)?$'                    => [ '2.10.0',       '1'    ],
		'^gtk-doc$'                                 => [ '1.5',          '1'    ],
		'^kde\S+(i18n|3|3-unified)(-dev|-shlibs)?$' => [ undef,          '+'    ],
		'^libmal10(-shlibs)?$'                      => [ undef,          '+'    ],
		'^libcdparanoia0-dev$'                      => [ '3a9.8',        '11'   ],
		'^libpqxx2(-dev|-shlibs)?$'                 => [ '1:2.6.8',      '1'    ],
#		'^qt3(-.+)?$'                               => [ undef,          '+'    ],
#		'^pango1-xft2-ft219(-dev|-shlibs)?$'        => [ '1.14.0',       '1'    ],
		'^postgresql\S+$'                           => [ undef,          '+'    ],
		'^unsermake$'                               => [ '0.4',          '0.20060316.1' ],
	},
};

my @KEYS = (
	'Package', 'Version', 'Revision', 'Epoch', 'Architecture', 'Distribution',
		'Description', 'Type', 'License', 'Maintainer', '<CR>',
	'Depends', 'BuildDepends', 'BuildConflicts', 'Provides', 'Conflicts', 'Replaces',
		'Recommends', 'Suggests', 'Enhances', 'Pre-Depends', 'Essential',
		'BuildDependsOnly', 'GCC', '<CR>',
	'CustomMirror', 'Source', 'Source<N>', 'SourceDirectory', 'Source<N>Directory',
		'NoSourceDirectory', 'SourceExtractDir', 'Source<N>ExtractDir', 'SourceRename',
		'Source<N>Rename', 'Source-MD5', 'Source<N>-MD5', 'TarFilesRename',
		'Tar<N>FilesRename', 'UpdateConfigGuess', 'UpdateConfigGuessInDirs',
		'UpdateLibtool', 'UpdateLibtoolInDirs', 'UpdatePoMakefile', 'Patch',
		'PatchScript', 'PatchFile', 'PatchFile-MD5', '<CR>',
	'Set<S>', 'NoSet<S>', 'ConfigureParams', 'CompileScript', '<CR>',
	'UpdatePOD', 'InstallScript', 'NoPerlTests', 'JarFiles', 'DocFiles',
		'RuntimeVars', 'SplitOff', 'SplitOff<N>', 'Files', 'Shlibs', '<CR>',
	'PreInstScript', 'PostInstScript', 'PreRmScript', 'PostRmScript', 'ConfFiles',
		'InfoDocs', 'DaemonicFile', 'DaemonicName', '<CR>',
	'Homepage', 'DescDetail', 'DescUsage', 'DescPackaging', 'DescPort',
);

my @TREES = qw( 10.4 );

my $APPEND_USAGE = '^arts|kde\S+3|kdevelop|koffice|bundle-kde|kgpg';

if (not @files) {
	find(sub {
		push(@files, $File::Find::name);
	}, $path . '/common', $path . '/3rdparty/common');
}

FILELOOP: for my $file (@files) {
	next if ($file eq "-p");
	if ($file !~ /^\//) {
		$file = $path . '/' . $file;
	}
	my ($dir, $filename) = (dirname($file), basename($file));

	next if ($file =~ /\/\.svn\//);
	next unless ($file =~ /\.(info|patch)$/);

	my $matched = 0;
	for my $regex (@$translate) {
		$matched++ if ($file =~ /$regex/);
	}
	next if (not $matched);
	next if ($file =~ /notready/);

	my $contents;
	if (open (FILEIN, $file)) {
		local $/ = undef;
		$contents = <FILEIN>;
		close (FILEIN);
	} else {
		warn "unable to read from $file: $!\n";
		next;
	}

	print $file, "\n";
	if ($file =~ /\.info$/) {
		my $properties = info_hash_from_var(
			$file,
			$contents,
			{ case_sensitive => 1 },
		);

#		print Dumper($properties), "\n";

		for my $tree (@TREES) {
			next if ($file =~ /postgresql73/ and $tree ne "10.3");

			my $treeproperties = clone($properties);
			$treeproperties->{'Tree'} = $tree;

			$treeproperties = transform_fields($treeproperties, clone($treeproperties));

			my $todir = $dir;
			$todir =~ s#/common/#/${tree}/#;
			$todir =~ s#/3rdparty/common/#/3rdparty/${tree}/#;
			mkdir_p($todir) unless (-d $todir);

			my $info = serialize_to_info($treeproperties) . "\n";
			if (open (FILEOUT, '>' . $todir . '/' . $filename)) {
				print FILEOUT $info;
				close (FILEOUT);
			}
		}

	} elsif ($file =~ /\.patch$/) {
		for my $tree (@TREES) {
			next if ($file =~ /postgresql73/ and $tree ne "10.3");

			my $todir = $dir;
			$todir =~ s#/common/#/${tree}/#;
			$todir =~ s#/3rdparty/common/#/3rdparty/${tree}/#;
			mkdir_p($todir) unless (-d $todir);

			if (open (FILEOUT, '>' . $todir . '/' . $filename)) {
				print FILEOUT transform_patch($tree, $contents);
				close (FILEOUT);
			}
		}

	} else {
		warn "unhandled file: $file\n";
	}

}

sub transform_fields {
	my $packagehash = shift;
	my $properties  = shift;

	for my $field (keys %$properties) {
		my $lcfield = lc($field);
		no strict qw(refs);
		if ($field =~ /^splitoff/i) {
			$properties->{$field} = transform_fields($packagehash, $properties->{$field});
		} elsif (defined &{"transform_$lcfield"}) {
			$properties->{$field} = &{"transform_$lcfield"}($packagehash, $properties->{$field});
		} else {
			#warn "unhandled field: $field\n";
		}
	}

	if (exists $properties->{'Type'} and $properties->{'Type'} =~ /^perl\(/ and $properties->{'Tree'} ge "10.4") {
		if (exists $properties->{'Architecture'}) {
			warn "type = perl, but architecture is already set!\n";
		} else {
			$properties->{'Architecture'} = '(%type_pkg[perl] = 581) powerpc, (%type_pkg[perl] = 584) powerpc';
		}
		if (exists $properties->{'Distribution'}) {
			warn "type = perl, but distribution is already set!\n";
		} else {
			$properties->{'Distribution'} = '(%type_pkg[perl] = 581) 10.3, (%type_pkg[perl] = 581) 10.4, (%type_pkg[perl] = 584) 10.3, (%type_pkg[perl] = 584) 10.4';
		}
	}

	if ($packagehash->{'Package'} =~ /$APPEND_USAGE/i) {
		$properties->{'DescUsage'} = transform_descusage($packagehash, $properties->{'DescUsage'});
	}

	return $properties;
}

sub print_indent {
	my $field_name = shift;
	my $text       = shift;
	my $indent     = shift || 0;

	$text =~ s/^\n+//gsi;
	$text =~ s/\n+$//gsi;

	my $return = "";

	if ($text =~ /\n/) {
		$return .= "\t" x $indent . $field_name . ": <<\n";
		if ($field_name =~ /^(builddepends|conffiles|conflicts|custommirror|depends|enhances|files|patchscript|recommends|replaces|runtimedepends|shlibs|suggests)$/i) {
			for my $line (split(/\n/, $text)) {
				$line =~ s/^\s+//;
				$return .= "\t" x ($indent + 1) . $line . "\n";
			}
		} else {
			$return .= $text . "\n";
		}
		$return .= "\t" x $indent . "<<\n";
	} else {
		$return .= "\t" x $indent . $field_name . ": " . $text . "\n";
	}

	return $return;
}

sub serialize_to_info {
	my $package = clone(shift);
	my $indent  = shift || 0;

	#print Dumper($package), "\n";
	my $output = "";

	delete $package->{'Tree'};
	my $infolevel = int($package->{'InfoLevel'});
	delete $package->{'InfoLevel'};

	$output .= "Info${infolevel}: <<\n" if ($infolevel >= 2 and not $indent);

	for my $key (@KEYS) {
		if ($key eq "<CR>") {
			$output .= "\n" unless ($output =~ /\n\n$/gs or $indent);
		} elsif ($key =~ /<N>/) {
			my $regex = $key;
			$regex =~ s/<N>/\\d\+/gs;
			for my $field (sort keys %$package) {
				if ($field =~ /^\s*${regex}\s*$/gsi) {
					if (ref $package->{$field}) {
						$output .= print_indent($field, serialize_to_info($package->{$field}, $indent + 1), $indent);
					} else {
						$output .= print_indent($field, $package->{$field}, $indent);
					}
					delete $package->{$field};
					#warn "$key matched $field (/^$regex\$/i\n";
				} else {
					#warn "$key did not match $field (/^$regex\$/i\n";
				}
			}
		} elsif ($key =~ /<S>/) {
			my $regex = $key;
			$regex =~ s/<S>/\.\+/gs;
			for my $field (sort keys %$package) {
				if ($field =~ /^\s*${regex}\s*$/gsi) {
					if (ref $package->{$field}) {
						$output .= print_indent($field, serialize_to_info($package->{$field}, $indent + 1), $indent);
					} else {
						$output .= print_indent($field, $package->{$field}, $indent);
					}
					delete $package->{$field};
					#warn "$key matched $field (/^$regex\$/i\n";
				} else {
					#warn "$key did not match $field (/^$regex\$/i\n";
				}
			}
		} else {
			for my $field (keys %$package) {
				if ($field =~ /^\s*${key}\s*$/gsi) {
					if (ref $package->{$field}) {
						$output .= print_indent($key, serialize_to_info($package->{$field}, $indent + 1), $indent);
					} else {
						$output .= print_indent($key, $package->{$field}, $indent);
					}
					delete $package->{$field};
				}
			}
		}
	}

	for my $key (sort keys %$package) {
		die "ERROR: '$key' is missing from \@KEYS!\n";
	}

	$output =~ s/\n\n+/\n\n/gsi;
	$output .= "<<\n" if ($infolevel >= 2 and not $indent);

	# do a second pass to reorder Source: lines, 'cause doing it
	# in a generic way will take an insane amount of code  :P
	my $final_output = '';
	my $done_source  = 0;
	my $in_source    = 0;
	my %source_items;
	for my $line (split(/\n/, $output))
	{
		if ($line =~ /^[^:]*Source[^:]*:/ and not $done_source)
		{
			if (not $in_source)
			{
				$final_output .= "<<<<SOURCE_PLACEHOLDER>>>>\n";
				$in_source = 1;
			}
			my ($key, $value) = $line =~ /^(\s*[^\:]+):(.*)$/;
			$source_items{$key} = $value;
			next;
		}
		elsif ($in_source)
		{
			$in_source = 0;
		}
		$final_output .= $line . "\n";
	}

	my $source_lines = join("\n", map { $_ = $_ . ":" . $source_items{$_} } sort(keys(%source_items)));
	$final_output =~ s/<<<<SOURCE_PLACEHOLDER>>>>/$source_lines/gs;
	return $final_output;
}

sub prettify_field_name {
	my $field = shift;

	for my $key (@KEYS) {
		if ($key =~ /<N>/) {
			my $regex = $key;
			$regex =~ s/<N>/\(\\d\+\)/gs;
			if (my ($number) = $field =~ /^${regex}$/gsi) {
				my $field_name = $key;
				$field_name =~ s/<N>/$number/gsi;
				return $field_name;
			}
		} elsif (my ($set, $var) = $field =~ /^(NoSet|Set)(.*)$/i) {
			if ($set =~ /^no/i) {
				return "NoSet" . uc($var);
			} else {
				return "Set" . uc($var);
			}
		} elsif ($key =~ /<S>/i) {
			my $regex = $key;
			$regex =~ s/<S>/\(\.\+\)/gsi;
			if (my ($string) = $field =~ /^${regex}$/i) {
				my $field_name = $key;
				$field_name =~ s/<S>/$string/gsi;
				return $field_name;
			}
		} elsif ($field =~ /^\s*${key}\s*$/gsi) {
			# warn "prettify: $key =~ /^${field}\$/gsi matched\n";
			return $key;
		} else {
			# warn "prettify: $key =~ /^${field}\$/gsi did not match\n";
		}
	}
	warn "prettify: no match for '$field'\n";
	return $field;
}

sub transform_builddepends {
	return transform_depends(@_);
}

sub transform_compilescript {
	my $tree          = shift->{'Tree'};
	my $compilescript = shift;

	if ($tree eq '10.4') {
		# I really don't like having these hardcoded here, need to figure out a way to
		# make it more configurable
		$compilescript =~ s/(gcc|g\+\+)-3.3/$1/gs;
		$compilescript =~ s/USE_EXCEPTIONS=\"[^\"]+\"//gs;
	}

	return $compilescript;
}

sub transform_configureparams {
	my $tree   = shift->{'Tree'};
	my $params = shift;

	if ($tree eq '10.4') {
		$params =~ s/--disable-java//gs;
	}

	return $params;
}

sub transform_conflicts {
	transform_depends(@_);
}

sub transform_custommirror {
	my $packagehash = shift;
	my $contents    = shift;

	if ($contents =~ /^\s*rangermirror\s*$/gsi) {
		if (open (RANGER, "rangermirror.txt")) {
			$contents = "";
			while (<RANGER>) {
				next if (/CustomMirror:/i);
				next if (/^\s*\<\<\s*$/);
				$contents .= $_;
			}
			chomp($contents);
			close(RANGER);
		}
	}
	return $contents;
}

sub transform_depends {
	my $packagehash = shift;
	my $depends     = pkglist2lol(shift);
	my @newdepends;

	for my $dep (@$depends) {
		my @newdep;
		for my $pkg (@$dep) {
			my $newdep = transform_dependency($packagehash->{'Tree'}, $pkg);
			push(@newdep, $newdep) if (defined $newdep);
		}
		push(@newdepends, \@newdep);
	}

	my $list = lol2pkglist(\@newdepends);
	$list =~ s/\s*,\s*/,\n/gs;
	return $list;
}

sub transform_dependency {
	my $tree     = shift;
	my $dep_spec = shift;
	my $delete   = 0;

	my ($prefix, $package, $comparator, $version, $revision);
	if ($dep_spec =~ s/^\s*\(([^\)]+)\)\s+//) {
		$prefix = $1;
	}
	if (($package, $comparator, $version, $revision) = $dep_spec =~ /^(\S+)\s+\(([\>\=\<]+)\s*(\S+)\-(\S+)\)$/) {
		#print "transform_dependency[$dep_spec]: $package matched long-form dep\n";
	} elsif (($package) = $dep_spec =~ /^(\S+)$/) {
		#print "transform_dependency[$dep_spec]: $package matched short-form dep\n";
	} elsif (($package, $comparator, $version) = $dep_spec =~ /^(\S+)\s+\(([\>\=\<]+)\s*([^\-\s]+)\)$/) {
		#print "transform_dependency[$dep_spec]: $package matched incorrect dep\n";
		$revision = 0;
	} elsif ($dep_spec =~ /^\#/) {
		# don't do anything, it's a comment
	} else {
		warn "transform_dependency[$dep_spec]: unhandled dependency specification\n";
	}

	my $matched = 0;
	for my $tree_iterator ($tree, 'all') {
		last if ($matched);
		if (exists $package_lookup->{$tree_iterator}) {
			for my $key (keys %{$package_lookup->{$tree_iterator}}) {
				my $replace = $package_lookup->{$tree_iterator}->{$key};
				if ($package =~ /$key/i) {
					if (not defined $replace) {
						$delete++;
					} else {
						$package =~ s/$key/$replace/gsi;
					}
				}
			}
		}
		if (exists $version_lookup->{$tree_iterator} and $comparator =~ /\>/) {
			#print "checking in $tree_iterator\n";
	
			for my $key (keys %{$version_lookup->{$tree_iterator}}) {
				if ($package =~ /$key/i) {
					#print "transform_dependency[$dep_spec]: $package matches $key\n";
					my ($newversion, $newrevision) = @{$version_lookup->{$tree_iterator}->{$key}};
					if (defined $version and defined $revision and $revision ne '%r' and $newrevision eq '+') {
						$revision = transform_revision( $tree, $revision );
					} elsif (defined $newversion and defined $newrevision and $revision ne '%r') {
						$version  = $newversion;
						$revision = $newrevision;
					} else {
						if ((not defined $version and not defined $revision) or ($version eq '%v' and $revision eq '%r')) {
							# it's OK to do nothing here
						} else {
							warn "transform_dependency[$dep_spec]: not sure how to handle ($newversion, $newrevision) when version = $version and revision = $revision\n";
						}
					}
					$matched++;
					last;
				} else {
					#print "transform_dependency[$dep_spec]: $package does not match $key\n";
				}
			}
		}
	}

	if (defined $package and defined $version and defined $revision) {
		$comparator = '>=' unless (defined $comparator);
		$dep_spec = $package . ' (' . $comparator . ' ' . $version . '-' . $revision . ')';
		$dep_spec = '(' . $prefix . ') ' . $dep_spec if (defined $prefix);
	} elsif (defined $package) {
		$dep_spec = $package;
		$dep_spec = '(' . $prefix . ') ' . $dep_spec if (defined $prefix);
	}

	#print "transform_dependency: returning $dep_spec\n";

	return undef if ($delete);
	return $dep_spec;
}

sub transform_descusage {
	my $packagehash = shift;
	my $descusage   = shift;

	if ($packagehash->{'Package'} =~ /$APPEND_USAGE/i) {
		if (open (FILEIN, $path . '/kdedesc.txt')) {
			local $/ = undef;
			if ($descusage !~ /^[\s\n]*$/gsi) {
				warn "descusage is not empty, overwriting:\n$descusage\n";
			}
			$descusage = <FILEIN>;
			close (FILEIN);
		} else {
			warn "unable to open kdedesc.txt: $!\n";
		}
	}

	return $descusage;
}

sub transform_enhances {
	return transform_depends(@_);
}

sub transform_files {
	my $tree  = shift->{'Tree'};
	my $files = shift;

	my @newlines;

	for my $line (split(/\r?\n/, $files)) {
		if ($tree eq "10.3") {
			next if ($line =~ /libkfontinst/i);
		}
		push(@newlines, $line);
	}

	return join("\n", @newlines);
}

sub transform_gcc {
	my $tree = shift->{'Tree'};
	my $gcc  = shift;

	if ($tree eq "10.4") {
		$gcc = "4.0";
	} else {
		$gcc = "3.3";
	}

	return $gcc;
}

sub transform_patch {
	my $tree = shift;
	my $text = shift;

	if ($tree eq "10.4") {
		$text =~ s/g(cc|\+\+)-3\.3/g$1-4.0/gi;
		$text =~ s/-fno-coalesce//gs;
	}

	$text =~ s/(^|[\r\n]+)diff -uN[^\r\n]*//gs;

	return $text;
}

sub transform_patchscript {
	my $tree = shift->{'Tree'};
	my $text = shift;

	if ($tree eq "10.4") {
		$text =~ s/g(cc|\+\+)-3\.3/g$1-4.0/gi;
		$text =~ s/-fno-coalesce//gs;
	}

	return $text;
}

sub transform_recommends {
	return transform_depends(@_);
}

sub transform_replaces {
	return transform_depends(@_);
}

sub transform_revision {
	my $tree     = shift;
	my $revision = shift;
	$tree = $tree->{'Tree'} if (ref $tree eq "HASH");

	if ($tree eq '10.3') {
		$revision = revision_add($revision, 10);
	} elsif ($tree eq '10.4') {
		$revision = revision_add($revision, 0);
	} elsif ($tree eq '10.5') {
		$revision = revision_add($revision, 20);
	} else {
		warn "unhandled tree '$tree'\n";
	}
	return $revision;
}

sub transform_runtimedepends {
	return transform_depends(@_);
}

sub transform_setcc {
	my $tree  = shift->{'Tree'};
	my $setcc = shift;

	if ($tree eq '10.4') {
		$setcc =~ s/3\.3/4.0/gs;
	}

	return $setcc;
}

sub transform_setcflags {
	my $tree = shift->{'Tree'};
	my $text = shift;

	if ($tree eq "10.3") {
		$text =~ s/\-D_POLL_EMUL_H_//gs;
	}

	return $text;
}

sub transform_setcppflags {
	transform_setcflags(@_);
}

sub transform_setcxx {
	transform_setcc(@_);
}

sub transform_setcxxflags {
	transform_setcflags(@_);
}

sub transform_shlibs {
	my $tree   = shift->{'Tree'};
	my $shlibs = shift;
	my @newlines;

	for my $line (split(/\r?\n/, $shlibs)) {
		if ($tree eq "10.3") {
			next if ($line =~ /libkfontinst/i);
		}

		# whoo!  crazy lexing!
		my $newline;
		while ($line =~ /\G(.+?\(\S+\s+\S+\-)([^\-]+)\)/gsi) {
			my ($rest, $revision) = ($1, $2);
			$newline .= $rest . transform_revision( $tree, $revision ) . ')';
		}
		$line =~ /\G\(.*$/;
		$newline .= $1;

		push(@newlines, $line);
	}

	return join("\n", @newlines);
}

sub transform_suggests {
	return transform_depends(@_);
}

sub transform_type {
	my $tree = shift->{'Tree'};
	my $type = shift;
	if ($type =~ /^perl\s*\(0\)/i) {
		my @versions = qw(5.6.0 5.6.1 5.8.0 5.8.1 5.8.4 5.8.5 5.8.6 5.8.8);
		if ($tree =~ /^10.3/) {
			@versions = qw(5.6.0 5.8.0 5.8.1 5.8.4 5.8.6);
		} elsif ($tree =~ /^10.4/) {
			@versions = qw(5.8.1 5.8.4 5.8.6 5.8.8);
		}
		$type = "perl(@versions)";
	} elsif ($type =~ /^python\s*\(0\)/i) {
		my @versions = qw(2.1 2.2 2.3 2.4 2.5);
		if ($tree =~ /^10.3/) {
			@versions = qw(2.2 2.3 2.4);
		} elsif ($tree =~ /^10.4/) {
			@versions = qw(2.3 2.4 2.5);
		}
		$type = "python(@versions)";
	} elsif ($type =~ /^java\s\(0\)/i) {
		if ($tree =~ /^10.3/) {
			$type = "java(1.4)";
		} else {
			$type = "java(1.5)";
		}
	}

	return $type;
}

sub transform_version {
	my $packagehash = shift;
	my $version     = shift;
	return $version;
}

sub revision_add {
	my $revision = shift;
	my $amount   = shift;

	if (my ($pre, $post) = $revision =~ /^(.*\.)(\d+)$/) {
		$post += $amount;
		$revision = $pre . $post;
	} else {
		$revision += $amount;
	}
	return $revision;
}

sub info_hash_from_var {
	my $filename = shift;
	my $var      = shift;
	my $options  = shift;
	my $infolevel = 0;

	my $properties = read_properties_var(
		$filename,
		$var,
		$options,
	);
	($properties, $infolevel) = Fink::PkgVersion->handle_infon_block($properties, $filename);

	my $return;

	for my $key (keys %$properties) {
		my $newkey = prettify_field_name($key);
		#print "$key = $newkey\n";
		if ($key =~ /^splitoff/i) {
			$return->{$newkey} = info_hash_from_var(
				$filename . ' (' . $key . ')',
				$properties->{$key},
				{ remove_space => 1, %$options },
			);
		} else {
			$return->{$newkey} = $properties->{$key};
		}
	}

	$return->{'InfoLevel'} = $infolevel;

	return $return;
}

sub mkdir_p {
	my $dir = shift;

	eval { mkpath($dir, 0, 0775) };
	if ($@) {
		warn "unable to create $dir: $!\n";
	} else {
		return 1;
	}
	return;
}
