#!/usr/bin/perl
BEGIN {
  use File::Basename;
  use lib dirname($0).'/../tredlib';
  use Treex::PML;
  use Treex::PML::Instance;
};

my $filename = 'test.t';
my $a_file;
if (@ARGV>1) {
  die "Usage: $0 [a-file]\n";
} elsif (@ARGV) {
  $a_file = shift;
  print STDERR "Assuming a-file: $a_file\n";
} else {
  print STDERR "No a-file: use $0 <a-filename>\n";
}

# where to look for PML schemata?
Treex::PML::AddResourcePath(dirname($0).'/../resources');

my $aref = defined $a_file ?
  qq(<reffile id="a" href="$a_file" name="adata"/>) : q();
my $pml = <<"EOF";
<?xml version="1.0" encoding="utf-8"?>
<tdata xmlns="http://ufal.mff.cuni.cz/pdt/pml/">
 <head>
  <schema href="tdata_schema.xml"/>
  <references>
   $aref
   <reffile id="v" href="vallex.xml" name="vallex"/>
  </references>
 </head>
 <meta>
  <annotation_info>
   <desc>Automatically generated by PML_A2T.mak</desc>
  </annotation_info>
 </meta>
 <trees/>
</tdata>
EOF

my $fsfile = Treex::PML::Instance->load({
  string   => $pml,
  filename => $filename,
})->convert_to_fsfile();

my $schema = $fsfile->metaData('schema');

# create 10 sample trees
my ($root,$node);
foreach my $i (1..10) {
  # create a new tree
  $root=Treex::PML::Factory->createTypedNode('t-root.type' => $schema);
  $fsfile->insert_tree($root, $i-1);

  # fill-in required attributes
  $root->{id}="tree.$i";
  $root->{nodetype}="root";
  $root->{deepord}=0;

  foreach my $j (1..4) {
    # create a new node
    $node=Treex::PML::Factory->createTypedNode('t-node.type' => $schema);

    # fill-in required attributes
    $node->{id}="node-$i.$j";
    $node->{nodetype}="complex";
    $node->{t_lemma}="$j";
    $node->{functor}="RSTR";
    $node->{deepord}=$j;

    # paste the node on root
    $node->paste_on($root,'deepord');
  }
  {
    # validate the tree against PML Schema
    my @log;
    $root->validate_subtree(\@log);
    warn join("\n",@log) if @log;
  }
}

print STDERR "Saving $filename\n";
$fsfile->writeFile();
