 /*
  * Khoros: $Id: lminvert.c,v 1.4 1992/03/20 23:46:33 dkhoros Exp $
  */

#if !defined(lint) && !defined(SABER)
static char rcsid[] = "Khoros: $Id: lminvert.c,v 1.4 1992/03/20 23:46:33 dkhoros Exp $";
#endif

 /*
  * $Log: lminvert.c,v $
 * Revision 1.4  1992/03/20  23:46:33  dkhoros
 * VirtualPatch5
 *
  */

/*
 *----------------------------------------------------------------------
 *
 * Copyright 1992, University of New Mexico.  All rights reserved.
 * Permission to copy and modify this software and its documen-
 * tation only for internal use in your organization is hereby
 * granted, provided that this notice is retained thereon and
 * on all copies.  UNM makes no representations as to the sui-
 * tability and operability of this software for any purpose.
 * It is provided "as is" without express or implied warranty.
 * 
 * UNM DISCLAIMS ALL WARRANTIES WITH REGARD TO THIS SOFTWARE,
 * INCLUDING ALL IMPLIED WARRANTIES OF MERCHANTABILITY AND FIT-
 * NESS.  IN NO EVENT SHALL UNM BE LIABLE FOR ANY SPECIAL,
 * INDIRECT OR CONSEQUENTIAL DAMAGES OR ANY OTHER DAMAGES WHAT-
 * SOEVER RESULTING FROM LOSS OF USE, DATA OR PROFITS, WHETHER
 * IN AN ACTION OF CONTRACT, NEGLIGENCE OR OTHER TORTIOUS
 * ACTION, ARISING OUT OF OR IN CONNECTION WITH THE USE OR PER-
 * FORMANCE OF THIS SOFTWARE.
 * 
 * No other rights, including, for example, the right to redis-
 * tribute this software and its documentation or the right to
 * prepare derivative works, are granted unless specifically
 * provided in a separate license agreement.
 *---------------------------------------------------------------------
 */

#include "unmcopyright.h"        /* Copyright 1992 by UNM */

/*>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>  <<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<
 >>>>
 >>>>         File Name: lminvert.c
 >>>>
 >>>>      Program Name: minvert
 >>>>
 >>>> Date Last Updated: Tue Feb 25 00:54:30 1992 
 >>>>
 >>>>          Routines: lminvert - the library call for minvert
 >>>>
 >>>>>>>>>>>>>>>>>>>>>>>>>>>>>>   <<<<<<<<<<<<<<<<<<<<<<<<<<<<<<*/


#include "vinclude.h"


/* -library_includes */
#define CLEANUP \
    {  /* cleanup workspace before leaving */ \
       if(amatrix!=NULL)free(amatrix); \
       if(zvector!=NULL)free(zvector); \
       if(ipvt!=NULL)free(ipvt); \
    } /* end of cleanup code */

typedef struct complex {
  double re,im;
} complex;
/* -library_includes_end */


/****************************************************************
*
* Routine Name: lminvert - library call for minvert
*
* Purpose:
*    
*    compute the inverse of a real or complex matrix
*    
*    

* Input:
*    
*    image          an image containing one or  more  square  matrices
*                   (one per band) of any data type.
*    
*    

* Output:
*    
*    iamge          double or  double  complex  image  containing  the
*                   inverses of the input image's matrices.
*    
*    Return Value:  1 on success, 0 on failure.
*    
*    

*
* Written By: Jeremy Worley
*    
*    Jeremy Worley Tue Feb 25 00:53:13 MST 1992
*              arguments rows and cols to  linvert()  were  explicitly
*              declared  and  functions  in lminvert() were explicitly
*              declared.
*    
*    

****************************************************************/


/* -library_def */
int lminvert(image)
    struct xvimage *image;
/* -library_def_end */

/* -library_code */
{
  int i,rows,cols,bands,type;
  double *mat,*kern;
  char *program = "lminvert";
  int proper_num_images(), lvcast(), linvert();
 
  bands = (int)image->num_data_bands; 
  rows = (int)image->col_size;
  cols = (int)image->row_size;

  if(!proper_num_images(program,image,1,FALSE)){
     fprintf(stderr,"%s:  image structure must contain only one image.\n",
             program);
     return(0);
  }

/*
** cast all of the data up to double or double complex
*/

   if(image->data_storage_type==VFF_TYP_COMPLEX || image->data_storage_type==
        VFF_TYP_DCOMPLEX){
      if(!lvcast(&image,(int)1,(int)VFF_TYP_DCOMPLEX)){
         fprintf(stderr,"%s:  Failure to cast up to double complex.\n",program);
         return(0);
      }
      type = 1;
   }else{
      if(!lvcast(&image,(int)1,(int)VFF_TYP_DOUBLE)){
         fprintf(stderr,"%s:  Failure to cast up to double.\n",program);
         return(0);
      }
      type = 0;
   }

  if((mat = (double *)malloc(2*rows*cols*sizeof(double)))==NULL){
     fprintf(stderr,"%s:  Failure to allocate necessary data.\n",program);
     return(0);
  }

/*
** process all of the data
*/

   kern = (double *)(image->imagedata);
   for(i=0;i<bands;i++){
      if(!linvert(mat,kern,rows,cols,type)){
         fprintf(stderr,"%s:  Failed call to static routine.\n",program);
         free((char *)mat);
         return(0);
      }

      bcopy(mat,kern,(type+1)*rows*cols*sizeof(double));
      kern += (type+1)*rows*cols;
   }

   return(1);
}
 
/***********************************************************************
*
*  Routine Name: static linvert
*
*          Date:
*        
*       Purpose:  
*
*         Input: 
*
*        Output: 
*
*    Written By:  
*
* Modifications:
*
***********************************************************************/

int linvert(imatrix,matrix,rows,cols,type)
  double *imatrix, *matrix;
  int type,rows,cols;
{
  int   index1,index2,k,j;
  void zgedi_(), zgeco_(); 
  void swap();

  complex *amatrix,*zvector=NULL,det[2];
  int *ipvt=NULL;
  double rcond;

  char *program = "lminvert";
  int job = 1; /* invert only */

/*
** test some junk
*/

  if(rows!=cols){
     fprintf(stderr,"%s:  matrix must be square.\n",program);
     return(0);
  }

  if(rows<=0 || cols<=0){
     fprintf(stderr,"%s:  matrix dimensions must be nonzero.\n",program);
     return(0);
  }

  if(matrix==NULL || imatrix==NULL){
     fprintf(stderr,"%s:  null matrix not allowed.\n",program);
     return(0);
  }

/*
** allocate memory for junk
*/

  amatrix = (complex *)malloc((unsigned)rows * cols * sizeof(complex));
  if(amatrix==NULL){
     fprintf(stderr,"%s:  [1]memory allocation failure.\n",program);
     CLEANUP;
     return(0);
  }

  zvector = (complex *)malloc((unsigned)cols * sizeof(complex));
  if(zvector==NULL){
     fprintf(stderr,"%s:  [2]memory allocation failure.\n",program);
     CLEANUP;
     return(0);
  }

  ipvt = (int *)malloc((unsigned)cols * sizeof(int));
  if(ipvt==NULL){
     fprintf(stderr,"%s:  [3]memory allocation failure.\n",program);
     CLEANUP;
     return(0);
  }

/*
** transpose data 'cause were working with that brain-dead excuse for
** a language FORTRAN... 
*/

  if(type == 0){
     for(j=0;j<rows;j++){
         for(k=0;k<cols;k++){
            amatrix[j*cols+k].re = (double) matrix[j+k*cols];
            amatrix[j*cols+k].im = (double) 0.0;
         }
     }
  }else{
     for(j=0;j<rows;j++){
         for(k=0;k<cols;k++){
            index1 = j*cols + k;
            index2 = j + k*cols ;
            amatrix[index1].re = (double) matrix[2*index2];
            amatrix[index1].im = (double) matrix[2*index2 + 1];
         }
     }
  }

/*
** zgeco factors a complex*16 matrix by gaussian elimination
** and estimates the condition of the matrix.
*/

  (void)zgeco_(amatrix,&rows,&cols,ipvt,&rcond,zvector);

/*
** if the condition of the matrix is less than zero, then zgesl won't
** function properly.
*/

  if(rcond<=0.0){
     (void)fprintf(stderr,"%s:  condition of matrix less than 0.\n",
           program);
     return(0);
  }

  if(rcond+1.0==1.0){
     (void)fprintf(stderr,
     "%s:  WARNING - condition of matrix is sufficiently small that results may be inaccurate.\n",
     program);
  }

/*
** zgesl solves the complex*16 system
** a * x = b using the factors computed by zgeco
*/

  (void)zgedi_(amatrix,&rows,&cols,ipvt,det,zvector,&job);

/*
** copy the data to imatrix and get the hell outa here....
*/

  if(type == 0){
     for(j=0;j<rows;j++){
         for(k=0;k<cols;k++){
            imatrix[j+k*cols] = (double) amatrix[j*cols+k].re;
         }
     }
  }else{
     for(j=0;j<rows;j++){
         for(k=0;k<cols;k++){
            index1 = j*cols + k;
            index2 = j + k*cols ;
            imatrix[2*index2] = (double) amatrix[index1].re;
            imatrix[2*index2 + 1] = (double) amatrix[index1].im;
         }
     }
  }

  return(1);
}
/* -library_code_end */
