#!/usr/bin/env python
#
# Copyright (C) 2006 Anders Logg
# Licensed under the GNU LGPL Version 2.1
#
# Modified by Garth N. Wells (gmsh function)
# Modified by Alexander H. Jarosch (gmsh fix)
# Modified by Angelo Simone (Gmsh and Medit fix)
# Modified by Andy R. Terrel (gmsh fix)
# Modified by Magnus Vikstrom (metis and scotch function)
# Modified by Bartosz Sawicki (diffpack function)
# Modified by Gideon Simpson (Exodus II function)
# Modified by Arve Knudsen (move logic into module meshconvert)
# Modified by Kent-Andre Mardal (Star-CD function)
#
# Script for converting between various data formats

import getopt
import sys
import os
from dolfin_utils.commands import getoutput
import re
import warnings
import os.path

from dolfin.mesh import meshconvert

def main(argv):
    "Main function"

    # Get command-line arguments
    try:
        opts, args = getopt.getopt(argv, "hi:o:", ["help", "input=", "output="])
    except getopt.GetoptError:
        usage()
        sys.exit(2)

    # Get options
    iformat = None
    oformat = None
    for opt, arg in opts:
        if opt in ("-h", "--help"):
            usage()
            sys.exit()
        elif opt in ("-i", "--input"):
            iformat = arg
        elif opt in ("-o", "--output"):
            oformat = arg

    # Check that we got two filenames
    if not len(args) == 2:
        usage()
        sys.exit(2)

    # Get filenames
    ifilename = args[0]
    ofilename = args[1]

    # Can only convert to XML
    if oformat and oformat != "xml":
        error("Unable to convert to format %s." % (oformat,))

    # Convert to XML
    meshconvert.convert2xml(ifilename, ofilename, iformat=iformat)

    # Order mesh
    os.system("dolfin-order %s" % ofilename)

def usage():
    "Display usage"
    print """\
Usage: dolfin-convert [OPTIONS] ... input.x output.y

Options:

  -h         display this help text and exit
  -i format  specify input format
  -o format  specify output format

Alternatively, the following long options may be used:

  --help     same as -h
  --input    same as -i
  --output   same as -o

Supported formats:

  xml      - DOLFIN XML mesh format (current)
  xml-old  - DOLFIN XML mesh format (DOLFIN 0.6.2 and earlier)
  mesh     - Medit, generated by tetgen with option -g
  gmsh     - Gmsh, version 2.0 file format
  metis    - Metis graph file format
  scotch   - Scotch graph file format
  diffpack - Diffpack tetrahedral grid format
  abaqus   - Abaqus tetrahedral grid format
  ExodusII - Sandia Format (requires ncdump utility from NetCDF)
  Star-CD  - Star-CD terahedral grid format

If --input or --output are not specified, the format will
be deduced from the suffix:

  .xml  - xml
  .mesh - mesh
  .gmsh - gmsh
  .msh  - gmsh
  .gra  - metis
  .grf  - scotch
  .grid - diffpack
  .inp  - abaqus
  .e	- Exodus II
  .exo  - Exodus II
  .ncdf - ncdump'ed Exodus II
  .vrt and .cell  - starcd
"""
if __name__ == "__main__":
    main(sys.argv[1:])
