from math import isnan, fabs, floor


def compute_spatial_reference_factory_code(latitude, longitude): 
    """
    Computes spatial reference factory code. This value may be used as out_sr value in create image collection function

    Parameters
    ----------
    latitude : latitude value in decimal degress that will be used to compute UTM zone
    longitude : longitude value in decimal degress that will be used to compute UTM zone

    Returns
    -------
    factory_code : spatial reference factory code
    """
    zone = 0
    if (isnan(longitude) or isnan(latitude) or fabs(longitude) > 180.0 or fabs(latitude) > 90.0):
        raise RuntimeError("Incorrect latitude or longitude value")

    zone = floor((longitude + 180)/6) + 1
    if (latitude >= 56.0 and latitude < 64.0 and longitude >= 3.0 and longitude < 12.0):
        zone = 32;

    if (latitude >= 72.0 and latitude < 84.0):
        if  (longitude >= 0.0  and longitude <  9.0):
            zone = 31;
        elif (longitude >= 9.0  and longitude < 21.0):
            zone = 33;
        elif (longitude >= 21.0 and longitude < 33.0):
            zone = 35;
        elif (longitude >= 33.0 and longitude < 42.0): 
            zone = 37

    if(latitude>=0):
        srid = 32601
    else:
        srid = 32701

    factory_code = srid + zone -1

    return factory_code