/****************************************************************************

    PROGRAM: WizUnzip.c

    PURPOSE:  Windows Info-ZIP Unzip, an Unzipper for Windows
    FUNCTIONS:

        WinMain() - calls initialization function, processes message loop
        WizUnzipInit() - initializes window data and registers window
        WizUnzipWndProc() - processes messages
        About() - processes messages for "About" dialog box

    AUTHOR: Robert A. Heath,  157 Chartwell Rd. Columbia, SC 29210
	I place this source module, WizUnzip.c, in the public domain.  Use it as you will.
****************************************************************************/

#include <sys\types.h>
#include <sys\stat.h>
#include <time.h>                
#include <string.h>             
#include <windows.h>    /* required for all Windows applications */
#include <assert.h>    
#include "wizunzip.h"                /* specific to this program              */


#define MAXLISTBOXLINES 200 /* max records in list box 	*/

static char FIRSTUSE[] = "FirstUse"; /* first use keyword in WIN.INI */
char FORMAT_KEY[] = "Format"; 		/* Format keyword in WIN.INI		*/
char OVERWRITE_KEY[] = "Overwrite";	/* Overwrite keyword in WIN.INI		*/
char TRANSLATE_KEY[] = "Translate";	/* Translate keyword in WIN.INI		*/
char LBSELECTION_KEY[] = "LBSelection";	/* LBSelection keyword in WIN.INI */
char RECREATE_DIRS_KEY[] = "Re-createDirs"; /* re-create directory structure WIN.INI keyword 			*/
char UNZIP_TO_ZIP_DIR_KEY[] = "UnzipToZipDir"; /* unzip to .ZIP dir WIN.INI keyword */
												
/* Values for listbox selection WIN.INI keyword
 */
char *LBSelectionTable[] = {
	"extract", "display", "test" 
};
#define LBSELECTIONTABLE_ENTRIES (sizeof(LBSelectionTable)/sizeof(char *))

HANDLE hInst;                       /* current instance                      */
HMENU  hMenu;			    /* main menu handle			*/
HANDLE hAccTable;

HANDLE hHourGlass;			  /* handle to hourglass cursor	     */
HANDLE hSaveCursor;			  /* current cursor handle	     */
HANDLE hHelpCursor;			/* help cursor						*/
HANDLE hFixedFont;			/* handle to fixed font				*/
HANDLE hOldFont;			/* handle to old font				*/

int hFile;				  /* file handle		     */
HWND	hMainWnd;		  /* the main window handle. 				*/
HWND hWndHeaderLine1;			  /* list box header line 1 handle	*/
HWND hWndHeaderLine2;			  /* list box header line 1 handle	*/
HWND	hWndList;			  /* list box handle		*/
HWND hWndTotalLine1;			  /* list box total line 1 handle	*/
HWND hWndTotalLine2;			  /* list box total line 2 handle	*/
HWND hWndStatus;		/* status	(a.k.a. Messages) window */
HWND hDlgAbout;				/* handle to about box				*/
HWND hExtract;			/* extract button				*/
HWND hDisplay;			/*display button				*/
HWND hTest;				/* test button				*/
HWND hShowComment;			/* show comment button			*/
BOOL bHelp = FALSE;		/* Shift-F1 has been struck when TRUE		*/

/* Global values defined by WIN.INI settings:
 */
BOOL bRecreateDirs;	/* re-create directory structures when TRUE */
BOOL bTranslate = FALSE;	/* translate LF to CR-LF					*/
WORD wFormat = 0;		/* display format: 0 = short, 1 = long */
BOOL bOverwrite = FALSE;	/* overwrite or prompt: IDM_OVERWRITE, IDM_PROMPT */
BOOL bUnzipToZipDir = FALSE; /* unzip only to .ZIP directory		*/
WORD wLBSelection = IDM_LB_DISPLAY;	/* default listbox selection action */


BOOL bStatusMaxed = FALSE;	/* status box is maximized		*/

RECT Rect;				  /* dimension of the client window  */
HWND hDlgHelp;			  	  /* Help dialog handler	     */

HBRUSH hBrush ;			/* brush for  standard window backgrounds  */

/* File and Path Name variables
 */
char szAppName[] = "WizUnzip";		/* application title		*/
char szStatusClass[] = "MsgWndw";/* status window class	*/
char szFileName[80] = "";	/* fully-qualified file name in OEM char set */
char szDirName[MAX_DIRNAME_LEN+1] = "";  /* resultant Directory Name	*/
char szOrigDirName[MAX_DIRNAME_LEN+1];	/* original directory name		*/
int ofretval;		/* return value from initial open if filename given */

WORD	TotalZippedFiles;		/* total personal records in file	*/
WORD 	ListBoxLines; /* max list box lines showing on screen */
WORD MessageWinLines; /* max visible lines on message window  */
WORD wCommentLength ;			/* length of comment in .ZIP file	*/

/* Client window size factors:
 */
#ifdef NEEDME
short nLBVscrollMax;
short nLBVscrollPos = 0;
short nLBVscrollInc;	/* vertical scroll incr	*/
#endif



/* Forward References
 */
int PASCAL WinMain(HANDLE, HANDLE, LPSTR, int);
long FAR PASCAL WizUnzipWndProc(HWND, unsigned, WORD, LONG);


/****************************************************************************

    FUNCTION: DoCaption(HWND hWnd,  PSTR szOemFileName)
				szFileName is OEM char set.

    PURPOSE: Set new caption for main window

****************************************************************************/
void 
DoCaption(HWND hWnd, PSTR szOemFileName)
{
WORD wMenuState;
char szSimpleFileName[15];	/* just the 8.3 part in ANSI char set */
char szCaption[100];
PSTR pFileName;		/* pointer to simple filename				*/
BOOL	bIconic = IsIconic(hWnd);	/* is window iconic ?	*/

	/* point to simple filename in OEM char set					*/
	if ((pFileName = strrchr(szOemFileName, '\\')) ||
	    (pFileName = strrchr(szOemFileName, ':')))
			pFileName++;	/* point to filename				*/

	else
			pFileName = szOemFileName;

	OemToAnsi(pFileName, szSimpleFileName);
	(void)wsprintf(szCaption, "%s - %s %s %s", 
					(LPSTR)szAppName, 
					(LPSTR)(szSimpleFileName[0] ? 
						szSimpleFileName : "(No .ZIP file)"),
					(LPSTR)(!bIconic && szOrigDirName[0] ? " - " : ""),
					(LPSTR)(!bIconic ? szOrigDirName : ""));
    SetWindowText(hWnd, (LPSTR)szCaption);
	wMenuState = (WORD)(szSimpleFileName[0] ? MF_ENABLED : MF_GRAYED) ;
	EnableMenuItem(hMenu, IDM_SELECT_ALL, wMenuState|MF_BYCOMMAND); 
	EnableMenuItem(hMenu, IDM_DESELECT_ALL, wMenuState|MF_BYCOMMAND); 
}

/****************************************************************************

    FUNCTION: WinMain(HANDLE, HANDLE, LPSTR, int)

    PURPOSE: calls initialization function, processes message loop

    COMMENTS:

        This will initialize the window class if it is the first time this
        application is run.  It then creates the window, and processes the
        message loop until a WM_QUIT message is received.  It exits the
        application by returning the value passed by the PostQuitMessage.

****************************************************************************/

int PASCAL WinMain(hInstance, hPrevInstance, lpCmdLine, nCmdShow)
HANDLE hInstance;                            /* current instance             */
HANDLE hPrevInstance;                        /* previous instance            */
LPSTR lpCmdLine;                             /* command line                 */
int nCmdShow;                                /* show-window type (open/icon) */
{
    HWND hWnd;                               /* window handle                */
    MSG msg;                                 /* message                      */
    int	i;		/* index into name				*/
	OFSTRUCT OfStruct;					/* open file structure			*/
	char szBuffer[64];					/* option strings from WIN.INI	*/


    if (!hPrevInstance)                 /* Has application been initialized? */
        if (!WizUnzipInit(hInstance))
            return (NULL);              /* Exits if unable to initialize     */


	if (_fstrlen(lpCmdLine))			/* if filename passed on start-up	*/
	{
 		if ((ofretval = OpenFile(lpCmdLine, &OfStruct, OF_EXIST)) >= 0)
		{
			strcpy(szFileName, OfStruct.szPathName); /* save file name	*/
		}
	}
	/* Get initial Re-create dirs format
	 */
	GetProfileString(szAppName, RECREATE_DIRS_KEY, "no", szBuffer, sizeof(szBuffer));
	bRecreateDirs = (BOOL)(!stricmp(szBuffer, "yes"));

	/* Get translate flag
	 */
	GetProfileString(szAppName, TRANSLATE_KEY, "no", szBuffer, sizeof(szBuffer));
	bTranslate = (BOOL)(!stricmp(szBuffer, "yes"));

	/* Get initial display format: short or long
	 */
	GetProfileString(szAppName, FORMAT_KEY, "long", szBuffer, sizeof(szBuffer));
	wFormat = (WORD)(!stricmp(szBuffer, "long") ? 1 : 0);

	/* Get overwrite option: yes=IDM_OVERWRITE, no=IDM_PROMPT			*/
	GetProfileString(szAppName, OVERWRITE_KEY, "no", szBuffer, sizeof(szBuffer));
	bOverwrite = (BOOL)(!stricmp(szBuffer, "yes"));

	/* Get Unzip to .ZIP dir option: yes or no 							*/
	GetProfileString(szAppName, UNZIP_TO_ZIP_DIR_KEY, "no", szBuffer, sizeof(szBuffer));
	bUnzipToZipDir = (BOOL)(!stricmp(szBuffer, "yes"));

	/* Get default listbox selection operation
	 */
	GetProfileString(szAppName, LBSELECTION_KEY, "display", 
						szBuffer, sizeof(szBuffer));

	for (i = 0; i < LBSELECTIONTABLE_ENTRIES &&
		stricmp(LBSelectionTable[i], szBuffer) ; i++)
		;

	wLBSelection = IDM_LB_DISPLAY;		/* assume default is to display		*/
	if (i < LBSELECTIONTABLE_ENTRIES)
		wLBSelection = IDM_LB_EXTRACT + i;

    hWnd = CreateWindow(szAppName,                /* window class            */
     	szAppName,                                /* window name             */
        WS_OVERLAPPEDWINDOW,                      /* window style            */
        0,                            		            /* x position              */
        0,                            		            /* y position              */
        CW_USEDEFAULT,                            /* width                   */
        0,                           		            /* height                  */
        NULL,                                     /* parent handle           */
        NULL,                                     /* menu or child ID        */
        hInstance,                                /* instance                */
        NULL);                                    /* additional info         */

    if (!hWnd)                                    /* Was the window created? */
        return (NULL);

	hMainWnd = hWnd;		/* globalize the main window				*/
	/* On first usage, throw up About box, saying what WizUnzip is, etc.
	 */
	GetProfileString(szAppName, FIRSTUSE, "yes", 
				 szBuffer, sizeof(szBuffer));
	if (!stricmp(szBuffer, "yes"))
	{
		WriteProfileString(szAppName,FIRSTUSE, "no");
		PostMessage(hWnd, WM_COMMAND, IDM_ABOUT, 0L);
	}
   	hHelpCursor = LoadCursor(hInstance,"HelpCursor");

    ShowWindow(hWnd, nCmdShow);                   /* Shows the window        */
    UpdateWindow(hWnd);                           /* Sends WM_PAINT message  */

     while (GetMessage(&msg,        /* message structure                      */
            NULL,                  /* handle of window receiving the message */
            NULL,                  /* lowest message to examine              */
            NULL))                 /* highest message to examine             */
    {
		if (!TranslateAccelerator(hWnd, hAccTable, &msg))
		{
        	TranslateMessage(&msg);    /* Translates virtual key codes    */
        	DispatchMessage(&msg);     /* Dispatches message to window    */
		}
    }
    return (msg.wParam);           /* Returns the value from PostQuitMessage */
}
