#include once "window9.bi"

Function SaveFileRequester(ByRef Title As USTRING, _
							ByRef curentdir As USTRING, _
							ByRef sPattern As USTRING, _
							ByVal defaultsetpattern As bool, _
							ByRef templateName As USTRING, _
							ByVal hParentWin as HWND = 0) As USTRING export
	dim as HWND hwFocus = GetFocus()
	Dim ofn       As OPENFILENAME
	Dim fbguiTemp As Integer
	#ifdef UNICODE
		Dim filename  As WString * MAX_PATH+1	
		Dim DefExt As USTRING = wspace(10)	
		dim as Long iLen = len(sPattern)	
		dim as UByte ptr pPatternDest = callocate((iLen+2)*2)
		if pPatternDest = 0 then
			dim as USTRING sRet
			return sRet
		EndIf
		dim iIndex as Long	
		dim as UByte ptr pPatternString = cast(Byte ptr , *sPattern)	
		for i as Long = 0 to iLen*2		
			if pPatternString[i] = &h7C then			
				pPatternString[i] = 0			
			EndIf		
			pPatternDest[iIndex] = pPatternString[i]		
			iIndex +=1		
		Next			
	#else	
		Dim filename  As ZString * MAX_PATH+1	
		Dim DefExt As USTRING*10		
	#EndIf
		
	filename = templateName
	With ofn
		.hwndOwner        = hParentWin
		.nMaxFileTitle    = SizeOf(Title)
		.nMaxFile         = SizeOf(filename)
		.lStructSize      = SizeOf(OPENFILENAME)
		.Flags            = OFN_EXPLORER Or OFN_FILEMUSTEXIST Or OFN_OVERWRITEPROMPT
		#ifdef UNICODE
			.lpstrFilter      = cast(LPCWSTR,pPatternDest)
			.lpstrFile        = @filename
			.lpstrFileTitle   = cast(any ptr , *Title)
			.lpstrInitialDir  = Cast(LPCTSTR,*curentdir)
			.lpstrTitle       = Cast(LPCTSTR,*Title)		
			If defaultsetpattern=1 Then
				.lpstrDefExt = *DefExt
			EndIf			
		#else	
			.lpstrFilter      = Cast(LPCTSTR,StrPtr(sPattern))
			.lpstrFile        = StrPtr(filename)	
			.lpstrFileTitle   = StrPtr(Title)		
			.lpstrInitialDir  = Cast(LPCTSTR,StrPtr(curentdir))
			.lpstrTitle       = Cast(LPCTSTR,StrPtr(Title))		
			If defaultsetpattern=1 Then
				.lpstrDefExt = StrPtr(DefExt)
			EndIf			
		#EndIf
	End With
	dim as USTRING sRet
	if GetSaveFileName( @ofn ) then
		sRet = filename
	end If
	#ifdef UNICODE		
		if pPatternDest then deallocate(pPatternDest)		
	#EndIf
	SetFocus(hwFocus)
	return sRet
End Function
