@*
RImport.tmpl

Created by Rafael Laboissiere on 2013-01-04.

Based on MatlabOctaveImport.tmpl, which was:

Created by Joe Hope on 2009-01-07.
Modified by Gregory Bogomiagkov and Liam Madge on 2013-07-18.

Copyright (c) 2009-2013, Joe Hope and Graham Dennis

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 of the License, or
(at your option) any later version.

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.

You should have received a copy of the GNU General Public License
along with this program.  If not, see <http://www.gnu.org/licenses/>.

*@

@def description: Creates text to import data from XSIL files into R.

@attr $defaultExtension = 'r'
@attr $stringFormat = '.12e'
@attr $name = 'R'

@def generateVariableName(xsilVariable, xsilObjectNumber)
  @return c'${xsilVariable.name}_${xsilObjectNumber+1}'
@end def

@def loadXSILFile($xsilFile)
  @for objectNum, xsilObject in enumerate(xsilFile.xsilObjects):
    @if xsilObject.data.format == 'hdf5'
${handleHDF5XSILObject(objectNum, xsilObject)}@slurp
    @else
      @raise Exception("No support for R output for XSIL format '%s'." % xsilObject.data.format)
    @end if
  @end for
@end def


@def handleHDF5XSILObject(objectNum, xsilObject)
tryCatch (library (hdf5),
          error = function (e) {
                      message (e)
                      cat ("\n")
                      stop ("Install the hdf5 library for loading XSIL data", call. = FALSE)
                      return (NA)
          })

  @set $filename = xsilObject.data.filename
hdf5load ("${filename}")
  @for var in xsilObject.independentVariables:
${var.name}.${objectNum+1} <- get ("${objectNum+1}")\$${var.name}
  @end for
  @for var in xsilObject.dependentVariables:
${var.name}.${objectNum+1} <- get ("${objectNum+1}")\$${var.name}
  @end for
rm ("${objectNum+1}")
@end def
