
(* LinearProgramming.m *)

Begin["System`"]

Unprotect[ LinearProgramming]

Clear[ LinearProgramming]

LinearProgramming::usage = 
"LinearProgramming[c, m, b] finds the vector x which minimizes
the quantity c.x subject to the constraints m.x >= b and x >= 0."

Begin["`Private`"]

AreWeValid[vector1_, matrix_, vector2_]:= 
	Block[{length1, length2, length3, length4},
	If[!(VectorQ[vector1, NumberQ]&&
	MatrixQ[matrix, NumberQ]&&VectorQ[vector2, NumberQ]),
	 Return[False]];
	length1=Length[vector1];
	length2=Length[matrix];
	length3=Length[vector2];
	length4=Length[matrix[[1]]];
	If[length2!=length3, Return[False]];
	If[Length1!=length4, Return[False]];
	True]

LinearProgramming[vector1_, matrix_, vector2_]:= 
	Block[{tempans=LPAux[vector1, matrix, vector2]},
	Map[#[[2]]&, tempans[[2]]]/; !SameQ[Head[tempans],
							ConstrainedMin]]/; AreWeValid[vector1, matrix, vector2]

LPAux[vector1_, matrix_, vector2_]:=
	Block[{vars=Table[OptVar[i], {i, Length[vector1]}],
		nopt, neqns,
		tempans, indicator},
		nopt = vars . vector1;	
		neqns = Map[( # . vars) &, matrix] - vector2;
	        neqns = Map[(# >= 0) &, neqns];
		tempans = ConstrainedMin[nopt, neqns, vars]
	        ]	

Protect[LinearProgramming]

End[]
End[]

Null
