#!/usr/bin/perl

use strict;

BEGIN {

    # find Koha's Perl modules
    # test carefully before changing this
    use FindBin;
    eval { require "$FindBin::Bin/../kohalib.pl" };
}

use C4::Context;
use C4::Biblio;
use C4::Items;
use C4::Record;
use Getopt::Long;

$| = 1;

my $dbh= C4::Context->dbh;

my $sth= $dbh->prepare("SELECT biblionumber,itemnumber FROM items");
$sth->execute;

my $query=$dbh->prepare("SELECT marcxml FROM biblioitems WHERE biblionumber=?");

my $i=0;
while (my ($biblionumber,$itemnumber) = $sth->fetchrow) {
    # Get marcxml from biblioitem
    $query->execute($biblionumber);
    while ( my $marcxml = $query->fetchrow) {
        # create Marc record from marcxml
        my $itemrecord = C4::Record::marcxml2marc($marcxml);
#warn "DUMP : ".$itemrecord->as_formatted;
        my $frameworkcode = GetFrameworkCode($biblionumber);
        my ( $itemtag, $itemsubfield ) = GetMarcFromKohaField("items.itemnumber", $frameworkcode );
        # for each 995 field found
        ITEMFIELD: foreach my $item_field ( $itemrecord->field($itemtag) ) {
            # create an item
            my $localitemmarc = MARC::Record->new;
            $localitemmarc->append_fields( $item_field );
#warn "localitemmarc : ".Data::Dumper::Dumper($localitemmarc);
            my $item = &TransformMarcToKoha( $dbh, $localitemmarc, $frameworkcode, 'items' );
            # step to next if it does not match current itemnumber
            next ITEMFIELD unless ($item->{'itemnumber'} eq $itemnumber);
#warn Data::Dumper::Dumper($item);
            # get unlinked subfield (list should have changed if we use this script)
            my $unlinked_item_subfields = C4::Items::_get_unlinked_subfields_xml(C4::Items::_get_unlinked_item_subfields($localitemmarc, $frameworkcode ));
#warn "more_subfield = ".Data::Dumper::Dumper($unlinked_item_subfields);
            # modify item with values from marcxml
            ModItem($item, $biblionumber, $itemnumber, $dbh, $frameworkcode, $unlinked_item_subfields ); 
        }   
        print ".";
        print "$i\n" unless ($i++ % 50);
    }
}

