def fix_lines(text, ending='\n', replace=True, final=False):
    """fix line ending in text: 'replace' all or not, ensure 'final' line ending"""
    if not text or not ending:
        return text
    if replace:
        if ending == '\n':
            text = text.replace('\r\n', '\n')
        elif ending == '\r\n':
            text = text.replace('\r\n', '\n').replace('\n', '\r\n')
    if not final:
        return text
    return text.rstrip() + ending
