def read_cp2k(in_name, pop='ESP'):
    """
    Read the charges and energy in a cp2k output file.

    Uses CP2K 4.1 formats. Choose between Mulliken, Hirshfeld or RESP charges.

    Parameters
    ----------
    in_name : str
        Name of the file to read
    pop : str
        Kind of charge to read: mulliken, esp or hirshfeld
    Returns
    -------
    charges : list of floats
        Each partial charge value in the file
    energy : float
        CP2K calculated energy (Kohn-Sham or otherwise) in Hartree

    """
    with open(in_name) as cp2k_file:
        cp2k_content = cp2k_file.readlines()
    if pop.lower() == 'mulliken':
        start_tag = 'Mulliken Population Analysis'
        char_pos = 4
        line_test = lambda x: x.split()[0].isdigit()
    if pop.lower() == 'esp' or pop.lower() == 'resp':
        start_tag = ' RESP charges:'
        char_pos = 3
        line_test = lambda x: x.split()[0] == 'RESP' and len(x.split()) == 4
    if pop.lower() in ('hirshfeld', 'hirsh'):
        start_tag = 'Hirshfeld Charges'
        char_pos = 5
        line_test = lambda x: x.split()[0].isdigit()
    reading = False
    charges = []
    for line in cp2k_content:
        if line.strip():
            if start_tag in line:
                reading = True
            if reading and line_test(line):
                charges.append(float(line.split()[char_pos]))
            if 'Total' in line:
                reading = False
            if 'ENERGY|' in line:
                energy = float(line.split()[8])
    cp2k_file.close()
    return charges, energy
