 /*
  * Khoros: $Id: lmsvd.c,v 1.4 1992/03/20 23:47:15 dkhoros Exp $
  */

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

 /*
  * $Log: lmsvd.c,v $
 * Revision 1.4  1992/03/20  23:47:15  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: lmsvd.c
 >>>>
 >>>>      Program Name: msvd
 >>>>
 >>>> Date Last Updated: Tue Feb 25 01:00:46 1992 
 >>>>
 >>>>          Routines: lmsvd - the library call for msvd
 >>>>
 >>>>>>>>>>>>>>>>>>>>>>>>>>>>>>   <<<<<<<<<<<<<<<<<<<<<<<<<<<<<<*/


#include "vinclude.h"


/* -library_includes */
#define CLEANUP \
    {  /* cleanup workspace before leaving */ \
       if(amatrix!=NULL)free((char *)amatrix); \
       if(scvect!=NULL)free((char *)scvect); \
       if(ecvect!=NULL)free((char *)ecvect); \
       if(ucmatrix!=NULL)free((char *)ucmatrix); \
       if(vcmatrix!=NULL)free((char *)vcmatrix); \
       if(work!=NULL)free((char *)work); \
    } /* end of cleanup code */

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


/****************************************************************
*
* Routine Name: lmsvd - library call for msvd
*
* Purpose:
*    
*    compute the Singular Value Dcomposition of a matrix
*    
*    

* Input:
*    
*    image          image which contains one or more matrices of arbi-
*                   trary dimension that will be decomposed.
*    
*    

* Output:
*    
*    image          double or double complex matrix containing  the  U
*                   part of the decomposition of the input matrix.
*    
*    simage         double or double complex matrix containing  the  S
*                   part  of  the  decomposition  of  the of the input
*                   matrix.
*    
*    vimage         double or double complex matrix containing  the  V
*                   part  of  the  decomposition  of  the of the input
*                   matrix.
*    
*    Return Value:  1 on success, 0 on failure.
*    
*    

*
* Written By: Jeremy Worley
*    
*    Jeremy Worley Tue Feb 25 00:59:35 MST 1992
*              arguments rows  and  cols  to  lsvd()  were  explicitly
*              declared  and functions used in lmsvd() were explicitly
*              declared.
*    
*    

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


/* -library_def */
int lmsvd(image,simage,vimage)
  struct xvimage *simage, *vimage, *image;
/* -library_def_end */

/* -library_code */
{
  int i,uidx,vidx,sidx,rows,cols,bands,type;
  double *kern,*smatrix,*umatrix,*vmatrix;
  char *program = "lmsvd";
  int proper_num_images(),lvcast(),lsvd();
 
  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 should 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((smatrix = (double *)malloc(bands*rows*cols*(type+1)*sizeof(double)))
       ==NULL){
     (void)fprintf(stderr,"%s:  unable to allocate s matrix.\n",program);
     return(0);
  }

  if((umatrix = (double *)malloc(bands*rows*rows*(type+1)*sizeof(double)))
       ==NULL){
     (void)fprintf(stderr,"%s:  unable to allocate u matrix.\n",program);
     return(0);
  }

  if((vmatrix = (double *)malloc(bands*cols*cols*(type+1)*sizeof(double)))
       ==NULL){
     (void)fprintf(stderr,"%s:  unable to allocate v matrix.\n",program);
     return(0);
  }

/*
** process all of the data
*/

   kern = (double *)(image->imagedata);
   for(i=0;i<bands;i++){
      uidx = (type+1)*rows*rows*i;
      sidx = (type+1)*rows*cols*i;
      vidx = (type+1)*cols*cols*i;
      if(!lsvd(&(umatrix[uidx]),&(smatrix[sidx]),&(vmatrix[vidx]),kern,
         rows,cols,type)){
         fprintf(stderr,"%s:  Failed call to static routine.\n",program);
         return(0);
      }

      kern += (type+1)*rows*cols;
   }

/*
** free up our junk and get the heck outa here.
*/

   simage->data_storage_type = vimage->data_storage_type = 
       image->data_storage_type;
   simage->row_size = cols;
   vimage->row_size = cols;
   vimage->col_size = cols;
   simage->col_size = rows;
   image->row_size = rows;
   image->col_size = rows;
   simage->num_data_bands = vimage->num_data_bands = bands;

   image->imagedata = (char *)umatrix;
   vimage->imagedata = (char *)vmatrix;
   simage->imagedata = (char *)smatrix;

   return(1);
}

/***********************************************************************
*
*  Routine Name: 
*
*          Date:
*        
*       Purpose:  
*
*         Input: 
*
*        Output: 
*
*    Written By:  
*
* Modifications:
*
***********************************************************************/

int lsvd(umatrix,smatrix,vmatrix,matrix,rows,cols,type)
  double *smatrix, *umatrix, *vmatrix, *matrix;
  int type,rows,cols;
{
  int   index1,index2,k,j;
  void zsvdc_(); 
  
  void swap();

  complex *amatrix,*scvect=NULL,*ecvect=NULL,*ucmatrix=NULL,
          *vcmatrix=NULL,*work=NULL;

  char *program = "lmsvd";
  int info;
  int job = 11; /* want both u and v */ 

/*
** test some junk
*/

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

  if(matrix==NULL || smatrix==NULL || umatrix==NULL || vmatrix==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);
  }

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

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

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

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

  vcmatrix = (complex *)malloc((unsigned)cols*cols*sizeof(complex));
  if(vcmatrix==NULL){
     fprintf(stderr,"%s:  [6]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++){
            index1 = k*rows + j;
            index2 = j*cols + k;
            amatrix[index1].re = matrix[index2];
            amatrix[index1].im = 0.0;
         }
     }
  }else{
     for(j=0;j<rows;j++){
         for(k=0;k<cols;k++){
            index1 = k*rows + j;
            index2 = j*cols + k;
            amatrix[index1].re = matrix[2*index2];
            amatrix[index1].im = matrix[2*index2 + 1];
         }
     }
  }

/*
** zsvdc pretty much does all of the work we need to do...
*/

  (void)zsvdc_(amatrix,&rows,&rows,&cols,scvect,ecvect,
               ucmatrix,&rows,vcmatrix,&cols,work,&job,&info);
  if(info!=0){
     fprintf(stderr,"%s: unable to generate correct singular values.\n",program);
     return(0);
  }

/*
** extract the resulting matrices from the complex work matrices and
** transpose them as we go.
*/

  if(type == 0){
     for(j=0;j<rows;j++){
         for(k=0;k<rows;k++){
              index1 = k*rows + j;
              index2 = j*rows + k;
              umatrix[index2] = ucmatrix[index1].re;
         }
     }
     for(j=0;j<cols;j++){
         for(k=0;k<cols;k++){
              index1 = k*cols + j;
              index2 = j*cols + k;
              vmatrix[index2] = vcmatrix[index1].re;
         }
     }
     for(j=0;j<rows;j++){
         for(k=0;k<cols;k++){
              /* index1 = k*rows + j; */
              index2 = j*cols + k;
              if(k==j){
                 smatrix[index2] = scvect[j].re;
              }else{
                 smatrix[index2] = 0.0;
              }
         }
     }
  }else{
     for(j=0;j<rows;j++){
         for(k=0;k<rows;k++){
              index1 = k*rows + j;
              index2 = j*rows + k;
              umatrix[2*index2] = ucmatrix[index1].re;
              umatrix[2*index2+1] = ucmatrix[index1].im;
         }
     }
     for(j=0;j<cols;j++){
         for(k=0;k<cols;k++){
              index1 = k*cols + j;
              index2 = j*cols + k;
              vmatrix[2*index2] = vcmatrix[index1].re;
              vmatrix[2*index2+1] = vcmatrix[index1].im;
         }
     }
     for(j=0;j<rows;j++){
         for(k=0;k<cols;k++){
              /* index1 = k*rows + j; */
              index2 = j*cols + k;
              if(k==j){
                 smatrix[2*index2] = scvect[j].re;
                 smatrix[2*index2+1] = scvect[j].im;
              }else{
                 smatrix[2*index2] = smatrix[2*index2+1] = 0.0;
              }
         }
     }
  }

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