/************************************************************************
       -= SEER - C-Scripting engine v 0.7a =-
State      : under implementation
Author     : Przemyslaw Podsiadly
             email: ppodsiad@elka.pw.edu.pl
             WWW:   http://home.elka.pw.edu.pl/~ppodsiad
File:exmulti.c
Desc:example:writing compiled script to file,forking , protecting
************************************************************************/
#include <stdio.h>
#include <stdlib.h>
#include <seer.h>

//script imports these:
int key;
void delay()
{int i,x;
 for(i=0;i<1000000;i++) x=i?10-i:i*3;
}

char *stdio=
"import int printf(char *,...);                 \n"
"import int scanf(char *,...);                  \n"
;
//this function is forbidden to be used by instances not having
// at least KERNEL priority
void ForVIPsONLY()
{
 scKernelOnly(;)
}

void test(scScript sc)
{int rep;
 scInstance *in1,*in2,*in3;
 scAdd_External_Symbol("printf",printf);
 scAdd_External_Symbol("scanf",scanf);
 scAddExtSym(ForVIPsONLY);
 //Create instances:

 in1=scCreate_Instance(sc,"");
 in2=scFork_Instance(in1);
 in3=scFork_Instance(in2);
 scSet_Priority(in1,scrights_KERNEL);
 //the parent is kernel, all other forks are not
 if (!in1||!in2||!in3)
  {printf("Error creating instance!");return;}

 scLaunch_Instance(in2,40,scGet_Symbol(in2,"second"));
 if (scErrorNo)
  {printf("2:%s",scErrorMsg);exit(1);
  }
 scLaunch_Instance(in1,60,scGet_Symbol(in1,"first"),1);
 if (scErrorNo)
  {printf("1:%s",scErrorMsg);exit(1);
  }
 scLaunch_Instance(in3,25,scGet_Symbol(in3,"third"));
 if (scErrorNo)
  {printf("3:%s",scErrorMsg);exit(1);
  }

 printf("\n Start of the test: one instance should cause an error!\n");
 printf("because it attempts to use functions not allowed for it\n");
 rep=0;
 while ((rep<10)&&scContinue_Instances())
 {delay();
  rep++;
  fflush(stdout);
  if (scErrorNo)
   {printf("!\n%s\n!",scErrorMsg);getchar();}
 }
 scKill_Instance(in1);
 scFree_Instance(in1);
 printf("\nDeleting parent.Now another child becomes a parent.\n");
 printf("<KEY>\n");
 getchar();
 rep=0;
 while ((rep<10)&&scContinue_Instances())
 {delay();
  rep++;
  fflush(stdout);
  if (scErrorNo)
   {printf("!\n%s\n!",scErrorMsg);getchar();}
 }
}

int main()
{FILE *file;
 scScript scrpt;
 printf("Compiling the script...\n");

//setup SeeR
 scInit_SeeR();
 scSeeR_Set(scSeeR_ExprOpcode,1);//generate EXPR opcodes
 //it's needed in multitasking (only in EXPR SeeR can interrupt script)

 scAdd_Internal_Header("stdio",stdio);
 scExport_Kernel();
 scrpt=scCompile_File("exmulti.sc");
 if (!scrpt)
  {printf("Error during compilation:\n%s\nIn line:%s\n",scErrorMsg,scErrorLine);exit(1);
  }
 printf("Compiled.\n");

 file=fopen("exmulti.cs","wb");
 fwrite(scrpt,scGet_Script_Size(scrpt),1,file);
 fclose(file);
 printf("Written to file\n");
 test(scrpt);
 printf("\n\nEnd(press a key).\n");
 free(scrpt);
 getchar();
 return 0;
}

