/*=======================================================================

Author: Warren Furlow (email: warren@furlow.org)

License: PUBLIC DOMAIN - May be freely copied and incorporated into any work

Description:  Reads and checks a MOD file, then outputs its contents and info

=========================================================================*/

#define _CRT_SECURE_NO_WARNINGS
#define _CRT_NONSTDC_NO_WARNINGS

#include<stdio.h>
#include<stdlib.h>
#include<string.h>
#include<io.h>
#include<memory.h>
#include"MODFile.h"

/******************************/
void main(
  int argc,
  char *argv[])
  {
  char MODFileName[255]={""};
  int i,errors=0;
  int Verbose=0,Extract=0,DecodeFat=0,All=0;

  for (i=1;i<argc;i++)
    {
    if (0==strcmpi(argv[i],"/v")||0==strcmpi(argv[i],"-V"))
      Verbose=1;
    else if (0==strcmpi(argv[i],"/f")||0==strcmpi(argv[i],"-f"))
      DecodeFat=1;
    else if (0==strcmpi(argv[i],"/e")||0==strcmpi(argv[i],"-e"))
      Extract=1;
    else if (0==strcmp(argv[i],"*"))
      All=1;
    else
      {
      strcpy(MODFileName,argv[i]);
      strcat(MODFileName,".mod");
      }
    }
  if (argc==1)
    {
    fprintf(stderr,"Module File Utility for HP-41\n");
    fprintf(stderr,"USAGE: MODFILE [options] [filename|*]\n");
    fprintf(stderr,"   /v Verbose\n");
    fprintf(stderr,"   /f Decode FAT, if any - assumes verbose mode\n");
    fprintf(stderr,"   /e Extract ROM images, if any\n");
    fprintf(stderr,"   Filename must not include .MOD extension\n");
    fprintf(stderr,"   If * is specified, all .MOD files in current directory will be processed\n");
    }
  else if (All)
    {
    struct _finddata_t fileinfo;
    long hDirectory;
    char drive[_MAX_DRIVE],dir[_MAX_DIR],fname[_MAX_FNAME],ext[_MAX_EXT],dir2[_MAX_DIR];
    _splitpath(argv[0],drive,dir,fname,ext);
    strcpy(dir2,dir);
    strcat(dir2,"*.mod");
    hDirectory=_findfirst(dir2,&fileinfo);
    if (hDirectory==-1)
      return;
    do
      {
      if ((0==strcmp(fileinfo.name,".")) || (0==strcmp(fileinfo.name,"..")))
        continue;
      _makepath(MODFileName,drive,dir,fileinfo.name,"");
      if (output_mod_info(stdout,MODFileName,Verbose,DecodeFat,NULL))
        errors++;
      if (Extract && extract_roms(MODFileName))
        errors++;
      }
    while (0==_findnext(hDirectory,&fileinfo));
    _findclose(hDirectory);
    }
  else
    {
    if (output_mod_info(stdout,MODFileName,Verbose,DecodeFat,NULL))
      errors++;
    if (Extract && extract_roms(MODFileName))
      errors++;
    }
  if (errors)
    fprintf(stderr,"*** %d ERROR(S)\n",errors);
  }
