#include <windows.h>
#include <commctrl.h>
#include <commdlg.h>
#include <richedit.h>
#include <stdio.h>

#include "header.h"
#include <ctype.h>
extern HINSTANCE hInstance ;

char szSourceFilter[] = 
			"Source files (*.c,*.cpp)\0*.c;*.cpp\0"
			"Headers (*.h,*.p)\0*.h;*.p\0"
			"Assembly files (*.asm)\0*.asm\0"
			"Resource files (*.rc)\0*.rc\0"
			"Any file\0*.*\0" ;

char szProjectFilter[] =
			"Project files (*.prj)\0*.prj\0" ;

char szTargetFilter[] = 
			"Executables (*.exe)\0*.exe\0"
			"DLLs (*.dll)\0*.dll\0"
			"Librarys (*.lib)\0*.lib\0" ;

static char szFileName[10000],szFileTitle[260] ;
static char szDefExt[] = "" ;
void setofndata(OPENFILENAME * ofn, char *name, HWND handle, char *dir, char *filter)
{
	memset(ofn,0,sizeof(*ofn)) ;
	if (name)
		strcpy(szFileName,name) ;
	else
		szFileName[0] = 0 ;
	szFileTitle[0] = 0 ;
	ofn->lStructSize = sizeof(OPENFILENAME) ;
	ofn->hwndOwner = handle ;
	ofn->hInstance = hInstance ;
	ofn->lpstrFilter = filter ;
	ofn->nFilterIndex = 1 ;
	ofn->lpstrFile = szFileName ;
	ofn->nMaxFile = 260 ;
	ofn->lpstrFileTitle = szFileTitle ;
	ofn->nMaxFileTitle = 260 ;
	ofn->lpstrInitialDir = dir ;
   ofn->Flags = OFN_EXPLORER;
	ofn->lpstrDefExt = 0 ;
}
void savedir (char *name, char *reg) 
{
	char buf[260],*p ;
	strcpy(buf,name) ;
	p = strrchr(buf,'\\') ;
	if (p)
		*p = 0 ;
	else {
		p = strrchr(buf,':') ;
		if (p) {
			*(++p) = '\\' ;
			*(++p) = 0 ;
		} else
			buf[0] = 0 ;
	}
	StringToProfile(reg,buf) ;	
	
}
int  OpenFileDialog(OPENFILENAME *ofn, char *name, HWND handle, int new, int multiple, char *filter, char *reg)
{
	char cwd[256] ;
	HFILE xhandle ;
	setofndata(ofn, name,handle,(char *)ProfileToString(reg,getcwd(cwd,256)),filter) ;
	if (!new)
		ofn->Flags |= OFN_CREATEPROMPT ;
   if (multiple)
      ofn->Flags |= OFN_ALLOWMULTISELECT ;
	xhandle = GetOpenFileName(ofn) ;
	if (xhandle && xhandle != HFILE_ERROR) {
		_lclose(xhandle) ;
		savedir(szFileName,reg) ;
		return 1 ;
	}
	return 0 ;
}
int SaveFileDialog(OPENFILENAME *ofn, char *name, HWND handle, int saveas,char *filter, char*reg)
{
	char cwd[256] ;
	HFILE xhandle ;
	setofndata(ofn, name,handle,(char *)ProfileToString(reg,getcwd(cwd,256)),filter) ;
	if (saveas)
		 ofn->Flags |= OFN_OVERWRITEPROMPT ;
	xhandle = GetSaveFileName(ofn) ;
	if (xhandle && xhandle != HFILE_ERROR) {
		_lclose(xhandle) ;
		savedir(szFileName,reg) ;
		return 1 ;
	}
	return 0 ;
}