/*--------------------------------------
    EXTRACT - resolves a ScriptEdit type
    master Handle to a CDR Handle.

    cdrHand = EXTRACT(masterHand);

    Marc Wolfgram,  7/23/92 15:12:47
*/

#pragma noroot
#pragma lint        3
#pragma memorymodel 0
#pragma optimize   14 /* until Mike fixes dead code generation */

#include <memory.h>
#include <control.h>

Handle EXTRACT(Handle);
Handle cdrInsert(Handle, Handle);

#define DBUG(x) asm { brk x }

extern word edMemID;

Handle EXTRACT(Handle mainH)
{
char            *p;
word            cardCnt, ctlCnt;
long            addSize, oldSize;
HandlePtr       cardHP;
CtlRecHndlPtr   ctlHP;
CtlRecHndl      ctlH;
Handle          cdrH, cdr;

    cdrH = NewHandle(25L, edMemID, 0x0008, 0L);     /* first alloc trailer */

    cardCnt = (word) (GetHandleSize(mainH)) >> 2;   /* get card count       */
    HLock(mainH);
    cardHP = (HandlePtr) *mainH;                    /* resolve cardArray    */
    while (cardCnt) {                               /* for each card...     */
        cardCnt--;                                      /* zero based       */
        ctlCnt = GetHandleSize(cardHP[cardCnt]) >> 2;   /* get ctl count    */
        HLock(cardHP[cardCnt]);
        ctlHP = (CtlRecHndlPtr) cardHP[cardCnt];        /* resolve ctlArray */
        while (ctlCnt) {                                /* for each ctl...  */
            ctlCnt--;                                       /* zero based   */
            ctlH = ctlHP[ctlCnt];                           /* resolve ctl  */
            cdr = (Handle) (**ctlH).ctlRefCon;
            oldSize = GetHandleSize(cdrH);
            addSize = GetHandleSize(cdr);
            SetHandleSize(oldSize + addSize, cdrH);
            p = (char *) *cdrH;
            BlockMove(p, &p[addSize], oldSize);
            HandToPtr(cdr, p, addSize);
        }
        HUnlock(cardHP[cardCnt]);
    }
    HUnlock(mainH);

    oldSize = GetHandleSize(cdrH);                  /* insert the header    */
    SetHandleSize(oldSize + 25L, cdrH);
    p = (char *) *cdrH;
    BlockMove(p, &p[25], oldSize);

    return cdrH;
}
