#!/usr/local/bin/perl -w
#
#  Copyright (c) 1997-2004
#  Ewgenij Gawrilow, Michael Joswig (Technische Universitaet Berlin, Germany)
#  http://www.math.tu-berlin.de/polymake,  mailto:polymake@math.tu-berlin.de
#
#  This program is free software; you can redistribute it and/or modify it
#  under the terms of the GNU General Public License as published by the
#  Free Software Foundation; either version 2, or (at your option) any
#  later version: http://www.gnu.org/licenses/gpl.txt.
#
#  This program is distributed in the hope that it will be useful,
#  but WITHOUT ANY WARRANTY; without even the implied warranty of
#  MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
#  GNU General Public License for more details.
#-----------------------------------------------------------------------------
#  $Project: polymake $$Id: obj2surf 7068 2006-02-22 12:22:18Z thilosch $

#  @file obj2surf
#
#  Convert a Wavefront obj description of a polyhedral surface into
#  polymake Surface format.
#
#  @synopsis obj2surf <out_file> <in_file>
#
#  @index utilities

die "usage: obj2poly <out_file> <in_file>\n" unless($#ARGV == 1);

open IN, "<$ARGV[1]" or die("Can't open $ARGV[1] for reading.");
open OUT, ">$ARGV[0]" or die("Can't open $ARGV[0] for writing.");
print OUT <<".";
_application surface
_version 2.1.1
_type Surface

GEOMETRIC_REALIZATION
.
my $facets = 0;
while(<IN>) {
  if(/^[v|f]\s+/) {
    if(/^v\s+/) {
      s/^v\s+//;
      print OUT $_;
    }
    if(/^f\s+/) {
      if(!$facets) {
	$facets = 1;
	print OUT "\nFACETS_CYCLIC\n";
      }
      s/^f\s+//;
      s/(\d+)(?:\/\d*\/\d*)?/$1-1/eg;
      chomp;
      print OUT "{$_}\n";
    }
  }
}

if(!$facets) {
  die "No facets found in $ARGV[1]\n";
  unlink $ARGV[0];
}
