##This is the implementation of the Gauss-Jacques method
##It is an extension of function inv2 by Mohamed badwi
##Created by Abraham Jacques on Septembner, 12th 2018.
##Copyright 2018 Abraham Jacques 
##Copyright 2018 GNU General Public Licence v2 

##The function receives a square matrix and a modular value
##It obtains the modular inverse matrix in Zn+



function y=invmodJac(x, m)
row = size(x,1);
col = size(x,2);
    if ~isequal(row,col)
        errordlg('the matrix must be sequared')
    else
        newmat = [x,eye(row,col)];
        ##METHOD STARTS HERE
        for i = 1:col #pivots
            pivot = newmat(i,i);
            theX = findX(m, pivot);
            
            yidash = i+1;
            if yidash > col
                yidash= yidash - col;
            end
            for j = i+1:i+col #col of pivot matrix
                ##row of the pivot matrix
                rowyidash = yidash+ (row-2);
                if rowyidash > row
                    rowyidash = rowyidash - row;
                    yidashmat = [yidash:row 1:rowyidash];
                else
                    yidashmat = yidash:rowyidash;
                end
                
                for k = yidashmat #The multiplicative inverse found and mod m
                    newmat(k,j) = (newmat(k,j)-((newmat(k,i)*newmat(i, j))*theX));
                    newmat(k, j) = mod(newmat(k, j), m);               
                end
            end
            ##The multiplicative inverse mod m
            newmat(i,:)= mod((newmat(i,:)*theX), m);  
            newmat(:,i)=0;%pivot column
            newmat(i,i)=1;   
        end
    end
    y = newmat(:,col+1:end);
end

##It finds the multiplicative inverse of each pivots 
##It can be any existed function to do so.

function y=findX(modu, num)
  y=0;
     if num>=1 
        for i=1:999
          total=0;
      
          total = ((modu*i)+1)/num;
      
           if(total-fix(total)==0)
            y=fix(total);
          endif 
      
        endfor 
      else
      y=num;
  endif #general
 endfunction
 