This file is indexed.

/usr/lib/python2.7/dist-packages/instant/codegeneration.py is in python-instant 2016.2.0-2.

This file is owned by root:root, with mode 0o644.

The actual contents of the file can be viewed below.

  1
  2
  3
  4
  5
  6
  7
  8
  9
 10
 11
 12
 13
 14
 15
 16
 17
 18
 19
 20
 21
 22
 23
 24
 25
 26
 27
 28
 29
 30
 31
 32
 33
 34
 35
 36
 37
 38
 39
 40
 41
 42
 43
 44
 45
 46
 47
 48
 49
 50
 51
 52
 53
 54
 55
 56
 57
 58
 59
 60
 61
 62
 63
 64
 65
 66
 67
 68
 69
 70
 71
 72
 73
 74
 75
 76
 77
 78
 79
 80
 81
 82
 83
 84
 85
 86
 87
 88
 89
 90
 91
 92
 93
 94
 95
 96
 97
 98
 99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
"""This module contains helper functions for code generation."""

# Copyright (C) 2010, 2013 Kent-Andre Mardal
# Copyright (C) 2008 Martin Sandve Alnes
# Copyright (C) 2009 Ilmar Wilbers
# Copyright (C) 2013 Garth N. Wells
#
# This file is part of Instant.
#
# Instant is free software: you can redistribute it and/or modify
# it under the terms of the GNU Lesser General Public License as published by
# the Free Software Foundation, either version 3 of the License, or
# (at your option) any later version.
#
# Instant 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 Lesser General Public License for more details.
#
# You should have received a copy of the GNU Lesser General Public License
# along with Instant. If not, see <http://www.gnu.org/licenses/>.
#
# Alternatively, Instant may be distributed under the terms of the BSD license.

import sys
import re, os
from .output import instant_assert, instant_warning, instant_debug, write_file
from .config import get_swig_binary

def mapstrings(format, sequence):
    return "\n".join(format % i for i in sequence)

def reindent(code):
    '''Reindent a multiline string to allow easier to read syntax.

    Each line will be indented relative to the first non-empty line.
    Start the first line without text like shown in this example::

        code = reindent("""
            Foo
            Bar
                Blatti
            Ping
            """)

    makes all indentation relative to Foo.
    '''
    lines = code.split("\n")
    space = ""
    # Get initial spaces from first non-empty line:
    for l in lines:
        if l:
            r = re.search(r"^( [ ]*)", l)
            if r is not None:
                space = r.groups()[0]
            break
    if not space:
        return code
    n = len(space)
    instant_assert(space == " "*n, "Logic breach in reindent.")
    return "\n".join(re.sub(r"^%s" % space, "", l) for l in lines)

def write_interfacefile(filename, modulename, code, init_code,
                        additional_definitions, additional_declarations,
                        system_headers, local_headers, wrap_headers, arrays):
    """Generate a SWIG interface file. Intended for internal library use.

    The input arguments are as follows:
      - modulename (Name of the module)
      - code (Code to be wrapped)
      - init_code (Code to put in the init section of the interface file)
      - additional_definitions (Definitions to be placed in initial block with
        C code as well as in the main section of the SWIG interface file)
      - additional_declarations (Declarations to be placed in the main section
        of the SWIG interface file)
      - system_headers (A list of system headers with declarations needed by the wrapped code)
      - local_headers (A list of local headers with declarations needed by the wrapped code)
      - wrap_headers (A list of local headers that will be included in the code and wrapped by SWIG)
      - arrays (A nested list, the inner lists describing the different arrays)

    The result of this function is that a SWIG interface with
    the name modulename.i is written to the current directory.
    """
    instant_debug("Generating SWIG interface file '%s'." % filename)

    # create typemaps
    typemaps = ""
    valid_types = ['float', 'double', 'short', 'int', 'long', 'long long',
                   'unsigned short', 'unsigned int', 'unsigned long',
                   'unsigned long long']
    for a in arrays:
        if isinstance(a, tuple):
            a = list(a)
        DATA_TYPE = 'double'
        for vt in valid_types:
            if vt in a:
                DATA_TYPE = vt
                a.remove(vt)
        if 'in' in a:
            # input arrays
            a.remove('in')
            instant_assert(len(a) > 1 and len(a) < 5,
                           "Wrong number of elements in input array")
            if len(a) == 2:
                # 1-dimensional arrays, i.e. vectors
                typemaps += reindent("""
                %%apply (int DIM1, %(dtype)s* IN_ARRAY1) {(int %(n1)s, %(dtype)s* %(array)s)};
                """ % { 'n1' : a[0], 'array' : a[1], 'dtype' : DATA_TYPE })
            elif len(a) == 3:
                # 2-dimensional arrays, i.e. matrices
                typemaps += reindent("""
                %%apply (int DIM1, int DIM2, %(dtype)s* IN_ARRAY2) {(int %(n1)s, int %(n2)s, %(dtype)s* %(array)s)};
                """ % { 'n1' : a[0], 'n2' : a[1], 'array' : a[2], 'dtype' : DATA_TYPE })
            else:
                # 3-dimensional arrays, i.e. tensors
                typemaps += reindent("""
                %%apply (int DIM1, int DIM2, int DIM3, %(dtype)s* IN_ARRAY3) {(int %(n1)s, int %(n2)s, int %(n3)s, %(dtype)s* %(array)s)};
                """ % { 'n1' : a[0], 'n2' : a[1], 'n3' : a[2], 'array' : a[3], 'dtype' : DATA_TYPE })
        elif 'out' in a:
            # output arrays
            a.remove('out')
            instant_assert(len(a) == 2, "Output array must be 1-dimensional")
            # 1-dimensional arrays, i.e. vectors
            typemaps += reindent("""
            %%apply (int DIM1, %(dtype)s* ARGOUT_ARRAY1) {(int %(n1)s, %(dtype)s* %(array)s)};
            """ % { 'n1' : a[0], 'array' : a[1], 'dtype' : DATA_TYPE })
        else:
            # in-place arrays
            instant_assert(len(a) > 1 and len(a) < 5,
                           "Wrong number of elements in output array")
            if 'multi' in a:
                # n-dimensional arrays, i.e. tensors > 3-dimensional
                a.remove('multi')
                typemaps += reindent("""
                %%typemap(in) (int %(n)s,int* %(ptv)s,%(dtype)s* %(array)s){
                  if (!PyArray_Check($input)) {
                    PyErr_SetString(PyExc_TypeError, "Not a NumPy array");
                    return NULL; ;
                  }
                  PyArrayObject* pyarray;
                  pyarray = (PyArrayObject*)$input;
                  $1 = int(pyarray->nd);
                  int* dims = new int[$1];
                  for (int d=0; d<$1; d++) {
                     dims[d] = int(pyarray->dimensions[d]);
                  }

                  $2 = dims;
                  $3 = (%(dtype)s*)pyarray->data;
                }
                %%typemap(freearg) (int %(n)s,int* %(ptv)s,%(dtype)s* %(array)s){
                    // deleting dims
                    delete $2;
                }
                """ % { 'n' : a[0] , 'ptv' : a[1], 'array' : a[2], 'dtype' : DATA_TYPE })
            elif len(a) == 2:
                # 1-dimensional arrays, i.e. vectors
                typemaps += reindent("""
                %%apply (int DIM1, %(dtype)s* INPLACE_ARRAY1) {(int %(n1)s, %(dtype)s* %(array)s)};
                """ % { 'n1' : a[0], 'array' : a[1], 'dtype' : DATA_TYPE })
            elif len(a) == 3:
                # 2-dimensional arrays, i.e. matrices
                typemaps += reindent("""
                %%apply (int DIM1, int DIM2, %(dtype)s* INPLACE_ARRAY2) {(int %(n1)s, int %(n2)s, %(dtype)s* %(array)s)};
                """ % { 'n1' : a[0], 'n2' : a[1], 'array' : a[2], 'dtype' : DATA_TYPE })
            else:
                # 3-dimensional arrays, i.e. tensors
                typemaps += reindent("""
                %%apply (int DIM1, int DIM2, int DIM3, %(dtype)s* INPLACE_ARRAY3) {(int %(n1)s, int %(n2)s, int %(n3)s, %(dtype)s* %(array)s)};
                """ % { 'n1' : a[0], 'n2' : a[1], 'n3' : a[2], 'array' : a[3], 'dtype' : DATA_TYPE})
            # end
        # end if
    # end for

    system_headers_code = mapstrings('#include <%s>', system_headers)
    local_headers_code  = mapstrings('#include "%s"', local_headers)
    wrap_headers_code1  = mapstrings('#include "%s"', wrap_headers)
    wrap_headers_code2  = mapstrings('%%include "%s"', wrap_headers)

    numpy_i_include = ''
    if arrays:
        numpy_i_include = r'%include "numpy.i"'

    # Do not reindent as SWIG interface code can also include Python code.
    interface_string = """%%module  %(modulename)s
//%%module (directors="1") %(modulename)s

//%%feature("director");

%%{
#include <iostream>
%(additional_definitions)s
%(system_headers_code)s
%(local_headers_code)s
%(wrap_headers_code1)s
%(code)s
%%}

//%%feature("autodoc", "1");
%(numpy_i_include)s

%%init%%{
%(init_code)s
%%}

%(additional_definitions)s
%(additional_declarations)s
%(wrap_headers_code2)s
//%(typemaps)s
%(code)s;

""" % locals()

    write_file(filename, interface_string)
    instant_debug("Done generating interface file.")

def write_setup(filename, modulename, csrcs, cppsrcs, local_headers, include_dirs, library_dirs, libraries, swig_include_dirs, swigargs, cppargs, lddargs):
    """Generate a setup.py file. Intended for internal library use."""
    instant_debug("Generating %s." % filename)

    swig_include_dirs.append(os.path.join(os.path.dirname(__file__), 'swig'))

    # Handle arguments
    swigfilename = "%s.i" % modulename
    wrapperfilename = "%s_wrap.cxx" % modulename

    # Treat C and C++ files in the same way for now
    cppsrcs = cppsrcs + csrcs + [wrapperfilename]

    swig_args = ""
    if swigargs:
        swig_args = " ".join(swigargs)

    compile_args = ""
    if cppargs:
        compile_args = ", extra_compile_args=%r" % cppargs

    link_args = ""
    if lddargs:
        link_args = ", extra_link_args=%r" % lddargs

    swig_include_dirs = " ".join("-I%s"%d for d in swig_include_dirs)
    if len(local_headers) > 0:
        swig_include_dirs += " -I.."

    py3 = "" if sys.version_info[0] < 3 else "-py3"

    # Generate code
    code = reindent("""
        import os
        from distutils.core import setup, Extension
        name = '%s'
        swig_cmd =r'%s -python %s %s %s %s'
        os.system(swig_cmd)
        sources = %s
        setup(name = '%s',
              ext_modules = [Extension('_' + '%s',
                             sources,
                             include_dirs=%s,
                             library_dirs=%s,
                             libraries=%s %s %s)])
        """ % (modulename, get_swig_binary(), py3, swig_include_dirs, swig_args, \
               swigfilename, cppsrcs, modulename, modulename, include_dirs, \
               library_dirs, libraries, compile_args, link_args))

    write_file(filename, code)
    instant_debug("Done writing setup.py file.")


def _test_write_interfacefile():
    modulename = "testmodule"
    code = "void foo() {}"
    init_code = "/* custom init code */"
    additional_definitions = "/* custom definitions */"
    additional_declarations = "/* custom declarations */"
    system_headers = ["system_header1.h", "system_header2.h"]
    local_headers = ["local_header1.h", "local_header2.h"]
    wrap_headers = ["wrap_header1.h", "wrap_header2.h"]
    arrays = [["length1", "array1"], ["dims", "lengths", "array2"]]

    write_interfacefile("%s.i" % modulename, modulename, code, init_code, \
                        additional_definitions, additional_declarations, \
                        system_headers, local_headers, wrap_headers, arrays)
    print("".join(open("%s.i" % modulename).readlines()))

def _test_write_setup():
    modulename = "testmodule"
    csrcs = ["csrc1.c", "csrc2.c"]
    cppsrcs = ["cppsrc1.cpp", "cppsrc2.cpp"]
    local_headers = ["local_header1.h", "local_header2.h"]
    include_dirs = ["includedir1", "includedir2"]
    library_dirs = ["librarydir1", "librarydir2"]
    libraries = ["lib1", "lib2"]
    swig_include_dirs = ["swigdir1", "swigdir2"],
    swigargs = ["-Swigarg1", "-Swigarg2"]
    cppargs = ["-cpparg1", "-cpparg2"]
    lddargs = ["-Lddarg1", "-Lddarg2"]

    write_setup("setup.py", modulename, csrcs, cppsrcs, local_headers, \
                include_dirs, library_dirs, libraries, swig_include_dirs, \
                swigargs, cppargs, lddargs)
    print("".join(open("setup.py").readlines()))

def unique(sequence):
    return list(set(sequence))


def find_vtk_classes(str):
    pattern = "vtk\w*"
    l = unique(re.findall(pattern, str))
    return l

def create_typemaps(classes):
    s = ""

    typemap_template = """
%%typemap(in) %(class_name)s * {
    vtkObjectBase* obj = vtkPythonGetPointerFromObject($input, "%(class_name)s");
    %(class_name)s * oobj = NULL;
    if (obj->IsA("%(class_name)s")) {
        oobj = %(class_name)s::SafeDownCast(obj);
        $1 = oobj;
    }
}

%%typemap(out) %(class_name)s * {
   $result = vtkPythonGetObjectFromPointer($1);
}

   """

    for cl in classes:
        s += typemap_template % { "class_name" : cl }

    return s


def generate_vtk_includes(classes):
    s = """
#include "vtkPythonUtil.h"
    """
    for cl in classes:
        s += """
#include \"%s.h\" """ % cl
    return s


def generate_interface_file_vtk(signature, code):

    interface_template =  """
%%module test
%%{

%(includes)s

%(code)s

%%}

%(typemaps)s

%(code)s

"""
    class_list = find_vtk_classes(code)
    includes = generate_vtk_includes(class_list)
    typemaps = create_typemaps(class_list)
    s = interface_template % { "typemaps" : typemaps, "code" : code, "includes" : includes }
    return s

def write_cmakefile(module_name, cmake_packages, csrcs, cppsrcs, local_headers, include_dirs, library_dirs, libraries, swig_include_dirs, swigargs, cppargs, lddargs):

    find_package_template = """
# Configuration for package %(package)s
FIND_PACKAGE(%(package)s REQUIRED)
IF(%(package)s_FOUND)
 INCLUDE(${%(PACKAGE)s_USE_FILE})
ENDIF(%(package)s_FOUND)
"""

    cmake_form = dict(module_name=module_name)

    cmake_form["extra_libraries"] = ";".join(libraries)
    cmake_form["extra_include_dirs"] = ";".join(include_dirs)
    cmake_form["extra_library_dirs"] = ";".join(library_dirs)
    cmake_form["extra_swig_include_dirs"] = " -I".join([" "] + swig_include_dirs)

    cmake_form["extra_swigargs"] = " ".join(swigargs)

    cmake_form["swig_executable"] =  "\n".join(\
        """if (DEFINED %(package)s_SWIG_EXECUTABLE)
  set(SWIG_EXECUTABLE ${%(package)s_SWIG_EXECUTABLE})
endif()
""" % dict(package=package.upper()) for package in cmake_packages)


    cmake_form["find_packages"] = "\n\n".join(find_package_template % \
                                              dict(package=package,
                                                   PACKAGE=package.upper())\
                                              for package in cmake_packages)
    cmake_form["packages_definitions"] = "\n".join(
        "${%s_CXX_DEFINITIONS}" % package.upper()
        for package in cmake_packages)

    cmake_form["packages_definitions"] += "\n"+"\n".join(
        "${%s_PYTHON_DEFINITIONS}" % package.upper()
        for package in cmake_packages)

    cmake_form["package_include_dirs"] = "\n".join(\
        "include_directories(${%(package)s_PYTHON_INCLUDE_DIRS} ${%(package)s_3RD_PARTY_INCLUDE_DIRS} ${${NAME}_SOURCE_DIR})" %
        dict(package=package.upper()) for package in cmake_packages)

    cmake_form["package_flags"] = "\n".join(\
        """set(CMAKE_EXE_LINKER_FLAGS \"${CMAKE_EXE_LINKER_FLAGS} ${%(package)s_LINK_FLAGS}\")
set(CMAKE_SHARED_LINKER_FLAGS \"${CMAKE_SHARED_LINKER_FLAGS} ${%(package)s_LINK_FLAGS}\")
""" %
        dict(package=package.upper()) for package in cmake_packages)

    cmake_form["package_swig_link_libraries"] = "\n".join(\
        """if (DEFINED %(package)s_LIBRARIES OR DEFINED %(package)s_3RD_PARTY_LIBRARIES OR DEFINED %(package)s_PYTHON_LIBRARIES)
  swig_link_libraries(${SWIG_MODULE_NAME} ${%(package)s_LIBRARIES} ${%(package)s_3RD_PARTY_LIBRARIES} ${%(package)s_PYTHON_LIBRARIES} ${EXTRA_SOURCE_LIB})
endif()""" %
        dict(package=package.upper()) for package in cmake_packages)

    cmake_form["package_python_definitions"] = "\n".join(\
        """if (DEFINED %(package)s_PYTHON_DEFINITIONS)
  add_definitions(${%(package)s_PYTHON_DEFINITIONS})
endif()""" %
        dict(package=package.upper()) for package in cmake_packages)

    cppsrcs.extend(csrcs)
    if len(cppsrcs) > 0:
        cmake_form["extra_sources_files"] = "set(SOURCE_FILES %s) " %  " ".join(cppsrcs)
    else:
        cmake_form["extra_sources_files"] = "set(SOURCE_FILES)"

    if cppargs:
        cmake_form["cppargs"] = "set(CMAKE_CXX_FLAGS \"${CMAKE_CXX_FLAGS} %s\")" % \
                                (" ".join(cppargs))
    else:
        cmake_form["cppargs"] = ""

    if lddargs:
        cmake_form["lddargs"] = "set(CMAKE_EXE_LINKER_FLAGS \""\
                                "${CMAKE_EXE_LINKER_FLAGS} %s\")" % (" ".join(lddargs))
    else:
        cmake_form["lddargs"] = ""

    cmake_template = """
cmake_minimum_required(VERSION 2.6.0)

set (NAME %(module_name)s)

PROJECT(${NAME})

%(find_packages)s

%(cppargs)s
%(lddargs)s

%(swig_executable)s

find_package(SWIG REQUIRED)
include(${SWIG_USE_FILE})

set(SWIG_MODULE_NAME ${NAME})
set(CMAKE_SWIG_FLAGS
  -module ${SWIG_MODULE_NAME}
  -shadow
  -modern
  -modernargs
  -fastdispatch
  -fvirtual
  -nosafecstrings
  -noproxydel
  -fastproxy
  -fastinit
  -fastunpack
  -fastquery
  -nobuildnone
%(packages_definitions)s
%(extra_swigargs)s
%(extra_swig_include_dirs)s
  )

set(CMAKE_SWIG_OUTDIR ${CMAKE_CURRENT_BINARY_DIR})

set(SWIG_SOURCES ${NAME}.i)

set_source_files_properties(${SWIG_SOURCES} PROPERTIES CPLUSPLUS ON)

set(EXTRA_INCLUDE_DIRS \"%(extra_include_dirs)s\")
if(EXTRA_INCLUDE_DIRS)
  include_directories(${EXTRA_INCLUDE_DIRS})
endif()
%(package_include_dirs)s

%(package_flags)s

set(EXTRA_LIBRARY_DIRS \"%(extra_library_dirs)s\")
if(EXTRA_LIBRARY_DIRS)
  link_directories(${EXTRA_LIBRARY_DIRS})
endif()

%(extra_sources_files)s

%(package_python_definitions)s

# Work-around for bug in CMake 3.0.0 (see
# http://www.cmake.org/Bug/view.php?id=14990)
set(SWIG_MODULE_NAME_ORIG "${SWIG_MODULE_NAME}")
if (${CMAKE_VERSION} MATCHES "3.0.0")
  set(SWIG_MODULE_NAME "_${SWIG_MODULE_NAME}")
endif()

swig_add_module(${SWIG_MODULE_NAME} python ${SWIG_SOURCES})

set(EXTRA_LIBRARIES %(extra_libraries)s)
if(SOURCE_FILES)
  set(CMAKE_CXX_FLAGS \"${CMAKE_CXX_FLAGS} -fpic\")
  add_library(source_file_lib
    STATIC
    ${SOURCE_FILES})
  set(EXTRA_LIBRARIES \"source_file_lib;${EXTRA_LIBRARIES}\")
endif()

if(EXTRA_LIBRARIES)
  string(STRIP \"${EXTRA_LIBRARIES}\" EXTRA_LIBRARIES)
  swig_link_libraries(${SWIG_MODULE_NAME} ${EXTRA_LIBRARIES})
endif()

%(package_swig_link_libraries)s

""" % cmake_form

    filename = "CMakeLists.txt"
    write_file(filename, cmake_template)

def write_itk_cmakefile(name):
    file_template = """
cmake_minimum_required(VERSION 2.6.0)

# This project is designed to be built outside the Insight source tree.
PROJECT(%(name)%s)

# Find ITK.
FIND_PACKAGE(ITK REQUIRED)
IF(ITK_FOUND)
  INCLUDE(${ITK_USE_FILE})
ENDIF(ITK_FOUND)

# Find VTK.
FIND_PACKAGE(VTK REQUIRED)
IF(VTK_FOUND)
  INCLUDE(${VTK_USE_FILE})
ENDIF(VTK_FOUND)

find_package(SWIG REQUIRED)
include(${SWIG_USE_FILE})

set(SWIG_MODULE_NAME %(name)s)
set(CMAKE_SWIG_FLAGS
  -module ${SWIG_MODULE_NAME}
  -shadow
  -modern
  -modernargs
  -fastdispatch
  -fvirtual
  -nosafecstrings
  -noproxydel
  -fastproxy
  -fastinit
  -fastunpack
  -fastquery
  -nobuildnone
  -Iinclude/swig
  )

set(CMAKE_SWIG_OUTDIR ${CMAKE_CURRENT_BINARY_DIR})

set(SWIG_SOURCES %(name)s.i)

set_source_files_properties(${SWIG_SOURCES} PROPERTIES CPLUSPLUS ON)

include_directories(${PYTHON_INCLUDE_PATH} ${%(name)s_SOURCE_DIR})

set(VTK_LIBS ITKCommon vtkCommon vtkImaging vtkIO vtkFiltering vtkRendering vtkGraphics vtkCommonPythonD vtkFilteringPythonD)

# Work-around for bug in CMake 3.0.0 (see
# http://www.cmake.org/Bug/view.php?id=14990)
set(SWIG_MODULE_NAME_ORIG "${SWIG_MODULE_NAME}")
if (${CMAKE_VERSION} MATCHES "3.0.0")
  set(SWIG_MODULE_NAME "_${SWIG_MODULE_NAME}")
endif()

swig_add_module(${SWIG_MODULE_NAME} python ${SWIG_SOURCES})

swig_link_libraries(${SWIG_MODULE_NAME} ${PYTHON_LIBRARIES} ${VTK_LIBS})


    """ % { "name" : name }

    f = open("CMakeLists.txt", 'w')

    f.write(file_template)


def write_vmtk_cmakefile(name):
    file_template = """
cmake_minimum_required(VERSION 2.6.0)

# This project is designed to be built outside the Insight source tree.
PROJECT(%(name)%s)

# Find ITK.
FIND_PACKAGE(ITK REQUIRED)
IF(ITK_FOUND)
  INCLUDE(${ITK_USE_FILE})
ENDIF(ITK_FOUND)

# Find VTK.
FIND_PACKAGE(VTK REQUIRED)
IF(VTK_FOUND)
  INCLUDE(${VTK_USE_FILE})
ENDIF(VTK_FOUND)

# Find VMTK.
#FIND_PACKAGE(VMTK REQUIRED)
#IF(VMTK_FOUND)
#  INCLUDE(${VMTK_USE_FILE})
#ENDIF(ITK_FOUND)

find_package(SWIG REQUIRED)
include(${SWIG_USE_FILE})

set(SWIG_MODULE_NAME %(name)s)
set(CMAKE_SWIG_FLAGS
  -module ${SWIG_MODULE_NAME}
  -shadow
  -modern
  -modernargs
  -fastdispatch
  -fvirtual
  -nosafecstrings
  -noproxydel
  -fastproxy
  -fastinit
  -fastunpack
  -fastquery
  -nobuildnone
  -Iinclude/swig
  )

set(CMAKE_SWIG_OUTDIR ${CMAKE_CURRENT_BINARY_DIR})

set(SWIG_SOURCES %(name)s.i)

set_source_files_properties(${SWIG_SOURCES} PROPERTIES CPLUSPLUS ON)

include_directories(${PYTHON_INCLUDE_PATH} ${%(name)s_SOURCE_DIR} /usr/local/include/vmtk)
link_directories(/usr/local/lib/vmtk .)

set(VTK_LIBS ITKCommon vtkCommon vtkImaging vtkIO vtkFiltering vtkRendering vtkGraphics vtkCommonPythonD vtkFilteringPythonD)
set(VMTK_LIBS vtkvmtkCommonPythonD vtkvmtkITKPythonD vtkvmtkCommon vtkvmtkITK vtkvmtkComputationalGeometryPythonD vtkvmtkMiscPythonD vtkvmtkComputationalGeometry vtkvmtkMisc vtkvmtkDifferentialGeometryPythonD vtkvmtkSegmentationPythonD vtkvmtkDifferentialGeometry vtkvmtkSegmentation vtkvmtkIOPythonD)

# Work-around for bug in CMake 3.0.0 (see
# http://www.cmake.org/Bug/view.php?id=14990)
set(SWIG_MODULE_NAME_ORIG "${SWIG_MODULE_NAME}")
if (${CMAKE_VERSION} MATCHES "3.0.0")
  set(SWIG_MODULE_NAME "_${SWIG_MODULE_NAME}")
endif()

swig_add_module(${SWIG_MODULE_NAME} python ${SWIG_SOURCES})

swig_link_libraries(${SWIG_MODULE_NAME} ${PYTHON_LIBRARIES} ${VTK_LIBS} ${VMTK_LIBS})


    """ % { "name" : name }

    f = open("CMakeLists.txt", 'w')

    f.write(file_template)

def write_vtk_interface_file(signature, code):
    filename = signature
    ifile = filename + ".i"
    iff = open(ifile, 'w')
    ifile_code = generate_interface_file_vtk(signature, code)
    iff.write(ifile_code)


if __name__ == "__main__":
    _test_write_interfacefile()
    print("\n"*3)
    _test_write_setup()