/*    
   Crunch.c - Move all data to the front of the disk.

   Copyright (C) 2002 Imre Leber

   This program is free software; you can redistribute it and/or modify
   it under the terms of the GNU General Public License as published by
   the Free Software Foundation; either version 2 of the License, or
   (at your option) any later version.

   This program is distributed in the hope that it will be useful,
   but WITHOUT ANY WARRANTY; without even the implied warranty of
   MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
   GNU General Public License for more details.

   You should have received a copy of the GNU General Public License
   along with this program; if not, write to the Free Software
   Foundation, Inc., 675 Mass Ave, Cambridge, MA 02139, USA.

   If you have any questions, comments, suggestions, or fixes please
   email me at:  imre.leber@worldonline.be
*/

#include "fte.h"
#include "..\dtstruct\ClMovMap.h"
#include "..\..\modlgate\expected.h"

BOOL CrunchVolume(RDWRHandle handle)
{
    BOOL isMovableS, isMovableP;
    CLUSTER seeker=2, placer=2, label;
    unsigned long labelsinfat;

    labelsinfat = GetLabelsInFat(handle);
    if (!labelsinfat) return FALSE;

    while (seeker < labelsinfat)
    {
       if (!GetNthCluster(handle, seeker, &label))
          return FALSE;

       if (!IsClusterMovable(handle, seeker, &isMovableS))
          return FAIL;
       if (!IsClusterMovable(handle, placer, &isMovableP))
          return FAIL;

       if (FAT_FREE(label))
       {
          seeker++;
       }
       else if (FAT_BAD(label) || !isMovableS)
       {
          seeker++;
       }
       else
       {
          if (!GetNthCluster(handle, placer, &label))
             return FALSE;

          if (FAT_FREE(label) && (seeker != placer))
          {
             DrawOnDriveMap(placer, WRITESYMBOL);
             DrawOnDriveMap(seeker, READSYMBOL);

             if (!RelocateCluster(handle, seeker, placer))
                return FALSE;

             DrawOnDriveMap(placer, OPTIMIZEDSYMBOL);
             DrawOnDriveMap(seeker, UNUSEDSYMBOL);

             seeker++;
             placer++;
          }
          else if (FAT_BAD(label) || !isMovableP)
          {
             placer++;       /* bad cluster */
          }
          else
          {
             DrawOnDriveMap(placer, OPTIMIZEDSYMBOL);

             seeker++;
             placer++;
          }
       }
    }

    return TRUE;
}