/*
 *                            COPYRIGHT
 *
 *  camv-rnd - electronics-related CAM viewer
 *  Copyright (C) 2022 Tibor 'Igor2' Palinkas
 *  (code borrowed from sch-rnd from the same author)
 *
 *  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., 31 Milk Street, # 960789 Boston, MA 02196 USA.
 *
 *  Contact:
 *    Project page: http://repo.hu/projects/camv-rnd
 *    lead developer: http://repo.hu/projects/camv-rnd/contact.html
 *    mailing list: pcb-rnd (at) list.repo.hu (send "subscribe")
 */

#include <librnd/config.h>
#include <librnd/core/compat_misc.h>

#include <genvector/gds_char.h>

#include "data.h"
#include "export.h"

char *camv_export_filename(rnd_design_t *hl, const char *explicit, const char *ext)
{
	camv_design_t *dsg = (camv_design_t *)hl;
	gds_t tmp;
	char *fn;

	if (explicit != NULL)
		return rnd_strdup(explicit);


	gds_init(&tmp);

	fn = hl->loadname; /* try to use project name first */
	if ((fn == NULL) && (dsg->layers.used > 0)) { /* if that fails, use first layer's name */
		camv_layer_t *ly = dsg->layers.array[0];
		fn = ly->name;
	}

	if (fn != NULL) {
		int n;
		gds_append_str(&tmp, fn);

		/* truncate "extension" */
		for(n = tmp.used-1; n > 0; n--) {
			if (tmp.array[n] == '.') {
				tmp.used = n;
				break;
			}
		}
	}
	else
		gds_append_str(&tmp, "unknown");

	gds_append_str(&tmp, ext);

	return tmp.array; /* tmp is not uninited because ownership is passed back to the caller */
}
