# usage:  polymake --script half_projection FILE [ lower | upper ]

application 'polytope';

if (@ARGV < 1 || @ARGV > 2 ||
    ! -f $ARGV[0] ||
    (@ARGV==2 && $ARGV[1] !~ /^(?:lower|upper)$/i)) {
   die "usage: polymake --script half_projection FILE [ lower | upper ]\n";
}

my $src=load($ARGV[0]);
my $last_dim=$src->AMBIENT_DIM-1;
my $matching_facet_re= lc($ARGV[1]) eq "upper" ? qr/\s-\S+$/ : qr/\s(?!-|0$)\S+$/;
my $n=0;
my (@matching_facets, @facet_indices);

foreach my $f (@{$src->FACETS}) {
   if ($f =~ $matching_facet_re) {
      my $tmp=new Apps::polytope::RationalPolytope;
      Modules::client("facet", $tmp, $src, $n, "-relabel");
      my @vertices=map { /(.*)\s+\S+$/ } @{$tmp->VERTICES};
      my $new_f=new Apps::polytope::RationalPolytope($src->name . "_facet_$n",
						     VERTICES => \@vertices,
						     VERTEX_LABELS => $tmp->VERTEX_LABELS);
      $new_f->commit;
      push @facet_indices, $n;
      push @matching_facets, $new_f;
   }
   ++$n;
}

my @complex_dual_graph;
Modules::client("induced_subgraph", $src, "DUAL_GRAPH", [ "{@facet_indices}\n" ], \@complex_dual_graph, "-nol");

# $_->VISUAL for @matching_facets;
save($_) for @matching_facets;

visualize( new Visual::Graph( Name => "dual graph of the ".(lc($ARGV[1]) eq "upper" ? "upper" : "lower")." half of ".$src->name,
			      Graph => \@complex_dual_graph,
			      NodeLabels => \@facet_indices,
			      Coord => spring_embedding_3d($src, \@complex_dual_graph),
			    ));

1;
