/* 
LS-SCRIPT: extract X-stresses for all 3-layer of the shell element of part 2,
then find the absolute maximun value amoung the 3 layers of a, then write the results to file
*/

define:
void main(void)
{
    Int numState;
    Int numShellEle;
    Int i = 0;
    Int j = 0;
    char buf[256];
    Int *eleconn = NULL;
    Int *eleid = NULL;
    Int *internalid = NULL;
    Int pid,size,numele;
    FILE *fp;
    Float *result_top = NULL;
    Float *result_bot = NULL;
    Float *result_mid = NULL;
    Float val,val1,val2,val3;
    Float sgn,sgn1,sgn2,sgn3;

/* get number of shell elements in the model */
    numShellEle = SCLGetDataCenterInt("num_shell_elements");
    sprintf(buf,"no. of shell elems = %d",numShellEle);
    Echo(buf);
    if (numShellEle == 0) {
       Echo("No shell elements in model");
       exit(0);
    }

/* get number of states */
    numState = SCLGetDataCenterInt("num_states");
    sprintf(buf,"no. of states = %d",numState);
    Echo(buf);

/* Open file for data writing to */
    fp = fopen("stress_output.txt","w+");

/* allocate memory */
    eleid = malloc(numShellEle*sizeof(Int));
    internalid = malloc(numShellEle*sizeof(Int));
    result_top = malloc(numShellEle*sizeof(Float));
    result_bot = malloc(numShellEle*sizeof(Float));
    result_mid = malloc(numShellEle*sizeof(Float));

/* Switch to the last state */
    SCLSwitchStateTo(numState);

/* get element ids  */
    size = SCLGetDataCenterIntArray("element_ids",&eleid,SHELL,0);
    sprintf(buf,"no. of shell elements = %d",size);
    Echo(buf);

/* get shell element stress array */
        /* char* usrname: compenont name
         * Int typename: 0=Whole, SHELL, TSHELL, BEAM, SOLID
         * Int ipt: MID, INNER=Botom, OUTTER=top
         * Float** results: results array
         */

    size = SCLGetDataCenterFloatArray("stress_x",SHELL,MID,&result_mid);
    size = SCLGetDataCenterFloatArray("stress_x",SHELL,INNER,&result_bot);
    size = SCLGetDataCenterFloatArray("stress_x",SHELL,OUTER,&result_top);

/* get internal element id for part 2 */
    pid = 2;
    numele = SCLGetDataCenterIntArray("elemofpart_ids",&internalid,0,pid);
    sprintf(buf,"no. of elements in pid %d = %d",pid,numele);
    Echo(buf);

    fprintf(fp,"Shell X-Stress at time step no. %d\n",numState);
    fprintf(fp,"    Ele ID.     X-Stress\n");
    for (i=0; i<numele; i=i+1) {
      j = internalid[i];

      val1 = result_mid[j];
      sgn1=sgn2=sgn3=1.0;

      if (val1 < 0.0) { val1 = -val1; sgn1=-1.0; }
      val2 = result_top[j];
      if (val2 < 0.0) { val2 = -val2; sgn2=-1.0; }
      val3 = result_bot[j];
      if (val3 < 0.0) { val3 = -val3; sgn3=-1.0; }
      val = val1; sgn =sgn1;
      if (val2 > val) {val = val2; sgn=sgn2; }
      if (val3 > val) {val = val3; sgn=sgn3; }
      val = val * sgn;
      fprintf(fp,"%10d, %13e\n",eleid[j],val);
    }
    
    free(eleid);
    free(internalid);
    free(result_top);
    free(result_bot);
    free(result_mid);
    fclose(fp);
}
main();
