///////////////////////////////////////////////////////////////////////////
//    Copyright (C) 2014 Wizardry and Steamworks - License: GNU GPLv3    //
///////////////////////////////////////////////////////////////////////////
// Writes data to the filesystem in the partition between ead and tail 
// and returns the number of written bytes. 
//
// data cannot contain the = (equal, ASCII 061) sign, a restriction of 
// the key-value data semantics (http://grimore.org/fuss:data_structures:key-value_pairs).
integer wasPrimFSWrite(string k, string data, integer head, integer tail) {
    integer b;
    do {
        string d = wasGetLinkDescription(tail);
        string v = "";
        if(llSubStringIndex(d, k) != -1)
            v = wasKeyValueGet(k, d);
        integer s = llStringLength(v);
        // if the key was found
        if(s != 0) {
            s = BYTES_PER_SECTOR - llStringLength(d) + s;
            v = llGetSubString(data, 0, s-1);
            if(llStringLength(v) != 0) jump write;
            wasSetLinkDescription(tail,
                wasKeyValueDelete(
                    k,
                    d
                )
            );
            jump continue;
        }
        // if the key was not found
        if(llStringLength(d) >= BYTES_PER_SECTOR) jump continue;
        s = BYTES_PER_SECTOR - llStringLength(d) - llStringLength(k) - 1;
        // &
        if(llStringLength(d) != 0) --s;
        if(s < 0) jump continue;
        v = llGetSubString(data, 0, s-1);
        if(llStringLength(v) == 0) jump continue;
        // write
@write;
        b += llStringLength(v) + llStringLength(k) + 1;
        v = wasKeyValueSet(k, v, d);
        wasSetLinkDescription(tail,v);
        // GC
        v = "";
        data = llDeleteSubString(data, 0, s-1);
@continue;
        // GC
        d = "";
    } while(--tail>=head);
    // return written bytes
    return b;
}