FUNCTION_BLOCK "FB_Test_RotierenMT"
{ S7_Optimized_Access := 'TRUE' }
VERSION : 0.1
   VAR_INPUT 
      stInStorageLine : Array[1..21] of "stStorageLine";
      stInMFRState : "UDT_MFRState";
      nInExitJamCount : UInt;
      nInNoOfLines : Int;
      nInNoOfPositions : Int;
      nInDestDefault : Int;
      xInStart : Bool;
   END_VAR

   VAR_OUTPUT 
      stInOutExitJamDestination : Int;
   END_VAR

   VAR_IN_OUT 
      stInOutBlockRemovalModul : "udt_LagerTROModulHMI";
   END_VAR

   VAR RETAIN
      nState : Int := 1;
      nLine : Int;
      xFound : Bool;
   END_VAR

   VAR_TEMP 
      i : Int;
   END_VAR


BEGIN
	CASE #nState OF
	    1: //Wait TRO Ready
	        IF (#nLine <= 0) OR (#nLine > #nInNoOfLines) THEN
	            #nLine := 1;
	        END_IF;
	        
	        //Find line
	        IF NOT #xFound THEN
	            FOR #i := 1 TO #nInNoOfLines DO
	                IF #stInStorageLine[#i].stData.Status.nCount >= #nInNoOfPositions THEN
	                    #nLine := #i;
	                    #xFound := TRUE;
	                    EXIT;
	                END_IF;
	            END_FOR;
	        END_IF;
	        
	        IF #xFound AND #stInMFRState.xReady AND #xInStart
	        THEN
	            #nState := 2;
	        END_IF;
	        
	    2: //Select Line and Start
	        
	        #xFound := FALSE;
	        #stInOutBlockRemovalModul.str_Ctrl.n_RemovalLine := #nLine;
	        #stInOutBlockRemovalModul.str_Ctrl.x_StartRemoval := TRUE;
	        
	        IF #stInMFRState.xBusy THEN
	            #nState := 3;
	        END_IF;
	    3:
	        #xFound := FALSE;
	        IF #stInMFRState.xReady
	            AND (#nInExitJamCount = 0)
	        THEN
	            #nLine += 1;
	            IF #nLine > #nInNoOfLines THEN
	                #nLine := 1;
	            END_IF;
	            #nState := 1;
	        END_IF;
	END_CASE;
	
	IF #nLine >= 1 AND #nLine < #nInNoOfLines THEN
	    #stInOutExitJamDestination := #nInDestDefault + #nLine + 1;
	ELSE
	    #stInOutExitJamDestination := #nInDestDefault + 1;
	END_IF;
END_FUNCTION_BLOCK

