/* This file is DPMI_V2.C
**
** this program shows allocating memory in the DPMI-enviroment
** compile with smallmodel,protected mode instuctions
** link with dpmiutil.obj
*/

#include <stdlib.h>
#include <stdio.h>
#include <time.h>
#include "DPMI.H"
#include <dos.h>

typedef struct node {
		unsigned long 	num;
        void far        *data ;
		struct node far	*next ;
		} NODE ;

void protected_program()
{
    FREEMEMINFO free;
    NODE far *p,far *q;
    unsigned long nodes=0;
    unsigned nodesize ;
    time_t t1,t2;

    getfreeinfo(&free);
    printf("\n");
    printfreeinfo(&free);

    printf("\nSet NodeSize (try 4092) : ");
    scanf("%lu",&nodesize);

    time(&t1);

    for (q= NULL ;;q->next =p) {
        p=q ;
        if ((q=extmalloc(sizeof(NODE)))== NULL)
            break;
        if ((q->data=extmalloc((DWORD)nodesize))==NULL) {
            extfree(q);
            break;
            }
        q->num=nodes++;
        }
    printf("\n%lu nodes ; %lu seconds\n",nodes,time(&t2)-t1);
    printf("Allocated %lu KB\n", (nodes* ((DWORD)nodesize)+sizeof(NODE))>>10 );

    getfreeinfo(&free);
    printf("\n");
    printfreeinfo(&free);

    printf("\nFree descriptor..\n");

    time(&t1);
    for (;p!=NULL; p=q) {
        q=p->next;
        if (p->num != --nodes)
		printf("list corrupt: nodes=%lu num=%lu\n",nodes,p->num);
        extfree(p->data);
        extfree(p);
        }
    time(&t2);
    printf("..end\n");
    printf("%lu seconds\n",t2-t1);
}

void main()
{
    real_to_protected();
    protected_program();
    protected_to_real();
}
