'Set the path to the directory containing this books files based on its
current title and author. If there was a previous directory, its contents
are copied and it is deleted.'

def set_path(self, index, index_is_id=False):

    id = (index if index_is_id else self.id(index))
    path = self.construct_path_name(id)
    current_path = self.path(id, index_is_id=True).replace(os.sep, '/')
    formats = self.formats(id, index_is_id=True)
    formats = (formats.split(',') if formats else [])
    fname = self.construct_file_name(id)
    changed = False
    for format in formats:
        name = self.format_filename_cache[id].get(format.upper(), None)
        if (name and (name != fname)):
            changed = True
            break
    if ((path == current_path) and (not changed)):
        return
    spath = os.path.join(self.library_path, *current_path.split('/'))
    tpath = os.path.join(self.library_path, *path.split('/'))
    source_ok = (current_path and os.path.exists(spath))
    wam = (WindowsAtomicFolderMove(spath) if (iswindows and source_ok) else None)
    try:
        if (not os.path.exists(tpath)):
            os.makedirs(tpath)
        if source_ok:
            self.copy_cover_to(id, os.path.join(tpath, 'cover.jpg'), index_is_id=True, windows_atomic_move=wam, use_hardlink=True)
            for format in formats:
                copy_function = functools.partial(self.copy_format_to, id, format, index_is_id=True, windows_atomic_move=wam, use_hardlink=True)
                try:
                    self.add_format(id, format, None, index_is_id=True, path=tpath, notify=False, copy_function=copy_function)
                except NoSuchFormat:
                    continue
        self.conn.execute('UPDATE    books    SET    path=?    WHERE    id=?', (path, id))
        self.dirtied([id], commit=False)
        self.conn.commit()
        self.data.set(id, self.FIELD_MAP['path'], path, row_is_id=True)
        if source_ok:
            if (not samefile(spath, tpath)):
                if (wam is not None):
                    wam.delete_originals()
                self.rmtree(spath, permanent=True)
                parent = os.path.dirname(spath)
                if (len(os.listdir(parent)) == 0):
                    self.rmtree(parent, permanent=True)
    finally:
        if (wam is not None):
            wam.close_handles()
    curpath = self.library_path
    (c1, c2) = (current_path.split('/'), path.split('/'))
    if ((not self.is_case_sensitive) and (len(c1) == len(c2))):
        for (oldseg, newseg) in zip(c1, c2):
            if ((oldseg.lower() == newseg.lower()) and (oldseg != newseg)):
                try:
                    os.rename(os.path.join(curpath, oldseg), os.path.join(curpath, newseg))
                except:
                    break
            curpath = os.path.join(curpath, newseg)
