(*********************************************************************************
* Copyright: Bernecker+Rainer
* Author:    Mikael Regard
* Created:   Sep 12, 2019/8:21 AM 
 *********************************************************************************
 * Description:

 * 
 *Input:

 *
 *
 * Output:

 *********************************************************************************)


FUNCTION_BLOCK PM_GetMacroList	
	CASE ReadDirState OF	
		DIR_WAIT:
			IF(Read)THEN
				ReadDirState := DIR_INFO;
			END_IF;
		
		DIR_INFO:
			DirInfo_0.enable := TRUE;
			DirInfo_0.pDevice	:= ADR(FileDevice);
			DirInfo_0.pPath		:= 0;
			DirInfo_0();
			
			
			DirStatus 	:= DirInfo_0.status;
			DirNum 	:= DirInfo_0.dirnum;
			NumOfMacro 	:= DirInfo_0.filenum;
			IF(DirStatus = ERR_OK)THEN
				FileCount := 0;
				ReadDirState := DIR_READ;
				FOR i := 0 TO NUM_MACRO_FILES DO
					MacroList[i] := '';
				END_FOR;								
			ELSIF(DirStatus = fiERR_DIR_NOT_EXIST)THEN
				ReadDirState := DIR_CREATE;
			ELSIF(DirStatus <> ERR_FUB_BUSY)THEN
				ErrorID := DirStatus;
				ReadDirState := DIR_ERROR;
			END_IF;
			
				
		DIR_CREATE:
			DirCreate_0.enable := TRUE;
			DirCreate_0.pDevice	:= ADR(FileDevice);
			DirCreate_0.pName	:= ADR('Macro');
			DirCreate_0();
			DirStatus := DirCreate_0.status;			
			IF(DirStatus = ERR_OK)THEN
				ReadDirState := DIR_WAIT;
			ELSIF(DirStatus <> ERR_FUB_BUSY)THEN
				IF(DirStatus = fiERR_SYSTEM)THEN
					ErrorID := FileIoGetSysError();
				ELSE
					ErrorID := DirStatus;
				END_IF;
				ReadDirState 	:= DIR_ERROR;
			END_IF;	
			
		DIR_READ:
			IF((FileCount < UDINT_TO_INT(NumOfMacro)) AND (FileCount < USINT_TO_INT(NUM_MACRO_FILES)))THEN
				DirRead_0.enable 	:= TRUE;
				DirRead_0.pDevice	:= ADR(FileDevice);
				DirRead_0.pPath		:= 0;
				DirRead_0.entry	 	:= FileCount;
				DirRead_0.option	:= FILE_FILE;
				DirRead_0.pData		:= ADR(ReadData);
				DirRead_0.data_len	:= SIZEOF(ReadData);
				DirRead_0();
				DirStatus			:= DirRead_0.status;				
				IF(DirStatus = ERR_OK)THEN
					brsmemcpy(ADR(MacroList[FileCount]),ADR(ReadData.Filename[0]),260);
					FileCount := FileCount +1;
				ELSIF(DirStatus <> ERR_FUB_BUSY)THEN
					IF(DirStatus = fiERR_SYSTEM)THEN
						ErrorID := FileIoGetSysError();
					ELSE
						ErrorID := DirStatus;
					END_IF;
					ReadDirState := DIR_ERROR;
				END_IF;
			ELSE
				ReadDirState := DIR_DONE;
			END_IF;
		
		DIR_DONE:
			IF(NOT(Read))THEN
				ReadDirState := DIR_WAIT;
			END_IF;
		
		DIR_ERROR:
			IF(NOT(Read))THEN
				ReadDirState := DIR_WAIT;
			END_IF;
								
	END_CASE;
	Error := ReadDirState = DIR_ERROR;
	Done  := (ReadDirState = DIR_DONE);
	Busy  := (ReadDirState <> DIR_ERROR) AND (ReadDirState<> DIR_WAIT);
	

	
	
END_FUNCTION_BLOCK



