#!/usr/bin/perl -w
#
# This script will try (hard) to convert database from
# PhpMyLibrary (http://phpmylibrary.sourceforge.net/) back
# to MARC format
#
# 2003-01-31 Dobrica Pavlinusic <dpavlin@rot13.org>
#
# This script is written for WebPac project available at
# http://webpac.sourceforge.net/
#
# MARC file format documentation is taken from
# http://www.ariadne.ac.uk/issue7/marc/
#
# 

use DBI;
use strict;
use Getopt::Long;

my $database = "postnuke";
my $host = "localhost";
my $user = "root";
my $passwd = "";

my $usage = 0;

my $result = GetOptions(
	"database=s" => \$database,
	"host=s" => \$host,
	"user=s" => \$user,
	"password=s" => \$passwd,
	"help!" => \$usage,
	);

if ($usage) {
	print qq{usage: $0 [--database="$database" --host="$host" --user="$user" --password="$passwd"] > file.marc\n
This script will convert PhpMyLibrary database to standard UNIMARC format\n};
	exit 1;
}

my $dsn = "DBI:mysql:database=$database;host=$host";
my $dbh = DBI->connect($dsn, $user, $passwd, {'RaiseError' => 1});

# UNIMARC leader format
my $leader_fmt = qq{%05diam0 22%05d   45  };


my $sth = $dbh->prepare("SELECT marc FROM tblbib");
$sth->execute();
while (my $row = $sth->fetchrow_hashref()) {
	my $marc = $row->{'marc'};

	my $real_len = length($marc);

	# fix PhpMyLibrary MARC (why do I have to do this? It's MARC,
	# for gaddem sake!!!
	
	# Byte        Name
	# ----        ----
	# 0-4         Record Length
	# 5           Status (n=new, c=corrected and d=deleted)
	# 6           Type of Record (a=printed material)
	# 7           Bibliographic Level (m=monograph)
	# 8-9         Blanks
	# 10          Indictator count (2 for monographs)
	# 11          Subfield code count (2 - 0x1F+subfield code itself)
	# 12-16       Base address of data
	# 17          Encoding level (blank=full level, 1=sublevel 1, 2=sublevel 2,
	# 		3=sublevel 3)
	# 18          Descriptive Cataloguing Form (blank=record is full ISBD,
	#		n=record is in non-ISBD format, i=record is in
	#		an incomplete ISBD format)
	# 19          Blank
	# 20          Length of length field in directory (always 4 in UNIMARC)
	# 21          Length of Starting Character Position in directory (always
	# 		5 in UNIMARC)
	# 22          Length of implementation defined portion in directory (always
	# 		0 in UNIMARC)
	# 23          Blank
	#
	#           |0   4|5  89  |12 16|1n 450 |
	#           (xxxxx)nam  22(.....)   450 <---
	$marc =~ m/^(.....)......(.....)polerioj/ || die "record: '$marc' unparsable!";
	my ($reclen,$base_addr) = ($1,$2);
	my $leader = sprintf($leader_fmt,length($marc)+1,$base_addr);

	print $leader . substr($marc,24).chr(29);
}
$sth->finish();
$dbh->disconnect();
