/* \file SerialToVec.cpp
 * \brief: convert a serial vector on all cpus into a parallel vector
 */

#ifdef HAVE_CONFIG_H
	#include <config.h>
#else
#error "Cannot compile with HAVE_CONFIG_H symbol! run configure first!"
#endif

/*Petsc includes: */
#include "petscmat.h"
#include "petscvec.h"
#include "petscksp.h"

#include "../../../shared/shared.h"

Vec  SerialToVec(double* vector,int vector_size){

	int i;

	/*output: */
	Vec outvector=NULL;

	/*petsc indices: */
	int* idxn=NULL;
	double* values=NULL;
	int lower_row,upper_row,range;
	
		
	/*Create parallel vector: */
	outvector=NewVec(vector_size);

	/*plug values from local vector into new parallel vector: */
	VecGetOwnershipRange(outvector,&lower_row,&upper_row);
	upper_row--;
	range=upper_row-lower_row+1;    

	if (range){
		idxn=xNew<int>(range); 
		values=xNew<double>(range);
		for (i=0;i<range;i++){
			idxn[i]=lower_row+i;
			values[i]=vector[idxn[i]];
		}

		VecSetValues(outvector,range,idxn,values,INSERT_VALUES);
	}


	/*Assemble vector: */
	VecAssemblyBegin(outvector);
	VecAssemblyEnd(outvector);

	/*Free ressources:*/
	xDelete<int>(idxn);
	xDelete<double>(values);

	return outvector;
}
