/*
 *                            COPYRIGHT
 *
 *  cschem - modular/flexible schematics editor - libcschem (core library)
 *  Copyright (C) 2023 Tibor 'Igor2' Palinkas
 *
 *  (Supported by NLnet NGI0 Entrust in 2023)
 *
 *  This library is free software; you can redistribute it and/or
 *  modify it under the terms of the GNU Lesser General Public
 *  License as published by the Free Software Foundation; either
 *  version 2.1 of the License, or (at your option) any later version.*
 *
 *  This library 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
 *  Lesser General Public License for more details.
 *
 *  You should have received a copy of the GNU Lesser General Public
 *  License along with this library; if not, write to the Free Software
 *  Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA  02110-1301  USA
 *
 *  Contact:
 *    Project page: http://repo.hu/projects/sch-rnd
 *    contact lead developer: http://www.repo.hu/projects/sch-rnd/contact.html
 *    mailing list: http://www.repo.hu/projects/sch-rnd/contact.html
 */

#include "config.h"

#include <stdlib.h>
#include <assert.h>
#include <librnd/core/compat_lrealpath.h>
#include <librnd/core/compat_fs.h>
#include <genvector/gds_char.h>

#include "util_path.h"

char *csch_relative_path_files(const char *pth, const char *relto)
{
	char *freeme1 = NULL, *freeme2 = NULL;
	const char *s, *s1, *s2;
	int offs, commsep = -1;
	gds_t res = {0};
	

	/* make sure both inputs are full paths */
	if (!rnd_is_path_abs(pth))
		pth = freeme1 = rnd_lrealpath(pth);
	if (!rnd_is_path_abs(relto))
		relto = freeme2 = rnd_lrealpath(relto);

	/* calculate common part */
	for(offs = 0, s1 = pth, s2 = relto; *s1 == *s2; s1++, s2++, offs++)
		if ((*s1 == '/') && (*s2 == '/'))
			commsep = offs;

	assert(commsep >= 0); /* both paths are absolute, worst case first char match */

	/* add all the ../ */
	for(s = relto+commsep+1; *s != '\0'; s++) {
		if ((s[0] == '/') && (s[1] != '/'))
			gds_append_str(&res, "../");
	}

	/* append partial path to dest file */
	gds_append_str(&res, pth+commsep+1);

	free(freeme1);
	free(freeme2);
	return res.array;
}

const char *csch_basename(const char *path)
{
	char *res = strrchr(path, '/');
	if (res == NULL) return path;
	return res+1;
}

const char *csch_parent_dir_name(const char *fullpath)
{
	const char *bn;
	int seps = 0;

	for(bn = fullpath + strlen(fullpath) - 1; bn > fullpath; bn--) {
		if ((bn[0] == '/') && (bn[1] != '/')) {
			seps++;
			if (seps == 2) {
				bn++;
				return bn;
			}
		}
	}

	return bn;
}
