/* ------------------------------------------------------------------- */
/* wfetch    : Fetch a remote file using the htget() "HTTP client"     */
/*                                                                     */
/* syntax    : wfatch(char *url, char *filename)                       */
/*                                                                     */
/*             The file will be written to "filename"                  */
/*                                                                     */
/* Returns   : 0 if fail                                               */
/*           : 1 if HTML file (text/html)                              */
/*           : 2 if MARC file (application/marc)                       */
/*                                                                     */
/* NOTE      : Timeout period (HTTP) is set here.                      */
/*                                                                     */
/* Author    : Ole Husby, BIBSYS                                       */
/* Updated   : 1998-08-11                                              */
/* ------------------------------------------------------------------- */

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

#define  TIMEOUT_SECONDS       10

int wfetch(char *url, char *filename)
{
  int i, type, argtype, timeout, rc, retc;
  char iurl[1024], content_type[128], location[128];

  retc = 1;

  strcpy(iurl, url);
  timeout = TIMEOUT_SECONDS;

  type = 6;                           /* Fetch HTML HEAD or MARC      */

  rc = htget(iurl, type, timeout, filename, content_type, location);


/* Try again if redirect                                              */

  if ( ( ( rc == 301 ) || ( rc == 302 ) ) && *location )
  {
    strcpy(iurl, location);
    rc = htget(iurl, type, timeout, filename, content_type, location);
  }

  if (rc)
    retc = 0;
  else if (strcmp(content_type, "application/marc") == 0)
    retc = 2;

  return retc;
}
