for action in self.actions():
            if not action.menu():
                continue

            menu = action.menu()
            visible = any(action.isVisible() for action in menu.actions())
            action.setVisible(visible)

import os
import json
import logging
from collections import defaultdict

from .vendor.Qt import QtWidgets, QtCore
from . import action

log = logging.getLogger(__name__)

class ScriptsMenu(QtWidgets.QMenu):
    """A Qt menu that displays a list of searchable actions"""

    updated = QtCore.Signal(QtWidgets.QMenu)

    def __init__(self, *args, **kwargs):
        """Initialize Scripts menu

        Args:
            title (str): the name of the root menu which will be created

            parent (QtWidgets.QObject) : the QObject to parent the menu to

        Returns:
            None

        """
        QtWidgets.QMenu.__init__(self, *args, **kwargs)

        self.searchbar = None
        self.update_action = None

        self._script_actions = []
        self._callbacks = defaultdict(list)

        # Automatically add it to the parent menu
        parent = kwargs.get("parent", None)
        if parent:
            parent.addMenu(self)

        objectname = kwargs.get("objectName", "scripts")
        title = kwargs.get("title", "Scripts")
        self.setObjectName(objectname)
        self.setTitle(title)

        # add default items in the menu
        self.create_default_items()

    def on_update(self):
        self.updated.emit(self)

    @property
    def registered_callbacks(self):
        return self._callbacks.copy()

    def create_default_items(self):
        """Add a search bar to the top of the menu given"""

        # create widget and link function
        searchbar = QtWidgets.QLineEdit()
        searchbar.setFixedWidth(120)
        searchbar.setPlaceholderText("Search ...")
        searchbar.textChanged.connect(self._update_search)
        self.searchbar = searchbar

        # create widget holder
        searchbar_action = QtWidgets.QWidgetAction(self)

        # add widget to widget holder
        searchbar_action.setDefaultWidget(self.searchbar)
        searchbar_action.setObjectName("Searchbar")

        # add update button and link function
        update_action = QtWidgets.QAction(self)
        update_action.setObjectName("Update Scripts")
        update_action.setText("Update Scripts")
        update_action.setVisible(False)
        update_action.triggered.connect(self.on_update)
        self.update_action = update_action

        # add action to menu
        self.addAction(searchbar_action)
        self.addAction(update_action)

        # add separator object
        separator = self.addSeparator()
        separator.setObjectName("separator")

    def add_menu(self, title, parent=None):
        """Create a sub menu for a parent widget

        Args:
            parent(QtWidgets.QWidget): the object to parent the menu to

            title(str): the title of the menu

        Returns:
             QtWidget.QMenu instance
        """

        if not parent:
            parent = self

        menu = QtWidgets.QMenu(parent, title)
        menu.setTitle(title)
        menu.setObjectName(title)
        menu.setTearOffEnabled(True)
        parent.addMenu(menu)

        return menu

    def add_script(self, parent, title, command, sourcetype, icon=None,
                   tags=None, label=None, tooltip=None):
        """Create an action item which runs a script when clicked

        Args:
            parent (QtWidget.QWidget): The widget to parent the item to

            title (str): The text which will be displayed in the menu

            command (str): The command which needs to be run when the item is
                           clicked.

            sourcetype (str): The type of command, the way the command is
                              processed is based on the source type.

            icon (str): The file path of an icon to display with the menu item

            tags (list, tuple): Keywords which describe the action

            label (str): A short description of the script which will be displayed
                         when hovering over the menu item

            tooltip (str): A tip for the user about the usage fo the tool

        Returns:
            QtWidget.QAction instance

        """

        assert tags is None or isinstance(tags, (list, tuple))
        # Ensure tags is a list
        tags = list() if tags is None else list(tags)
        tags.append(title.lower())

        assert icon is None or isinstance(icon, str), (
            "Invalid data type for icon, supported : None, string")

        # create new action
        script_action = action.Action(parent)
        script_action.setText(title)
        script_action.setObjectName(title)
        script_action.tags = tags

        # link action to root for callback library
        script_action.root = self

        # Set up the command
        script_action.sourcetype = sourcetype
        script_action.command = command

        try:
            script_action.process_command()
        except RuntimeError as e:
            raise RuntimeError("Script action can't be "
                               "processed: {}".format(e))

        if icon:
            iconfile = os.path.expandvars(icon)
            script_action.iconfile = iconfile
            script_action_icon = QtWidgets.QIcon(iconfile)
            script_action.setIcon(script_action_icon)

        if label:
            script_action.label = label

        if tooltip:
            script_action.setStatusTip(tooltip)

        script_action.triggered.connect(script_action.run_command)
        parent.addAction(script_action)

        # Add to our searchable actions
        self._script_actions.append(script_action)

        return script_action

    def build_from_configuration(self, parent, configuration):
        """Process the configurations and store the configuration

        This creates all submenus from a configuration.json file.

        When the configuration holds the key `main` all scripts under `main` will
        be added to the main menu first before adding the rest

        Args:
            parent (ScriptsMenu): script menu instance
            configuration (list): A ScriptsMenu configuration list

        Returns:
            None

        """

        for item in configuration:
            assert isinstance(item, dict), "Configuration is wrong!"

            # skip items which have no `type` key
            item_type = item.get('type', None)
            if not item_type:
                log.warning("Missing 'type' from configuration item")
                continue

            # add separator
            # Special behavior for separators
            if item_type == "separator":
                parent.addSeparator()

            # add submenu
            # items should hold a collection of submenu items (dict)
            elif item_type == "menu":
                assert "items" in item, "Menu is missing 'items' key"
                menu = self.add_menu(parent=parent, title=item["title"])
                self.build_from_configuration(menu, item["items"])

            # add script
            elif item_type == "action":
                # filter out `type` from the item dict
                config = {key: value for key, value in
                          item.items() if key != "type"}

                self.add_script(parent=parent, **config)

    def set_update_visible(self, state):
        self.update_action.setVisible(state)

    def clear_menu(self):
        """Clear all menu items which are not default

        Returns:
            None

        """

        # TODO: Set up a more robust implementation for this
        # Delete all except the first three actions
        for _action in self.actions()[3:]:
            self.removeAction(_action)

    def register_callback(self, modifiers, callback):
        self._callbacks[modifiers].append(callback)

    def _update_search(self, search):
        """Hide all the samples which do not match the user's import

        Returns:
            None

        """

        if not search:
            for action in self._script_actions:
                action.setVisible(True)
        else:
            for action in self._script_actions:
                if not action.has_tag(search.lower()):
                    action.setVisible(False)

        # Set visibility for all submenus

def load_configuration(path):
    """Load the configuration from a file

    Read out the JSON file which will dictate the structure of the scripts menu

    Args:
        path (str): file path of the .JSON file

    Returns:
        dict

    """

    if not os.path.isfile(path):
        raise AttributeError("Given configuration is not "
                             "a file!\n'{}'".format(path))

    extension = os.path.splitext(path)[-1]
    if extension != ".json":
        raise AttributeError("Given configuration file has unsupported "
                             "file type, provide a .json file")

    # retrieve and store config
    with open(path, "r") as f:
        configuration = json.load(f)

    return configuration

def application(configuration, parent):
    import sys
    app = QtWidgets.QApplication(sys.argv)

    scriptsmenu = ScriptsMenu(configuration, parent)
    scriptsmenu.show()

    sys.exit(app.exec_())


try:
            script_action.process_command()
        except RuntimeError as e:
            raise RuntimeError("Script action can't be "
                               "processed: {}".format(e))

import os
import json
import logging
from collections import defaultdict

from .vendor.Qt import QtWidgets, QtCore
from . import action

log = logging.getLogger(__name__)

class ScriptsMenu(QtWidgets.QMenu):
    """A Qt menu that displays a list of searchable actions"""

    updated = QtCore.Signal(QtWidgets.QMenu)

    def __init__(self, *args, **kwargs):
        """Initialize Scripts menu

        Args:
            title (str): the name of the root menu which will be created

            parent (QtWidgets.QObject) : the QObject to parent the menu to

        Returns:
            None

        """
        QtWidgets.QMenu.__init__(self, *args, **kwargs)

        self.searchbar = None
        self.update_action = None

        self._script_actions = []
        self._callbacks = defaultdict(list)

        # Automatically add it to the parent menu
        parent = kwargs.get("parent", None)
        if parent:
            parent.addMenu(self)

        objectname = kwargs.get("objectName", "scripts")
        title = kwargs.get("title", "Scripts")
        self.setObjectName(objectname)
        self.setTitle(title)

        # add default items in the menu
        self.create_default_items()

    def on_update(self):
        self.updated.emit(self)

    @property
    def registered_callbacks(self):
        return self._callbacks.copy()

    def create_default_items(self):
        """Add a search bar to the top of the menu given"""

        # create widget and link function
        searchbar = QtWidgets.QLineEdit()
        searchbar.setFixedWidth(120)
        searchbar.setPlaceholderText("Search ...")
        searchbar.textChanged.connect(self._update_search)
        self.searchbar = searchbar

        # create widget holder
        searchbar_action = QtWidgets.QWidgetAction(self)

        # add widget to widget holder
        searchbar_action.setDefaultWidget(self.searchbar)
        searchbar_action.setObjectName("Searchbar")

        # add update button and link function
        update_action = QtWidgets.QAction(self)
        update_action.setObjectName("Update Scripts")
        update_action.setText("Update Scripts")
        update_action.setVisible(False)
        update_action.triggered.connect(self.on_update)
        self.update_action = update_action

        # add action to menu
        self.addAction(searchbar_action)
        self.addAction(update_action)

        # add separator object
        separator = self.addSeparator()
        separator.setObjectName("separator")

    def add_menu(self, title, parent=None):
        """Create a sub menu for a parent widget

        Args:
            parent(QtWidgets.QWidget): the object to parent the menu to

            title(str): the title of the menu

        Returns:
             QtWidget.QMenu instance
        """

        if not parent:
            parent = self

        menu = QtWidgets.QMenu(parent, title)
        menu.setTitle(title)
        menu.setObjectName(title)
        menu.setTearOffEnabled(True)
        parent.addMenu(menu)

        return menu

    def add_script(self, parent, title, command, sourcetype, icon=None,
                   tags=None, label=None, tooltip=None):
        """Create an action item which runs a script when clicked

        Args:
            parent (QtWidget.QWidget): The widget to parent the item to

            title (str): The text which will be displayed in the menu

            command (str): The command which needs to be run when the item is
                           clicked.

            sourcetype (str): The type of command, the way the command is
                              processed is based on the source type.

            icon (str): The file path of an icon to display with the menu item

            tags (list, tuple): Keywords which describe the action

            label (str): A short description of the script which will be displayed
                         when hovering over the menu item

            tooltip (str): A tip for the user about the usage fo the tool

        Returns:
            QtWidget.QAction instance

        """

        assert tags is None or isinstance(tags, (list, tuple))
        # Ensure tags is a list
        tags = list() if tags is None else list(tags)
        tags.append(title.lower())

        assert icon is None or isinstance(icon, str), (
            "Invalid data type for icon, supported : None, string")

        # create new action
        script_action = action.Action(parent)
        script_action.setText(title)
        script_action.setObjectName(title)
        script_action.tags = tags

        # link action to root for callback library
        script_action.root = self

        # Set up the command
        script_action.sourcetype = sourcetype
        script_action.command = command

        if icon:
            iconfile = os.path.expandvars(icon)
            script_action.iconfile = iconfile
            script_action_icon = QtWidgets.QIcon(iconfile)
            script_action.setIcon(script_action_icon)

        if label:
            script_action.label = label

        if tooltip:
            script_action.setStatusTip(tooltip)

        script_action.triggered.connect(script_action.run_command)
        parent.addAction(script_action)

        # Add to our searchable actions
        self._script_actions.append(script_action)

        return script_action

    def build_from_configuration(self, parent, configuration):
        """Process the configurations and store the configuration

        This creates all submenus from a configuration.json file.

        When the configuration holds the key `main` all scripts under `main` will
        be added to the main menu first before adding the rest

        Args:
            parent (ScriptsMenu): script menu instance
            configuration (list): A ScriptsMenu configuration list

        Returns:
            None

        """

        for item in configuration:
            assert isinstance(item, dict), "Configuration is wrong!"

            # skip items which have no `type` key
            item_type = item.get('type', None)
            if not item_type:
                log.warning("Missing 'type' from configuration item")
                continue

            # add separator
            # Special behavior for separators
            if item_type == "separator":
                parent.addSeparator()

            # add submenu
            # items should hold a collection of submenu items (dict)
            elif item_type == "menu":
                assert "items" in item, "Menu is missing 'items' key"
                menu = self.add_menu(parent=parent, title=item["title"])
                self.build_from_configuration(menu, item["items"])

            # add script
            elif item_type == "action":
                # filter out `type` from the item dict
                config = {key: value for key, value in
                          item.items() if key != "type"}

                self.add_script(parent=parent, **config)

    def set_update_visible(self, state):
        self.update_action.setVisible(state)

    def clear_menu(self):
        """Clear all menu items which are not default

        Returns:
            None

        """

        # TODO: Set up a more robust implementation for this
        # Delete all except the first three actions
        for _action in self.actions()[3:]:
            self.removeAction(_action)

    def register_callback(self, modifiers, callback):
        self._callbacks[modifiers].append(callback)

    def _update_search(self, search):
        """Hide all the samples which do not match the user's import

        Returns:
            None

        """

        if not search:
            for action in self._script_actions:
                action.setVisible(True)
        else:
            for action in self._script_actions:
                if not action.has_tag(search.lower()):
                    action.setVisible(False)

        # Set visibility for all submenus
        for action in self.actions():
            if not action.menu():
                continue

            menu = action.menu()
            visible = any(action.isVisible() for action in menu.actions())
            action.setVisible(visible)

def load_configuration(path):
    """Load the configuration from a file

    Read out the JSON file which will dictate the structure of the scripts menu

    Args:
        path (str): file path of the .JSON file

    Returns:
        dict

    """

    if not os.path.isfile(path):
        raise AttributeError("Given configuration is not "
                             "a file!\n'{}'".format(path))

    extension = os.path.splitext(path)[-1]
    if extension != ".json":
        raise AttributeError("Given configuration file has unsupported "
                             "file type, provide a .json file")

    # retrieve and store config
    with open(path, "r") as f:
        configuration = json.load(f)

    return configuration

def application(configuration, parent):
    import sys
    app = QtWidgets.QApplication(sys.argv)

    scriptsmenu = ScriptsMenu(configuration, parent)
    scriptsmenu.show()

    sys.exit(app.exec_())


import re
import sys
import os
import glob
from distutils.dep_util import newer

__all__ = ['needs_g77_abi_wrapper', 'split_fortran_files',
           'get_g77_abi_wrappers',
           'needs_sgemv_fix', 'get_sgemv_fix']

def uses_veclib(info):
    if sys.platform != "darwin":
        return False
    r_accelerate = re.compile("vecLib")
    extra_link_args = info.get('extra_link_args', '')
    for arg in extra_link_args:
        if r_accelerate.search(arg):
            return True
    return False

def uses_accelerate(info):
    if sys.platform != "darwin":
        return False
    r_accelerate = re.compile("Accelerate")
    extra_link_args = info.get('extra_link_args', '')
    for arg in extra_link_args:
        if r_accelerate.search(arg):
            return True
    return False

def uses_mkl(info):
    r_mkl = re.compile("mkl")
    libraries = info.get('libraries', '')
    for library in libraries:
        if r_mkl.search(library):
            return True

    return False

def needs_g77_abi_wrapper(info):
    """Returns True if g77 ABI wrapper must be used."""
    if uses_accelerate(info) or uses_veclib(info):
        return True
    elif uses_mkl(info):
        return True
    else:
        return False

def get_g77_abi_wrappers(info):
    """
    Returns file names of source files containing Fortran ABI wrapper
    routines.
    """
    wrapper_sources = []

    path = os.path.abspath(os.path.dirname(__file__))
    if needs_g77_abi_wrapper(info):
        wrapper_sources += [
            os.path.join(path, 'src', 'wrap_g77_abi_f.f'),
            os.path.join(path, 'src', 'wrap_g77_abi_c.c'),
        ]
        if uses_accelerate(info):
            wrapper_sources += [
                    os.path.join(path, 'src', 'wrap_accelerate_c.c'),
                    os.path.join(path, 'src', 'wrap_accelerate_f.f'),
            ]
        elif uses_mkl(info):
            wrapper_sources += [
                    os.path.join(path, 'src', 'wrap_dummy_accelerate.f'),
            ]
        else:
            raise NotImplementedError("Do not know how to handle LAPACK %s on mac os x" % (info,))
    else:
        wrapper_sources += [
            os.path.join(path, 'src', 'wrap_dummy_g77_abi.f'),
            os.path.join(path, 'src', 'wrap_dummy_accelerate.f'),
        ]
    return wrapper_sources

def needs_sgemv_fix(info):
    """Returns True if SGEMV must be fixed."""
    if uses_accelerate(info):
        return True
    else:
        return False

""" Returns source file needed to correct SGEMV """
    path = os.path.abspath(os.path.dirname(__file__))
    if needs_sgemv_fix(info):
        return [os.path.join(path, 'src', 'apple_sgemv_fix.c')]
    else:
        return []

def split_fortran_files(source_dir, subroutines=None):
    """Split each file in `source_dir` into separate files per subroutine.

    Parameters
    ----------
    source_dir : str
        Full path to directory in which sources to be split are located.
    subroutines : list of str, optional
        Subroutines to split. (Default: all)

    Returns
    -------
    fnames : list of str
        List of file names (not including any path) that were created
        in `source_dir`.

    Notes
    -----
    This function is useful for code that can't be compiled with g77 because of
    type casting errors which do work with gfortran.

    Created files are named: ``original_name + '_subr_i' + '.f'``, with ``i``
    starting at zero and ending at ``num_subroutines_in_file - 1``.

    """

    if subroutines is not None:
        subroutines = [x.lower() for x in subroutines]

    def split_file(fname):
        with open(fname, 'rb') as f:
            lines = f.readlines()
            subs = []
            need_split_next = True

            # find lines with SUBROUTINE statements
            for ix, line in enumerate(lines):
                m = re.match(b'^\\s+subroutine\\s+([a-z0-9_]+)\\s*\\(', line, re.I)
                if m and line[0] not in b'Cc!*':
                    if subroutines is not None:
                        subr_name = m.group(1).decode('ascii').lower()
                        subr_wanted = (subr_name in subroutines)
                    else:
                        subr_wanted = True
                    if subr_wanted or need_split_next:
                        need_split_next = subr_wanted
                        subs.append(ix)

            # check if no split needed
            if len(subs) <= 1:
                return [fname]

            # write out one file per subroutine
            new_fnames = []
            num_files = len(subs)
            for nfile in range(num_files):
                new_fname = fname[:-2] + '_subr_' + str(nfile) + '.f'
                new_fnames.append(new_fname)
                if not newer(fname, new_fname):
                    continue
                with open(new_fname, 'wb') as fn:
                    if nfile + 1 == num_files:
                        fn.writelines(lines[subs[nfile]:])
                    else:
                        fn.writelines(lines[subs[nfile]:subs[nfile+1]])

        return new_fnames

    exclude_pattern = re.compile('_subr_[0-9]')
    source_fnames = [f for f in glob.glob(os.path.join(source_dir, '*.f'))
                             if not exclude_pattern.search(os.path.basename(f))]
    fnames = []
    for source_fname in source_fnames:
        created_files = split_file(source_fname)
        if created_files is not None:
            for cfile in created_files:
                fnames.append(os.path.basename(cfile))

    return fnames


if sys.platform != "darwin":
        return False
    r_accelerate = re.compile("Accelerate")
    extra_link_args = info.get('extra_link_args', '')
    for arg in extra_link_args:
        if r_accelerate.search(arg):
            return True
    return False

import re
import sys
import os
import glob
from distutils.dep_util import newer

__all__ = ['needs_g77_abi_wrapper', 'split_fortran_files',
           'get_g77_abi_wrappers',
           'needs_sgemv_fix', 'get_sgemv_fix']

def uses_veclib(info):
    if sys.platform != "darwin":
        return False
    r_accelerate = re.compile("vecLib")
    extra_link_args = info.get('extra_link_args', '')
    for arg in extra_link_args:
        if r_accelerate.search(arg):
            return True
    return False

def uses_accelerate(info):

def uses_mkl(info):
    r_mkl = re.compile("mkl")
    libraries = info.get('libraries', '')
    for library in libraries:
        if r_mkl.search(library):
            return True

    return False

def needs_g77_abi_wrapper(info):
    """Returns True if g77 ABI wrapper must be used."""
    if uses_accelerate(info) or uses_veclib(info):
        return True
    elif uses_mkl(info):
        return True
    else:
        return False

def get_g77_abi_wrappers(info):
    """
    Returns file names of source files containing Fortran ABI wrapper
    routines.
    """
    wrapper_sources = []

    path = os.path.abspath(os.path.dirname(__file__))
    if needs_g77_abi_wrapper(info):
        wrapper_sources += [
            os.path.join(path, 'src', 'wrap_g77_abi_f.f'),
            os.path.join(path, 'src', 'wrap_g77_abi_c.c'),
        ]
        if uses_accelerate(info):
            wrapper_sources += [
                    os.path.join(path, 'src', 'wrap_accelerate_c.c'),
                    os.path.join(path, 'src', 'wrap_accelerate_f.f'),
            ]
        elif uses_mkl(info):
            wrapper_sources += [
                    os.path.join(path, 'src', 'wrap_dummy_accelerate.f'),
            ]
        else:
            raise NotImplementedError("Do not know how to handle LAPACK %s on mac os x" % (info,))
    else:
        wrapper_sources += [
            os.path.join(path, 'src', 'wrap_dummy_g77_abi.f'),
            os.path.join(path, 'src', 'wrap_dummy_accelerate.f'),
        ]
    return wrapper_sources

def needs_sgemv_fix(info):
    """Returns True if SGEMV must be fixed."""
    if uses_accelerate(info):
        return True
    else:
        return False

def get_sgemv_fix(info):
    """ Returns source file needed to correct SGEMV """
    path = os.path.abspath(os.path.dirname(__file__))
    if needs_sgemv_fix(info):
        return [os.path.join(path, 'src', 'apple_sgemv_fix.c')]
    else:
        return []

def split_fortran_files(source_dir, subroutines=None):
    """Split each file in `source_dir` into separate files per subroutine.

    Parameters
    ----------
    source_dir : str
        Full path to directory in which sources to be split are located.
    subroutines : list of str, optional
        Subroutines to split. (Default: all)

    Returns
    -------
    fnames : list of str
        List of file names (not including any path) that were created
        in `source_dir`.

    Notes
    -----
    This function is useful for code that can't be compiled with g77 because of
    type casting errors which do work with gfortran.

    Created files are named: ``original_name + '_subr_i' + '.f'``, with ``i``
    starting at zero and ending at ``num_subroutines_in_file - 1``.

    """

    if subroutines is not None:
        subroutines = [x.lower() for x in subroutines]

    def split_file(fname):
        with open(fname, 'rb') as f:
            lines = f.readlines()
            subs = []
            need_split_next = True

            # find lines with SUBROUTINE statements
            for ix, line in enumerate(lines):
                m = re.match(b'^\\s+subroutine\\s+([a-z0-9_]+)\\s*\\(', line, re.I)
                if m and line[0] not in b'Cc!*':
                    if subroutines is not None:
                        subr_name = m.group(1).decode('ascii').lower()
                        subr_wanted = (subr_name in subroutines)
                    else:
                        subr_wanted = True
                    if subr_wanted or need_split_next:
                        need_split_next = subr_wanted
                        subs.append(ix)

            # check if no split needed
            if len(subs) <= 1:
                return [fname]

            # write out one file per subroutine
            new_fnames = []
            num_files = len(subs)
            for nfile in range(num_files):
                new_fname = fname[:-2] + '_subr_' + str(nfile) + '.f'
                new_fnames.append(new_fname)
                if not newer(fname, new_fname):
                    continue
                with open(new_fname, 'wb') as fn:
                    if nfile + 1 == num_files:
                        fn.writelines(lines[subs[nfile]:])
                    else:
                        fn.writelines(lines[subs[nfile]:subs[nfile+1]])

        return new_fnames

    exclude_pattern = re.compile('_subr_[0-9]')
    source_fnames = [f for f in glob.glob(os.path.join(source_dir, '*.f'))
                             if not exclude_pattern.search(os.path.basename(f))]
    fnames = []
    for source_fname in source_fnames:
        created_files = split_file(source_fname)
        if created_files is not None:
            for cfile in created_files:
                fnames.append(os.path.basename(cfile))

    return fnames


if sys.platform != "darwin":
        return False
    r_accelerate = re.compile("vecLib")

import re
import sys
import os
import glob
from distutils.dep_util import newer

__all__ = ['needs_g77_abi_wrapper', 'split_fortran_files',
           'get_g77_abi_wrappers',
           'needs_sgemv_fix', 'get_sgemv_fix']

def uses_veclib(info):

    extra_link_args = info.get('extra_link_args', '')
    for arg in extra_link_args:
        if r_accelerate.search(arg):
            return True
    return False

def uses_accelerate(info):
    if sys.platform != "darwin":
        return False
    r_accelerate = re.compile("Accelerate")
    extra_link_args = info.get('extra_link_args', '')
    for arg in extra_link_args:
        if r_accelerate.search(arg):
            return True
    return False

def uses_mkl(info):
    r_mkl = re.compile("mkl")
    libraries = info.get('libraries', '')
    for library in libraries:
        if r_mkl.search(library):
            return True

    return False

def needs_g77_abi_wrapper(info):
    """Returns True if g77 ABI wrapper must be used."""
    if uses_accelerate(info) or uses_veclib(info):
        return True
    elif uses_mkl(info):
        return True
    else:
        return False

def get_g77_abi_wrappers(info):
    """
    Returns file names of source files containing Fortran ABI wrapper
    routines.
    """
    wrapper_sources = []

    path = os.path.abspath(os.path.dirname(__file__))
    if needs_g77_abi_wrapper(info):
        wrapper_sources += [
            os.path.join(path, 'src', 'wrap_g77_abi_f.f'),
            os.path.join(path, 'src', 'wrap_g77_abi_c.c'),
        ]
        if uses_accelerate(info):
            wrapper_sources += [
                    os.path.join(path, 'src', 'wrap_accelerate_c.c'),
                    os.path.join(path, 'src', 'wrap_accelerate_f.f'),
            ]
        elif uses_mkl(info):
            wrapper_sources += [
                    os.path.join(path, 'src', 'wrap_dummy_accelerate.f'),
            ]
        else:
            raise NotImplementedError("Do not know how to handle LAPACK %s on mac os x" % (info,))
    else:
        wrapper_sources += [
            os.path.join(path, 'src', 'wrap_dummy_g77_abi.f'),
            os.path.join(path, 'src', 'wrap_dummy_accelerate.f'),
        ]
    return wrapper_sources

def needs_sgemv_fix(info):
    """Returns True if SGEMV must be fixed."""
    if uses_accelerate(info):
        return True
    else:
        return False

def get_sgemv_fix(info):
    """ Returns source file needed to correct SGEMV """
    path = os.path.abspath(os.path.dirname(__file__))
    if needs_sgemv_fix(info):
        return [os.path.join(path, 'src', 'apple_sgemv_fix.c')]
    else:
        return []

def split_fortran_files(source_dir, subroutines=None):
    """Split each file in `source_dir` into separate files per subroutine.

    Parameters
    ----------
    source_dir : str
        Full path to directory in which sources to be split are located.
    subroutines : list of str, optional
        Subroutines to split. (Default: all)

    Returns
    -------
    fnames : list of str
        List of file names (not including any path) that were created
        in `source_dir`.

    Notes
    -----
    This function is useful for code that can't be compiled with g77 because of
    type casting errors which do work with gfortran.

    Created files are named: ``original_name + '_subr_i' + '.f'``, with ``i``
    starting at zero and ending at ``num_subroutines_in_file - 1``.

    """

    if subroutines is not None:
        subroutines = [x.lower() for x in subroutines]

    def split_file(fname):
        with open(fname, 'rb') as f:
            lines = f.readlines()
            subs = []
            need_split_next = True

            # find lines with SUBROUTINE statements
            for ix, line in enumerate(lines):
                m = re.match(b'^\\s+subroutine\\s+([a-z0-9_]+)\\s*\\(', line, re.I)
                if m and line[0] not in b'Cc!*':
                    if subroutines is not None:
                        subr_name = m.group(1).decode('ascii').lower()
                        subr_wanted = (subr_name in subroutines)
                    else:
                        subr_wanted = True
                    if subr_wanted or need_split_next:
                        need_split_next = subr_wanted
                        subs.append(ix)

            # check if no split needed
            if len(subs) <= 1:
                return [fname]

            # write out one file per subroutine
            new_fnames = []
            num_files = len(subs)
            for nfile in range(num_files):
                new_fname = fname[:-2] + '_subr_' + str(nfile) + '.f'
                new_fnames.append(new_fname)
                if not newer(fname, new_fname):
                    continue
                with open(new_fname, 'wb') as fn:
                    if nfile + 1 == num_files:
                        fn.writelines(lines[subs[nfile]:])
                    else:
                        fn.writelines(lines[subs[nfile]:subs[nfile+1]])

        return new_fnames

    exclude_pattern = re.compile('_subr_[0-9]')
    source_fnames = [f for f in glob.glob(os.path.join(source_dir, '*.f'))
                             if not exclude_pattern.search(os.path.basename(f))]
    fnames = []
    for source_fname in source_fnames:
        created_files = split_file(source_fname)
        if created_files is not None:
            for cfile in created_files:
                fnames.append(os.path.basename(cfile))

    return fnames


import re
import sys
import os
import glob
from distutils.dep_util import newer

__all__ = ['needs_g77_abi_wrapper', 'split_fortran_files',
           'get_g77_abi_wrappers',
           'needs_sgemv_fix', 'get_sgemv_fix']

def uses_veclib(info):
    if sys.platform != "darwin":
        return False
    r_accelerate = re.compile("vecLib")

    for arg in extra_link_args:
        if r_accelerate.search(arg):
            return True
    return False

def uses_accelerate(info):
    if sys.platform != "darwin":
        return False
    r_accelerate = re.compile("Accelerate")
    extra_link_args = info.get('extra_link_args', '')
    for arg in extra_link_args:
        if r_accelerate.search(arg):
            return True
    return False

def uses_mkl(info):
    r_mkl = re.compile("mkl")
    libraries = info.get('libraries', '')
    for library in libraries:
        if r_mkl.search(library):
            return True

    return False

def needs_g77_abi_wrapper(info):
    """Returns True if g77 ABI wrapper must be used."""
    if uses_accelerate(info) or uses_veclib(info):
        return True
    elif uses_mkl(info):
        return True
    else:
        return False

def get_g77_abi_wrappers(info):
    """
    Returns file names of source files containing Fortran ABI wrapper
    routines.
    """
    wrapper_sources = []

    path = os.path.abspath(os.path.dirname(__file__))
    if needs_g77_abi_wrapper(info):
        wrapper_sources += [
            os.path.join(path, 'src', 'wrap_g77_abi_f.f'),
            os.path.join(path, 'src', 'wrap_g77_abi_c.c'),
        ]
        if uses_accelerate(info):
            wrapper_sources += [
                    os.path.join(path, 'src', 'wrap_accelerate_c.c'),
                    os.path.join(path, 'src', 'wrap_accelerate_f.f'),
            ]
        elif uses_mkl(info):
            wrapper_sources += [
                    os.path.join(path, 'src', 'wrap_dummy_accelerate.f'),
            ]
        else:
            raise NotImplementedError("Do not know how to handle LAPACK %s on mac os x" % (info,))
    else:
        wrapper_sources += [
            os.path.join(path, 'src', 'wrap_dummy_g77_abi.f'),
            os.path.join(path, 'src', 'wrap_dummy_accelerate.f'),
        ]
    return wrapper_sources

def needs_sgemv_fix(info):
    """Returns True if SGEMV must be fixed."""
    if uses_accelerate(info):
        return True
    else:
        return False

def get_sgemv_fix(info):
    """ Returns source file needed to correct SGEMV """
    path = os.path.abspath(os.path.dirname(__file__))
    if needs_sgemv_fix(info):
        return [os.path.join(path, 'src', 'apple_sgemv_fix.c')]
    else:
        return []

def split_fortran_files(source_dir, subroutines=None):
    """Split each file in `source_dir` into separate files per subroutine.

    Parameters
    ----------
    source_dir : str
        Full path to directory in which sources to be split are located.
    subroutines : list of str, optional
        Subroutines to split. (Default: all)

    Returns
    -------
    fnames : list of str
        List of file names (not including any path) that were created
        in `source_dir`.

    Notes
    -----
    This function is useful for code that can't be compiled with g77 because of
    type casting errors which do work with gfortran.

    Created files are named: ``original_name + '_subr_i' + '.f'``, with ``i``
    starting at zero and ending at ``num_subroutines_in_file - 1``.

    """

    if subroutines is not None:
        subroutines = [x.lower() for x in subroutines]

    def split_file(fname):
        with open(fname, 'rb') as f:
            lines = f.readlines()
            subs = []
            need_split_next = True

            # find lines with SUBROUTINE statements
            for ix, line in enumerate(lines):
                m = re.match(b'^\\s+subroutine\\s+([a-z0-9_]+)\\s*\\(', line, re.I)
                if m and line[0] not in b'Cc!*':
                    if subroutines is not None:
                        subr_name = m.group(1).decode('ascii').lower()
                        subr_wanted = (subr_name in subroutines)
                    else:
                        subr_wanted = True
                    if subr_wanted or need_split_next:
                        need_split_next = subr_wanted
                        subs.append(ix)

            # check if no split needed
            if len(subs) <= 1:
                return [fname]

            # write out one file per subroutine
            new_fnames = []
            num_files = len(subs)
            for nfile in range(num_files):
                new_fname = fname[:-2] + '_subr_' + str(nfile) + '.f'
                new_fnames.append(new_fname)
                if not newer(fname, new_fname):
                    continue
                with open(new_fname, 'wb') as fn:
                    if nfile + 1 == num_files:
                        fn.writelines(lines[subs[nfile]:])
                    else:
                        fn.writelines(lines[subs[nfile]:subs[nfile+1]])

        return new_fnames

    exclude_pattern = re.compile('_subr_[0-9]')
    source_fnames = [f for f in glob.glob(os.path.join(source_dir, '*.f'))
                             if not exclude_pattern.search(os.path.basename(f))]
    fnames = []
    for source_fname in source_fnames:
        created_files = split_file(source_fname)
        if created_files is not None:
            for cfile in created_files:
                fnames.append(os.path.basename(cfile))

    return fnames


import re
import sys
import os
import glob
from distutils.dep_util import newer

__all__ = ['needs_g77_abi_wrapper', 'split_fortran_files',
           'get_g77_abi_wrappers',
           'needs_sgemv_fix', 'get_sgemv_fix']

def uses_veclib(info):
    if sys.platform != "darwin":
        return False
    r_accelerate = re.compile("vecLib")
    extra_link_args = info.get('extra_link_args', '')

def uses_accelerate(info):
    if sys.platform != "darwin":
        return False
    r_accelerate = re.compile("Accelerate")
    extra_link_args = info.get('extra_link_args', '')
    for arg in extra_link_args:
        if r_accelerate.search(arg):
            return True
    return False

def uses_mkl(info):
    r_mkl = re.compile("mkl")
    libraries = info.get('libraries', '')
    for library in libraries:
        if r_mkl.search(library):
            return True

    return False

def needs_g77_abi_wrapper(info):
    """Returns True if g77 ABI wrapper must be used."""
    if uses_accelerate(info) or uses_veclib(info):
        return True
    elif uses_mkl(info):
        return True
    else:
        return False

def get_g77_abi_wrappers(info):
    """
    Returns file names of source files containing Fortran ABI wrapper
    routines.
    """
    wrapper_sources = []

    path = os.path.abspath(os.path.dirname(__file__))
    if needs_g77_abi_wrapper(info):
        wrapper_sources += [
            os.path.join(path, 'src', 'wrap_g77_abi_f.f'),
            os.path.join(path, 'src', 'wrap_g77_abi_c.c'),
        ]
        if uses_accelerate(info):
            wrapper_sources += [
                    os.path.join(path, 'src', 'wrap_accelerate_c.c'),
                    os.path.join(path, 'src', 'wrap_accelerate_f.f'),
            ]
        elif uses_mkl(info):
            wrapper_sources += [
                    os.path.join(path, 'src', 'wrap_dummy_accelerate.f'),
            ]
        else:
            raise NotImplementedError("Do not know how to handle LAPACK %s on mac os x" % (info,))
    else:
        wrapper_sources += [
            os.path.join(path, 'src', 'wrap_dummy_g77_abi.f'),
            os.path.join(path, 'src', 'wrap_dummy_accelerate.f'),
        ]
    return wrapper_sources

def needs_sgemv_fix(info):
    """Returns True if SGEMV must be fixed."""
    if uses_accelerate(info):
        return True
    else:
        return False

def get_sgemv_fix(info):
    """ Returns source file needed to correct SGEMV """
    path = os.path.abspath(os.path.dirname(__file__))
    if needs_sgemv_fix(info):
        return [os.path.join(path, 'src', 'apple_sgemv_fix.c')]
    else:
        return []

def split_fortran_files(source_dir, subroutines=None):
    """Split each file in `source_dir` into separate files per subroutine.

    Parameters
    ----------
    source_dir : str
        Full path to directory in which sources to be split are located.
    subroutines : list of str, optional
        Subroutines to split. (Default: all)

    Returns
    -------
    fnames : list of str
        List of file names (not including any path) that were created
        in `source_dir`.

    Notes
    -----
    This function is useful for code that can't be compiled with g77 because of
    type casting errors which do work with gfortran.

    Created files are named: ``original_name + '_subr_i' + '.f'``, with ``i``
    starting at zero and ending at ``num_subroutines_in_file - 1``.

    """

    if subroutines is not None:
        subroutines = [x.lower() for x in subroutines]

    def split_file(fname):
        with open(fname, 'rb') as f:
            lines = f.readlines()
            subs = []
            need_split_next = True

            # find lines with SUBROUTINE statements
            for ix, line in enumerate(lines):
                m = re.match(b'^\\s+subroutine\\s+([a-z0-9_]+)\\s*\\(', line, re.I)
                if m and line[0] not in b'Cc!*':
                    if subroutines is not None:
                        subr_name = m.group(1).decode('ascii').lower()
                        subr_wanted = (subr_name in subroutines)
                    else:
                        subr_wanted = True
                    if subr_wanted or need_split_next:
                        need_split_next = subr_wanted
                        subs.append(ix)

            # check if no split needed
            if len(subs) <= 1:
                return [fname]

            # write out one file per subroutine
            new_fnames = []
            num_files = len(subs)
            for nfile in range(num_files):
                new_fname = fname[:-2] + '_subr_' + str(nfile) + '.f'
                new_fnames.append(new_fname)
                if not newer(fname, new_fname):
                    continue
                with open(new_fname, 'wb') as fn:
                    if nfile + 1 == num_files:
                        fn.writelines(lines[subs[nfile]:])
                    else:
                        fn.writelines(lines[subs[nfile]:subs[nfile+1]])

        return new_fnames

    exclude_pattern = re.compile('_subr_[0-9]')
    source_fnames = [f for f in glob.glob(os.path.join(source_dir, '*.f'))
                             if not exclude_pattern.search(os.path.basename(f))]
    fnames = []
    for source_fname in source_fnames:
        created_files = split_file(source_fname)
        if created_files is not None:
            for cfile in created_files:
                fnames.append(os.path.basename(cfile))

    return fnames


import re
import sys
import os
import glob
from distutils.dep_util import newer

__all__ = ['needs_g77_abi_wrapper', 'split_fortran_files',
           'get_g77_abi_wrappers',
           'needs_sgemv_fix', 'get_sgemv_fix']

def uses_veclib(info):
    if sys.platform != "darwin":
        return False
    r_accelerate = re.compile("vecLib")
    extra_link_args = info.get('extra_link_args', '')
    for arg in extra_link_args:
        if r_accelerate.search(arg):
            return True
    return False

def uses_accelerate(info):
    if sys.platform != "darwin":
        return False
    r_accelerate = re.compile("Accelerate")
    extra_link_args = info.get('extra_link_args', '')
    for arg in extra_link_args:
        if r_accelerate.search(arg):
            return True
    return False

def uses_mkl(info):
    r_mkl = re.compile("mkl")
    libraries = info.get('libraries', '')
    for library in libraries:
        if r_mkl.search(library):
            return True

    return False

def needs_g77_abi_wrapper(info):
    """Returns True if g77 ABI wrapper must be used."""
    if uses_accelerate(info) or uses_veclib(info):
        return True
    elif uses_mkl(info):
        return True
    else:
        return False

def get_g77_abi_wrappers(info):
    """
    Returns file names of source files containing Fortran ABI wrapper
    routines.
    """
    wrapper_sources = []

    path = os.path.abspath(os.path.dirname(__file__))
    if needs_g77_abi_wrapper(info):
        wrapper_sources += [
            os.path.join(path, 'src', 'wrap_g77_abi_f.f'),
            os.path.join(path, 'src', 'wrap_g77_abi_c.c'),
        ]
        if uses_accelerate(info):
            wrapper_sources += [
                    os.path.join(path, 'src', 'wrap_accelerate_c.c'),
                    os.path.join(path, 'src', 'wrap_accelerate_f.f'),
            ]
        elif uses_mkl(info):
            wrapper_sources += [
                    os.path.join(path, 'src', 'wrap_dummy_accelerate.f'),
            ]
        else:
            raise NotImplementedError("Do not know how to handle LAPACK %s on mac os x" % (info,))
    else:
        wrapper_sources += [
            os.path.join(path, 'src', 'wrap_dummy_g77_abi.f'),
            os.path.join(path, 'src', 'wrap_dummy_accelerate.f'),
        ]
    return wrapper_sources

def needs_sgemv_fix(info):
    """Returns True if SGEMV must be fixed."""
    if uses_accelerate(info):
        return True
    else:
        return False

def get_sgemv_fix(info):
    """ Returns source file needed to correct SGEMV """
    path = os.path.abspath(os.path.dirname(__file__))
    if needs_sgemv_fix(info):
        return [os.path.join(path, 'src', 'apple_sgemv_fix.c')]
    else:
        return []

def split_fortran_files(source_dir, subroutines=None):
    """Split each file in `source_dir` into separate files per subroutine.

    Parameters
    ----------
    source_dir : str
        Full path to directory in which sources to be split are located.
    subroutines : list of str, optional
        Subroutines to split. (Default: all)

    Returns
    -------
    fnames : list of str
        List of file names (not including any path) that were created
        in `source_dir`.

    Notes
    -----
    This function is useful for code that can't be compiled with g77 because of
    type casting errors which do work with gfortran.

    Created files are named: ``original_name + '_subr_i' + '.f'``, with ``i``
    starting at zero and ending at ``num_subroutines_in_file - 1``.

    """

    if subroutines is not None:
        subroutines = [x.lower() for x in subroutines]

    def split_file(fname):
        with open(fname, 'rb') as f:
            lines = f.readlines()
            subs = []
            need_split_next = True

            # find lines with SUBROUTINE statements
            for ix, line in enumerate(lines):
                m = re.match(b'^\\s+subroutine\\s+([a-z0-9_]+)\\s*\\(', line, re.I)
                if m and line[0] not in b'Cc!*':
                    if subroutines is not None:
                        subr_name = m.group(1).decode('ascii').lower()
                        subr_wanted = (subr_name in subroutines)
                    else:
                        subr_wanted = True
                    if subr_wanted or need_split_next:
                        need_split_next = subr_wanted
                        subs.append(ix)

            # check if no split needed
            if len(subs) <= 1:
                return [fname]

            # write out one file per subroutine
            new_fnames = []
            num_files = len(subs)
            for nfile in range(num_files):
                new_fname = fname[:-2] + '_subr_' + str(nfile) + '.f'
                new_fnames.append(new_fname)
                if not newer(fname, new_fname):
                    continue
                with open(new_fname, 'wb') as fn:
                    if nfile + 1 == num_files:
                        fn.writelines(lines[subs[nfile]:])
                    else:
                        fn.writelines(lines[subs[nfile]:subs[nfile+1]])

        return new_fnames

    exclude_

    source_fnames = [f for f in glob.glob(os.path.join(source_dir, '*.f'))
                             if not exclude_pattern.search(os.path.basename(f))]
    fnames = []
    for source_fname in source_fnames:
        created_files = split_file(source_fname)
        if created_files is not None:
            for cfile in created_files:
                fnames.append(os.path.basename(cfile))

    return fnames


    if uses_accelerate(info) or uses_veclib(info):
        return True
    elif uses_mkl(info):
        return True
    else:
        return False

import re
import sys
import os
import glob
from distutils.dep_util import newer

__all__ = ['needs_g77_abi_wrapper', 'split_fortran_files',
           'get_g77_abi_wrappers',
           'needs_sgemv_fix', 'get_sgemv_fix']

def uses_veclib(info):
    if sys.platform != "darwin":
        return False
    r_accelerate = re.compile("vecLib")
    extra_link_args = info.get('extra_link_args', '')
    for arg in extra_link_args:
        if r_accelerate.search(arg):
            return True
    return False

def uses_accelerate(info):
    if sys.platform != "darwin":
        return False
    r_accelerate = re.compile("Accelerate")
    extra_link_args = info.get('extra_link_args', '')
    for arg in extra_link_args:
        if r_accelerate.search(arg):
            return True
    return False

def uses_mkl(info):
    r_mkl = re.compile("mkl")
    libraries = info.get('libraries', '')
    for library in libraries:
        if r_mkl.search(library):
            return True

    return False

def needs_g77_abi_wrapper(info):
    """Returns True if g77 ABI wrapper must be used."""

def get_g77_abi_wrappers(info):
    """
    Returns file names of source files containing Fortran ABI wrapper
    routines.
    """
    wrapper_sources = []

    path = os.path.abspath(os.path.dirname(__file__))
    if needs_g77_abi_wrapper(info):
        wrapper_sources += [
            os.path.join(path, 'src', 'wrap_g77_abi_f.f'),
            os.path.join(path, 'src', 'wrap_g77_abi_c.c'),
        ]
        if uses_accelerate(info):
            wrapper_sources += [
                    os.path.join(path, 'src', 'wrap_accelerate_c.c'),
                    os.path.join(path, 'src', 'wrap_accelerate_f.f'),
            ]
        elif uses_mkl(info):
            wrapper_sources += [
                    os.path.join(path, 'src', 'wrap_dummy_accelerate.f'),
            ]
        else:
            raise NotImplementedError("Do not know how to handle LAPACK %s on mac os x" % (info,))
    else:
        wrapper_sources += [
            os.path.join(path, 'src', 'wrap_dummy_g77_abi.f'),
            os.path.join(path, 'src', 'wrap_dummy_accelerate.f'),
        ]
    return wrapper_sources

def needs_sgemv_fix(info):
    """Returns True if SGEMV must be fixed."""
    if uses_accelerate(info):
        return True
    else:
        return False

def get_sgemv_fix(info):
    """ Returns source file needed to correct SGEMV """
    path = os.path.abspath(os.path.dirname(__file__))
    if needs_sgemv_fix(info):
        return [os.path.join(path, 'src', 'apple_sgemv_fix.c')]
    else:
        return []

def split_fortran_files(source_dir, subroutines=None):
    """Split each file in `source_dir` into separate files per subroutine.

    Parameters
    ----------
    source_dir : str
        Full path to directory in which sources to be split are located.
    subroutines : list of str, optional
        Subroutines to split. (Default: all)

    Returns
    -------
    fnames : list of str
        List of file names (not including any path) that were created
        in `source_dir`.

    Notes
    -----
    This function is useful for code that can't be compiled with g77 because of
    type casting errors which do work with gfortran.

    Created files are named: ``original_name + '_subr_i' + '.f'``, with ``i``
    starting at zero and ending at ``num_subroutines_in_file - 1``.

    """

    if subroutines is not None:
        subroutines = [x.lower() for x in subroutines]

    def split_file(fname):
        with open(fname, 'rb') as f:
            lines = f.readlines()
            subs = []
            need_split_next = True

            # find lines with SUBROUTINE statements
            for ix, line in enumerate(lines):
                m = re.match(b'^\\s+subroutine\\s+([a-z0-9_]+)\\s*\\(', line, re.I)
                if m and line[0] not in b'Cc!*':
                    if subroutines is not None:
                        subr_name = m.group(1).decode('ascii').lower()
                        subr_wanted = (subr_name in subroutines)
                    else:
                        subr_wanted = True
                    if subr_wanted or need_split_next:
                        need_split_next = subr_wanted
                        subs.append(ix)

            # check if no split needed
            if len(subs) <= 1:
                return [fname]

            # write out one file per subroutine
            new_fnames = []
            num_files = len(subs)
            for nfile in range(num_files):
                new_fname = fname[:-2] + '_subr_' + str(nfile) + '.f'
                new_fnames.append(new_fname)
                if not newer(fname, new_fname):
                    continue
                with open(new_fname, 'wb') as fn:
                    if nfile + 1 == num_files:
                        fn.writelines(lines[subs[nfile]:])
                    else:
                        fn.writelines(lines[subs[nfile]:subs[nfile+1]])

        return new_fnames

    exclude_pattern = re.compile('_subr_[0-9]')
    source_fnames = [f for f in glob.glob(os.path.join(source_dir, '*.f'))
                             if not exclude_pattern.search(os.path.basename(f))]
    fnames = []
    for source_fname in source_fnames:
        created_files = split_file(source_fname)
        if created_files is not None:
            for cfile in created_files:
                fnames.append(os.path.basename(cfile))

    return fnames


if subr_wanted or need_split_next:
                        need_split_next = subr_wanted
                        subs.append(ix)

import re
import sys
import os
import glob
from distutils.dep_util import newer

__all__ = ['needs_g77_abi_wrapper', 'split_fortran_files',
           'get_g77_abi_wrappers',
           'needs_sgemv_fix', 'get_sgemv_fix']

def uses_veclib(info):
    if sys.platform != "darwin":
        return False
    r_accelerate = re.compile("vecLib")
    extra_link_args = info.get('extra_link_args', '')
    for arg in extra_link_args:
        if r_accelerate.search(arg):
            return True
    return False

def uses_accelerate(info):
    if sys.platform != "darwin":
        return False
    r_accelerate = re.compile("Accelerate")
    extra_link_args = info.get('extra_link_args', '')
    for arg in extra_link_args:
        if r_accelerate.search(arg):
            return True
    return False

def uses_mkl(info):
    r_mkl = re.compile("mkl")
    libraries = info.get('libraries', '')
    for library in libraries:
        if r_mkl.search(library):
            return True

    return False

def needs_g77_abi_wrapper(info):
    """Returns True if g77 ABI wrapper must be used."""
    if uses_accelerate(info) or uses_veclib(info):
        return True
    elif uses_mkl(info):
        return True
    else:
        return False

def get_g77_abi_wrappers(info):
    """
    Returns file names of source files containing Fortran ABI wrapper
    routines.
    """
    wrapper_sources = []

    path = os.path.abspath(os.path.dirname(__file__))
    if needs_g77_abi_wrapper(info):
        wrapper_sources += [
            os.path.join(path, 'src', 'wrap_g77_abi_f.f'),
            os.path.join(path, 'src', 'wrap_g77_abi_c.c'),
        ]
        if uses_accelerate(info):
            wrapper_sources += [
                    os.path.join(path, 'src', 'wrap_accelerate_c.c'),
                    os.path.join(path, 'src', 'wrap_accelerate_f.f'),
            ]
        elif uses_mkl(info):
            wrapper_sources += [
                    os.path.join(path, 'src', 'wrap_dummy_accelerate.f'),
            ]
        else:
            raise NotImplementedError("Do not know how to handle LAPACK %s on mac os x" % (info,))
    else:
        wrapper_sources += [
            os.path.join(path, 'src', 'wrap_dummy_g77_abi.f'),
            os.path.join(path, 'src', 'wrap_dummy_accelerate.f'),
        ]
    return wrapper_sources

def needs_sgemv_fix(info):
    """Returns True if SGEMV must be fixed."""
    if uses_accelerate(info):
        return True
    else:
        return False

def get_sgemv_fix(info):
    """ Returns source file needed to correct SGEMV """
    path = os.path.abspath(os.path.dirname(__file__))
    if needs_sgemv_fix(info):
        return [os.path.join(path, 'src', 'apple_sgemv_fix.c')]
    else:
        return []

def split_fortran_files(source_dir, subroutines=None):
    """Split each file in `source_dir` into separate files per subroutine.

    Parameters
    ----------
    source_dir : str
        Full path to directory in which sources to be split are located.
    subroutines : list of str, optional
        Subroutines to split. (Default: all)

    Returns
    -------
    fnames : list of str
        List of file names (not including any path) that were created
        in `source_dir`.

    Notes
    -----
    This function is useful for code that can't be compiled with g77 because of
    type casting errors which do work with gfortran.

    Created files are named: ``original_name + '_subr_i' + '.f'``, with ``i``
    starting at zero and ending at ``num_subroutines_in_file - 1``.

    """

    if subroutines is not None:
        subroutines = [x.lower() for x in subroutines]

    def split_file(fname):
        with open(fname, 'rb') as f:
            lines = f.readlines()
            subs = []
            need_split_next = True

            # find lines with SUBROUTINE statements
            for ix, line in enumerate(lines):
                m = re.match(b'^\\s+subroutine\\s+([a-z0-9_]+)\\s*\\(', line, re.I)
                if m and line[0] not in b'Cc!*':
                    if subroutines is not None:
                        subr_name = m.group(1).decode('ascii').lower()
                        subr_wanted = (subr_name in subroutines)
                    else:
                        subr_wanted = True

            # check if no split needed
            if len(subs) <= 1:
                return [fname]

            # write out one file per subroutine
            new_fnames = []
            num_files = len(subs)
            for nfile in range(num_files):
                new_fname = fname[:-2] + '_subr_' + str(nfile) + '.f'
                new_fnames.append(new_fname)
                if not newer(fname, new_fname):
                    continue
                with open(new_fname, 'wb') as fn:
                    if nfile + 1 == num_files:
                        fn.writelines(lines[subs[nfile]:])
                    else:
                        fn.writelines(lines[subs[nfile]:subs[nfile+1]])

        return new_fnames

    exclude_pattern = re.compile('_subr_[0-9]')
    source_fnames = [f for f in glob.glob(os.path.join(source_dir, '*.f'))
                             if not exclude_pattern.search(os.path.basename(f))]
    fnames = []
    for source_fname in source_fnames:
        created_files = split_file(source_fname)
        if created_files is not None:
            for cfile in created_files:
                fnames.append(os.path.basename(cfile))

    return fnames


import re
import sys
import os
import glob
from distutils.dep_util import newer

__all__ = ['needs_g77_abi_wrapper', 'split_fortran_files',
           'get_g77_abi_wrappers',
           'needs_sgemv_fix', 'get_sgemv_fix']

def uses_veclib(info):
    if sys.platform != "darwin":
        return False
    r_accelerate = re.compile("vecLib")
    extra_link_args = info.get('extra_link_args', '')
    for arg in extra_link_args:
        if r_accelerate.search(arg):
            return True
    return False

def uses_accelerate(info):
    if sys.platform != "darwin":
        return False
    r_accelerate = re.compile("Accelerate")
    extra_link_args = info.get('extra_link_args', '')

    return False

def uses_mkl(info):
    r_mkl = re.compile("mkl")
    libraries = info.get('libraries', '')
    for library in libraries:
        if r_mkl.search(library):
            return True

    return False

def needs_g77_abi_wrapper(info):
    """Returns True if g77 ABI wrapper must be used."""
    if uses_accelerate(info) or uses_veclib(info):
        return True
    elif uses_mkl(info):
        return True
    else:
        return False

def get_g77_abi_wrappers(info):
    """
    Returns file names of source files containing Fortran ABI wrapper
    routines.
    """
    wrapper_sources = []

    path = os.path.abspath(os.path.dirname(__file__))
    if needs_g77_abi_wrapper(info):
        wrapper_sources += [
            os.path.join(path, 'src', 'wrap_g77_abi_f.f'),
            os.path.join(path, 'src', 'wrap_g77_abi_c.c'),
        ]
        if uses_accelerate(info):
            wrapper_sources += [
                    os.path.join(path, 'src', 'wrap_accelerate_c.c'),
                    os.path.join(path, 'src', 'wrap_accelerate_f.f'),
            ]
        elif uses_mkl(info):
            wrapper_sources += [
                    os.path.join(path, 'src', 'wrap_dummy_accelerate.f'),
            ]
        else:
            raise NotImplementedError("Do not know how to handle LAPACK %s on mac os x" % (info,))
    else:
        wrapper_sources += [
            os.path.join(path, 'src', 'wrap_dummy_g77_abi.f'),
            os.path.join(path, 'src', 'wrap_dummy_accelerate.f'),
        ]
    return wrapper_sources

def needs_sgemv_fix(info):
    """Returns True if SGEMV must be fixed."""
    if uses_accelerate(info):
        return True
    else:
        return False

def get_sgemv_fix(info):
    """ Returns source file needed to correct SGEMV """
    path = os.path.abspath(os.path.dirname(__file__))
    if needs_sgemv_fix(info):
        return [os.path.join(path, 'src', 'apple_sgemv_fix.c')]
    else:
        return []

def split_fortran_files(source_dir, subroutines=None):
    """Split each file in `source_dir` into separate files per subroutine.

    Parameters
    ----------
    source_dir : str
        Full path to directory in which sources to be split are located.
    subroutines : list of str, optional
        Subroutines to split. (Default: all)

    Returns
    -------
    fnames : list of str
        List of file names (not including any path) that were created
        in `source_dir`.

    Notes
    -----
    This function is useful for code that can't be compiled with g77 because of
    type casting errors which do work with gfortran.

    Created files are named: ``original_name + '_subr_i' + '.f'``, with ``i``
    starting at zero and ending at ``num_subroutines_in_file - 1``.

    """

    if subroutines is not None:
        subroutines = [x.lower() for x in subroutines]

    def split_file(fname):
        with open(fname, 'rb') as f:
            lines = f.readlines()
            subs = []
            need_split_next = True

            # find lines with SUBROUTINE statements
            for ix, line in enumerate(lines):
                m = re.match(b'^\\s+subroutine\\s+([a-z0-9_]+)\\s*\\(', line, re.I)
                if m and line[0] not in b'Cc!*':
                    if subroutines is not None:
                        subr_name = m.group(1).decode('ascii').lower()
                        subr_wanted = (subr_name in subroutines)
                    else:
                        subr_wanted = True
                    if subr_wanted or need_split_next:
                        need_split_next = subr_wanted
                        subs.append(ix)

            # check if no split needed
            if len(subs) <= 1:
                return [fname]

            # write out one file per subroutine
            new_fnames = []
            num_files = len(subs)
            for nfile in range(num_files):
                new_fname = fname[:-2] + '_subr_' + str(nfile) + '.f'
                new_fnames.append(new_fname)
                if not newer(fname, new_fname):
                    continue
                with open(new_fname, 'wb') as fn:
                    if nfile + 1 == num_files:
                        fn.writelines(lines[subs[nfile]:])
                    else:
                        fn.writelines(lines[subs[nfile]:subs[nfile+1]])

        return new_fnames

    exclude_pattern = re.compile('_subr_[0-9]')
    source_fnames = [f for f in glob.glob(os.path.join(source_dir, '*.f'))
                             if not exclude_pattern.search(os.path.basename(f))]
    fnames = []
    for source_fname in source_fnames:
        created_files = split_file(source_fname)
        if created_files is not None:
            for cfile in created_files:
                fnames.append(os.path.basename(cfile))

    return fnames


def oneVsAll(X, y, num_labels, the_lambda):

from numpy import shape, hstack, matrix
from numpy import ones, zeros
from scipy.optimize import fmin_bfgs
from lrCostFunction import lrCostFunction
from gradientDescent import lrGD

m, n = shape(X)
    all_theta = matrix(zeros((num_labels, n+1)))
    X = hstack((ones((m, 1)), X))
    for c in range(num_labels):
        print 'Training for %d/34' % (c+1)
        initial_theta = zeros((n+1, 1))
        args = (X, (y == c), the_lambda)
        theta = fmin_bfgs(lrCostFunction, initial_theta, fprime=lrGD, args=args, maxiter=50)
        all_theta[c, :] = theta.transpose()

    return all_theta


m, n = shape(X)
    all_theta = matrix(zeros((num_labels, n+1)))
    X = hstack((ones((m, 1)), X))
    for c in range(num_labels):
        print 'Training for %d/34' % (c+1)
        initial_theta = zeros((n+1, 1))
        args = (X, (y == c), the_lambda)
        theta = fmin_bfgs(lrCostFunction, initial_theta, fprime=lrGD, args=args, maxiter=50)
        all_theta[c, :] = theta.transpose()

    return all_theta

from numpy import shape, hstack, matrix
from numpy import ones, zeros
from scipy.optimize import fmin_bfgs
from lrCostFunction import lrCostFunction
from gradientDescent import lrGD

def oneVsAll(X, y, num_labels, the_lambda):


m, n = shape(X)
    all_theta = matrix(zeros((num_labels, n+1)))

    X = hstack((ones((m, 1)), X))
    for c in range(num_labels):
        print 'Training for %d/34' % (c+1)
        initial_theta = zeros((n+1, 1))
        args = (X, (y == c), the_lambda)
        theta = fmin_bfgs(lrCostFunction, initial_theta, fprime=lrGD, args=args, maxiter=50)
        all_theta[c, :] = theta.transpose()

    return all_theta


from numpy import shape, hstack, matrix
from numpy import ones, zeros
from scipy.optimize import fmin_bfgs
from lrCostFunction import lrCostFunction
from gradientDescent import lrGD

def oneVsAll(X, y, num_labels, the_lambda):
    m, n = shape(X)
    all_theta = matrix(zeros((num_labels, n+1)))

    for c in range(num_labels):
        print 'Training for %d/34' % (c+1)
        initial_theta = zeros((n+1, 1))
        args = (X, (y == c), the_lambda)
        theta = fmin_bfgs(lrCostFunction, initial_theta, fprime=lrGD, args=args, maxiter=50)
        all_theta[c, :] = theta.transpose()

    return all_theta


for c in range(num_labels):
        print 'Training for %d/34' % (c+1)
        initial_theta = zeros((n+1, 1))
        args = (X, (y == c), the_lambda)
        theta = fmin_bfgs(lrCostFunction, initial_theta, fprime=lrGD, args=args, maxiter=50)
        all_theta[c, :] = theta.transpose()

    return all_theta

from numpy import shape, hstack, matrix
from numpy import ones, zeros
from scipy.optimize import fmin_bfgs
from lrCostFunction import lrCostFunction
from gradientDescent import lrGD

def oneVsAll(X, y, num_labels, the_lambda):
    m, n = shape(X)
    all_theta = matrix(zeros((num_labels, n+1)))
    X = hstack((ones((m, 1)), X))


from numpy import shape, hstack, matrix
from numpy import ones, zeros
from scipy.optimize import fmin_bfgs
from lrCostFunction import lrCostFunction
from gradientDescent import lrGD

def oneVsAll(X, y, num_labels, the_lambda):
    m, n = shape(X)
    all_theta = matrix(zeros((num_labels, n+1)))
    X = hstack((ones((m, 1)), X))
    for c in range(num_labels):
        print 'Training for %d/34' % (c+1)
        initial_theta = zeros((n+1, 1))
        args = (X, (y == c), the_lambda)
        theta = fmin_bfgs(lrCostFunction, initial_theta, fprime=lrGD, args=args, maxiter=50)
        all_theta[c, :] = theta.transpose()

    return all_thet


for c in range(num_labels):
        print 'Training for %d/34' % (c+1)
        initial_theta = zeros((n+1, 1))
        args = (X, (y == c), the_lambda)
        theta = fmin_bfgs(lrCostFunction, initial_theta, fprime=lrGD, args=args, maxiter=50)
        all_theta[c, :] = theta.transpose()