#
#       class to hold a summary of a genome (or database)
#
#                                       Gaston H. Gonnet (Sep 15, 2004)
GenomeSummary := proc(
  FileNameOrig:{string, # the name of the external file containing the database
        database},      # a database structure to extract the information
  String:string,        # the header part of the  database as a string
  TotAA:posint,         # the total number of amino acids or bases in the dbase
  TotChars:posint,      # the total number of characters in the database
  TotEntries:posint,    # the total number of entries in the database
  Type:string,          # dna, rna, mixed or peptide
  EntryLengths:list(posint), # length of each entry
  Id:string,            # 5-letter code for genome
  Kingdom:string,       # either Bacteria, Archaea, Eukaryota, Viruses or Mitochondira
  Lineage:list(string), # Lineage as a list (from OS tags)
                        # genus (from the binomial nomenclature)
                        # epithet (from the binomial nomenclature)
  SingleSeqIndex:list(posint),  # index array pointing to a canonical
                                # entry number with identical SEQ.
  SkipIsoform:string)   # string 0/1 of length TotEntries indicating if isoform is relevant
global DB; option NoIndexing;

if nargs=1 and type(FileNameOrig,database) then
     curDB := DB:
     DB := d := FileNameOrig;
     i := SearchString('<E>',d[string]);
     if i<0 then error('no entries in database') fi;
     en_len := [seq(length(Sequence(Entry(i))), i=1..d['TotEntries'])];
     if type(curDB, database) then DB := curDB fi:
     return( procname( d, d[string,1..i], d['TotAA'],
        d['TotChars'], d['TotEntries'], d[type], en_len ))

elif nargs=7 then
     t := SearchTag('5LETTERNAME',String);
     if length(t)=5 or length(t)=6 and t[1]='m' then
          return( procname( args, t ))
     else error('missing 5LETTERNAME in header part') fi

elif nargs=8 then
     t := SearchTag('KINGDOM',String);
     if member(t,{'Bacteria','Archaea','Eukaryota','Viruses','Mitochondria'}) then
          return( procname(args,t))
     else error(t,'missing or incorrect KINGDOM in header part') fi

elif nargs=9 then
     t := SearchTag('OS',String);
     r := [];
     do  i := SearchString(';',t);
         if i < 0 then r := append(r,t);  break fi;
         r := append(r,t[1..i]);
         t := (i+1) + t;
         while length(t) > 0 and t[1] = ' ' do t := 1+t od;
         od;
     if length(r) < 2 then error(Id,r,'Lineage from OS in header is incomplete')
     elif r[1] <> Kingdom then
          error(Id,r[1],Kingdom,'Kingdom and Lineage[1] do not coincide') fi;
     return( procname(args,r) )

elif nargs=10 then
     canonicalENr := [seq(i, i=1..TotEntries)];
     if type(args[1], database) then
        curDB := DB:
        DB := args[1];
        processed := CreateString(DB['TotEntries'], '0'):
        skip_isoform := CreateString(DB['TotEntries'], '0'):
        for eNr to DB['TotEntries'] do 
            if SearchTag('SPLICE', Entry(eNr))='skip' then
                 skip_isoform[eNr] := '1';
            fi:
            if processed[eNr]<>'0' then next fi:
            se := Sequence(Entry(eNr));
            pat := SearchSeqDb(se);
            if pat[1,2]>pat[1,1] then 
               sse := []:
               for pi from pat[1,1] to pat[1,2] do
                   i := GetEntryNumber(DB[Pat,pi]):
                   if Sequence(Entry(i))=se then sse := append(sse, [i, SearchTag('SPLICE',Entry(i))]) fi:
               od:
               for z in sse while z[2]='skip' do od: if z[2]='skip' then z:=sse[1] fi:
               for cur in sse do 
                   canonicalENr[cur[1]] := z[1]:
                   processed[cur[1]] := '1';
               od:
            fi:
        od:
        if type(curDB,database) then DB := curDB fi:
        return( procname( args[1,'FileName'], args[2..-1], canonicalENr, skip_isoform ));
    else return(procname(args, canonicalENr));
    fi:

elif nargs = 11 then
    # for backward compability reasons, don't skip any protein/isoforms
    return( procname(args, CreateString(TotEntries,'0')) );

elif nargs <> 12 then error('invalid number of arguments') fi;

if not ( length(Id)=5 and uppercase(Id)=Id or
         length(Id)=6 and Id[1]='m' and uppercase(Id[2..6])=Id[2..6] ) then
     error(Id,'is not a valid 5-letter code for the species')
elif not member(lowercase(Type),{'dna','rna','mixed','peptide'}) then
     error(Id,Type,'is not a valid database Type')
elif not member(Kingdom,{'Bacteria','Archaea','Eukaryota','Viruses','Mitochondria'}) then
     error(Id,Kingdom,'is an invalid Kingdom name')
elif length(Lineage) < 2 then error(Id,Lineage,'Lineage is too short')
elif Kingdom <> Lineage[1] then
     error(Id,Kingdom,Lineage,'Kingdom and Lineage[1] do not coincide')
elif TotAA <> sum(EntryLengths) then error(Id,TotAA,sum(EntryLengths),
        'TotAA and sum(EntryLengths) do not coincide')
elif length(SkipIsoform) <> TotEntries or length(SingleSeqIndex) <> TotEntries then
     error('Length of SkipIsoform and SingleSeqIndex do not match TotEntries')
fi;
noeval(procname(args))
end:

GenomeSummary_select := proc( gs:GenomeSummary, sel, val )
option internal;
if nargs=3 then error('cannot assign to selector',sel)
elif sel='Entry' then error('GenomeSummary does not have Entries')
elif sel='Pat' then error('GenomeSummary does not have a Pat index')
elif sel=string then gs[String]
elif sel=type then gs[Type]
elif sel='Genus' then
     sci := gs['Lineage',-1];
     i := SearchString(' ',sci);
     if i<0 then sci else sci[1..i] fi
elif sel='Epithet' then
     sci := gs['Lineage',-1];
     i := SearchString(' ',sci);
     if i<0 then error('cannot find Epithet in Lineage') fi;
     sci := i+1+sci;
     i := SearchString(' ',sci);
     if i<0 then sci else sci[1..i] fi
elif sel='FileName' then
     origFn := gs['FileNameOrig'];
     genomePath := getenv('DARWIN_GENOMES_PATH');
     if genomePath='' then 
         return(origFn);
     else 
         k := SearchAllString('/', origFn);
         if length(k)>2 then
             return( genomePath.origFn[k[-2]..-1] );
         else return( origFn ); fi:
     fi:
elif sel='SameSeq' then
     sameseq := CreateArray(1..gs['TotEntries'], {}):
     ssi := gs['SingleSeqIndex']:
     idx := sort([seq(i,i=1..gs['TotEntries'])], x->ssi[x]):
     for i to gs['TotEntries'] do
         idx_i := ssi[idx[i]];
         for j from i+1 to gs['TotEntries'] while ssi[idx[j]]=idx_i do od:
         eqSet := {op(idx[i..j-1])};
         for e in idx[i..j-1] do sameseq[e] := eqSet od:
         i := j-1;
     od:
     return( sameseq ):
elif not type(sel,string) then error(sel,'invalid selector')
else SearchTag( sel, gs[String] ) fi
end:


GenomeSummary_print := proc( gs:GenomeSummary )
option internal;
for z in  ['FileName', 'string', 'TotAA', 'TotChars', 'TotEntries',
        'type', 'Id', 'Kingdom', 'Lineage'] do
    if z='string' then
         gsst := gs[string];
         printf( '    string: %a...\n', gsst[1..min(65,length(gsst))] )
    else printf( '%10.10s: %a\n', z, gs[z] ) fi od
end:


CompleteClass( GenomeSummary );
