static char help[] = "Reads a PETSc matrix and transposes it.\n\
-fi <input_file> : input file\n\
-fo <output_file> : output file\n\n";


#include "petsc.h"
#include "petscmat.h" 

int main(int argc,char **args) {
  Mat A, Atrans;                /* matrix */
  PetscViewer fd, ispis, upisUFajl;               /* viewer */
  char file[2][PETSC_MAX_PATH_LEN];     /* input file name */
  PetscErrorCode ierr;
  PetscTruth flg,PreLoad = PETSC_FALSE;
  int Arows, Acols;

  PetscInitialize(&argc,&args,(char *)0,help);


  // gets command line parameters
  PetscOptionsGetString(PETSC_NULL,"-fi",file[0],PETSC_MAX_PATH_LEN-1,&flg);
  if (!flg) SETERRQ(1,"Must indicate binary file with the -fi option");
  
  PetscOptionsGetString(PETSC_NULL,"-fo",file[1],PETSC_MAX_PATH_LEN-1,&flg);
  if (!flg) SETERRQ(1,"Must indicate binary file with the -fo option");
  
  // loads a matrix from a binary file
  PetscViewerBinaryOpen(PETSC_COMM_WORLD,file[0],FILE_MODE_READ,&fd);
  MatLoad(fd,MATDENSE,&A);
  PetscViewerDestroy(fd);
  
  MatAssemblyBegin(A, MAT_FINAL_ASSEMBLY);
  MatAssemblyEnd(A, MAT_FINAL_ASSEMBLY); 
  
  
  // gets the dimensions of input matrix
  MatGetSize(A, &Arows, &Acols);
  // dimensions of new matrix are oposite: rows are columns and columns are rows
  MatCreate(PETSC_COMM_WORLD, &Atrans);
  MatSetSizes(Atrans, PETSC_DECIDE, PETSC_DECIDE, Acols, Arows);
  MatSetFromOptions(Atrans);
  //transposes the input matrix 
  ierr = MatTranspose(A, MAT_REUSE_MATRIX, &Atrans);
  MatAssemblyBegin(Atrans, MAT_FINAL_ASSEMBLY);
  MatAssemblyEnd(Atrans, MAT_FINAL_ASSEMBLY);  
  /*
   * output to the screen, for presentation purpose
   * commented out
  PetscViewerCreate(PETSC_COMM_WORLD, &ispis);
  PetscViewerSetType(ispis, PETSC_VIEWER_ASCII);
  PetscViewerSetFromOptions(ispis);

  PetscPrintf(PETSC_COMM_WORLD, "\nMatrica A: \n");
  MatView(A, ispis);

  PetscPrintf(PETSC_COMM_WORLD, "\nMatrica Atrans: \n");
  MatView(Atrans, ispis);
  */
  
  // prepares the viewer for output to a binary file
  ierr = PetscViewerBinaryOpen(PETSC_COMM_WORLD,file[1],FILE_MODE_WRITE,&upisUFajl);CHKERRQ(ierr);
  // writes matrix to a file
  ierr = MatView(Atrans,upisUFajl);CHKERRQ(ierr);

  PetscFinalize();
  
  return 0;
}
