#include <stdio.h>

#include <exec/types.h>

#include "diskstruct.h"
#include "read.h"

struct Root *r;
struct Map *m;

struct sector {
    int bnum;
    UBYTE *blk;
} *blocks;

int nexttowrite = 0;

void Flush()
{
    struct sector *p;

    printf( "Insert destination\n" ); (void)getchar();
    p = blocks;

    while( p->bnum < nexttowrite ) p++;

    while( nexttowrite < 11*160 ) {
        if( p->blk != NULL ) {
            while( nexttowrite < p->bnum ) {
                FillBlock();
                nexttowrite++;
            }
            (void)WriteBlock( p->blk );
            free( p->blk );
            p->blk = NULL;
        } else {
            return;
        }
        p++;
    }
    return;
}

void main()
{
    ULONG *b, k;
    int n, i, x;
    UBYTE *bx;

    D_Init();

    r = (struct Root *)ReadBlock( 880, 0 );
    if( r->r_flag != -1 ) {
        free( r );
        printf( "Bitmap not valid!\n" );
    }

    m = (struct Map *)ReadBlock( r->r_bmpages[0], 0 );

    free( r );

    n = 11*160/32;

    b = &m->m_map[0];

    for( x = 0,i = 0; i < n; i++ ) {
        k = b[i];
        while( k ) {
            x += k&1;
            k >>= 1;
        }
    }

    x = 11*160 - x;

    blocks = (struct sector *)calloc( x, sizeof( struct sector ) );

    if( blocks != NULL ) {
        blocks[0].bnum = 0; blocks[0].blk = ReadBlock( 0, 0 );
        blocks[1].bnum = 1; blocks[1].blk = ReadBlock( 1, 0 );

        n = 2;

        for( i = 0; i < 11*160 - 2; i++ ) {
            if( i % 32 == 0 ) {
                k = b[i/32];
            }
            if( !(k & 1) ) {
                blocks[n].bnum = i+2;
                while( (bx = ReadBlock( i+2, 0 )) == NULL ) {
                    printf( "Flush\n" );
                    Flush();
                    printf( "Insert source\n" ); getchar();
                }
                blocks[n].blk = bx;
                n++;
            }
        }

        Flush();
        free( blocks );
    } else {
        printf( "Not enough mem\n" );
    }

    free( m );

    D_Clean();
}


