# Path: smtk/sm_utils.py
# def convert_accel_units(acceleration, from_, to_='cm/s/s'):  # noqa
#     """
#     Converts acceleration from/to different units
# 
#     :param acceleration: the acceleration (numeric or numpy array)
#     :param from_: unit of `acceleration`: string in "g", "m/s/s", "m/s**2",
#         "m/s^2", "cm/s/s", "cm/s**2" or "cm/s^2"
#     :param to_: new unit of `acceleration`: string in "g", "m/s/s", "m/s**2",
#         "m/s^2", "cm/s/s", "cm/s**2" or "cm/s^2". When missing, it defaults
#         to "cm/s/s"
# 
#     :return: acceleration converted to the given units (by default, 'cm/s/s')
#     """
#     m_sec_square = ("m/s/s", "m/s**2", "m/s^2")
#     cm_sec_square = ("cm/s/s", "cm/s**2", "cm/s^2")
#     acceleration = np.asarray(acceleration)
#     if from_ == 'g':
#         if to_ == 'g':
#             return acceleration
#         if to_ in m_sec_square:
#             return acceleration * g
#         if to_ in cm_sec_square:
#             return acceleration * (100 * g)
#     elif from_ in m_sec_square:
#         if to_ == 'g':
#             return acceleration / g
#         if to_ in m_sec_square:
#             return acceleration
#         if to_ in cm_sec_square:
#             return acceleration * 100
#     elif from_ in cm_sec_square:
#         if to_ == 'g':
#             return acceleration / (100 * g)
#         if to_ in m_sec_square:
#             return acceleration / 100
#         if to_ in cm_sec_square:
#             return acceleration
# 
#     raise ValueError("Unrecognised time history units. "
#                      "Should take either ''g'', ''m/s/s'' or ''cm/s/s''")
# 
# def get_time_vector(time_step, number_steps):
#     """
#     General SMTK utils
#     """
#     return np.cumsum(time_step * np.ones(number_steps, dtype=float)) - time_step
# 
# Path: smtk/parsers/base_database_parser.py
# def get_float(xval):
#     """
#     Returns a float value, or none
#     """
#     if xval.strip():
#         try:
#             return float(xval)
#         except:
#             return None
#     else:
#         return None
# 
# def get_int(xval):
#     """
#     Returns an int value or none
#     """
#     if xval.strip():
#         try:
#             return int(xval)
#         except:
#             return None
#     else:
#         return None
# 
# class SMDatabaseReader(with_metaclass(abc.ABCMeta)):
#     """
#     Abstract base class for strong motion database parser
#     """
# 
#     def __init__(self, db_id, db_name, filename, record_folder=None):
#         """
#         Instantiate and conduct folder checks
#         """
#         self.id = db_id
#         self.name = db_name
#         self.filename = filename
#         self.database = None
#         if record_folder:
#             self.record_folder = record_folder
#         else:
#             self.record_folder = self.filename
# 
#     @abc.abstractmethod
#     def parse(self):
#         """
#         Parses the database
#         """
# 
# class SMTimeSeriesReader(with_metaclass(abc.ABCMeta)):
#     """
#     Abstract base class for a reader of a ground motion time series
#     """
#     def __init__(self, input_files, folder_name=None, units="cm/s/s"):
#         """
#         Instantiate and conduct folder checks
#         """
#         self.input_files = []
#         for fname in input_files:
#             if folder_name:
#                 filename = os.path.join(folder_name, fname)
#                 if os.path.exists(filename):
#                     self.input_files.append(filename)
#             else:
#                 if os.path.exists(fname):
#                     self.input_files.append(fname)
#         self.time_step = None
#         self.number_steps = None
#         self.units = units
#         self.metadata = None
# 
#     @abc.abstractmethod
#     def parse_records(self, record=None):
#         """
#         Parse the strong motion record
#         """


import os
import re
from collections import OrderedDict
from linecache import getline
from datetime import datetime
from math import sqrt
from openquake.hazardlib.geo import *
from smtk.sm_database import *
from smtk.sm_utils import convert_accel_units, get_time_vector
from smtk.parsers.base_database_parser import (get_float,
                                               get_int,
                                               SMDatabaseReader,
                                               SMTimeSeriesReader)
        """

        epi_lon = -get_float(
            metadata["COORDENADAS DEL EPICENTRO"].split(" ")[3])
        epi_lat = get_float(
            metadata["COORDENADAS DEL EPICENTRO"].split(" ")[0])
        sta_lon = -get_float(
            metadata["COORDENADAS DE LA ESTACION"].split(" ")[3])
        sta_lat = get_float(
            metadata["COORDENADAS DE LA ESTACION"].split(" ")[0])

        p = Point(longitude=epi_lon, latitude=epi_lat)
        repi = p.distance(Point(longitude=sta_lon, latitude=sta_lat))

        # No hypocentral distance in file - calculate from event
        rhypo = sqrt(repi ** 2. + eqk.depth ** 2.)

        azimuth = Point(epi_lon, epi_lat, eqk.depth).azimuth(
            Point(sta_lon, sta_lat))

        dists = RecordDistance(repi, rhypo)
        dists.azimuth = azimuth
        return dists

    def _parse_site_data(self, metadata):
        """
        Parses the site metadata. Coordinates in western hemisphere
        are returned as negative values.
        """
        try:

# Path: smtk/sm_utils.py
# def convert_accel_units(acceleration, from_, to_='cm/s/s'):  # noqa
#     """
#     Converts acceleration from/to different units
# 
#     :param acceleration: the acceleration (numeric or numpy array)
#     :param from_: unit of `acceleration`: string in "g", "m/s/s", "m/s**2",
#         "m/s^2", "cm/s/s", "cm/s**2" or "cm/s^2"
#     :param to_: new unit of `acceleration`: string in "g", "m/s/s", "m/s**2",
#         "m/s^2", "cm/s/s", "cm/s**2" or "cm/s^2". When missing, it defaults
#         to "cm/s/s"
# 
#     :return: acceleration converted to the given units (by default, 'cm/s/s')
#     """
#     m_sec_square = ("m/s/s", "m/s**2", "m/s^2")
#     cm_sec_square = ("cm/s/s", "cm/s**2", "cm/s^2")
#     acceleration = np.asarray(acceleration)
#     if from_ == 'g':
#         if to_ == 'g':
#             return acceleration
#         if to_ in m_sec_square:
#             return acceleration * g
#         if to_ in cm_sec_square:
#             return acceleration * (100 * g)
#     elif from_ in m_sec_square:
#         if to_ == 'g':
#             return acceleration / g
#         if to_ in m_sec_square:
#             return acceleration
#         if to_ in cm_sec_square:
#             return acceleration * 100
#     elif from_ in cm_sec_square:
#         if to_ == 'g':
#             return acceleration / (100 * g)
#         if to_ in m_sec_square:
#             return acceleration / 100
#         if to_ in cm_sec_square:
#             return acceleration
# 
#     raise ValueError("Unrecognised time history units. "
#                      "Should take either ''g'', ''m/s/s'' or ''cm/s/s''")
# 
# def get_time_vector(time_step, number_steps):
#     """
#     General SMTK utils
#     """
#     return np.cumsum(time_step * np.ones(number_steps, dtype=float)) - time_step
# 
# Path: smtk/parsers/base_database_parser.py
# def get_float(xval):
#     """
#     Returns a float value, or none
#     """
#     if xval.strip():
#         try:
#             return float(xval)
#         except:
#             return None
#     else:
#         return None
# 
# def get_int(xval):
#     """
#     Returns an int value or none
#     """
#     if xval.strip():
#         try:
#             return int(xval)
#         except:
#             return None
#     else:
#         return None
# 
# class SMDatabaseReader(with_metaclass(abc.ABCMeta)):
#     """
#     Abstract base class for strong motion database parser
#     """
# 
#     def __init__(self, db_id, db_name, filename, record_folder=None):
#         """
#         Instantiate and conduct folder checks
#         """
#         self.id = db_id
#         self.name = db_name
#         self.filename = filename
#         self.database = None
#         if record_folder:
#             self.record_folder = record_folder
#         else:
#             self.record_folder = self.filename
# 
#     @abc.abstractmethod
#     def parse(self):
#         """
#         Parses the database
#         """
# 
# class SMTimeSeriesReader(with_metaclass(abc.ABCMeta)):
#     """
#     Abstract base class for a reader of a ground motion time series
#     """
#     def __init__(self, input_files, folder_name=None, units="cm/s/s"):
#         """
#         Instantiate and conduct folder checks
#         """
#         self.input_files = []
#         for fname in input_files:
#             if folder_name:
#                 filename = os.path.join(folder_name, fname)
#                 if os.path.exists(filename):
#                     self.input_files.append(filename)
#             else:
#                 if os.path.exists(fname):
#                     self.input_files.append(fname)
#         self.time_step = None
#         self.number_steps = None
#         self.units = units
#         self.metadata = None
# 
#     @abc.abstractmethod
#     def parse_records(self, record=None):
#         """
#         Parse the strong motion record
#         """


# Path: smtk/parsers/asa_database_parser.py
import os
import re
from collections import OrderedDict
from linecache import getline
from datetime import datetime
from math import sqrt
from openquake.hazardlib.geo import *
from smtk.sm_database import *
from smtk.sm_utils import convert_accel_units, get_time_vector
from smtk.parsers.base_database_parser import (get_float,
                                               get_int,
                                               SMDatabaseReader,
                                               SMTimeSeriesReader)

        """

        epi_lon = -get_float(
            metadata["COORDENADAS DEL EPICENTRO"].split(" ")[3])
        epi_lat = get_float(
            metadata["COORDENADAS DEL EPICENTRO"].split(" ")[0])
        sta_lon = -get_float(
            metadata["COORDENADAS DE LA ESTACION"].split(" ")[3])
        sta_lat = get_float(
            metadata["COORDENADAS DE LA ESTACION"].split(" ")[0])

        p = Point(longitude=epi_lon, latitude=epi_lat)
        repi = p.distance(Point(longitude=sta_lon, latitude=sta_lat))

        # No hypocentral distance in file - calculate from event
        rhypo = sqrt(repi ** 2. + eqk.depth ** 2.)

        azimuth = Point(epi_lon, epi_lat, eqk.depth).azimuth(
            Point(sta_lon, sta_lat))

        dists = RecordDistance(repi, rhypo)
        dists.azimuth = azimuth
        return dists

    def _parse_site_data(self, metadata):
        """
        Parses the site metadata. Coordinates in western hemisphere
        are returned as negative values.
        """
        try:

            altitude = get_float(metadata["ALTITUD (msnm)"])