#!/usr/bin/env python
# coding: utf-8

import glob
import os

import numpy as np
import scipy.ndimage as ndi

import smartcarb as sc
import config


def read_clouds(month):
    filenames = sorted(glob.glob(
        os.path.join(config.path_2d_fields, '*2015%02d*.nc' % month)
    ))

    clct_mean = []
    clct_std = []

    for filename in filenames:
        print(filename)
        rlon,rlat,clct = sc.map.load_cosmo_data(filename, 'CLCT')

        clct_mean.append( clct.mean() )
        clct_std.append( clct.std() )


    return np.array(clct_mean), np.array(clct_std)


def read_data(tracer, thr=0.1, cc_thr=0.01, month=1, hour=11):

    filenames = sorted(glob.glob(
        os.path.join(config.path_2d_fields,
            '*2015%02d??%02d*.nc' % (month, hour)
        )
    ))

    values = []
    values_cloudy = []

    for filename in filenames:
        print(os.path.basename(filename))

        rlon,rlat,co2 = sc.map.load_cosmo_data(filename, tracer)
        rlon,rlat,clct = sc.map.load_cosmo_data(filename, 'CLCT')

        # reduce resolution from 1x1 to 2x2
        co2 = ndi.convolve(co2, 0.25 * np.ones((2,2)))[::2,::2]
        clct = ndi.convolve(clct, 0.25 * np.ones((2,2)))[::2,::2]

        values.append( np.sum((co2 > thr)) )
        values_cloudy.append( np.sum((co2 > thr) & (clct < cc_thr)) )

    return np.array(values), np.array(values_cloudy)


def main():
    values = read_data('XCO2_BV', month=1)
    np.savetxt('BerlinPlume.dat', values)


if __name__ == '__main__':
    main()

