/*
 * This file is part of uudeview, the simple and friendly multi-part multi-
 * file uudecoder  program  (c)  1994 by Frank Pilhofer. The author may be
 * contacted by his email address,          fp@informatik.uni-frankfurt.de
 *
 * 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.
 */


/*
 * uncompress / gunzip file
 **/

#include <stdio.h>

#ifndef NO_POSIX
#include <stdlib.h>
#include <string.h>
#endif

#include "uudeview.h"
#include "uuerror.h"
#include "uuutil.h"
#include "uunconc.h"
#include "uufree.h"

/*
 * We'd need system() for this one
 * Can't do in Windows
 */

#ifndef _WINDOWS

uulist *uncompress (uulist *data)
{
  char bef[255], *ptr;
  uulist *unew;

  if (!(data->state & ST_DECODED))
    if (uudecode (data) != 1)
      return NULL;
  if (data->state & ST_UNCOMP)
    return data->branch;

  if ((ptr = strrchr (data->filename, '.')) == NULL) {
    uuerror = NOCOMP;
    return NULL;
  }
  if (strcmp (ptr, ".Z") == 0 || strcmp (ptr, ".tz") == 0 ||
      strcmp (ptr, ".z") == 0)
    strcpy (bef, "uncompress");
  else if (strcmp (ptr, ".gz" ) == 0 || strcmp (ptr, ".tgz") == 0 ||
           strcmp (ptr, ".taz") == 0)
    strcpy (bef, "gunzip");
  else {
    uuerror = NOCOMP;
    return NULL;
  }

  if ((unew = (uulist *) malloc (sizeof (uulist))) == NULL) {
    uuerror = NOMEM;
    return NULL;
  }
  if ((unew->filename = (char *) malloc (strlen(data->filename)+2)) == NULL) {
    free (unew);
    uuerror = NOMEM;
    return NULL;
  }
  strcpy (unew->filename, data->filename);

  if ((unew->binfile = tempnam (NULL, "uu")) == NULL) {
    free (unew->filename);
    free (unew);
    uuerror = NOMEM;
    return NULL;
  }
  ptr = strrchr (unew->filename, '.');

  if (strcmp (ptr, ".tz" ) == 0 || strcmp (ptr, ".tgz") == 0 ||
      strcmp (ptr, ".taz") == 0)
    strcpy (ptr, ".tar");
  else
    *ptr = '\0';
  
  strcat (bef, " -c ");
  strcat (bef, data->binfile);
  strcat (bef, " > ");
  strcat (bef, unew->binfile);
  
  system (bef);

  data->state     = data->state | ST_UNCOMP;
  unew->state     = ST_OK | ST_DECODED;
  unew->mode      = data->mode;
  unew->subfname  = _CopyLine (data->subfname, -1);
  unew->tarblock  = -1;
  unew->thisfile  = NULL;
  unew->misparts  = NULL;
  unew->branch    = NULL;
  unew->NEXT      = NULL;

  if (exists (unew->binfile) < 2) { /* File empty ? */
    killlist (unew);
    uuerror = NOCOMP;
    unew    = NULL;
  }

  data->branch   = unew;

  return unew;
}
#endif /* _WINDOWS */
