--- /dev/null
+CREATE OR REPLACE FUNCTION conifer.osul_to_lusys(record BIGINT) RETURNS TEXT AS $func$
+use strict;
+use MARC::Record;
+use MARC::File::XML (BinaryEncoding => 'UTF-8');
+use MARC::Charset;
+use Encode;
+use Unicode::Normalize;
+
+MARC::Charset->assume_unicode(1);
+
+my $q = spi_prepare('SELECT marc FROM biblio.record_entry WHERE id = $1', 'BIGINT');
+my $marc = spi_exec_prepared($q, $_[0])->{rows}->[0]->{marc};
+
+my $record = MARC::Record->new_from_xml($marc);
+
+my @eights = $record->field('856');
+foreach my $ocho (@eights) {
+ my @ous = $ocho->subfield('9');
+ foreach my $ou (@ous) {
+ if ($ou eq 'WINDSYS') {
+ $record->delete_field($ocho);
+ }
+ if ($ou eq 'OSUL') {
+ $ocho->update('9' => 'LUSYS');
+ }
+ }
+}
+
+my @access = $record->field('506');
+foreach my $note (@access) {
+ my @ous = $note->subfield('9');
+ foreach my $ou (@ous) {
+ if ($ou eq 'OWA') {
+ $record->delete_field($note);
+ }
+ }
+}
+
+my $xml = $record->as_xml_record();
+$xml =~ s/\n//sgo;
+$xml =~ s/^<\?xml.+\?\s*>//go;
+$xml =~ s/>\s+</></go;
+$xml =~ s/\p{Cc}//go;
+
+# Embed a version of OpenILS::Application::AppUtils->entityize()
+# to avoid having to set PERL5LIB for PostgreSQL as well
+
+$xml = NFC($xml);
+
+# Convert raw ampersands to entities
+$xml =~ s/&(?!\S+;)/&/gso;
+
+# Convert Unicode characters to entities
+$xml =~ s/([\x{0080}-\x{fffd}])/sprintf('&#x%X;',ord($1))/sgoe;
+
+$xml =~ s/[\x00-\x1f]//go;
+
+return $xml;
+$func$ LANGUAGE PLPERLU;