//////////////////////////////////////////////////////////////////////////////
// SplitIndex.cpp v1.2
//
// February 20, 1996
//
// ©1995,96 SynthoWare
// Splits aminet index files into respective dir files
//
// i.e. Index-> dev, comm, ...wb
//
// See guide file for original author information
//
// Programmed By: Deryk B Robosson
// E-mail:        newlook@free.org
//                nur_hutsko@online.emich.edu
// Snail-mail:    32609 Manistee
//                Westland, MI  48186
//                +1.313.990.3599
// IRC: Channel #amiga as newlook
//
// Used: * AFrame
//         - Amiga C++ OOP Programmers Enhancements
//         - By Jeffry A Worth
//           - e-Mail: worth@online.emich.edu
//                     73410.1112@compuserve.com
//         - And Deryk B Robosson
//           - See above or guide for bug reports etc.
//
//       * CygnusEd Professional v3.6
//         - From CygnusSoft Software
//         - Copyright © 1987-1993 CygnusSoft Software
//
//////////////////////////////////////////////////////////////////////////////

//////////////////////////////////////////////////////////////////////////////
// Includes
#include "aframe:include/amigaapp.hpp"
#include "aframe:include/window.hpp"
#include "aframe:include/rastport.hpp"
#include "aframe:include/rect.hpp"
#include "aframe:include/button.hpp"
#include "aframe:include/reqtools.hpp"
#include "aframe:include/string.hpp"
#include <stdlib.h>
#include <stdio.h>

#define LINESIZE    81          // max size of line in index
#define DIRSIZE     5           // max size of aminent directory +1 - e.g.:
                                // MODS, DIR, WB, COMM
FILE *indexfile, *outfile = NULL; // input and output file pointers

char    line[LINESIZE], dirold[DIRSIZE], dirnew[DIRSIZE];
AFString sourcefile, destfile, desttemp;  // set aside three strings to use
char    *q;
int     ok=TRUE;

//////////////////////////////////////////////////////////////////////////////
// ControlWindow Class Definition

class ControlWindow : public AFWindow

{
public:
  virtual void OnCreate();
  virtual void OnCloseWindow(LPIntuiMessage imess);
  virtual void OnGadgetUp(LPIntuiMessage imess);
  virtual void DestroyWindow();
  virtual ULONG WindowFlags();

  AFReqTools rt;
  AFButton SourceBut, DestBut, GoBut;
};

//////////////////////////////////////////////////////////////////////////////
// ControlWindow Implementation routines

void ControlWindow::OnCloseWindow(LPIntuiMessage imess)
{
  AFWindow::DestroyWindow();
}

void ControlWindow::DestroyWindow()     // cleanup
{
    if(indexfile) {
        fclose(indexfile);
        indexfile=NULL;
    }
    if(outfile)
        outfile=NULL;
}

void ControlWindow::OnCreate()          // things to do when window created
{
    rt.RTCreate();  // create reqtools object
}

void ControlWindow::OnGadgetUp(LPIntuiMessage imess)  // handle gadget up messages
{
  AFReqTools rt;
  static ULONG sourcetags[]={ RTEZ_ReqTitle,(ULONG)"Source",TAG_END };
  static ULONG desttags[]={ RTEZ_ReqTitle,(ULONG)"Destination",TAG_END };
  static int i;

  switch(((struct Gadget*)imess->IAddress)->GadgetID) {

  case 100:     // Get source filename
    if(!(rt.RTFileRequest()))
        rt.RTEZRequestA((char *)"You didn't select a SOURCE file!",(char *)"Ok",NULL,sourcetags);
    else
        if(rt.m_filerequester->Dir != NULL) {
            sourcefile = rt.m_filerequester->Dir;

            if(sourcefile[sourcefile.length()-1]==':') // are we a device?
                sourcefile += rt.filename;
            else {                                     // or device/directory?
                sourcefile += "/";
                sourcefile += rt.filename;
            }
        } else sourcefile=(AFString)rt.filename;

    break;

  case 101:     // Get destination directory
    if(!(rt.RTFileRequest()))
        rt.RTEZRequestA((char *)"You didn't select a DESTINATION directory!",(char *)"Ok",NULL,desttags);
    else
        if(rt.m_filerequester->Dir != NULL) {
            desttemp = rt.m_filerequester->Dir;
            if(desttemp[desttemp.length()-1]==(char)':'){ // are we a device?
                //do nothing
                desttemp += rt.filename;
            } else {                                       // or a device/directory?
                desttemp += "/";
                desttemp += rt.filename;
            }
        } else desttemp=(AFString)rt.filename;

    break;

  case 102:     // Create subindex files
    if (!(indexfile=fopen((const char *)sourcefile.data(),"r"))) {
        rt.RTEZRequest("Unable to open SOURCEFILE","Ok");
        sourcefile=NULL;
        break;
    }

    fgets (line,LINESIZE,indexfile); // move file pointer past index header info

    while (*line=='|')
        fgets (line,LINESIZE,indexfile);

    // Now pointing to start of aminet listings

    while (ok) {  // loop through index line by line
        fgets (line,LINESIZE,indexfile);

        if (! feof(indexfile)) { // end of file??
            // copy DIR type (comm,dir,wb etc...) to dirnew

            // NB: the check for the space is there because I discovered an
            // INDEX file with an entry under "gfx" only, not "gfx/xxx", which
            // caused an error... The check stops this occurance from crashing
            // the machine, or producing another list.gfx file due to the anomoly
            for (i=0, q=&line[19]; !(*q=='/' || *q==' ') ; q++, i++)
                dirnew[i] = *q;

            dirnew[i]=NULL;                 // add NULL-terminator

            if (strcmp((const char *)dirnew,dirold) != 0) { // different DIR type?
                // close old output file
                if(outfile) fclose(outfile);

                destfile = desttemp;
                destfile += "_";
                destfile += dirnew;

                // open new file
                if(!(outfile=fopen((const char *)destfile.data(),"w"))) {
                    // can't open output file - cleanup
                
                    rt.RTEZRequestA("ERROR! Unable to open DESTINATION file",
                               "Ok",NULL,desttags);

                    fclose(indexfile);
                    break;
                }
                strcpy(dirold,dirnew);      // make dirold = dirnew
            }
            fprintf(outfile,"%s",line);     // write item to outfile
        } else ok = FALSE;                  // quit while loop
    }

    rt.RTEZRequest("All Done!","Ok");
    break;

  default:  // message must have not been ours
    AFWindow::OnGadgetUp(imess);
    break;
  }
}

ULONG ControlWindow::WindowFlags()          // set our window flags
{
  return (AFWindow::WindowFlags() | WFLG_GIMMEZEROZERO);
}

//////////////////////////////////////////////////////////////////////////////
// MAIN

void main()
{
  AFAmigaApp theApp;
  AFRect rect(10,10,410,160);
  ControlWindow win;

  rect.SetRect(10,10,190,62);
  win.Create(&theApp,&rect,"SPlitIndex");

  rect.SetRect(2,2,52,35);
  win.SourceBut.Create("Source",&win,&rect,100);

  rect.SetRect(54,2,104,35);
  win.DestBut.Create("Dest",&win,&rect,101);

  rect.SetRect(106,2,156,35);
  win.GoBut.Create("GO!",&win,&rect,102);

  win.RefreshGadgets();

  theApp.RunApp();
}
