/*
 * 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 2
 * 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, write to the Free Software
 * Foundation, Inc., 59 Temple Place - Suite 330, Boston, MA  02111-1307, USA.
 *
 * See the COPYING file for license information.
 *
 * Guillaume Chazarain <guichaz@yahoo.fr>
 */

/***************************************************
 * A data structure to keep track of visited files *
 ***************************************************/

#include <sys/types.h>          /* dev_t, ino_t */
#include <sys/stat.h>           /* struct stat, stat() */
#include <stdio.h>              /* perror() */

#include "gliv.h"
#include "pathset.h"

/*
 * Files informations saved into
 * the AVL to uniquely identify them.
 */
typedef struct {
    dev_t dev;
    ino_t ino;
} file_info;

/* To build and search the AVL. */
static gint cmp_func(const file_info * file1, const file_info * file2)
{
    if (file1->ino < file2->ino)
        return -1;

    if (file1->ino > file2->ino)
        return 1;

    if (file1->dev < file2->dev)
        return -1;

    return file1->dev > file2->dev;
}

struct pathset *pathset_new(void)
{
    struct pathset *set = g_new(struct pathset, 1);

    set->tree = g_tree_new_full((GCompareDataFunc) cmp_func, NULL,
                                g_free, NULL);

    return set;
}

/* Return TRUE if the file has been correctly inserted. */
gboolean pathset_add(struct pathset * set, const gchar * path)
{
    struct stat st;
    file_info *file;

    if (stat(path, &st) < 0) {
        perror(path);
        return FALSE;
    }

    file = g_new(file_info, 1);

    file->dev = st.st_dev;
    file->ino = st.st_ino;

    if (g_tree_lookup(set->tree, file) != NULL) {
        g_free(file);
        return FALSE;
    }

    g_tree_insert(set->tree, file, file);
    return TRUE;
}

void pathset_free(struct pathset *set)
{
    g_tree_destroy(set->tree);
    g_free(set);
}
