/*
 * This file is part of the Poliqarp suite.
 * 
 * Copyright (C) 2004-2009 by Instytut Podstaw Informatyki Polskiej
 * Akademii Nauk (IPI PAN; Institute of Computer Science, Polish
 * Academy of Sciences; cf. www.ipipan.waw.pl).  All rights reserved.
 * 
 * This file may be distributed and/or modified under the terms of the
 * GNU General Public License version 2 as published by the Free Software
 * Foundation and appearing in the file gpl.txt included in the packaging
 * of this file.  (See http://www.gnu.org/licenses/translations.html for
 * unofficial translations.)
 * 
 * A commercial license is available from IPI PAN (contact
 * Michal.Ciesiolka@ipipan.waw.pl or ipi@ipipan.waw.pl for more
 * information).  Licensees holding a valid commercial license from IPI
 * PAN may use this file in accordance with that license.
 * 
 * This file is provided AS IS with NO WARRANTY OF ANY KIND, INCLUDING
 * THE WARRANTY OF DESIGN, MERCHANTABILITY AND FITNESS FOR A PARTICULAR
 * PURPOSE.
 */

#include <poliqarp-config.h>

#include <stdlib.h>
#include <string.h>
#include <libgen.h>

#include "utils.h"
#include "viewport.h"

char *text_trim(const char *text)
{
   const char *start;
   const char *end;
   char *result;
   while (*text && ascii_isspace(*text))
      ++text;
   start = text;
   end = strlen(start) + start;
   for (--end; end > start && ascii_isspace (*end); --end);
   result = malloc(end - start + 2);
   strncpy(result, start, end - start + 1);
   return result;
}

char *text_normalize(const char *text)
{
   char *result = strdup(text);
   register char *s;
   register int c;
   for (s = result; (c = *text); ++text) {
      if (ascii_isspace(c)) {
         for (++text; (c = *text) && ascii_isspace(c); ++text);
         if (c != 0) {
            if (s != result)
               *s++ = ' ';
            *s++ = c;
         } else {
            *s++ = 0;
            break;
         }
      } else
         *s++ = c;
   }
   *s = 0;
   return result;
}

FILE *xfopen(const char *fname, bool write)
{
   FILE *res = fopen(fname, write ? "wb" : "rb");
   if (res == NULL) {
      vp_eprintf("Fatal error: unable to open file %s for %sing\n", 
         fname, write ? "writ" : "read");
      exit(EXIT_FAILURE);
   }
   return res;
}

void split_pathname(const string_t path, string_t *dirname_str, string_t *basename_str)
{
   char *path_copy, *dirname_c, *basename_c;

   path_copy = strdup(string_str(path));
   if (path_copy == NULL)
      abort();
   dirname_c = dirname(path_copy);
   if (dirname_c == NULL)
      abort();
   *dirname_str = string_init(dirname_c);
   free(path_copy);

   path_copy = strdup(string_str(path));
   if (path_copy == NULL)
      abort();
   basename_c = basename(path_copy);
   if (basename_c == NULL)
      abort();
   *basename_str = string_init(basename_c);
   free(path_copy);
}
