#!/usr/bin/env python




##################################################
## DEPENDENCIES
import sys
import os
import os.path
try:
    import builtins as builtin
except ImportError:
    import __builtin__ as builtin
from os.path import getmtime, exists
import time
import types
from Cheetah.Version import MinCompatibleVersion as RequiredCheetahVersion
from Cheetah.Version import MinCompatibleVersionTuple as RequiredCheetahVersionTuple
from Cheetah.Template import Template
from Cheetah.DummyTransaction import *
from Cheetah.NameMapper import NotFound, valueForName, valueFromSearchList, valueFromFrameOrSearchList
from Cheetah.CacheRegion import CacheRegion
import Cheetah.Filters as Filters
import Cheetah.ErrorCatchers as ErrorCatchers
import fbcktemplate
from fbcktemplate import FbckTemplate

##################################################
## MODULE CONSTANTS
VFFSL=valueFromFrameOrSearchList
VFSL=valueFromSearchList
VFN=valueForName
currentTime=time.time
__CHEETAH_version__ = '2.4.2.1'
__CHEETAH_versionTuple__ = (2, 4, 2, 'final', 1)
__CHEETAH_genTime__ = 1281040829.902108
__CHEETAH_genTimestamp__ = 'Thu Aug  5 13:40:29 2010'
__CHEETAH_src__ = 'fbcktemplate/fbckmatlabexport.tmpl'
__CHEETAH_srcLastModified__ = 'Thu Aug  5 10:40:19 2010'
__CHEETAH_docstring__ = 'Autogenerated by Cheetah: The Python-Powered Template Engine'

if __CHEETAH_versionTuple__ < RequiredCheetahVersionTuple:
    raise AssertionError(
      'This template was compiled with Cheetah version'
      ' %s. Templates compiled before version %s must be recompiled.'%(
         __CHEETAH_version__, RequiredCheetahVersion))

##################################################
## CLASSES

class fbckmatlabexport(FbckTemplate):

    ##################################################
    ## CHEETAH GENERATED METHODS


    def __init__(self, *args, **KWs):

        super(fbckmatlabexport, self).__init__(*args, **KWs)
        if not self._CHEETAH__instanceInitialized:
            cheetahKWArgs = {}
            allowedKWs = 'searchList namespaces filter filtersLib errorCatcher'.split()
            for k,v in KWs.items():
                if k in allowedKWs: cheetahKWArgs[k] = v
            self._initCheetahInstance(**cheetahKWArgs)
        

    def cell_array(self, strings, **KWS):



        ## CHEETAH: generated from #def cell_array($strings) at line 4, col 1.
        trans = KWS.get("trans")
        if (not trans and not self._CHEETAH__isBuffering and not callable(self.transaction)):
            trans = self.transaction # is None unless self.awake() was called
        if not trans:
            trans = DummyTransaction()
            _dummyTrans = True
        else: _dummyTrans = False
        write = trans.response().write
        SL = self._CHEETAH__searchList
        _filter = self._CHEETAH__currentFilter
        
        ########################################
        ## START - generated method body
        
        strings = [VFN(VFFSL(SL,"s",True),"join",False)(['\'', '\'']) for s in VFFSL(SL,"strings",True)]
        write(u'''{''')
        _v = ';'.join(VFFSL(SL,"strings",True))
        if _v is not None: write(_filter(_v))
        write(u'''}''')
        
        ########################################
        ## END - generated method body
        
        return _dummyTrans and trans.response().getvalue() or ""
        

    def writeBody(self, **KWS):



        ## CHEETAH: main method generated for this template
        trans = KWS.get("trans")
        if (not trans and not self._CHEETAH__isBuffering and not callable(self.transaction)):
            trans = self.transaction # is None unless self.awake() was called
        if not trans:
            trans = DummyTransaction()
            _dummyTrans = True
        else: _dummyTrans = False
        write = trans.response().write
        SL = self._CHEETAH__searchList
        _filter = self._CHEETAH__currentFilter
        
        ########################################
        ## START - generated method body
        
        write(u'''% Setup
''')
        pvs = []
        devnames = []
        # ############## Actuators
        for i in VFFSL(SL,"used_indices",False)('A'): # generated from line 14, col 1
            _v = VFN(VFFSL(SL,"devnames",True),"append",False)(VFFSL(SL,"indexed_var",False)('$A{0}DEVNAME', VFFSL(SL,"i",True))) # u"$devnames.append($indexed_var('$A{0}DEVNAME', $i))" on line 15, col 1
            if _v is not None: write(_filter(_v, rawExpr=u"$devnames.append($indexed_var('$A{0}DEVNAME', $i))")) # from line 15, col 1.
            _v = VFN(VFFSL(SL,"pvs",True),"append",False)(VFFSL(SL,"indexed_var",False)('$A{0}HST_PV', VFFSL(SL,"i",True))) # u"$pvs.append($indexed_var('$A{0}HST_PV', $i))" on line 16, col 1
            if _v is not None: write(_filter(_v, rawExpr=u"$pvs.append($indexed_var('$A{0}HST_PV', $i))")) # from line 16, col 1.
        # ############## States
        for i in VFFSL(SL,"used_indices",False)('S'): # generated from line 19, col 1
            _v = VFN(VFFSL(SL,"devnames",True),"append",False)(VFFSL(SL,"indexed_var",False)('$S{0}NAME', VFFSL(SL,"i",True))) # u"$devnames.append($indexed_var('$S{0}NAME', $i))" on line 20, col 1
            if _v is not None: write(_filter(_v, rawExpr=u"$devnames.append($indexed_var('$S{0}NAME', $i))")) # from line 20, col 1.
            _v = VFN(VFFSL(SL,"pvs",True),"append",False)(VFFSL(SL,"indexed_var",False)('$S{0}HST_PV', VFFSL(SL,"i",True))) # u"$pvs.append($indexed_var('$S{0}HST_PV', $i))" on line 21, col 1
            if _v is not None: write(_filter(_v, rawExpr=u"$pvs.append($indexed_var('$S{0}HST_PV', $i))")) # from line 21, col 1.
            _v = VFN(VFFSL(SL,"devnames",True),"append",False)(VFFSL(SL,"indexed_var",False)('$S{0}NAME', VFFSL(SL,"i",True)) + ' SP') # u"$devnames.append($indexed_var('$S{0}NAME', $i) + ' SP')" on line 22, col 1
            if _v is not None: write(_filter(_v, rawExpr=u"$devnames.append($indexed_var('$S{0}NAME', $i) + ' SP')")) # from line 22, col 1.
            _v = VFN(VFFSL(SL,"pvs",True),"append",False)(VFFSL(SL,"indexed_var",False)('$S{0}DESHST_PV', VFFSL(SL,"i",True))) # u"$pvs.append($indexed_var('$S{0}DESHST_PV', $i))" on line 23, col 1
            if _v is not None: write(_filter(_v, rawExpr=u"$pvs.append($indexed_var('$S{0}DESHST_PV', $i))")) # from line 23, col 1.
        # ############## MEASUREMENTS
        for i in VFFSL(SL,"used_indices",False)('M'): # generated from line 26, col 1
            _v = VFN(VFFSL(SL,"devnames",True),"append",False)(VFFSL(SL,"indexed_var",False)('$M{0}DEVNAME', VFFSL(SL,"i",True))) # u"$devnames.append($indexed_var('$M{0}DEVNAME', $i))" on line 27, col 1
            if _v is not None: write(_filter(_v, rawExpr=u"$devnames.append($indexed_var('$M{0}DEVNAME', $i))")) # from line 27, col 1.
            _v = VFN(VFFSL(SL,"pvs",True),"append",False)(VFFSL(SL,"indexed_var",False)('$M{0}HST_PV', VFFSL(SL,"i",True))) # u"$pvs.append($indexed_var('$M{0}HST_PV', $i))" on line 28, col 1
            if _v is not None: write(_filter(_v, rawExpr=u"$pvs.append($indexed_var('$M{0}HST_PV', $i))")) # from line 28, col 1.
        write(u'''devnames = ''')
        _v = VFFSL(SL,"cell_array",False)(VFFSL(SL,"devnames",True)) # u'$cell_array($devnames)' on line 30, col 12
        if _v is not None: write(_filter(_v, rawExpr=u'$cell_array($devnames)')) # from line 30, col 12.
        write(u''';
pvs = ''')
        _v = VFFSL(SL,"cell_array",False)(VFFSL(SL,"pvs",True)) # u'$cell_array($pvs)' on line 31, col 7
        if _v is not None: write(_filter(_v, rawExpr=u'$cell_array($pvs)')) # from line 31, col 7.
        write(u""";

% Get FBCK data
fbckdata = cell(size(pvs));
for i=1:size(pvs)
    fbckdata{i}.pvname = pvs{i};
    fbckdata{i}.devname = devnames{i};
    [val, ts] = lcaGet(pvs{i});
    fbckdata{i}.waveform = val;
    if exist('epics2matlabTime')
        ts = epics2matlabTime(ts);
    end
    fbckdata{i}.timestamp = ts;
end

varname = 'fbckdata';

% Print FBCK data
celldisp(fbckdata);
whos(varname);

% Print help
path = sprintf('/u1/lcls/matlab/Feedback/fbckdata_%f', now());
path = regexprep(path, '\\.', '_');
help = sprintf('Type e.g. ''save %s %s'' to save %s to %s.mat.', path, varname, varname, path);
disp('--------------------------------------------------------------------------------------');
disp(help);""")
        
        ########################################
        ## END - generated method body
        
        return _dummyTrans and trans.response().getvalue() or ""
        
    ##################################################
    ## CHEETAH GENERATED ATTRIBUTES


    _CHEETAH__instanceInitialized = False

    _CHEETAH_version = __CHEETAH_version__

    _CHEETAH_versionTuple = __CHEETAH_versionTuple__

    _CHEETAH_genTime = __CHEETAH_genTime__

    _CHEETAH_genTimestamp = __CHEETAH_genTimestamp__

    _CHEETAH_src = __CHEETAH_src__

    _CHEETAH_srcLastModified = __CHEETAH_srcLastModified__

    _mainCheetahMethod_for_fbckmatlabexport= 'writeBody'

## END CLASS DEFINITION

if not hasattr(fbckmatlabexport, '_initCheetahAttributes'):
    templateAPIClass = getattr(fbckmatlabexport, '_CHEETAH_templateClass', Template)
    templateAPIClass._addCheetahPlumbingCodeToClass(fbckmatlabexport)


# CHEETAH was developed by Tavis Rudd and Mike Orr
# with code, advice and input from many other volunteers.
# For more information visit http://www.CheetahTemplate.org/

##################################################
## if run from command line:
if __name__ == '__main__':
    from Cheetah.TemplateCmdLineIface import CmdLineIface
    CmdLineIface(templateObj=fbckmatlabexport()).run()


