You write `//    PetscErrorCode ecode =` quite often.
If PETSc offers error management it would make sense to make use of it such that the programme doesn't simply crash if anything goes wrong...