%% Function selfpivot( M ) 
%%
%% By: Michael K. Pellegrino
%%
%% input: M = a kxn matrix
%% output: ret = M after a pivot
%%

function [ret] = selfpivot( M )
  [nrow,ncol]=size( M );
  phase1=0;
  crownsrule=0;
  A=[];
  B=[];

  %% is all of B positive? ie... do we need a phase 1?
  for( i=1:nrow-1)
    
    B=[B M(i,ncol)];

    if( M(i,ncol) < 0 )
      phase1=1;
    endif
  endfor


  if( phase1>0 )
    for( i=1:nrow-1)
      if( M(i,ncol)==min(B) )
	phase1row=i;
      endif
    endfor
    phase1col=firstnegative( M(phase1row,:) );
    if( phase1col < 0 )
      disp( "Feasible Set is Empty!" );
      return
    endif

    %% is all of Region A's Column positive? ie... do we need Crown's Rule?
    for( i=1:nrow-1)
      A=[A M(i,phase1col)];
      if( M(i,phase1col) < 0 )
	crownsrule+=1;
      endif
    endfor
    if( crownsrule==nrow-1 )
      %%then we need crowns rule
      pcol=-1*M(:,phase1col);
      rcol=-1*M(:,ncol);
      temp=[ pcol rcol ];
      phase1row= pivotrowmax(pivotratios( temp, 1 ));
    endif
    disp( "Phase 1 Pivot to: " );
    M=pivot( M, phase1row, phase1col )
    phase1=0;
  endif

  [r,c]=pivotelement( M );
  [r, c];
  if(r == nrow) 
    disp( "no more pivots!" );
    ret = M;
    return;
  endif
  if( c == ncol )
    disp( "no more pivots!" );
    ret = M;
    return;
  endif    
  if( r == -1 )
    disp( "no more pivots!" );
    ret = M;
    return;
  endif
  if( c == -1 )
    disp( "no more pivots!" );
    ret = M;
    return;
  endif
  ret=pivot( M, r, c );
endfunction
