#!/usr/bin/perl

use strict;
use warnings;

# open IN, '<', 'CCMED.TIT' or die $!;
open IN, '<', 'ccmed.out' or die $!;
open LST, '<', 'ccmedimages.lst' or die $!;

my $base = '3500.001:http://medsun.zbmed.uni-koeln.de/ccmedimages/';
$base = '3500:http://www.zbmed.de/ccmedimages/';

my %set;
my %orphants;
while (<LST>) {
    chomp;
    $orphants{$_} = 1;
}

URL:
while (<IN>) {
    chomp;
    s/^([^:]+:)\s+/$1/;
    # if (/^$base(?:(\d\d\d\d)\/)?(\d+\.pdf)/imso) {
    if (/^$base(?:(\d\d\d\d)\/)(\d+\.pdf)/imso) {
        next URL unless $orphants{$2};
        my $year = $1 ? $1 : '';
        # print "$2 gefunden in $year\n";
        # print "$2 gefunden\n";
        # print "scp $2 v440-1:/usr/local/www/zbmed/htdocs/ccmedimages/$1/\n";
        # print "mv $2 gefunden\n";
        print "mv ungeordnet/$2 $1/\n";
        $orphants{$2} = 0;  # keine Dubletten
    }
}

sub endbearbeitung {
    
    my $error = 0;
    # $set{file}    || $error++;
    $set{file}    || print "Keine URL in $set{'0000'}\n";
    $set{'0596'}  || $error++;
    $set{'03501'} && $error++;
    
    if ($error) {
        foreach my $kat (sort keys %set) {
            print STDERR "$kat: $set{$kat}\n";
        }
        exit;
    }

    if ($set{jahr}) {
        -e "/usr/local/www/zbmed/htdocs/ccmedimages/$set{jahr}/$set{file}" 
            || print "Datei $set{file} fehlt\n";
    } else {
        print "Kein Jahr zu $set{'0000'}\n";
    }

    if (!$set{'0425'} and $set{'0596'} =~ /^(.*\D)?(200[0-6])(\D.*)?$/) {
        $set{'0425'} = $2;
        $set{'jahr'} = $2;
        print "$set{'0000'}: Jahr aus 0596 ergaenzt: $set{'jahr'}/$set{file}\n";
    }
    
    print OUT "0000:$set{'0000'}\n";
    print OUT "0425:$set{'0425'}\n" if $set{'0425'};
    print OUT "0596.021:$set{'0596'}\n" if $set{'0596'};
    if ($set{jahr} and $set{file}) {
      print OUT "3500:http://www.zbmed.de/ccmedimages/$set{jahr}/$set{file}\n";
    } elsif ($set{file}) {
      print OUT "3500:http://www.zbmed.de/ccmedimages/$set{file}\n";
    }
    print OUT "9999:\n\n";
    %set = ();
}

# 3500.001:http://medsun.zbmed.uni-koeln.de/ccmedimages/2000/3764.pdf
