
(* TODO: Add your comment here *)
FUNCTION_BLOCK WriteFileOnDisk
	IF(Execute = FALSE)THEN
		step := 0;
		Done := FALSE;
	END_IF;
	
	CASE step OF
		0:	//Try to open the file		
			IF(Execute = TRUE)THEN
				file_open.enable := TRUE;
				file_open.pDevice := ADR(file_device);
				file_open.pFile := ADR(file_path);
				file_open.mode := FILE_RW;
				file_open();
				IF(file_open.status = 0)THEN //file opened successfully
					step := 2;
					ident := file_open.ident;
				ELSE
					IF(file_open.status = 20708)THEN //file doesn't exist
						step := 1;
					ELSIF(file_open.status <> ERR_FUB_BUSY)THEN
						step := 69;		
					END_IF;
				END_IF;
			END_IF;
		1:  //Create file if it doesn't exist
			file_create.enable := TRUE;
			file_create.pDevice := ADR(file_device);
			file_create.pFile := ADR(file_path);
			file_create();
			IF(file_create.status = 0)THEN	
				step := 2;		
				ident := file_create.ident;
			ELSIF(file_create.status <> ERR_FUB_BUSY)THEN
				step := 69;
			END_IF;
		2:  //Write to file
			file_write.enable := TRUE;
			file_write.ident := ident;
			file_write.offset := 0;
			file_write.pSrc := data_adr;
			file_write.len := file_size;
			file_write();
			IF(file_write.status = 0)THEN
				step := 3;
			ELSIF(file_write.status	<> ERR_FUB_BUSY)THEN
				step := 69;
			END_IF;
		3:	//close file
			file_close.enable := TRUE;
			file_close.ident := ident;
			file_close();
			IF(file_close.status = 0)THEN
				step := 4;
			ELSIF(file_close.status <> ERR_FUB_BUSY)THEN
				step := 69;
			END_IF;
		4:
			Done := TRUE;
	END_CASE
END_FUNCTION_BLOCK
