// E04: genuine LAPACKE thin SVD for an independent 4x2 matrix.
#include <lapacke.h>
#include <algorithm>
#include <cmath>
#include <iomanip>
#include <iostream>
#include <vector>
int main() {
    constexpr lapack_int m=4,n=2;
    const std::vector<double> original {1,0, 0,2, 1,1, 2,0};
    std::vector<double> a=original; // LAPACKE may overwrite its input
    std::vector<double> s(n),u(m*n),vt(n*n),superb(std::max(1,int(n)-1));
    const lapack_int info=LAPACKE_dgesvd(LAPACK_ROW_MAJOR,'S','S',
        m,n,a.data(),n,s.data(),u.data(),n,vt.data(),n,superb.data());
    if(info!=0) { std::cerr << "LAPACKE_dgesvd error; info="<<info<<'\n'; return 2; }
    double sqerror=0.,maxerror=0.,orthU=0.,orthV=0.;
    for(int i=0;i<m;++i) for(int j=0;j<n;++j) {
        double rec=0.;
        for(int k=0;k<n;++k) rec+=s[k]*u[i*n+k]*vt[k*n+j];
        const double delta=rec-original[i*n+j];
        sqerror+=delta*delta; maxerror=std::max(maxerror,std::abs(delta));
    }
    for(int k=0;k<n;++k) for(int l=0;l<n;++l) {
        double du=0.,dv=0.;
        for(int i=0;i<m;++i) du+=u[i*n+k]*u[i*n+l];
        for(int i=0;i<n;++i) dv+=vt[k*n+i]*vt[l*n+i];
        orthU=std::max(orthU,std::abs(du-(k==l?1.:0.)));
        orthV=std::max(orthV,std::abs(dv-(k==l?1.:0.)));
    }
    std::cout<<std::scientific<<std::setprecision(10);
    std::cout<<"E04 | 4x2 thin SVD; singular values: "<<s[0]<<", "<<s[1]<<'\n';
    std::cout<<"U shape 4x2; VT shape 2x2; row-major indices U[i*n+k], VT[k*n+j]\n";
    std::cout<<"reconstruction Frobenius error="<<std::sqrt(sqerror)<<'\n';
    std::cout<<"maximum entrywise error="<<maxerror<<'\n';
    std::cout<<"orthogonality max |U^TU-I|="<<orthU<<"; max |VV^T-I|="<<orthV<<'\n';
    return (maxerror<1e-12 && orthU<1e-12 && orthV<1e-12) ? 0 : 1;
}
