/* --------------- memopad.c ----------- */

#include <stdio.h>
#include <stdlib.h>
#include <string.h>
#include <sys\types.h>
#include <sys\stat.h>
#include <dos.h>
#ifndef MSC
#include <dir.h>
#endif
#include "dflat.h"

extern DBOX FileOpen;

static char Untitled[] = "Untitled";
static int wndpos = 0;
static int DocumentCount = 0;

static int MemoPadProc(WINDOW, MESSAGE, PARAM, PARAM);
static void NewFile(WINDOW);
#ifdef INCLUDE_DIALOG_BOXES
static void SelectFile(WINDOW);
#endif
static void PadWindow(WINDOW, char *);
static void OpenPadWindow(WINDOW, char *);
static void LoadFile(WINDOW, int);
static void PrintPad(WINDOW);
static void SaveFile(WINDOW, int);
static int EditorProc(WINDOW, MESSAGE, PARAM, PARAM);
static char *NameComponent(char *);

void main(int argc, char *argv[])
{
	int x,y;
	WINDOW wnd;
	init_messages();
	SendMessage(NULLWND, CURRENT_KEYBOARD_CURSOR, LPARAM(&x), LPARAM(&y));
	SendMessage(NULLWND, HIDE_CURSOR, 0, 0);

	wnd = CreateWindow(APPLICATION,
						"D-Flat MemoPad " VERSION,
						0, 0, -1, -1,
						MainMenu,
						NULL,
						MemoPadProc,
						MOVEABLE | SIZEABLE
#ifdef INCLUDE_MULTIDOCS
								 | HASBORDER
#endif
						);

	SendMessage(wnd, SETFOCUS, TRUE, 0);

	DeactivateCommand(MainMenu, ID_SAVE);
	DeactivateCommand(MainMenu, ID_SAVEAS);
	DeactivateCommand(MainMenu, ID_PRINT);

#ifdef INCLUDE_MULTIDOCS
	while (argc > 1)	{
		PadWindow(wnd, argv[1]);
		--argc;
		argv++;
	}
#else
	if (argc > 1)
		PadWindow(wnd, argv[1]);
#endif

	while (dispatch_message())
		;

	SendMessage(NULLWND, KEYBOARD_CURSOR, x, y);
	SendMessage(NULLWND, SHOW_CURSOR, 0, 0);
}

static void PadWindow(WINDOW wnd, char *FileName)
{
	int ax, criterr = 1;
	struct ffblk ff;
	char path[64];
	char *cp;
	CreatePath(path, FileName, FALSE, FALSE);
	cp = path+strlen(path);
	CreatePath(path, FileName, TRUE, FALSE);

	while (criterr == 1)	{
		ax = findfirst(path, &ff, 0);
		criterr = TestCriticalError();
	}
	while (ax == 0 && !criterr)	{
		strcpy(cp, ff.ff_name);
		OpenPadWindow(wnd, path);
		ax = findnext(&ff);
	}
}

static int MemoPadProc(WINDOW wnd, MESSAGE msg, PARAM p1, PARAM p2)
{
	switch (msg)	{
		case COMMAND:
			switch ((int)p1)	{
                case ID_NEW:
                    NewFile(wnd);
                    break;
#ifdef INCLUDE_DIALOG_BOXES
                case ID_OPEN:
                    SelectFile(wnd);
                    break;
#endif
                case ID_SAVE:
                    SaveFile(inFocus, FALSE);
					break;
#ifdef INCLUDE_DIALOG_BOXES
                case ID_SAVEAS:
                    SaveFile(inFocus, TRUE);
                    break;
#endif
                case ID_PRINT:
                    PrintPad(inFocus);
                    break;
				case ID_ABOUT:
					MessageBox(
						"About D-Flat and the MemoPad",
						"D-Flat is an operating environment\n"
						"that implements the SAA/CUA user\n"
						"interface in a C language library.\n"
						"    ------------------------ \n"
						"The MemoPad is a multiple document\n"
						"text editor that demonstrates the\n"
						"use of D-Flat.");
					break;
				default:
					break;
			}
			break;
		default:
			break;
	}
	return DefaultWndProc(wnd, msg, p1, p2);
}

/*
 *  The New command. Open an empty editor window
 */
static void NewFile(WINDOW wnd)
{
    OpenPadWindow(wnd, Untitled);
}

#ifdef INCLUDE_DIALOG_BOXES
/*
 *  The Open... command. Select a file 
 */
static void SelectFile(WINDOW wnd)
{
    char FileName[64];
    if (DlgOpenFile("*.PAD", FileName))	{
#ifdef INCLUDE_MULTIDOCS
		/* --- see if the document is already in a window --- */
		WINDOW wnd1 = GetFirstChild(wnd);
		while (wnd1 != NULLWND)	{
			if (stricmp(FileName, wnd1->extension) == 0)	{
				SendMessage(wnd1, SETFOCUS, TRUE, 0);
				SendMessage(wnd1, RESTORE, 0, 0);
				return;
			}
			wnd1 = GetNextChild(wnd);
		}
#endif
        OpenPadWindow(wnd, FileName);
	}
}
#endif

/*
 *  open a document window and load a file
 */
static void OpenPadWindow(WINDOW wnd, char *FileName)
{
    static WINDOW wnd1 = NULLWND;
    struct stat sb;
	char *Fname = FileName;
	char *ermsg;
    if (strcmp(FileName, Untitled))	{
		if (stat(FileName, &sb))    {
			if ((ermsg = malloc(strlen(FileName)+20)) != NULL)	{
				strcpy(ermsg, "No such file as\n");
				strcat(ermsg, FileName);
		        ErrorMessage(ermsg);
				free(ermsg);
			}
    	    return;
	    }
		Fname = NameComponent(FileName);
	}
#ifdef INCLUDE_MULTIDOCS
	wndpos += 2;
	if (wndpos == 20)
		wndpos = 2;
#else
	if (wnd1 != NULLWND)
		SendMessage(wnd1, CLOSE_WINDOW, 0, 0);
#endif

	wnd1 = CreateWindow(EDITBOX,
				Fname,
#ifdef INCLUDE_MULTIDOCS
				(wndpos-1)*2, wndpos, 10, 40,
#else
				GetClientLeft(wnd),GetClientTop(wnd),
				ClientHeight(wnd),ClientWidth(wnd),
#endif
				NULL, wnd, EditorProc,
#ifdef INCLUDE_MULTIDOCS
				SHADOW     |
				MINMAXBOX  |
				CONTROLBOX |
#endif
				VSCROLLBAR |
				HSCROLLBAR |
				MOVEABLE   |
				HASBORDER  |
				SIZEABLE   |
				MULTILINE
	);
    if (strcmp(FileName, Untitled))	{
		if ((wnd1->extension = malloc(strlen(FileName)+1)) != NULL)	{
			strcpy(wnd1->extension, FileName);
    	    LoadFile(wnd1, (int) sb.st_size);
		}
	}
	SendMessage(wnd1, SETFOCUS, TRUE, 0);
}

/*
 *  Load the notepad file into the editor text buffer
 */
static void LoadFile(WINDOW wnd, int tLen)
{
    char *Buf;
    FILE *fp;

    if ((Buf = malloc(tLen+1)) != NULL)    {
        if ((fp = fopen(wnd->extension, "rt")) != NULL)    {
            memset (Buf, 0, tLen+1);
            fread(Buf, tLen, 1, fp);
		    SendMessage(wnd, SETTEXT, LPARAM(Buf), 0);
            fclose(fp);
        }
		free(Buf);
    }
}

/*
 *  print the current notepad
 */
static void PrintPad(WINDOW wnd)
{
	char *text;

	/* ---------- print the file name ---------- */
	fputs("\r\n", stdprn);
	fputs(GetTitle(wnd), stdprn);
	fputs(":\r\n\n", stdprn);

	/* ---- get the address of the editor text ----- */
	text = GetText(wnd);

	/* ------- print the notepad text --------- */
	while (*text)	{
		if (*text == '\n')
			fputc('\r', stdprn);
		fputc(*text++, stdprn);
	}

	/* ------- follow with a form feed? --------- */
	if (YesNoBox("Form Feed?"))
		fputc('\f', stdprn);
}

static void SaveFile(WINDOW wnd, int Saveas)
{
	FILE *fp;
#ifdef INCLUDE_DIALOG_BOXES
	if (wnd->extension == NULL || Saveas)	{
		char FileName[64];
		if (DlgSaveAs(FileName))	{
			if (wnd->extension != NULL)
				free(wnd->extension);
			if ((wnd->extension = malloc(strlen(FileName)+1)) != NULL)	{
				strcpy(wnd->extension, FileName);
				AddTitle(wnd, NameComponent(FileName));
				SendMessage(wnd, BORDER, 0, 0);
			}
		}
	}
#endif
	if (wnd->extension != NULL)	{
		if ((fp = fopen(wnd->extension, "wt")) != NULL)	{
			fwrite(GetText(wnd), strlen(GetText(wnd)), 1, fp);
			fclose(fp);
			wnd->TextChanged = FALSE;
		}
	}
}

static int EditorProc(WINDOW wnd, MESSAGE msg, PARAM p1, PARAM p2)
{
	switch (msg)	{
		case CREATE_WINDOW:
			if (DocumentCount == 0)	{
				ActivateCommand(MainMenu, ID_SAVE);
				ActivateCommand(MainMenu, ID_SAVEAS);
				ActivateCommand(MainMenu, ID_PRINT);
			}
			DocumentCount++;
			break;
		case CLOSE_WINDOW:
			if (wnd->TextChanged)	{
				char *cp = malloc(25+strlen(GetTitle(wnd)));
				if (cp != NULL)	{
					strcpy(cp, GetTitle(wnd));
					strcat(cp, "\nText changed. Save it?");
					if (YesNoBox(cp))
						SendMessage(GetParent(wnd), COMMAND, ID_SAVE, 0);
					free(cp);
				}
			}
			if (--DocumentCount == 0)	{
				DeactivateCommand(MainMenu, ID_SAVE);
				DeactivateCommand(MainMenu, ID_SAVEAS);
				DeactivateCommand(MainMenu, ID_PRINT);
			}
			wndpos = 0;
			if (wnd->extension != NULL)	{
				free(wnd->extension);
				wnd->extension = NULL;
			}
			break;
		default:
			break;
	}
	return DefaultWndProc(wnd, msg, p1, p2);
}

static char *NameComponent(char *FileName)
{
	char *Fname;
	if ((Fname = strrchr(FileName, '\\')) == NULL)
		if ((Fname = strrchr(FileName, ':')) == NULL)
			Fname = FileName-1;
	return Fname + 1;
}

