def read_perm_file(filename):
    """
    Reads a permutation
    :param filename: Name of perm file
    :return: permutation as a list of numbers

    Check that the permutation is legal, raise ValueError if not
    """
    with open(filename, 'r') as f:
        line = f.read().split()
        used = set()
        result = []
        for num_str in line:
            try:
                num = int(num_str)
            except ValueError:
                raise ValueError(
                    'Invalid permutation %s - only numbers are allowed' % line)
            if num < 1 or num > len(line):
                raise ValueError('Invalid permutation %s - out of range' % line
                    )
            num -= 1
            if num in used:
                raise ValueError(
                    'Invalid permutation %s - number appears twice' % line)
            result.append(num)
            used.add(num)
    return result
