"""JPEG 2000 File Reader"""
from __future__ import absolute_import

__author__ = "Keith Hughitt"
__email__ = "keith.hughitt@nasa.gov"

import os
import subprocess
import tempfile
from xml.etree import cElementTree as ET

from matplotlib.image import imread
from glymur import Jp2k

from sunpy.util.xml import xml_to_dict
from sunpy.io.header import FileHeader

__all__ = ['read', 'get_header', 'write']

def read(filepath):
    """
    Reads a JPEG2000 file

    Parameters
    ----------
    filepath : string
        The file to be read

    j2k_to_image : string
        binary to use for reading?

    Returns
    -------
    pairs : list
        A list of (data, header) tuples
    """
    header = get_header(filepath)
    data = Jp2k(filepath).read()

    return [(data, header[0])]

def get_header(filepath):
    """
    Reads the header from the file

    Parameters
    ----------
    filepath : string
        The file to be read

    Returns
    -------
    headers : list
        A list of headers read from the file
    """
    jp2 = Jp2k(filepath)
    xml_box = [box for box in jp2.box if box.box_id == 'xml ']
    xmlstring = ET.tostring(xml_box[0].xml.find('fits'))
    pydict = xml_to_dict(xmlstring)["fits"]

    #Fix types
    for k, v in pydict.items():
        if v.isdigit():
            pydict[k] = int(v)
        elif _is_float(v):
            pydict[k] = float(v)

    # Remove newlines from comment
    if 'comment' in pydict:
        pydict['comment'] = pydict['comment'].replace("\n", "")

    return [FileHeader(pydict)]

def write(fname, data, header):
    """
    Place holder for required file writer
    """
    raise NotImplementedError("No jp2 writer is implemented")

def _is_float(s):
    """Check to see if a string value is a valid float"""
    try:
        float(s)
        return True
    except ValueError:
        return False

def _which(program):
    """Checks for existence of executable

    Source: http://stackoverflow.com/questions/377017/test-if-executable-exists-in-python/377028#377028
    """
    def is_exe(fpath):
        return os.path.exists(fpath) and os.access(fpath, os.X_OK)

    fpath, fname = os.path.split(program) #pylint: disable=W0612

    if fpath:
        if is_exe(program):
            return program
    else:
        for path in os.environ["PATH"].split(os.pathsep):
            exe_file = os.path.join(path, program)
            if is_exe(exe_file):
                return exe_file

    return None

@@ -1701,775 +1701,4 @@
 d%22)%0A
-%0Adef _is_float(s):%0A    %22%22%22Check to see if a string value is a valid float%22%22%22%0A    try:%0A        float(s)%0A        return True%0A    except ValueError:%0A        return False%0A%0Adef _which(program):%0A    %22%22%22Checks for existence of executable%0A%0A    Source: http://stackoverflow.com/questions/377017/test-if-executable-exists-in-python/377028#377028%0A    %22%22%22%0A    def is_exe(fpath):%0A        return os.path.exists(fpath) and os.access(fpath, os.X_OK)%0A%0A    fpath, fname = os.path.split(program) #pylint: disable=W0612%0A%0A    if fpath:%0A        if is_exe(program):%0A            return program%0A    else:%0A        for path in os.environ%5B%22PATH%22%5D.split(os.pathsep):%0A            exe_file = os.path.join(path, program)%0A            if is_exe(exe_file):%0A                return exe_file%0A%0A    return None%0A

remove more old stuff from jp2