#!/usr/bin/perl

BEGIN {
$ENV{KOHA_CONF} = "/usr/local/koha300/etc/koha-conf.xml";
$ENV{DOCUMENT_ROOT} = "/usr/local/koha300/intranet/htdocs";
push @INC, '/usr/local/koha300/lib';
}

use C4::Biblio;
use C4::Context;
use C4::Items;

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

#my $branch = '904';
#my $branch = shift @ARGV;
#die "No branch code given" unless ($branch);

#my $items_file = shift @ARGV;
#die "No Items File given" unless ($items_file);

#open $fh, $items_file;
#die "Couldn't open file" unless ($fh);
#while ( my $line = <$fh> ) {
#
#}
#close $fh;

die "Not enough params!  Need itemnumber and new biblioitemnumber"
  unless ( @ARGV == 2 );

my $itemnumber = shift @ARGV;
my $new_bib = shift @ARGV;
my ( $old_bib, $biblioitemnumber );

my $biblioitem_sth = $dbh->prepare("SELECT biblioitemnumber FROM biblioitems WHERE biblionumber = ?");
my $old_biblio_sth = $dbh->prepare("SELECT biblionumber FROM items WHERE itemnumber = ?");

$old_biblio_sth->execute( $itemnumber );

die "Bad itemnumber" unless ( ( $old_bib ) = $old_biblio_sth->fetchrow );

$biblioitem_sth->execute( $new_bib );

die "Bad biblionumber" unless ( ( $biblioitemnumber ) = $biblioitem_sth->fetchrow );

    # Mod item.
    my $item = { 'biblionumber' => $new_bib, 'biblioitemnumber' => $biblioitemnumber };

    ModItem( $item, $new_bib, $itemnumber );

    # Clean old biblio record
    # get the MARC record
    my $record = GetMarcBiblio($old_bib);
    my $frameworkcode = GetFrameworkCode($old_bib);
    $frameworkcode = "" unless ( $frameworkcode );

    #search item field code
    my ( $itemtag, $itemsubfield ) = GetMarcFromKohaField("items.itemnumber",$frameworkcode);
    my @fields = $record->field($itemtag);

    # delete the item specified
    foreach my $field (@fields) {
        if ( $field->subfield($itemsubfield) eq $itemnumber ) {
            $record->delete_field($field);
        }
    }
    &ModBiblioMarc( $record, $old_bib, $frameworkcode );
