# Copyright 2021 The Handcrafted Backdoors. All Rights Reserved.
#
# Licensed under the Apache License, Version 2.0 (the "License");
# you may not use this file except in compliance with the License.
# You may obtain a copy of the License at
#
#     http://www.apache.org/licenses/LICENSE-2.0
#
# Unless required by applicable law or agreed to in writing, software
# distributed under the License is distributed on an "AS IS" BASIS,
# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
# See the License for the specific language governing permissions and
# limitations under the License.
# ==============================================================================
""" I/O wrapper functions """
# basics
import csv
import h5py
import numpy as np
import scipy.io as sio


"""
    CSV
"""
def write_to_csv(filename, datalines, mode='a'):
    with open(filename, mode) as outfile:
        csv_writer = csv.writer(outfile)
        for eachline in datalines:
            csv_writer.writerow(eachline)
    # done.

def load_from_csv(filename):
    data = []
    with open(filename, 'r') as infile:
        csv_reader = csv.reader(infile)
        for eachrow in csv_reader:
            data.append(eachrow)
    return data


"""
    Numpy
"""
def store_to_numpy(filename, data):
    with open(filename, 'wb') as outfile:
        np.save(outfile, data)
    # done.

def load_from_numpy(filename):
    with open(filename, 'rb') as infile:
        return np.load(infile, allow_pickle=True)   # to retrieve JAX objects
    # done.


"""
    Matlab
"""
def load_from_matfile(filename):
    data = sio.loadmat(filename)
    return data


"""
    H5Py
"""
def load_from_h5file(filename):
    # load the data
    dataset = {}
    with h5py.File(filename, 'r') as hfile:
        for name in hfile:
            dataset[name] = np.array(hfile.get(name))
    return dataset

def store_to_h5py(filename, data):
    with h5py.File(filename, 'w') as hfile:
        for key, value in data.items():
            hfile.create_dataset(key, data=value)
    # done.
