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

#define readmtc readmtc_
#define dinfo1  dinfo1_

#define max(a,b) (((a)>(b))?(a):(b))

void errexit( char *f_str, ... )
{
  va_list argp;
  char out1[256], out2[256];

  va_start(argp, f_str);
  vsprintf(out1, f_str, argp);
  va_end(argp);

  sprintf(out2, "Error! %s\n", out1);

  fprintf(stdout, out2);
  fflush(stdout);

  exit( -1 );
}

void *Malloc( int nbytes, char *msg )
{
  void *ptr;

  if (nbytes == 0)
    return NULL;

  ptr = (void *)malloc(nbytes);
  if (ptr == NULL)
    errexit( "Not enough mem for %s. Requested size: %d bytes", msg, nbytes );

  return ptr;
}

int main( int argc, char **argv )
{
/*---------------------------------------------------------------------- 
 * usage    info1.ex HB_file 
 *
 * where info1 is the executable generated by makefile, HB_file is a 
 * file containing a matrix stored in Harwell-Boeing matrices.
 * Info1 will then dump the information into the standard output.
 *--------------------------------------------------------------------*/
    int job, ncol, nrow, nnz, nrhs, ierr, valued = 0;
    char guesol[3], title[73], key[9], type[4];
    int *ia = NULL, *ja = NULL, *ia1 = NULL, *ja1 = NULL;
    double *a = NULL, *a1 = NULL, *rhs = NULL;
    int tmp1, tmp2, maxnnz;
    int iout = 6;

    if( argc < 2 ) {
        printf( "usage: info1.ex HB_file\n" );
        return 0;
    }

/* find out size of Harwell-Boeing matrix ---------------------------*/
    job = 0;
    tmp1 = tmp2 = 1;
    readmtc( &tmp1, &tmp2, &job, argv[1], a, ja, ia, rhs, &nrhs,
             guesol, &nrow, &ncol, &nnz, title, key, type, &ierr );
    if( ierr != 0 ) {
        fprintf( stderr, "readhb: err in read matrix header = %d\n", ierr );
        exit(-1);
    }
/* allocate space ---------------------------------------------------*/
    maxnnz = max( nnz, 2*ncol+1 );
    ia     = (int *)Malloc( sizeof(int)*(ncol+1), "readhb" );
    ja     = (int *)Malloc( sizeof(int)*nnz, "readhb" );
    a      = (double *)Malloc( sizeof(double)*nnz, "readhb" );
    ia1    = (int *)Malloc( sizeof(int)*(ncol+1), "readhb" );
    ja1    = (int *)Malloc( sizeof(int)*maxnnz, "readhb" );
    a1     = (double *)Malloc( sizeof(double)*nnz, "readhb" );
/* read matrix ------------------------------------------------------*/
    job = 2;
    nrhs = 0;
    tmp1 = ncol+1;
    tmp2 = nnz;
    readmtc( &tmp1, &tmp2, &job, argv[1], a, ja, ia, rhs, &nrhs,
             guesol, &nrow, &ncol, &nnz, title, key, type, &ierr );
    if( ierr != 0 ) {
        fprintf( stderr, "readhb: err in read matrix data = %d\n", ierr );
        exit(-1);
    }

    if( job >= 2 ) valued = 1;

    dinfo1( &ncol, &iout, a, ja, ia, &valued, title, key, type,
            a1, ja1, ia1 );

    free( ia );
    free( ja );
    free( a );
    free( ia1 );
    free( ja1 );
    free( a1 );

    return 0;
}
