#!/usr/bin/env perl
BEGIN { $|=1; }
use warnings;
use utf8;

#########################################################################
#### Author: © Eckhard Bick 2003,2008,2014; contact: eckhard.bick@mail.dk ####
#########################################################################
#
# use: cat file.dep | dep2tree > file.tree
#
# turns Constraint Grammar dependency format into VISL constituent tree structures
#
# Input format is expected as "niceline", not cohort format
# word     [base] <...> ... POS MORF ... @FUNC #n->m
#
# The output format includes VISL source and text lines as sentence headers
# <....> meta lines will be maintained, but only between sentences.
# id's are recognized from <id=""...> lines.
#
#########################################################################

# slut =1 -- data lines found
# slut =2 -- potential sentence delimiter found
# slut =3 -- output printed

$wordid =0;

while (<>) {
    if (/^([^< \t\#]+)/ && ! $text) {
	$sentence .= "$1 ";
    }
#    if (/^(.*?) *\t *[\[\"](.*?)[\"\]](.*?) ([A-Z][A-Zn123\/\- ]+) \@([^ ]+?) .*\#([0-9]+)->([0-9]+)/) {

    s/<cjt-first>/<cjt-head>/;

### punctuation fix for dependency-less punctuation from cg3 dependency grammars like espcg.deptree (rather than cg2dep)

    s/ *\t.* PU .*$/ /; # remove punctuation tags (ending space is important)
    if (s/^(\$[^ \t]+)[ \t]+$/$1/) {
      $wordid++;
      s/$/ \#$wordid->0/;
    }
#    print "--$_\n";
    if (/^(.*?) *\t *[\[\"](.*?)[\"\]](.*?) ([A-Z][^\@]*) \@([^ ]+?) .*\#([0-9]+)->([0-9]+)/) {
	$slut =1;
	$wordform =$1;
	$base =$2;
	$extra =$3;
	$tags =$4;
	$func =$5;
	$wordid =$6;
	$headid =$7;

	$tags =~ m/^([A-Za-z]+)(.*)/;
	$pos =$1;
	$morf =$2;


 $wordform =~ s/=/_/g;
 $extra =~ s/=/_/g;
 $wordform =~ s/^\$//g; # numbers
 $base =~ s/=/_/g;
	$morf =~ s/=/_/g;
	if ($pos =~ /(DET|INDP)/) {$morf = " $1$morf";}
#create cg2visl tags

if (! $headid) {$func =~ s/ICL-AUX</UTT/;}

#	if ($extra =~ /<nofirstcjt>/) {$func =~ s/CO/AX/;} # warning marker from cg2dep, necessary only for Portuguese because the other dep2tree have fAco triggered by either <adv> CO or <nofirstcjt> CO
	$pos = "\L$pos";
# 	$pos =~ s/^(.*)$/\L$1/;
 	$pos =~ s/[kc]c/conj-c/;
 	$pos =~ s/[kc]s/conj-s/;
	$pos =~ s/^a$/adj/; # Sami
# 	$pos =~ s/^(indp|pers|det)$/pron/g;
# 	$pos =~ s/^(indp|pers|det)$/pron-$1/g;
	if (/ \@ADVL[^>]/ && $headid ==0) {$extra =~ s/ *<cjt>//; s/ <cjt>//;}
	if (/ \@(ADVL|NPHR)[^>]/ && ! / <cjt/) {
	  $topacl =1; # prepare extra top node
	  $headid =0; # make sure all ADVL and NPHR are attached to top node rather than each other (as would be normal in the dependency tree)
	}

	if ($extra =~ /poss/) {$pos =~ s/^(indp|pers|det|pron)$/pron-poss/g;}
	if ($extra =~ /rel/) {$pos =~ s/^(indp|pers|det|pron)$/pron-rel/g;}
	if ($extra =~ /interr/) {$pos =~ s/^(indp|pers|det|pron)$/pron-int/g;}
	if ($extra =~ /dem/) {$pos =~ s/^(indp|pers|det|pron)$/pron-dem/g;}
	if ($extra =~ /art/) {$pos =~ s/^(det|pron)$/art/g; $morf =~ s/DET *//;}
	$pos =~ s/^(pers)$/pron-pers/g;
	$pos =~ s/^(indp|pers|det)$/pron-indef/g; # <quant>, restkategori, også <diff>
	if ($morf =~ s/(INF|GER|PCP[12]?) *//) {$submorf =$1; $pos =~ s/^v/v-\L$submorf/;}
	else {$pos =~ s/^v$/v-fin/;}
	if ($morf =~ s/ PERS//) {$pos =~ s/pron$/pron-pers/;}
#	if ($morf =~ / <(rel|int)>/) {$pos =~ s/pron/pron-$1/;}
#	if ($morf =~ s/ <(dem|poss)>//) {$pos =~ s/pron/pron-$1/;}

 	$pos =~ s/^in$/intj/g;

	$func =~ s/^(FAUX|FMV)/FS-STA/;
	$func =~ s/^(IAUX|IMV)/ICL-UTT/;
#	$func =~ s/^ICL-AUX</Oaux/;
#	$func =~ s/^ICL->AUX/Oaux/;
	$func =~ s/^(FS|ICL|AS)\-//;
	$func =~ s/^ADVL>A(S<)?/fA/g; # also Portuguese ADVL>AS (though now as FOC> anyway, because that better fits in a pp [ex-acl])
	$func =~ s/^-FSUBJ/S/g; # Sami
	$func =~ s/^F-<*SUBJ>*/Sf/g;
	$func =~ s/^S-<*SUBJ>*/Ss/g;
	$func =~ s/^<*SUBJ>*/S/g;
	if ($func =~ s/^<*ACC>*-PASS/Od/g) {$extra .= " <pass>";}
	elsif ($func =~ s/^<*ACC>*-(REFL|PRON|PASS)/Od/g) {$extra .= " <\L$1>";} # Spanish
	$func =~ s/^<*ACC>*/Od/g;
	$func =~ s/^-?F?<*OBJ>*/Od/g; # sami

	$func =~ s/F-<?ACC>?/Of/g;
	$func =~ s/^<*DAT>*/Oi/g;
	$func =~ s/^<*PIV>*/Op/g;
	$func =~ s/^<*(SA|ADVS)>*/As/g; # also Portuguese variant
	$func =~ s/^<*(OA|ADVO)>*/Ao/g; # also Portuguese variant
	$func =~ s/^VO[CK]/fCvoc/g; # vocative adjunct
	$func =~ s/^<*SC>*/Cs/g;
#	$func =~ s/^FOC>/Dfoc/g;
	$func =~ s/^FOC>/FOC/g;
	$func =~ s/^<FOC/FOC/g;
	if ($base =~ /^(é=que|foi=que|é|foi|que)$/) {$func =~ s/^FOC/CLEFTFOC/;} # protect against indentation-raising
#print "--$func base=$base\n";
	$func =~ s/^<*OC>*/Co/g;
	$func =~ s/^<*ADVL>*/fA/g;
	$func =~ s/^<*ADV>*/A/g;
	$func =~ s/^<*PASS/fApass/g;
	$func =~ s/^TOP/fAtop/g;
	$func =~ s/^N<PRED/DNc/g;
	$func =~ s/^<*PRED>*/fCs/g;
	$func =~ s/^APP/DNapp/g;
	$func =~ s/^N<FUSE/DNfuse/g;
	$func =~ s/^>N/DN/g;
	$func =~ s/^N<+/DN/g;
	$func =~ s/^>AS/Dfoc/g;
	$func =~ s/^>A/DA/g;
	$func =~ s/^A<+/DA/g;
	$func =~ s/^KOMP</DAcom/g;
	$func =~ s/^P</DP/g;
	$func =~ s/^>>P/DP/g;
	if (/ (DIR|<adir>|N) /) {$func =~ s/^>P/DPmod/g;}
	else {$func =~ s/^>P/DPmod/;}
#	else {$func =~ s/^>P/DA/;} # not good for evaluation, since the treebank only knows DP
	$func =~ s/^PRT-AUX</AUX</g; # too early to turn into SUBaux, it will mess up the tree-generation
	$func =~ s/^PRD/SUBprd/g;
	$func =~ s/^CVP/SUB/g; # sami
	$func =~ s/^COM(adv|conj|prp)/SUBcom$1/g;
	$func =~ s/^AS<[A-Z]*/X/g; # argument of complementizer (clause body), problem: the complementizer may be either KS or <rel> ADV - X used instead of DCarg
	if ($line[$headid] && $line[$headid] =~ /( KS|:conj-s)/) {
	  $func =~ s/^S</DC/g;
	}
	else {
	  $func =~ s/^S</fCsta/g;
	}
	$func =~ s/^>S/DC/g;
	$func =~ s/^CMD/COM/g;
	$func =~ s/^(MV<|>MV)/Vpart/g;
#	$func =~ s/pu/PU/; # ???
	$func =~ s/^NPHR/X/g;
	$func =~ s/>>A/DA/g;
	if($func =~ /^D/ && $extra =~ m/foc/){
	    $func = "Dfoc";
	}
	if (/<parkc-1>/) {$func =~ s/^CO/FOC/;} # Portuguese a la Danish: Nem Lula nem o partido ainda ...
	if (/<(adv|nofirstcjt)>/) {
	  $func =~ s/CO/fAco/;  # does the same as the <nofirstcjt> AX transformation, but the latter also catches more general attachment CO problems
#	  print "--changing <adv> CO into $func, for id -> $headid\n";
	}

# "m.v.","m.m.","etc.","m.fl.","o.a."

	if (/\[(etc|m\.[mv]|m\.fl|o\.a|osv)\.\]/ && $func =~ /DN/ && $line[$headid] =~ /<cjt/) {
	    $headid = $head[$headid];
	    $func = "CJT";
	    $extra .= " <cjt>";
	}

### English specifics

    $func =~ s/>[ANPS](:adv.*\t(not|only|even|yet|not=even|at=least|also))/Dfoc$1/g;

### flattening KOMP<
	if ($func =~ /(KOMP<|DAcom)/) {
#	  $komphead =$headid;
	  $loop=0;
	  while ($head[$headid] && $head[$headid] < $wordid && $head[$headid] > $headid && $loop <= 5) {
#	    print "****wordid=$wordid headid=$headid -> $head[$headid]\n";
	    $headid =$head[$headid];
	    $loop++;
	  }
	  for ($i=$headid+1; $i<$wordid; $i++) {
	    if ($head[$i] && $head[$i] < $headid) {
	      $headid =$head[$i]; # problem with e.g. interfering clause-level constituents
	    }
	  }
	  if ($line[$headid] =~ /<mv>/) {$func =~ s/DAcom/fA/;}
	  elsif ($line[$headid] =~ / N /) {$func =~ s/DAcom/DNcom/;}
	}

# CJT
	if (/<vpcjt>.*<cjt>/) {
	    $extra =~ s/<cjt>//;
#	    $extra =~ s/<cjt-head>//;
	    $nform[$wordid] = "vpcjt";
	}
	if (/<cjt>/) {
	    $extra =~ s/<cjt>/<cjt-$func>/g;
	    $func ="CJT";
	}
#	if (/<cjt-head>/ && ! /<vpheadcjt>/) {
#	print "--$wordid $1\n";
	if (/<predco>/) {
	    $extra =~ s/<cjt-head>//;
	}
	elsif (/<cjt-head>/) {
	    $extra =~ s/(<cjt-head>)/$1 <cjt-head-$func>/g;
	    if (! /<headpar>/) {
	      $func = "¢" . $func;
	    }
	    else {
	      $func = "ð" . $func;
	    }
	}
#	print "$wordform - $base - $extra - $tags - $func - $wordid - $head\n";

	$line[$wordid] = "$func:$pos\(\"$base\"$extra$morf\)\t$wordform\n";
#	print "--$line[$wordid]\n";
	$head[$wordid] =$headid;
	$func_orig[$wordid] =$func;

#	if (! $daughters[$wordid]) {
#	    $daughters[$wordid] = $wordid; # left heads as "daughters"
#	}
	$daughters[$headid] .= " $wordid"; # compile daughters
#	print "--daughters($headid)=$daughters[$headid]\n";
	if (/<cjt>/)  {
	  $lastcjt[$headid] = $wordid;
#	  print "--setting lastcjt $wordid for cjthead $headid\n";
	}

 ### nonterminal form
	if (! $nform[$wordid]) {
	    if (" v-fin aux-fin " =~ / $pos / && $morf =~ /IMP( .*)?$/) {$nform[$wordid] = "fcl";}
	    elsif (" v-fin aux-fin " =~ / $pos / && ! (/<cjt>/)) {$nform[$wordid] = "fcl";} # changed to fcl only if SUBJ found, evt. x(predicate)
	    elsif (" v-fin aux-fin " =~ / $pos /) {$nform[$wordid] = "x";} # changed to fcl only if SUBJ found, evt. x(predicate)
	    elsif ($pos =~ /(v-pcp1|ger)/ && $func =~ /^f?A/) {$nform[$wordid] = "advp";}
	    elsif ($pos =~ /(v-pcp1|ger)/) {$nform[$wordid] = "adjp";}
	    elsif ($pos =~ /v-pcp2?$/ && ($morf =~ /STA/ || ! ($line[$wordid] =~ /<(mv|aux)>/))) {$nform[$wordid] = "adjp";}
#	    elsif (" v-pcp1 " =~ / $pos / && $func =~ /A/) {$nform[$wordid] = "advp";}
#	    elsif (" v-pcp1 " =~ / $pos /) {$nform[$wordid] = "adjp";}
#	    elsif (" v-pcp2 " =~ / $pos / && $morf =~ /STA/) {$nform[$wordid] = "adjp";}
	    elsif (" v-inf aux-inf v-ger v-pcp1 aux-pcp1 v-pcp v-pcp2 aux-pcp2 " =~ / $pos /) {
	      $nform[$wordid] = "icl";
#	      print "******$nform[$wordid]\n";
	    }
	    elsif (" conj-s adv adv-rel " =~ / $pos / && /AS-/) {
	      $nform[$wordid] = "acl";
#	      print "*******$line[$wordid]\n";
	    }
	    elsif (" n prop " =~ / $pos / || $_ =~ / (INDP|SPEC|PERS.*(NOM|ACC))/) {$nform[$wordid] = "np";}
	    elsif (" adj num " =~ / $pos / || $_ =~ / DET/) {$nform[$wordid] = "adjp";}
	    elsif (" adv " =~ / $pos /) {$nform[$wordid] = "advp";}
	    elsif (" prp " =~ / $pos /) {$nform[$wordid] = "pp";}
	    elsif (" conj-c conj-s " =~ / $pos /) {$nform[$wordid] = "cp";}
	    else {$nform[$wordid] = "x";}
#	    print "--morf=$morf\n";
	}
#	print "--$wordid->$head[$wordid] $func $line[$wordid]\n";
	if ($func =~ /(DNc?|APP)/) {$nform[$head[$wordid]] ="np";} # works on heads to the right, too, therefore IF NOT condition on the rules above
	if ($func =~ /^¢?[a-z]?S[a-z]?$/ && ! ($line[$wordid] =~ / (<cjt(-[^h][^>]*)?>) /)) {$nform[$head[$wordid]] = "fcl";}

	$num[$wordid] =$wordid; # counter array for word-id's

#	print $num[$wordid] . " " . $line[$wordid];
    }
    elsif (/^\$(.*?)[ \t]+\#([0-9]+)->([0-9]+)/) {
	$wordid =$2;
	$headid =$3;
	$line[$wordid] = "$1\n";
	$num[$wordid]=$wordid;
	$head[$wordid] =$headid;
    }

    if (/^<.*(ref=\"?([A-Za-z0-9\-]+)\"?.*?)(>| text=)/ || /^<s?[ _]?(id=\"?([A-Za-z0-9\-]+)\"?).*/) {
	$source = "$1";
	$sentid =$2;
	if (s/ text=\"(.*)\">/>/ || s/ text=\"(.*?)\"//) {
	  $text =$1;
	  $sentence = "$sentid $text\n";
	}
	else {
	  $sentence = "ID=$sentid\#";
	}
	print;
      }
    elsif (/^<.*>$/) {
      if (! $slut || $slut >2) {print "$_";}
      else {$metalines .= $_;}
    }
    if (/^<s/) {$s_marker =1;}

#    if (/\$[\.\:\;\?\!]/) {
    if ($slut && $slut ==1 && (/\$[\.\:\;\?\!]/ || /<\/s/)) {
	$slut =2;
    }
    if (/^[ \t]*$/ && $slut && $slut == 2) {
	&process;
    }
}
if ($slut < 3) {
    &process;
}

sub process {
	$head[0]="";
	$line[0]="A1\n";
	if ($topacl) {$line[0] .= "UTT:x\n";}
	&build_tree;
#	$text =$sentence;
	&cleantext;
#	$sentence =$text;
	&print;
	if ($metalines) {print $metalines;}
	$metalines ="";
	$slut =3;
	@line =();
	@open =();
#	@paropen =();
	@discopen =();
	@discontinuous =();
	@head =();
	@daughters =();
	@lastcjt =();
	@auxdep =();
#	@codep =();
	@num =();
	@aux =();
	@nform =();
	@func_orig =();
	@indent =();
	$source ="";
	$circularity ="";
	$sentence ="";
	$metalines ="";
	$text ="";
	$parindent = "";
	$tegnindent = "";
	$indent = "";
	$indentold = "";
	$addindent = 0; # not having this, gave wrong indentation for the 2. sentence in Alessandro Bokan's mail af 12/5 '14
	$depth = 0;
	$depis = "";
	$cjthead =0;
	$topacl =0;
    }

sub build_tree {

### flatten AUX<
#    print "---now building tree\n";

  foreach (@num) {
    if (! $_) {
      $cjthead =0;
      goto slutnum;
    }
#    if ($cjthead) {print "--$_->$head[$_], cjthead=$cjthead, lastcjt(cjthead)=$lastcjt[$cjthead] -- $line[$_]";}
    if ($_ && $line[$_] =~ /<cjt-head>/ && $lastcjt[$_]) {
      $cjthead =$_;
    }
    elsif ($cjthead && $lastcjt[$cjthead] && $_ == $lastcjt[$cjthead]) {$cjthead = 0;}
    if ($cjthead && $_ != $cjthead && $head[$_] < $cjthead && $lastcjt[$cjthead] && $lastcjt[$cjthead] > $_) { # cave par's without CO ...  therefore not the easy $paropen[$cjthead], but last cjt-daughter
      $line[$_] =~ s/(".*")/$1 <inpar>/; # in-par adverbial to be flattened into par indentation
#      print "--setting headid for $_ from $head[$_] to $cjthead\n";
      $head[$_] = $cjthead;
    }
#    if ($cjthead && ! $lastcjt[$cjthead]) {print "--cjthead=$cjthead\n";}
  slutnum:
  }

    foreach (@num) {
	if (! $_) {goto slutfocus;}
#   print "$_ -> $head[$_] $line[$_] *** $line[$head[$_]] ---\n";
	if ($_ && $line[$_] =~ /AUX</ && $head[$_] && $line[$head[$_]] =~ /<aux>/) {
	    $aux[$head[$_]] =$_;
#	    print "now aux($head[$_])=$_\n";
	}

	if ($line[$_] =~ /fA:.*<advlvp>/ && $line[$head[$_]] =~ /AUX</) {
#	  print "--$_ $line[$_]\n";
	  $head[$_] = $head[$head[$_]]; # raising vp-internal ADVL from AUX< to <aux> --> ensures correct indentation befor Oaux:par ('altså' in caaycrip, 'siden 1959' in caklmadx)
	}
	if ($line[$_] =~ /FOC:/) {
#	    $head[$_] = $head[$head[$_]]; # raising FOC> from CO-head to CO's head, i.e. first conjunct, avoids weird discontinuities
#	    print "--raising FOC> head to $head[$_] in $line[$_]\n";
	}
	$focus =$_; $focloop=0;
	while ($line[$head[$focus]] && $line[$head[$focus]] =~ /(AUX<|\@CO)/ && ($line[$head[$focus]] !~ /<cjt/ || $_ < $head[$head[$focus]]) && $focloop < 20) { # go on until mother is daughter of <aux>, don't if AUX< is co-ordinated (they'll each have their own daughters in Oaux:par), but go on nevertheless, if focus is left of <aux> (e.g. a shared fronted adverbial)
	    $focus =$head[$focus];
	    $focloop++;
	}
	if ($_ != $focus) {
	    $head[$_] =$head[$focus];
	    $daughters[$head[$focus]] .= " $_";
#	    print "***now: daughters of $head[$focus] = $daughters[$head[$focus]]\n";
#	    $daughters[$head[$_]] =~ s/ $_ / /;
#	    $daughters[$head[$_]] =~ s/ $_$//;
	}
	if ($line[$_] =~ /(AUX<)/ && ! ($line[$_] =~ /<cjt/)) {
	    $daughters[$_] ="";
	    $auxdep[$head[$_]] .= " $_";
	}
#	elsif ($line[$_] =~ /(CO|<cjt>)/) {
#	    $daughters[$_] ="";
#	    $codep[$head[$_]] .= " $_";
#	}
      slutfocus:
#    print "$_->$head[$_]\n";
    }

### sort daughters

# it is important that first daughters be first, otherwise they will remain outside the non-terminal bracket of their head
    $depnul =0;
    foreach (@num) {
	if ($_ && $daughters[$_] && $daughters[$_] =~ / .* /) {
#	    print "--daughters (1) =$daughters[$_]\n";
#	    print "--daughters (3) $daughters[3]\n";
	    $daughters[$_] =~ s/^ //;
	    @daughterlist = split / /, $daughters[$_];
	    @daughterlist = sort {$a <=> $b} @daughterlist;
	    $daughters[$_] = ' ' . join ' ', @daughterlist;
#	    print "--daughters($_) =$daughters[$_]\n";
	}
	if ($_ && $line[$_] =~ /:./ && ! $depnul && $head[$_] ==0) {
	    $depnul=$_;
#	    print "------depnul =$_\n";
	}
    }

### allocate depth

    foreach (@num) {
	if (! $_) {goto slutnum;}
#	    print "**$line[$_-4]";
	if ($addindent && $addindent ==20) { #!!!
	  $addindent =0;
	  if ($line[$_-1] && $line[$_-1] =~ /:/) {
	    if ($line[$_-1] =~ m/^[^ý]*?(=+)[^=]+$/) {
	      $addindent = length $1;
	      $addindent--;
	    }
	    $addindent_old =$addindent;
#	    if ($_ <4) {print "****num=$_ addindent=$addindent, $line[$_-1]\n";}
	  }
	  else {$addindent =$addindent_old;}
	}
#	if ($addindent && $addindent ==20) {
#	    if ($line[$_-1]) {$line[$_-1] =~ m/^[^ý]*?(=+)[^=]+$/;}
#	    if ($1) {$addindent = length $1;}
#	    else {$addindent =0;}
#	    if ($_ <4) {print "****num=$_ addindent=$addindent, $line[$_-1]\n";}
#	}
#	print "$_->$head[$_] - $line[$_]";
	$i =$_;
	$depth =0;
	$depis =" ";

	while ($head[$i] && $line[$head[$i]] && ! ($depis =~ / $i /)  && $depth < 30) {
	    if (! ($line[$head[$i]] =~ /<vpcjt>/)) {
		$depth++;
	    }
	    $depis .= "$i ";
#	    $depth++;
#	    if ($i==13) {print "---- $_ via $i->$head[$i] depth=$depth $line[$i]";}
	    if ($line[$i] =~ /<inpar>/) { # note: dep2tree_de has discontinuous par (parsplit)
	      $depth--; # extra indentation for in-par adverbial
	    }
	    if (($line[$i] !~ /((CO):|<cjt(-[^h>][^>]*)?>).*$/ || $line[$_] =~ /<co-vp>/) && $line[$head[$i]] =~ /<cjt-head>/) { # CJT removed, since first-heads on the way up are CJT, too, while they still should count as depth-increasers for lower level dependents, just not their own direct daughters
#		print "----$_ via $i->$head[$i] extra depth=$depth $line[$i]\n";
		$depth++;
	    }
	    if ($line[$head[$i]] =~ /<(predco)>/ && $i > $head[$i]) {
		$depth++;
		if (! ($line[$i] =~ /((CO):|<cjt(-[^h>][^>]*)?>).*$/)) {$depth++;}
	    }
	    $i =$head[$i];
#	    if ($line[$i] =~ /<cjt-head>/) {$depth++;}
	}
	if ($head[$i] ==0 && $line[$_] =~ /:./ && $i != $depnul) {  # maybe this is :. why punctuation needs its own indentation correction
#	    print "--$_ $indent[$_-1] depnul =$depnul\n";
	  if ($addindent) {
	    $depth =$depth + $addindent;
	  }
	}
	else {$addindent =20;}
	if ($depth >=30 || $depis =~ / $i /) {
	    $depth =1;
	    $circularity .= " $i";
#	    print "--i=$i depis=$depis depth=$depth\n";
	    $head[$i] =0;
	    if ($daughters[$head[$i]]) {$daughters[$head[$i]] =~ s/ $i//;}
	}
	if ($line[$_] =~ /<(cjt-head|co-vp)>/) {$depth++;}
#	print "--$_ final depth=$depth $line[$_]\n";


#### the following not a good idea - too hard to distinguish between <cjt line and its (higher up) CJT line indentation
#	if ($line[$_] =~ /<cjt/ && $line[$_] !~ /<cjt-head/ && $head[$_]) {
#	  $j =$head[$_];
#	  while ($line[$j] !~ /CJT/) {$j--;}
#	  if ($line[$j] =~ /^[^ý]*?(=+)[^=]*$/) {
#	    $depth = length $1; # copying depth from first conjunct, for the case of nested conjunctions: "Temis pri limigado de multaj brancxoj kiel metalurgio, elterigado de ercoj kaj hejtajxoj, amasa kemio, produktado de cemento, ktp, sed ankaux de peza masxinkonstruado."
#	    print "--copying depth=$depth for $_ from cjt-head $head[$_] cjt-line= $line[$j]\n";
#	  }
#	}

	$indent[$_] =$depth;
	$line[$_] = '=' x $depth . $line[$_];

#	print "********i=$_ head=$head[$_] depth=$depth line=$line[$_]\n";

#	if ($line[$_] =~ /:par/) {goto nohead;}

### head first in constituent
	if ($daughters[$_] && $daughters[$_] =~ /^ ([^ ]+)/ && ($firstdaughter =$1) && ($firstdaughter > $_ && ! $open[$_] || $discontinuous[$_] && $discontinuous[$_] <= $_ && $_ > $head[$_])) {

	    if ($line[$firstdaughter] =~ /(<cjt(-[a-gi-zA-Z¢]+)?>|<co-|\@CO|CO:conj)/ && $line[$firstdaughter] !~ /<cjt-head>/ ) {
#		if ($daughters[$_]) {print "---self=$_ head=$head[$_] daughters=$daughters[$_] firstdaughter=$firstdaughter $line[$firstdaughter]\n";}
#		$nform[$_] = "par";
#		$line[$_] =~ s/^(=*)¢?([^=:]+)/$1CJT/;
#		$func = $2;
#		$line[$_] =~ s/^=//; # cjt as first daughter means there's no real non-terminal, only par
#	      print "--head first $_: $line[$_]\n";
	    }
	    else {
#		if ($daughters[$_]) {print "---self=$_ head=$head[$_] daughters=$daughters[$_] firstdaughter=$firstdaughter $line[$firstdaughter]\n";}
		$line[$_] =~ s/^/=/; # general indentation after non-terminal
		$line[$_] =~ s/^(=*)([^=:]+)/$1H/;
		$func =$2;
		$line[$_] = '=' x ($depth) . $func . ":" . $nform[$_] . "\n" . $line[$_];
		if ($line[$_] =~ /=¢/) {
#		    $line[$_] =~ s/^=//; # first conjunct takes itself place of nonterminal, rather than being a real indentation-needing daughter
		}
	    }

#	    if ($daughters[$_]) {print "---self=$_ head=$head[$_] daughters=$daughters[$_]\n";}

	    if ($discontinuous[$_] && $discontinuous[$_] <= $_) {
		$line[$_] =~ s/=([A-Za-z<>¢])/=-$1/;
		$discontinuous[$_] =0; # newly introduced: Lo que sigo sin entender es porque esta oración no anda
	    }

	    if ($head[$_] > $_ && $daughters[$_] && $daughters[$_] =~ / ([^ ]+) *$/ && ($lastdaughter =$1) && ($lastdaughter > $head[$_])) {
		$discontinuous[$_] =$lastdaughter;
		$line[$_] =~ s/(\n=+H:)/-$1/;
#$headid =$head
		if ($daughters[$head[$head[$_]]] =~ / $head[$_] ([^ ]+)/ && ($nextdaughter =$1) && $nextdaughter < $lastdaughter && $daughters[$head[$_]] =~ / ([^ ]+)/ && ($firstdaughter =$1)) {
#		    print "--nextdaughter $nextdaughter $line[$nextdaughter]\n";
		    $discontinuous[$head[$_]] =$nextdaughter;
		    $line[$firstdaughter] =~ s/\n/-\n/;
		}
#		print "--her $_ $line[$_]\n";
	    }
	    else {
		$open[$_] =1;
	    }
	}

### dependent first in constituent
	$focus =$_;
	$focusdepth =0;
#	print "---$_ focus=$focus head=$head[$focus] headline=$line[$head[$focus]]\n";
#	print "-----open=$open[$head[$focus]], disc=$discontinuous[$head[$focus]]\n";
#	if ($daughters[$head[$focus]]) {print "--headdaughters=$daughters[$head[$focus]]\n";}
#	if ($head[$focus]) {print "---focus=$focus open=$open[$head[$focus]] disc=$discontinuous[$head[$focus]]\n";}

###??? recursive focus
	while ($head[$focus] && $line[$head[$focus]] && $head[$focus] >0 && (! $open[$head[$focus]] && ! $discopen[$focus] || $discontinuous[$head[$focus]] && $focus==$discontinuous[$head[$focus]] && ! $discopen[$focus] || $discontinuous[$head[$focus]] && $discontinuous[$head[$focus]] < $_) && ! ($line[$head[$focus]] =~ /(\@CO|CO:)/) && ($daughters[$head[$focus]] && $daughters[$head[$focus]] =~ /^ $focus/ || $discontinuous[$head[$focus]] || $discontinuous[$head[$_]] || $discontinuous[$focus])) { #  && $daughters[$head[$focus]] =~ /^ $focus/
#	  print "--$_ focus=$focus daughters(head(focus))=$daughters[$head[$focus]]*** dhf=$discontinuous[$head[$focus]] dhs=$discontinuous[$head[$_]] df=$discontinuous[$focus] open=$open[$head[$focus]] discopen=$discopen[$focus]\n";
	    $focusdepth++;
#	    $line[$head[$focus]] =~ s/^(=*)([^=:]+)/$1=H/;

	    $indent = '=' x ($depth-$focusdepth);
	    if (! $discontinuous[$head[$focus]]) {
#		print "--her: focus=$focus depth=$depth indent:$indent head=$head[$focus]: $line[$head[$focus]]\n";
		$line[$head[$focus]] =~ m/^(=*)([^=:]+):.*$/;
		$func ="$2";
	    }
	    else {
#		print "--her: focus=$focus head=$head[$focus]: $line[$head[$focus]]\n";
		$func =$func_orig[$head[$focus]];
#		$line[$head[$focus]] =~ m/^((.*?\n)*?$indent?)?¢?([A-Za-z<>]+):/;
#		$func ="$3";
#		if (! $func) {print "--nofunc focus=$focus head(focus)=$head[$focus]: $line[$head[$focus]] indent=$indent depth=$depth focusdepth=$focusdepth\n\n";}
		if (! $func) {$func ="XXX";}
	    }
	    $line[$_] = $indent . $func . ":" . $nform[$head[$focus]] . "\n" . $line[$_];

#	    print "--her: $_ focus=$focus head(focus)=$head[$focus] depth=$depth focusdepth=$focusdepth for $_ disc(head(focus))=$discontinuous[$head[$focus]], line=$line[$_]***\n";
		if ($line[$_] =~ /=¢/) {
#		    $line[$_] =~ s/^=//; # first conjunct takes itself place of nonterminal, rather than being a real indentation-needing daughter
		}

	    if ($discontinuous[$head[$focus]]) {
		$line[$_] =~ s/=([A-Za-z<>¢])/=-$1/;
#		print "--inserting left hyphen for $_, focus=$focus, head(focus) =$head[$focus], disc=$discontinuous[$head[$focus]]: $line[$_]\n";
	    }

	    $lastdaughter =0;

	    if ($head[$head[$focus]] && $head[$head[$focus]] > $_ && $head[$head[$focus]] < $head[$focus]) {
		$discontinuous[$head[$focus]] =$head[$focus];
		$line[$_] =~ s/\n/-\n/;
		$discopen[$focus] =1;
#		print "--open-marking for $focus\n";
#		print "--inserting right hyphen for $_: $line[$_]\n";
	    }
	    elsif ($aux[$head[$focus]] && $head[$head[$focus]] > $_ && $head[$head[$focus]] < $aux[$head[$focus]]) { # Bakterien kunne, anføres det, vise sig at være ...
		$discontinuous[$head[$focus]] =$head[$focus];
		$line[$_] =~ s/\n/-\n/;
#		print "***discontinuous aux: $_, focus=$focus, head(focus)=$head[$focus] -> $aux[$head[$focus]] $line[$_]\n";
	    }
	    elsif (! $discontinuous[$head[$focus]] && $daughters[$head[$focus]] =~ / ([^ ]+) *$/ && ($lastdaughter =$1) && $head[$focus] > $focus && $head[$head[$focus]] > $head[$focus] && $lastdaughter > $head[$head[$focus]]) { # Bakterien kunne, anføres det, vise sig at være ...
#		$discontinuous[$head[$focus]] =$head[$focus];
		$discontinuous[$head[$focus]] =$lastdaughter;
		$line[$_] =~ s/\n/-\n/;
		$line[$head[$focus]] =~ s/^(=*)([^=:]+)(:.*)$/$1=H$3/; # cave = before H??, how many??
		$open[$head[$focus]] =1;
#		print "***discontinuous focus=$focus, head(focus)=$head[$focus] head(head(focus))=$head[$head[$focus]] $line[$head[$focus]]\n";
	    }
#	    elsif (1==1) {print "--focus=$focus, head=$head[$focus], lastdaughter=$lastdaughter, daughters of head(head)=$daughters[$head[$head[$focus]]]\n";}
	    elsif ($lastdaughter && ($xx=$head[$focus]) && $daughters[$head[$head[$focus]]] =~ / $xx ([^ ]+)/ && ($nextdaughter =$1) && $nextdaughter < $lastdaughter) {
		$discontinuous[$head[$focus]] =$nextdaughter;
		$line[$_] =~ s/\n/-\n/;
		$open[$head[$focus]] =1;
		$line[$head[$focus]] =~ s/^(=*)([^=:]+)(:.*)$/$1=H$3/; # cave = be
#		print "--her $xx lastdaughter=$lastdaughter, splitdaughter=$nextdaughter head(head)daughters=$daughters[$head[$head[$focus]]] -- $line[$_]\n";
	    }
	    elsif ($head[$head[$focus]] && $discontinuous[$focus] && $head[$head[$focus]] > $_ && $head[$head[$focus]] < $discontinuous[$focus]) {
		$discontinuous[$head[$focus]] = $discontinuous[$focus];
		$line[$_] =~ s/\n/-\n/;
	    }
	    else {
		if (! $open[$head[$focus]]) {
		    $line[$head[$focus]] =~ s/^(=*)([^=:]+)(:.*)$/$1=H$3/; # H added, so it doesn't happen twice ('en anden status i samfundet end ...')
		}
		$open[$head[$focus]] =1;
#		print "--opening $head[$focus] for $focus\n";
		$discontinuous[$head[$focus]] =0;
	    }
#	  $open[$head[$focus]] =1; # ??? necessary for: Hvor stort afkast ACC>> kan man forvente at få
#		print "--2opening $head[$focus] for $focus\n";
	    $focus =$head[$focus];
#	    print "---focus=$focus head=$head[$focus] headline:$line[$head[$focus]]\n";
#	    if ($daughters[$head[$focus]]) {print "---headdaugthers($focus)=$daughters[$head[$focus]]\n";}
	}
### vp's

#	if ($auxdep[$_]) {print "--auxdep($_)=$auxdep[$_] line= $line[$_]\n";}
	if ($auxdep[$_] && $line[$_] =~ s/^([^\t]*?(=+))H:/$1Vaux:/ && ! $infm) {
	    $indent =$2;
	    $line[$_] =~ s/(Vaux)/P:vp\n=$indent$1/;
	    if ($line[$_] =~ /<predco>/) {$line[$_] =~ s/Vaux/==Vaux/;} # X:par and CJT:x will give 2 extra indentations
#	    print "--line= $line[$_]\n";
	    if ($auxdep[$_] =~ /^ ([0-9]+)/ && ($firstauxdep =$1) && ($firstauxdep - 1 > $_)) {
		$line[$_] =~ s/(:vp)/$1-/;
	    }
	    elsif ($auxdep[$_] =~ /^ ([0-9]+) ([0-9]+)/ && ($secondauxdep = $2) && ($secondauxdep - 2 > $_)) {
		$line[$_] =~ s/(:vp)/$1-/;
	    }
	}
	if ($line[$_] =~ /INFM/) { # check if icl should be vp, due to missing non-verbal arguments
#	    print "*** daughters =$daughters[$head[$_]]\n";
	    @daughterlist = split / /, $daughters[$head[$_]];
	    $complement =0;
	    foreach (@daughterlist) {
		if ($_ && ! ($line[$_] =~ /^=*([^ý]*INFM|<aux>|<mv>|AUX<|Vaux|Vm)/)) {$complement++;} # ^=* used to exclude clausal daughters, [^ý] used to also match \n in the icl ... infm line
	    }
	    if (! $complement) {
		$line[$_] =~ s/:icl/:vp/;
		$infm =1;
	    }
	}
	if ($complement && $line[$_] =~ s/^([^\t]*?(=+))INFM:/$1P:vp\n$2=INFM:/) {
	    $infm =1;
	}
	elsif ($line[$_] =~ /:v-inf/ && $infm) {
	    if ($complement) {$line[$_] =~ s/^/=/;}
	    $infm =0;
	    if ($line[$_] =~ /<mv>/) {$line[$_] =~ s/H:/Vm:/; $infm =0; $complement =0;}
	}
	elsif ($line[$_] =~ /=+(.+):v-inf/ && $1 !~ /^(P|H|Vm|Vaux)$/) {
#	  print "******$line[$_]\n";
#	  $line[$_] =~ s/^(=*)(.+?)(:v-inf)/$1$2:icl\n$1=P$3/; # emergency solution for unrecognized icl-nonterminal in naked infinitive before paratagma (esp. Romance languages without INFM) Danish example: han kom på grund af købe noget eller alt --> unnecessar, damages: "Iuj varoj kaj fruktoj venas el Pollando kaj oni devas importi."
#	  print "******$line[$_]\n";
	}
	if ($line[$_] =~ s/^(=*)(¢AUX<:v)/$1$2/) { # if icl hasn't been recognised yet ..., har jeg haft nedtur og følt ...
	    $indent =$1;
	    if ($line[$_] =~ /<aux>/) {
		$line[$_] =~ s/AUX</AUX<:icl\n$indent=P:vp\n$indent==Vaux/;
	    }
	    else {$line[$_] =~ s/AUX</AUX<:icl\n$indent=P/;}
	}
#	elsif ($line[$_] =~ /=[^HP][A-Za-z<>]*:v-fin/) { # error
#	    if ($line[$_+1] =~ /AUX</) {
#		$line[$_] =~ s/(=+)(¢?[^HP][A-Za-z<>]*:)v-fin/$1$2x\n$1=P:vp\n$1==Vaux:v-fin/;
#	    }
#	    else {
#		$line[$_] =~ s/(=+)(¢?[^HP][A-Za-z<>]*:)v-fin/$1$2x\n$1=P:v-fin/;
#	    }
#	}
	elsif ($line[$_] =~ s/^(=*)(AUX<)/$1=$2/) {
#	    print "-- now $line[$_]---before $line[$_-1]\n";
	    $indent =$1;
	    if (! ($line[$_-1] =~ /^([^ý]+\n)?$indent=(AUX<|Vaux|INFM):/)) {
		$line[$_] = $indent . "-P:vp\n" . $line[$_];
	    }
	    if ($auxdep[$head[$_]] =~ / $_$/) {$line[$_] =~ s/AUX</Vm/;}
	    else {$line[$_] =~ s/AUX</Vaux/;}
	}
	$line[$_] =~ s/H:(v-.* (AKT|PAS|IND|SUBJ|<mv>))/P:$1/;
#	print "--$_ $line[$_]";
	if ($line[$_] =~ s/AUX<:/Oaux:/) {
	    $line[$head[$_]] =~ s/(P|H):/Paux:/; # auxiliary with co-ordinated auxiliary objects
	    if ($discontinuous[$head[$_]] && $line[$_] !~ /-\n/) { # cave: -DN:fcl for "Her lærte han den disciplin og det taktisk-politiske håndværk, som han også langt senere skulle få så rigt brug for - og i øvrigt vise sig aldeles kapabel i."
		$line[$_] =~ s/=([A-Za-z<>¢])/=-$1/;
#		print "--left half: $_ $line[$_] *** head=$head[$_] - $line[$head[$_]]";
	    }
	}
	$line[$_] =~ s/=FOC/FOC/;

### vp-conjunct

	$line[$_] =~ s/CJT:vpcjt\n=*[A-Za-z]+:/=CJT:/; # Denne opfattelse var og er meget udbredt
	if ($line[$_] =~ /<vpheadcjt>/) {
	    $line[$_] =~ s/(=+)([A-Za-z]+)(:v-[a-z0-9])/$1$2:par\n$1=CJT$3/;
	}

#	print "--her: $_ $line[$_]\n\n";

### predication-co

	if ($line[$_] =~ /<predco>/) {
#	    print "--her: $_ $line[$_]\n\n";
	  if ($line[$_+1] =~ /^\$?,/ || $line[$_+1] =~ / KC/) {
	    $line[$_] =~ s/(=*)P:/$1X:par\n$1=CJT:/; # evt x(predicate)
	  }
	  else {
	    $line[$_] =~ s/(=*)P:/$1X:par\n$1=CJT:x\n$1==P:/; # evt x(predicate)
	  }
	}

### paratagmata

	if ($line[$_] =~ /¢[<>A-Za-z\-]+:/) {
	    $line[$_] =~ s/^=//; # first un-indentation
	    while ($line[$_] =~ s/\n=(.*¢)/XXX$1/) {
#	      $line[$_] =~ s/^=//; # second and further un-indentations (the first is done two proramme lines up) --> are already done in the  s/\n=(.*¢)/XXX$1/ and later s/XXX/\n/g;
	    }
#	    $line[$_] =~ s/\n=(.*¢)/XXX$1/;
	    $line[$_] =~ s/XXX/\n/g;


	    $line[$_] =~ s/(\n=*CJT.*)(\n=*FOC.*)/$2$1/; # FOC before CJT: "om ikke for andet, så fordi de lever" (Danish example)
	    $line[$_] =~ s/^(=*CJT.*)\n(=*FOC.*)/$2\n$1/; #

#		$adddepth++;
	}
	$partal =$line[$_];
	if ($partal =~ /¢/) {
#	  print "--CJT-line: $partal\n";
	  $partal =~ s/¢//; # special = reduction only after first CJT
	  while ($partal =~ s/¢//) { # necessary to provide for multiple par on same line
	    $line[$_] =~ s/^=//;
#	    print "--removing = for $line[$_]\n";
	  }
	}
	while ($line[$_] =~ s/(=*)¢(.*?):/$1$2:par\n=$1CJT:/) {
#	  $indent[$_]++; #???
#	  print "--indent for $_: $indent[$_]\n";
	}
	if ($line[$_] =~ s/=ð//) {
	  $line[$_] =~ s/\n=/\n/g;
	  $headpar =1;
	} # not indent a constituent if not full par, but headpar
	elsif ($line[$_] =~ /<headpar>/) {
	  $headpar =0;
	  $line[$_] =~ s/^(=+)=H:/$1H:par\n$1CJT:/;
	  $line[$_] =~ s/(CJT|CO)/=$1/;
	}
	elsif ($headpar) {
	  $line[$_] =~ s/^=//;
	  $line[$_] =~ s/\n=/\n/g;
	}
#	print "---$line[$_]\n";
	if  ($line[$_] =~ /FOC/) {
	  $focline =$_;
#	  print "--focline= $line[$focline]\n";
	}
	elsif ($focline && $line[$_] =~ /:par/) {
	    $line[$_] =~ s/(:par\n)/$1$line[$focline]/; # switch FOC- and par-lines, so as to place FOC inside the par
	    $line[$_] =~ s/(=*)([^=]*:par\n)=+/$1$2$1=/;
	    $line[$focline] ="";
	    $focline =0;
	}
	elsif ($focline) {
	  if ($line[$_] =~ /\n(=*)[^=]+\t/) { # i.e. if line has terminal (which always should be the case)
	    $indent =$1;
	    $focinsert = $line[$focline];
	    $focinsert =~ s/^=+//;
	    $line[$_] =~ s/\n([^\n\t]+\t)/\n$indent$focinsert$1/;
	    $line[$focline] = "";
	  }
	  else { # this is the old version of FOC treatment that stranded the FOC before the sentence in "Både folk i og udenfor cykelsporten har bemærket det."
#	    print "--postfocline= $line[$_]\n";
	    $line[$_] =~ m/(=*)[^=]+\n/;
	    $indent =$1;
	    $line[$focline] =~ s/^=+/$indent/; # adapt indentation of FOC when outside/before the par, judging from the indentation of the first intervening constituent
	  }
	  $focline =0;
	}
	else {
	    $focline =0;
	}

	$line[$_] =~ s/fAco/CO/;
#	    if ($line[$_] =~ /CO:.*<adv>/) {
#		$line[$_] =~ s/CO:/=CO:/;
#	    }

      slutnum:
#	print "$_ $line[$_]\n";
#	print "***$_: $line[$_]\n";
    }
}

sub print {
    $sentnr++;
    if (! $s_marker) {print "<s>\n\n"; $s_marker =0;}
    if ($source) {print "SOURCE: $source\n";}
    else {print "SOURCE: Running text\n";}
#    if (! $source) {$sentence = "ID=$sentnr " . $sentence;}
    if (! $source) {$sentence = "$sentnr\.\#" . $sentence;}
    $sentence =~ s/\# */ /;
    print $sentence . "\n";
    if ($circularity) {
	if ($source) {$circid =$source}
	else {$circid ="sentence $sentnr";}
	print "### CAVE CIRCULARITY in $circid at";
	$circularity =~ s/^ //;
	@circularities = split / /, $circularity;
	foreach (@circularities) {
	    $line[$_] =~ m/\t(.*)/;
	    $word =$1;
	    print " $_ ($word)";
	}
	print "\n";
    }
#    else {
#    print "A1\n";
    print $line[0];

### swap leading hyphen or quote onto second line
    if ($line[1] && $line[1] =~ /^[^A-Za-z=]/) {
	$line[2] =~ s/\n/\n$line[1]/;
	$line[1] ="";
    }
    elsif ($line[1] =~ /^=/) {$line[1] =~ s/^/UTT:x\n/;}

#    $secondtop =0;
	foreach (@num) {
	    if ($_) {
	      $line[$_] =~ s/Vaux:(prp|conj|ks)/SUBaux:$1/; # Portuguese/Spanish auxiliary particle (has to be Vaux during tree generation in order not to mess the program up)

### replace - by ¬ for the sake of javatrees and penn
		$line[$_] =~ s/\n- *\n/\n¬\n/g;
		$line[$_] =~ s/^- *\n/¬\n/g;
		$line[$_] =~ s/=¢/==/; # emergency solution, otherwise yields extra indentation (the error is cg2dep's, with wrong <cjt>'s or <cjt-head>'s) ???
		$line[$_] =~ s/¢/=/; # nødløsning
		if ($line[$_] =~ s/^=*([^ \n]|\.\.\.) *$/$1/) {
		    $next =$_ + 1;
		    if ($line[$next]) {
			$line[$next] =~ /^(=*)/;
			$line[$_] = $1 . $line[$_];
		    }
		}

### match right parenthesis to left

		if ($line[$_] =~ /^(=+)\(/) {$parindent =$1;}
		elsif ($parindent && $line[$_] =~ /^=*\)/) {$line[$_] =~ s/^=*/$parindent/; $parindent ="";}

### repair indented comma


		if ($line[$_] =~ /^(=+)[,\;\.:]/) {
		    $tegnindent =$1;
		    if ($tegnindent =~ /^$indent(=+)/) {
#			$restindent =$1;
#			$line[$_] =~ s/$restindent//;
		    }
		}
		$line[$_] =~ m/(=*)[^=]+$/;
		$indent =$1;

         #### group level dependents with zero indentation, after indented constituent, are always wrong -> indent to the same depth as the line before
		$indent =$1;
#	      print "-- $_ indent: $indent ** indentold: $indentold\n";
		if ($line[$_] =~ /^(>|[NAP]<|[\",\-¬\+\/:])/ && $indentold =~ /=/) {
#		  print "--$line[$_]***\n";
		  $line[$_] =~ s/^/$indentold/;
		  $indent =$indentold;
		}
		$indentold =$indent;
	      $line[$_] =~s/^((.*?\n)?)(=+)(-Oaux:par\n)=*(CJT:icl\n)/$1$3$4$3=-$5/; # correct second half indentation for discontinuous Oaux:par (e.g. "Her lærte han den disciplin og det taktisk-politiske håndværk, som han også langt senere skulle få så rigt brug for - og i øvrigt vise sig aldeles kapabel i.")
	      $line[$_] =~s/(Oaux:par)(\n=+CJT:icl-)/$1-$2/; # correcting first half hyphen marking for discontinuous Oaux:par
#	      if ($line[$_] =~ /Oaux/) {print "--$line[$_]***\n";}

### fA -> FOC

		if ($line[$_] =~ /=fA/ && $head[$_] < $_ && $line[$_-1] && $line[$_-1] =~ /^(=+)CO:/ && ($indent =$1)) {
		    $line[$_] =~ s/fA:/FOC:/;
		    $line[$_] =~ s/=+(FOC)/$indent$1/;
		}
		if ($line[$_] =~ /=fA/ && $head[$_] < $_ && $line[$_-2] && $line[$_-2] =~ /^(=+)CO:/ && ($indent =$1) && ! ($line[$_-1] && $line[$_-1] =~ /:/)) {
		    $line[$_] =~ s/fA:/FOC:/;
		    $line[$_] =~ s/=+(FOC)/$indent$1/;
		    $line[$_-1] =~ s/=+/$indent/;
		}
	    }
	}
#    }
    foreach (@num) {
	if ($_) {
### remove first indent a la visl
#		if ($_ > 1 && ($line[$_] =~ /^[^=]/ || $line[$_] =~ /\n[^=]/)) {
#		    $secondtop =1; # don't remove indentation a la visl, if there are other top-attaching nodes, e.g. isolated conjuncts or noun phrases, that would "lose" their daughters that way
#		}
#		elsif (! $secondtop) {

#		    $line[$_] =~ s/^=//;
#		    $line[$_] =~ s/\n=/\n/g;

#		}
#	  print "--$_ :: $line[$_]***\n";
	  if ($line[$_] =~ /\w:\w/) {
	    $line[$_] =~ s/\n([\[\(\{\w])/\n=$1/g; # repair of non-indented, isp. left bracket punctuation
	  }
	  $line[$_] =~ s/ +\)/\)/; # pre-bracket spaces
	  $line[$_] =~ s/  +/ /; # multiple spaces
	  $line[$_] =~s/^(=*[,;:\.\!\?]).*/$1/;
	  if ($line[$_] =~ /:adv.*<prp>/) {
	    $line[$_] =~ s/H:/SUB:/; # Segundo ele, ...
	  }
	  $line[$_] =~ s/\n[^\n]+\"Ø\"[^\n]+\tØ//;
	  $line[$_] =~ s/^[^\n]+\"Ø\"[^\n]+\tØ *\n//;
	  $line[$_] =~ s/CLEFTFOC/FOC/;
#	  $line[$_] =~ s/AX:/CO:/;
	  $line[$_] =~ s/^([^\w=])/=$1/; # indent remaining punctuation
	  $line[$_] =~ s/\n([^\w=])/\n=$1/g; # indent remaining punctuation
	  if ($topacl) {
	    $line[$_] =~ s/^(.)/=$1/g;
	    $line[$_] =~ s/\n(.)/\n=$1/g;
	  }
	  print $line[$_];
#	  print "***";
	}
    }
    print "\n";
}

sub cleantext {
    $sentence =~ s/ *\$([^0-9\-=])/$1/g;
    $sentence =~ s/\$([0-9\-])/$1/g;
    $sentence =~ s/ $//;
    $sentence =~ s/ ([,;:\.\?\!%\)])/$1/g;
    $sentence =~ s/([^ ])\_([^ ])/$1 $2/g; # polylexicals
    $sentence =~ s/([^ ])\_([^ ])/$1 $2/g; # polylexicals
    $sentence =~ s/\" ([^\"]+)\"/ \"$1\"/g; # attach quotes to words
    $sentence =~ s/([\(\[\{]) */$1/g; # attach left brackets


### Portuguese

    $sentence =~ s/ de (([ao]s*|aqu(el[ea]s*|ilo)|es[st][ea]s*|is[st]o|aqui|aí)([ \.,;]))/ d$1/g;
    $sentence =~ s/ em (([ao]s*|aqu(el[ea]s*|ilo)|es[st][ea]s*|is[st]o|umas*|um|uns|)([ \.,;]))/ n$1/g;
    $sentence =~ s/ a o((s)*[ \.,;])/ ao$1/g;
    $sentence =~ s/ a a((s|qu(el[ea]s*|ilo))*[ \.,;])/ à$1/g;
    $sentence =~ s/a[rz]-(l[ao]s*)([ ,\.\;\?\!])/á-$1$2/g;
    $sentence =~ s/e[rz]-(l[ao]s*)([ ,\.\;\?\!])/ê-$1$2/g;
    $sentence =~ s/([aeiou])i[rz]-(l[ao]s*)([ ,\.\;\?\!])/$1i-$2$3/g;
    $sentence =~ s/([^aeiou])i[rz]-(l[ao]s*)([ ,\.\;\?\!])/$1i-$2$3/g;
    $sentence =~ s/([ -])(m|t)e ([ao]s*)([ ,\.\;\?\!])/$1$2$3$4/g; # mo, lhas
    $sentence =~ s/([ -])(lh)es* ([ao]s*)([ ,\.\;\?\!])/$1$2$3$4/g; # mo, lhas
    $sentence =~ s/([ -])(no|vo)s-(l[ao]s*)([ ,\.\;\?\!])/$1$2-$3$4/g; # mo, lhas
    $sentence =~ s/s-(l[ao]s*|[mn][ao]s*)([ ,\.\;\?\!])/-$1$2/g;
    $sentence =~ s/ *\"?\»\"? */\» /g; #  Pedro Almodovar já filma"« Kika"»
    $sentence =~ s/ *\" *([,\.\n])/\»$1/g; #  --- problem: before komma
    $sentence =~ s/\"?\« */ \«/g; #  Pedro Almodovar já filma"« Kika"»


    $sentence =~ s/ ([a-zA-Z]|[qQ]u)\' ([a-zA-ZàÀéêèÉÊÈ])/ $1\'$2/g; # l'indifference, c'est, n'a  (French)
    $sentence =~ s/\' ([^\"\']+\'[^a-z])/ \'$1/g; # attach quotes to words
    $sentence =~ s/^ *([\"\']) ?/$1/g; # inital left only quote
    $sentence =~ s/^ +\-/\-/g; # inital hyphen
    $sentence =~ s/([^ ])\( +/$1 \(/g; # left bracket attachment
    $sentence =~ s/hyfen /- /g;
    $sentence =~ s/ *[\«\"] +/ \«/g;
    $sentence =~ s/([^ ])=([^ ])/$1 $2/g;
    $sentence =~ s/([^ ])=([^ ])/$1 $2/g;
    $sentence =~ s/^([A-Z]+) ([0-9]+[ \#])/$1=$2 /;
#    $sentence =~ s/\"/\'/g; # Tiger format problem
    $sentence =~ s/\n//g;
}
