# Some basic file io.
#
# Author       : Chris X. Weichenberger
# Created      : 2012-02-24
# License
# Twilight is a GUI for displaying ligands incompatible with electron density.
#    Copyright (C) 2012  Christian X. Weichenberger, Edwin Pozharski, and
#    Bernhard Rupp.
#
#    This program is free software: you can redistribute it and/or modify
#    it under the terms of the GNU General Public License as published by
#    the Free Software Foundation, either version 3 of the License, or
#    (at your option) any later version.
#
#    This program is distributed in the hope that it will be useful,
#    but WITHOUT ANY WARRANTY; without even the implied warranty of
#    MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
#    GNU General Public License for more details.
#
#    You should have received a copy of the GNU General Public License
#    along with this program.  If not, see <http://www.gnu.org/licenses/>.
#
# Modifications:
# YYYY-MM-DD (WHO) what
#

import os
import sys

def Output(text):
    """Write text + newline to stderr."""
    sys.stderr.write(text + os.linesep);

def Debug(thing):
    fh = open("/tmp/debug-dysplayer.txt", "a");
    fh.write(str(thing) + os.linesep);
    fh.close();

def GetVersionedInOutFileNames(fn):
    """Get the next versioned file name.
    - fn: Current file name. May be versionless or versioned.
    * return: 2-Tuple: (last existing versioned file name, next versioned file
      name which does not yet exist)
    """
    base, ext = os.path.splitext(fn);
    version   = 1;
    if( base[-5:-3]=="-V" ):
        try:
            version = int(base[-3:]);
            base    = base[:-5];
        except ValueError:
            # fall back to version number one.
            pass ;
    usedFFN = fn;
    # quite ugly, but save...
    for verNr in range(999, version-1, -1):
        ffn = base + "-V%03d" % verNr + ext;
        if( not os.path.exists(ffn) ):
            unusedFFN = ffn;
            continue ;
        usedFFN = ffn;
        break ;
    return usedFFN, unusedFFN;
