﻿#!/usr/bin/perl -w
use strict;
use warnings;
use utf8;
# binmode STDIN, ':utf8';
# binmode STDOUT, ':utf8';
use open qw(:std :utf8);
use integer;
use Unicode::Normalize;


# Filter_Archimedes_2_ECHO.pl
# 2010-04-12
# Wolfgang Schmidle

# what does it do?
# input
# output

my %entities = (
	"ldquo" => "“",
	"rdquo" => "”"
);


# text input

my @text;
while(<>) { push @text, $_; }


# go through the text

my $inHead = 0;
my $head = "";

my $pb = 0;

foreach (@text) {

	# spezifisch für Song Yingxing, "Tiangong kaiwu"
	# per Hand wurde bereits geändert: 
	# - Präambel, Metadaten, root element
	# - heading N402684
	
	while (m!<pb xlink:href="(.+?)\.jpg"/>!) {
		$pb++;
		my $file = $1;
		$file =~ s!/!.!g;
		s!<pb xlink:href=".+?"/>!<pb file="$file" n="$pb"/>!;
	}


	# allgemein für die Umwandlung Archimedes --> Schema
	
	foreach my $entity (keys %entities) {
		s!&$entity;!$entities{$entity}!g;
	}

	s! id=! xml:id=!;

	if (m!<front/>!) { $_ = ""; next; }
	if (m!<back/>!) { $_ = ""; next; }
	
	next if s!<body>!<div type="body" level="0" n="0">!;
	next if s!</body>!</div>!;
	
	next if s!<chap !<div type="chapter" level="0" n="0" !;
	next if s!</chap>!</div>!;
		
	s!<p (.*?)type="main"!<p $1!;

	if (m!type="head"!) { 
		$inHead= 1;
		$head = $_; 
		$_ = "";
		next;
	}
	if ($inHead) {
		$head .= $_;
		$_ = "";
		if ($head =~ m!</p>!) {
			$inHead = 0;
			$_ = $head;
			
			s!\n +!!g;
			s!<p xml:id="(.+?)" type="head"!<head!; 
			my $headID = $1;
			s!<s xml:id="(.+?)">!!;
			my $sID = $1;
			s!</s>!!;
			s!<head>!<head xml:id="$sID">!;
			s!</p>!</head>!;
			s#</head>#</head> <!-- head ID was "$headID" -->#;
		}
		next;
	}

}


# text output

print @text;


# TO DO:
# <lb/> einfügen?
# sollte auch für nicht-wohlformatierte Texte funktionieren
# bei europäischen Texten: <pb> in den Absatz hinein

